Programs & Examples On #Mod alias

Apache module providing namespace configuration & redirection.

How can I detect if a selector returns null?

My preference, and I have no idea why this isn't already in jQuery:

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

Used like this:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

Or, as it looks in CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

The "backspace" escape character '\b': unexpected behavior?

Use a single backspace after each character printf("hello wor\bl\bd\n");

How to grant remote access permissions to mysql server for user?

Two steps:

  1. set up user with wildcard:
    create user 'root'@'%' identified by 'some_characters'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD 'some_characters' WITH GRANT OPTION

  2. vim /etc/my.cnf
    add the following:
    bind-address=0.0.0.0

restart server, you should not have any problem connecting to it.

How to auto resize and adjust Form controls with change in resolution

this.WindowState = FormWindowState.Maximized;

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

Javascript seconds to minutes and seconds

Clean one liner using ES6


const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);

Swift_TransportException Connection could not be established with host smtp.gmail.com

firstly,check for gmail SMTP server . you should have to allow access for less secured apps without allowing swift mailer is not possible.for this login in your email account first then go into privacy settings and then click on sign and security then click on apps without access and then make on to less secure apps option then try mailer again, it will work then.

Regex in JavaScript for validating decimal numbers

^\d+(\.\d{1,2})?$

will allow:

  1. 244
  2. 10.89
  3. 9.5

will disallow:

  1. 10.895
  2. 10.
  3. 10.8.9

How to establish ssh key pair when "Host key verification failed"

When you try to connect your remote server with ssh:

$ ssh username@ip_address

then the error raise, to solve it:

$ ssh-keygen -f "/home/local_username/.ssh/known_hosts" -R "ip_address"

How to find nth occurrence of character in a string?

 ([.^/]*/){2}[^/]*(/)

Match anything followed by / two times, then again. The third one is the one you want

The Matcher state can be used to tell where the last / is

How to get the selected value from RadioButtonList?

Using your radio button's ID, try rb.SelectedValue.

Catching "Maximum request length exceeded"

I'm using a FileUpload control and client side script to check the file size.
HTML (note the OnClientClick - executed before OnClick):

<asp:FileUpload ID="FileUploader" runat="server" />
<br />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClientClick="return checkFileSize()" OnClick="UploadFile" />
<br />
<asp:Label ID="lblMessage" runat="server" CssClass="lblMessage"></asp:Label>

Then the script (note the 'return false' if the size is too big: this is to cancel the OnClick):

function checkFileSize() 
{
    var input = document.getElementById("FileUploader");
    var lbl = document.getElementById("lblMessage");
    if (input.files[0].size < 4194304)
    {
        lbl.className = "lblMessage";
        lbl.innerText = "File was uploaded";
    }
    else
    {
        lbl.className = "lblError";
        lbl.innerText = "Your file cannot be uploaded because it is too big (4 MB max.)";
        return false;
    }
}

Disable asp.net button after click to prevent double clicking

<asp:Button ID="btnSend" runat="server" Text="Submit"  OnClick="Button_Click"/>

        <script type = "text/javascript">
            function DisableButton()
            {
                document.getElementById("<%=btnSend.ClientID %>").disabled = true;
            }
            window.onbeforeunload = DisableButton;
        </script>

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

Configure apache to listen on port other than 80

In /etc/apache2/ports.conf, change the port as

Listen 8079

Then go to /etc/apache2/sites-enabled/000-default.conf

And change the first line as

<VirtualHost *: 8079>

Now restart

sudo service apache2 restart

Apache will now listen on port 8079 and redirect to /var/www/html

EntityType has no key defined error

The Model class should be changed to :

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    [Table("studentdetails")]
    public class student
    {
        [Key]
        public int RollNo { get; set; }

        public string Name { get; set; }

        public string Stream { get; set; }

        public string Div { get; set; }
    }
}

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is my attempt:

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp

    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.

        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If

    End With
End Function

What is the difference between `let` and `var` in swift?

Everyone has pretty much answered this but here's a way you can remember what's what

Let will always say the same think of "let" as let this work for once and always as for "var" variable's can always change hence them being called variable's

Get all mysql selected rows into an array

You could try:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);

Currency formatting in Python

My locale settings seemed incomplete, so I had too look beyond this SO answer and found:

http://docs.python.org/library/decimal.html#recipes

OS-independent

Just wanted to share here.

Why aren't Xcode breakpoints functioning?

Another thing to check is that if you have an "Entitlements" plist file for your debug mode (possibly because you're doing stuff with the Keychain), make sure that plist file has the "get-task-allow" = YES row. Without it, debugging and logging will be broken.

How to set $_GET variable

For the form, use:

<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">

and for getting the value, use the get method as follows:

$value = $_GET['name_to_send_using_get'];

Spring 3 MVC resources and tag <mvc:resources />

@Nanocom's answer works for me. It may be that lines have to be at the end, or could be because has to be after of some the bean class like this:

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="org.springframework.web.servlet.resource.ResourceHttpRequestHandler" />    

<mvc:resources mapping="/resources/**" 
               location="/resources/" 
               cache-period="10000" />

How to Install Font Awesome in Laravel Mix

npm install font-awesome --save

add ~/ before path

@import "~/font-awesome/scss/font-awesome.scss";

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

ArrayList: how does the size increase?

Lets look at this code (jdk1.8)

@Test
    public void testArraySize() throws Exception {
        List<String> list = new ArrayList<>();
        list.add("ds");
        list.add("cx");
        list.add("cx");
        list.add("ww");
        list.add("ds");
        list.add("cx");
        list.add("cx");
        list.add("ww");
        list.add("ds");
        list.add("cx");
        list.add("last");
    }

1)Put break point on the line when "last" is inserted

2)Go to the add method of ArrayList You will see

ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;

3) Go to ensureCapacityInternal method this method call ensureExplicitCapacity

4)

private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
            return true;

In our example minCapacity is equal to 11 11-10 > 0 therefore You need grow method

5)

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

Lets describe each step:

1) oldCapacity = 10 because we didn't put this param when ArrayList was init ,therefore it will use default capacity(10)

2) int newCapacity = oldCapacity + (oldCapacity >> 1); Here newCapacity is equal to oldCapacity plus oldCapacity with right shift by one (oldCapacity is 10 this is the binary representation 00001010 moving one bit to right we will get 00000101 which is 5 in decimal therefore newCapacity is 10 + 5 = 15)

3)

if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;

For example your init capacity is 1, when you add the second element into arrayList newCapacity will be equal to 1(oldCapacity) + 0 (moved to right by one bit) = 1 In this case newCapacity is less than minCapacity and elementData(array object inside arrayList) can't hold new element therefore newCapacity is equal to minCapacity

4)

if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);

Check if array size reach MAX_ARRAY_SIZE (which is Integer.MAX - 8) Why the maximum array size of ArrayList is Integer.MAX_VALUE - 8?

5) Finally it copy old values to the newArray with length 15

ASP.NET MVC: Custom Validation by DataAnnotation

You could write a custom validation attribute:

public class CombinedMinLengthAttribute: ValidationAttribute
{
    public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
    {
        this.PropertyNames = propertyNames;
        this.MinLength = minLength;
    }

    public string[] PropertyNames { get; private set; }
    public int MinLength { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
        var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
        var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
        if (totalLength < this.MinLength)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}

and then you might have a view model and decorate one of its properties with it:

public class MyViewModel
{
    [CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
    public string Foo { get; set; }
    public string Bar { get; set; }
    public string Baz { get; set; }
}

How to do a HTTP HEAD request from the windows command line?

On Linux, I often use curl with the --head parameter. It is available for several operating systems, including Windows.

[edit] related to the answer below, gknw.net is currently down as of February 23 2012. Check curl.haxx.se for updated info.

Add (insert) a column between two columns in a data.frame

Here's a quick and dirty way of inserting a column in a specific position on a data frame. In my case, I have 5 columns in the original data frame: c1, c2, c3, c4, c5 and I will insert a new column c2b between c2 and c3.

1) Let's first create the test data frame:

> dataset <- data.frame(c1 = 1:5, c2 = 2:6, c3=3:7, c4=4:8, c5=5:9)
> dataset
  c1 c2 c3 c4 c5
1  1  2  3  4  5
2  2  3  4  5  6
3  3  4  5  6  7
4  4  5  6  7  8
5  5  6  7  8  9

2) Add the new column c2b at the end of our data frame:

> dataset$c2b <- 10:14
> dataset
  c1 c2 c3 c4 c5 c2b
1  1  2  3  4  5  10
2  2  3  4  5  6  11
3  3  4  5  6  7  12
4  4  5  6  7  8  13
5  5  6  7  8  9  14

3) Reorder the data frame based on column indexes. In my case, I want to insert the new column (6) between existing columns 2 and 3. I do that by addressing the columns on my data frame using the vector c(1:2, 6, 3:5) which is equivalent to c(1, 2, 6, 3, 4, 5).

> dataset <- dataset[,c(1:2, 6, 3:5)]
> dataset
  c1 c2 c2b c3 c4 c5
1  1  2  10  3  4  5
2  2  3  11  4  5  6
3  3  4  12  5  6  7
4  4  5  13  6  7  8
5  5  6  14  7  8  9

There!

How to get equal width of input and select fields

I tried Gaby's answer (+1) above but it only partially solved my problem. Instead I used the following CSS, where content-box was changed to border-box:

input, select {
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Resolving instances with ASP.NET Core DI from within ConfigureServices

The IServiceCollection interface is used for building a dependency injection container. After it's fully built, it gets composed to an IServiceProvider instance which you can use to resolve services. You can inject an IServiceProvider into any class. The IApplicationBuilder and HttpContext classes can provide the service provider as well, via their ApplicationServices or RequestServices properties respectively.

IServiceProvider defines a GetService(Type type) method to resolve a service:

var service = (IFooService)serviceProvider.GetService(typeof(IFooService));

There are also several convenience extension methods available, such as serviceProvider.GetService<IFooService>() (add a using for Microsoft.Extensions.DependencyInjection).

Resolving services inside the startup class

Injecting dependencies

The runtime's hosting service provider can inject certain services into the constructor of the Startup class, such as IConfiguration, IWebHostEnvironment (IHostingEnvironment in pre-3.0 versions), ILoggerFactory and IServiceProvider. Note that the latter is an instance built by the hosting layer and contains only the essential services for starting up an application.

The ConfigureServices() method does not allow injecting services, it only accepts an IServiceCollection argument. This makes sense because ConfigureServices() is where you register the services required by your application. However you can use services injected in the startup's constructor here, for example:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // Use Configuration here
}

Any services registered in ConfigureServices() can then be injected into the Configure() method; you can add an arbitrary number of services after the IApplicationBuilder parameter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IFooService>();
}

public void Configure(IApplicationBuilder app, IFooService fooService)
{
    fooService.Bar();
}

Manually resolving dependencies

If you need to manually resolve services, you should preferably use the ApplicationServices provided by IApplicationBuilder in the Configure() method:

public void Configure(IApplicationBuilder app)
{
    var serviceProvider = app.ApplicationServices;
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();
}

It is possible to pass and directly use an IServiceProvider in the constructor of your Startup class, but as above this will contain a limited subset of services, and thus has limited utility:

public Startup(IServiceProvider serviceProvider)
{
    var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>();
}

If you must resolve services in the ConfigureServices() method, a different approach is required. You can build an intermediate IServiceProvider from the IServiceCollection instance which contains the services which have been registered up to that point:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IFooService, FooService>();

    // Build the intermediate service provider
    var sp = services.BuildServiceProvider();

    // This will succeed.
    var fooService = sp.GetService<IFooService>();
    // This will fail (return null), as IBarService hasn't been registered yet.
    var barService = sp.GetService<IBarService>();
}

Please note: Generally you should avoid resolving services inside the ConfigureServices() method, as this is actually the place where you're configuring the application services. Sometimes you just need access to an IOptions<MyOptions> instance. You can accomplish this by binding the values from the IConfiguration instance to an instance of MyOptions (which is essentially what the options framework does):

public void ConfigureServices(IServiceCollection services)
{
    var myOptions = new MyOptions();
    Configuration.GetSection("SomeSection").Bind(myOptions);
}

Manually resolving services (aka Service Locator) is generally considered an anti-pattern. While it has its use-cases (for frameworks and/or infrastructure layers), you should avoid it as much as possible.

Javascript Thousand Separator / string format

Combination of solutions for react

  let converter = Intl.NumberFormat();
  let salary =  monthlySalary.replace(/,/g,'')
  console.log(converter.format(salary))

  this.setState({
    monthlySalary: converter.format(salary)
  })
}

handleOnChangeMonthlySalary(1000)```

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

There's an architecture mismatch. Your JDBC Driver and your JDK should be of the same architecture. If your using 32bit Driver and your JDK is 64bits, you would get that error.

See this

Fix : Depends on your architecture.

You will need 64-bit drivers if your Java is 64-bit.

Download : http://www.microsoft.com/downloads/details.aspx?familyid=C06B8369-60DD-4B64-A44B-84B371EDE16D&displaylang=en

Xcode Error: "The app ID cannot be registered to your development team."

Meet same Issue on one mac, but ok on another mac. I'm sure bundle ID is fine and unique.

I know it is provisioning profile issue, so Try refreshing the provisioning profile on your Local computer. Then It Works!

  1. cd ~/Library/MobileDevice/Provisioning\ Profiles
  2. rm *
  3. Xcode > Preferences... > Accounts > click your Account and Team name > click Download Manual Profiles
  4. Run app again

Oracle DateTime in Where Clause?

Yes: TIME_CREATED contains a date and a time. Use TRUNC to strip the time:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED if it exists. An alternative approach without this problem is this:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') 
      AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1

javascript find and remove object in array based on key value

I can grep the array for the id, but how can I delete the entire object where id == 88

Simply filter by the opposite predicate:

var data = $.grep(data, function(e){ 
     return e.id != id; 
});

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Angular2 - Input Field To Accept Only Numbers

from @omeralper 's answer. I change a little bit that won't accept period ascii (keycode 110,190). and use let ch = (e.key); to compare with regular expression when you change language (such as Thai or Japanese language) it won't accept character of those language

export class OnlyNumber {

  regexStr = '^[0-9]*$';
  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
      // console.log(event, this.OnlyNumber);
        if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1) {
          return;
        }
      let ch = (e.key);
      let regEx =  new RegExp(this.regexStr);   
      if(regEx.test(ch))
        return;
      else
         e.preventDefault();
    }
  }
}

hope this help :)

Collection was modified; enumeration operation may not execute in ArrayList

Am I missing something? Somebody correct me if I'm wrong.

list.RemoveAll(s => s.Name == "Fred");

Iterating over Typescript Map

Just use Array.from() method to convert it to an Array:

myMap : Map<string, boolean>;
for(let key of Array.from( myMap.keys()) ) {
   console.log(key);
}

How to fix "set SameSite cookie to none" warning?

>= PHP 7.3

setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]);

< PHP 7.3

exploit the path
setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

Emitting javascript

echo "<script>document.cookie('key=value; SameSite=None; Secure');</script>";

Auto reloading python Flask app upon code changes

from the terminal u can simply say

expoort FLASK_APP=app_name.py
export FLASK_ENV=development
flask run

or in ur file

if __name__ == "__main__":
    app.run(debug=True)

Use CSS to remove the space between images

An easy way that is compatible pretty much everywhere is to set font-size: 0 on the container, provided you don't have any descendent text nodes you need to style (though it is trivial to override this where needed).

.nospace {
   font-size: 0;
}

jsFiddle.

You could also change from the default display: inline into block or inline-block. Be sure to use the workarounds required for <= IE7 (and possibly ancient Firefoxes) for inline-block to work.

SQL Insert Multiple Rows

You can use UNION All clause to perform multiple insert in a table.

ex:

INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'

Check here

Update my gradle dependencies in eclipse

I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:

eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"

Click on Browse button and provide path.

Even though question is answered, thought to share in case somebody else is facing similar issue.

Cheers !

Binding objects defined in code-behind

There's a much easier way of doing this. You can assign a Name to your Window or UserControl, and then binding by ElementName.

Window1.xaml

<Window x:Class="QuizBee.Host.Window1"
        x:Name="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>

Window1.xaml.cs

public partial class Window1:Window
{
    // the property must be public, and it must have a getter & setter
    public Dictionary<string, myClass> myDictionary { get; set; }

    public Window1()
    {
        // define the dictionary items in the constructor
        // do the defining BEFORE the InitializeComponent();

        myDictionary = new Dictionary<string, myClass>()
        {
            {"item 1", new myClass(1)},
            {"item 2", new myClass(2)},
            {"item 3", new myClass(3)},
            {"item 4", new myClass(4)},
            {"item 5", new myClass(5)},
        }; 

        InitializeComponent();
    }
}

How to scroll to specific item using jQuery?

You can use scrollIntoView() method in javascript. just give id.scrollIntoView();

For example

row_5.scrollIntoView();

What is a mutex?

In C#, the common mutex used is the Monitor. The type is 'System.Threading.Monitor'. It may also be used implicitly via the 'lock(Object)' statement. One example of its use is when constructing a Singleton class.

private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
    lock(instanceLock)
    {
        if(instance == null)
        {
            instance = new MySingleton();
        }
        return instance;
    }
}

The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.

Any sort of synchronization of a static member may use the lock statement similarly.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Rounding a double value to x number of decimal places in swift

Use the built in Foundation Darwin library

SWIFT 3

extension Double {
    func round(to places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }
}

Usage:

let number:Double = 12.987654321
print(number.round(to: 3)) 

Outputs: 12.988

PHP mail not working for some reason

The mail function do not guarantee the actual delivery of mail. All it do is to pass the message to external program (usually sendmail). You need a properly configured SMTP server in order for this to work. Also keep in mind it does not support SMTP authentication. You may check out the PEAR::Mail library of SwiftMailer, both of them give you more options.

How to pass macro definition from "make" command line arguments (-D) to C source code?

Find the C file and Makefile implementation in below to meet your requirements

foo.c

 main ()
    {
        int a = MAKE_DEFINE;
        printf ("MAKE_DEFINE value:%d\n", a);
    }

Makefile

all:
    gcc -DMAKE_DEFINE=11 foo.c

How to convert number of minutes to hh:mm format in TSQL?

You can convert the duration to a date and then format it:

DECLARE
    @FirstDate datetime,
    @LastDate datetime

SELECT
    @FirstDate = '2000-01-01 09:00:00',
    @LastDate = '2000-01-01 11:30:00'

SELECT CONVERT(varchar(12), 
       DATEADD(minute, DATEDIFF(minute, @FirstDate, @LastDate), 0), 114) 

/* Results: 02:30:00:000 */

For less precision, modify the size of the varchar:

SELECT CONVERT(varchar(5), 
       DATEADD(minute, DATEDIFF(minute, @FirstDate, @LastDate), 0), 114) 

/* Results: 02:30 */

How to generate gcc debug symbol outside the build target?

No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>.

  • This is provided by elfutils package.
  • The result will be that <input> file has been stripped of debug symbols which are now all in <out.debug>.

How to kill a child process after a given timeout in Bash?

One way is to run the program in a subshell, and communicate with the subshell through a named pipe with the read command. This way you can check the exit status of the process being run and communicate this back through the pipe.

Here's an example of timing out the yes command after 3 seconds. It gets the PID of the process using pgrep (possibly only works on Linux). There is also some problem with using a pipe in that a process opening a pipe for read will hang until it is also opened for write, and vice versa. So to prevent the read command hanging, I've "wedged" open the pipe for read with a background subshell. (Another way to prevent a freeze to open the pipe read-write, i.e. read -t 5 <>finished.pipe - however, that also may not work except with Linux.)

rm -f finished.pipe
mkfifo finished.pipe

{ yes >/dev/null; echo finished >finished.pipe ; } &
SUBSHELL=$!

# Get command PID
while : ; do
    PID=$( pgrep -P $SUBSHELL yes )
    test "$PID" = "" || break
    sleep 1
done

# Open pipe for writing
{ exec 4>finished.pipe ; while : ; do sleep 1000; done } &  

read -t 3 FINISHED <finished.pipe

if [ "$FINISHED" = finished ] ; then
  echo 'Subprocess finished'
else
  echo 'Subprocess timed out'
  kill $PID
fi

rm finished.pipe

How to calculate the SVG Path for an arc (of a circle)

you can use JSFiddle code i made for answer above:

https://jsfiddle.net/tyw6nfee/

all you need to do is change last line console.log code and give it your own parameter:

  console.log(describeArc(255,255,220,30,180));
  console.log(describeArc(CenterX,CenterY,Radius,startAngle,EndAngle))

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

Select fonts by specifying the weights you need on load

Font-families consist of several distinct fonts

For example, extra-bold will make the font look quite different in say, Photoshop, because you're selecting a different font. The same applies to italic font, which can look very different indeed. Setting font-weight:800 or font-style:italic may result in just a best effort of the web browser to fatten or slant the normal font in the family.

Even though you're loading a font-family, you must specify the weights and styles you need for some web browsers to let you select a different font in the family with font-weight and font-style.

Example

This example specifies the light, normal, normal italic, bold, and extra-bold fonts in the font family Open Sans:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <link rel="stylesheet"_x000D_
          href="https://fonts.googleapis.com/css?family=Open+Sans:100,400,400i,600,800">_x000D_
    <style>_x000D_
      body {_x000D_
        font-family: 'Open Sans', serif;_x000D_
        font-size: 48px;_x000D_
      }_x000D_
    </style>_x000D_
  </head>_x000D_
  <body>    _x000D_
    <div style="font-weight:400">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:600">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:800">Didn't work with all the fonts</div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference

(Quora warning, please remove if not allowed.)

https://www.quora.com/How-do-I-make-Open-Sans-extra-bold-once-imported-from-Google-Fonts

Testing

Tested working in Firefox 66.0.3 on Mac and Firefox 36.0.1 in Windows.

Non-Google fonts

Other fonts must be uploaded to the server, style and weight specified by their individual names.

System fonts

Assume nothing, font-wise, about what device is visiting your website or what fonts are installed on its OS.

(You may use the fall-backs of serif and sans-serif, but you will get the font mapped to these by the individual web browser version used, within the fonts available in the OS version it's running under, and not what you designed.)

Testing should be done with the font temporarily uninstalled from your system, to be sure that your design is in effect.

Uninstall Django completely

pip search command does not show installed packages, but search packages in pypi.

Use pip freeze command and grep to see installed packages:

pip freeze | grep Django

Cast a Double Variable to Decimal

You only use the M for a numeric literal, when you cast it's just:

decimal dtot = (decimal)doubleTotal;

Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.

ImportError: No module named 'pygame'

You don't need 64 bit Python on Win64 system, just install the 32bit versions of both Python and Pygame and they will work just fine (and there is a ton more modules for them anyways).

Replace spaces with dashes and make all letters lower-case

You can also use split and join:

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games

Setting dynamic scope variables in AngularJs - scope.<some_string>

Just to add into alread given answers, the following worked for me:

HTML:

<div id="div{{$index+1}}" data-ng-show="val{{$index}}">

Where $index is the loop index.

Javascript (where value is the passed parameter to the function and it will be the value of $index, current loop index):

var variable = "val"+value;
if ($scope[variable] === undefined)
{
    $scope[variable] = true;
}else {
    $scope[variable] = !$scope[variable];
}

tsql returning a table from a function or store procedure

Use this as a template

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Table_Function_Name, sysname, FunctionName> 
(
    -- Add the parameters for the function here
    <@param1, sysname, @p1> <data_type_for_param1, , int>, 
    <@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS 
<@Table_Variable_Name, sysname, @Table_Var> TABLE 
(
    -- Add the column definitions for the TABLE variable here
    <Column_1, sysname, c1> <Data_Type_For_Column1, , int>, 
    <Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
    -- Fill the table variable with the rows for your result set

    RETURN 
END
GO

That will define your function. Then you would just use it as any other table:

Select * from MyFunction(Param1, Param2, etc.)

How to write the Fibonacci Sequence?

The idea behind the Fibonacci sequence is shown in the following Python code:

def fib(n):
   if n == 1:
      return 1
   elif n == 0:   
      return 0            
   else:                      
      return fib(n-1) + fib(n-2)         

This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be:

fib(n-1) + fib(n-2)

Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic:

fib(2) = fib(1) + fib(0)
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(2) = 1 + 0
fib(2) = 1

We can calculate fib(3) the same way with the arithmetic shown below:

fib(3) = fib(2) + fib(1)
fib(2) = fib(1) + fib(0)
fib(2) = 1
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(3) = 1 + 1 + 0

The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming.

This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck!

Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield.

Simpler way to check if variable is not equal to multiple string values?

You need to multi value check. Try using the following code :

<?php
    $illstack=array(...............);
    $val=array('uk','bn','in');
    if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>

Show Hide div if, if statement is true

Use show/hide method as below

$("div").show();//To Show

$("div").hide();//To Hide

Unicode via CSS :before

In CSS, FontAwesome unicode works only when the correct font family is declared (version 4 or less):

font-family: "FontAwesome";
content: "\f066";

Update - Version 5 has different names:

Free

font-family: "Font Awesome 5 Free"

Pro

font-family: "Font Awesome 5 Pro"

Brands

font-family: "Font Awesome 5 Brands"

See this related answer: https://stackoverflow.com/a/48004111/2575724

As per comment (BuddyZ) some more info here https://fontawesome.com/how-to-use/on-the-desktop/setup/getting-started

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

You can use now() to set the value of a datetime column, but keep in mind that you can't use that as a default value.

How do I do top 1 in Oracle?

select * from (
    select FName from MyTbl
)
where rownum <= 1;

Comparing two collections for equality irrespective of the order of items in them

static bool SetsContainSameElements<T>(IEnumerable<T> set1, IEnumerable<T> set2) {
    var setXOR = new HashSet<T>(set1);
    setXOR.SymmetricExceptWith(set2);
    return (setXOR.Count == 0);
}

Solution requires .NET 3.5 and the System.Collections.Generic namespace. According to Microsoft, SymmetricExceptWith is an O(n + m) operation, with n representing the number of elements in the first set and m representing the number of elements in the second. You could always add an equality comparer to this function if necessary.

Get the Id of current table row with Jquery

$('#tblCart tr').click(function () {
        var tr_id = $(this).attr('id'); 
        alert(tr_id );
    });



<table class="table table-striped table-bordered table-hover" id="tblCart" cellspacing="0" align="center" >
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Item.ItemName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Price.PriceAmount)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Quantity)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Subtotal)
                    </th>
                    <th></th>
                </tr>

               @if (cart != null)
               {
                   foreach (var vm in cart)
                   {
                    <tr id="@vm.Id">
                        <td>
                            @Html.DisplayFor(modelItem => vm.Item.ItemName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => vm.Price.PriceAmount)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => vm.Quantity)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => vm.Subtotal)
                        </td>
                        <td >                            
                            <span style="width:80px; text-align:center;" class="glyphicon glyphicon-minus-sign" />                        
                        </td>
                    </tr>  
                   }
               }
            </table>

android: stretch image in imageview to fit screen

Trying using :

imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);

This will fit your imageview to the screen with the correct ratio.

Retrieving the COM class factory for component failed

I can understand your pain. In my case the error got resolved by performing below steps:

  1. Start > Run > dcomcnfg.
  2. Open the folder DCOM Config and Select Component Services > Computers > My Computer > DCOM Config.
  3. Select “Microsoft Office Word 97 – 2003 document”/”Microsoft Excel Application” and go to its properties.
  4. In "Security" tab set “Launch and Activation Permissions” need to be Customize (Authorized user).
  5. Now go to IIS and select application pool of the Web and go to its Advanced Settings and select “NETWORK SERVICE” as identity user.

Hope this helps.

SQLiteDatabase.query method

Where clause and args work together to form the WHERE statement of the SQL query. So say you looking to express

WHERE Column1 = 'value1' AND Column2 = 'value2'

Then your whereClause and whereArgs will be as follows

String whereClause = "Column1 =? AND Column2 =?";
String[] whereArgs = new String[]{"value1", "value2"};

If you want to select all table columns, i believe a null string passed to tableColumns will suffice.

Access-control-allow-origin with multiple domains

After reading every answer and trying them, none of them helped me. What I found while searching elsewhere is that you can create a custom attribute that you can then add to your controller. It overwrites the EnableCors ones and add the whitelisted domains in it.

This solution is working well because it lets you have the whitelisted domains in the webconfig (appsettings) instead of harcoding them in the EnableCors attribute on your controller.

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsByAppSettingAttribute : Attribute, ICorsPolicyProvider
{
    const string defaultKey = "whiteListDomainCors";
    private readonly string rawOrigins;
    private CorsPolicy corsPolicy;

    /// <summary>
    /// By default uses "cors:AllowedOrigins" AppSetting key
    /// </summary>
    public EnableCorsByAppSettingAttribute()
        : this(defaultKey) // Use default AppSetting key
    {
    }

    /// <summary>
    /// Enables Cross Origin
    /// </summary>
    /// <param name="appSettingKey">AppSetting key that defines valid origins</param>
    public EnableCorsByAppSettingAttribute(string appSettingKey)
    {
        // Collect comma separated origins
        this.rawOrigins = AppSettings.whiteListDomainCors;
        this.BuildCorsPolicy();
    }

    /// <summary>
    /// Build Cors policy
    /// </summary>
    private void BuildCorsPolicy()
    {
        bool allowAnyHeader = String.IsNullOrEmpty(this.Headers) || this.Headers == "*";
        bool allowAnyMethod = String.IsNullOrEmpty(this.Methods) || this.Methods == "*";

        this.corsPolicy = new CorsPolicy
        {
            AllowAnyHeader = allowAnyHeader,
            AllowAnyMethod = allowAnyMethod,
        };

        // Add origins from app setting value
        this.corsPolicy.Origins.AddCommaSeperatedValues(this.rawOrigins);
        this.corsPolicy.Headers.AddCommaSeperatedValues(this.Headers);
        this.corsPolicy.Methods.AddCommaSeperatedValues(this.Methods);
    }

    public string Headers { get; set; }
    public string Methods { get; set; }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request,
                                               CancellationToken cancellationToken)
    {
        return Task.FromResult(this.corsPolicy);
    }
}

    internal static class CollectionExtensions
{
    public static void AddCommaSeperatedValues(this ICollection<string> current, string raw)
    {
        if (current == null)
        {
            return;
        }

        var paths = new List<string>(AppSettings.whiteListDomainCors.Split(new char[] { ',' }));
        foreach (var value in paths)
        {
            current.Add(value);
        }
    }
}

I found this guide online and it worked like a charm :

http://jnye.co/Posts/2032/dynamic-cors-origins-from-appsettings-using-web-api-2-2-cross-origin-support

I thought i'd drop that here for anyone in need.

Force "git push" to overwrite remote files

Simple steps by using tortoisegit

GIT giving local files commit and pushing into git repository.

Steps :

1) stash changes stash name

2) pull

3) stash pop

4) commit 1 or more files and give commit changes description set author and Date

5) push

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

Extending from two classes

it is possible

public class ParallaxViewController<T extends View & Parallaxor> extends ParallaxController<T> implements AbsListView.OnScrollListener {

//blah
}

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

I got the same error using:

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">

But once I added https: in the beginning of the href the error disappeared.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">

Print DIV content by JQuery

I prefer this one, I have tested it and its working

https://github.com/jasonday/printThis

$("#mySelector").printThis();

or

$("#mySelector").printThis({
*      debug: false,              * show the iframe for debugging
*      importCSS: true,           * import page CSS
*      printContainer: true,      * grab outer container as well as the contents of the selector
*      loadCSS: "path/to/my.css", * path to additional css file
*      pageTitle: "",             * add title to print page
*      removeInline: false        * remove all inline styles from print elements
*  });

C# loop - break vs. continue

if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.

for(int i = 0; i < list.Count; i++){
   if(i == 5)
    i = list.Count;  //it will make "i<list.Count" false and loop will exit
}

Getting value from appsettings.json in .net core

Program and Startup class

.NET Core 2.x

You don't need to new IConfiguration in the Startup constructor. Its implementation will be injected by the DI system.

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();            
}

// Startup.cs
public class Startup
{
    public IHostingEnvironment HostingEnvironment { get; private set; }
    public IConfiguration Configuration { get; private set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        this.HostingEnvironment = env;
        this.Configuration = configuration;
    }
}

.NET Core 1.x

You need to tell Startup to load the appsettings files.

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
    }
}

//Startup.cs
public class Startup
{
    public IConfigurationRoot Configuration { get; private set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        this.Configuration = builder.Build();
    }
    ...
}

Getting Values

There are many ways you can get the value you configure from the app settings:

Let's say your appsettings.json looks like this:

{
    "ConnectionStrings": {
        ...
    },
    "AppIdentitySettings": {
        "User": {
            "RequireUniqueEmail": true
        },
        "Password": {
            "RequiredLength": 6,
            "RequireLowercase": true,
            "RequireUppercase": true,
            "RequireDigit": true,
            "RequireNonAlphanumeric": true
        },
        "Lockout": {
            "AllowedForNewUsers": true,
            "DefaultLockoutTimeSpanInMins": 30,
            "MaxFailedAccessAttempts": 5
        }
    },
    "Recaptcha": { 
        ...
    },
    ...
}

Simple Way

You can inject the whole configuration into the constructor of your controller/class (via IConfiguration) and get the value you want with a specified key:

public class AccountController : Controller
{
    private readonly IConfiguration _config;

    public AccountController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _config.GetValue<int>(
                "AppIdentitySettings:Password:RequiredLength"),
            RequireUppercase = _config.GetValue<bool>(
                "AppIdentitySettings:Password:RequireUppercase")
        };

        return View(vm);
    }
}

Options Pattern

The ConfigurationBuilder.GetValue<T> works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.

To use options pattern:

  1. Define classes to represent the structure
  2. Register the configuration instance which those classes bind against
  3. Inject IOptions<T> into the constructor of the controller/class you want to get values on

1. Define configuration classes to represent the structure

You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:

public class AppIdentitySettings
{
    public UserSettings User { get; set; }
    public PasswordSettings Password { get; set; }
    public LockoutSettings Lockout { get; set; }
}

public class UserSettings
{
    public bool RequireUniqueEmail { get; set; }
}

public class PasswordSettings
{
    public int RequiredLength { get; set; }
    public bool RequireLowercase { get; set; }
    public bool RequireUppercase { get; set; }
    public bool RequireDigit { get; set; }
    public bool RequireNonAlphanumeric { get; set; }
}

public class LockoutSettings
{
    public bool AllowedForNewUsers { get; set; }
    public int DefaultLockoutTimeSpanInMins { get; set; }
    public int MaxFailedAccessAttempts { get; set; }
}

2. Register the configuration instance

And then you need to register this configuration instance in ConfigureServices() in the start up:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
...

namespace DL.SO.UI.Web
{
    public class Startup
    {
        ...
        public void ConfigureServices(IServiceCollection services)
        {
            ...
            var identitySettingsSection = 
                _configuration.GetSection("AppIdentitySettings");
            services.Configure<AppIdentitySettings>(identitySettingsSection);
            ...
        }
        ...
    }
}

3. Inject IOptions

Lastly on the controller/class you want to get the values, you need to inject IOptions<AppIdentitySettings> through constructor:

public class AccountController : Controller
{
    private readonly AppIdentitySettings _appIdentitySettings;

    public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
    {
        _appIdentitySettings = appIdentitySettingsAccessor.Value;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
            RequireUppercase = _appIdentitySettings.Password.RequireUppercase
        };

        return View(vm);
    }
}

Get Windows version in a batch file

Just starting a new cmd-level from the command line gives you directly the version!

C:> cmd

Microsoft Windows [Version 10.0.17130.1233]

(c) 2018 Microsoft Corporation. All rights reserved.

Access to ES6 array element index inside for-of loop

You can also handle index yourself if You need the index, it will not work if You need the key.

let i = 0;
for (const item of iterableItems) {
  // do something with index
  console.log(i);

  i++;
}

How do I change the IntelliJ IDEA default JDK?

This setting is changed in the "Default Project Structure..." dialog. Navigate to "File" -> "Other Settings" -> "Default Project Structure...".

Select Default Project Structure

Next, modify the "Project language level" setting to your desired language level.

Setting the project language level

IntelliJ IDEA 12 had this setting in "Template Project Structure..." instead of "Default Project Structure..."

can you add HTTPS functionality to a python flask web server?

If this webserver is only for testing and demoing purposes. You can use ngrok, a open source too that tunnels your http traffic.

Bascially ngrok creates a public URL (both http and https) and then tunnels the traffic to whatever port your Flask process is running on.

https://ngrok.com/product

It only takes a couple minutes to set up. You first have to download the software. Then run the command
./ngrok http [port number your python process is running on]

It will then open up a window in terminal giving you both an http and https url to access your web app.

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

Recreate the default website in IIS

I deleted the C:\inetpub folder and reinstalled IIS which recreated the default website and settings.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How do I programmatically determine operating system in Java?

You can just use sun.awt.OSInfo#getOSType() method

Default values in a C Struct

While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:

const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
    dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);

This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.

Convert Json string to Json object in Swift 4

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

Append column to pandas dataframe

You can also use:

dat1 = pd.concat([dat1, dat2], axis=1)

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

Re-ordering columns in pandas dataframe based on column name

The quickest method is:

df.sort_index(axis=1)

Be aware that this creates a new instance. Therefore you need to store the result in a new variable:

sortedDf=df.sort_index(axis=1)

Excel CSV. file with more than 1,048,576 rows of data

The best way to handle this (with ease and no additional software) is with Excel - but using Powerpivot (which has MSFT Power Query embedded). Simply create a new Power Pivot data model that attaches to your large csv or text file. You will then be able to import multi-million rows into memory using the embedded X-Velocity (in-memory compression) engine. The Excel sheet limit is not applicable - as the X-Velocity engine puts everything up in RAM in compressed form. I have loaded 15 million rows and filtered at will using this technique. Hope this helps someone... - Jaycee

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How do I use PHP namespaces with autoload?

As mentioned Pascal MARTIN, you should replace the '\' with DIRECTORY_SEPARATOR for example:

$filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
include($filename);

Also I would suggest you to reorganize the dirrectory structure, to make the code more readable. This could be an alternative:

Directory structure:

ProjectRoot
 |- lib

File: /ProjectRoot/lib/Person/Barnes/David/Class1.php

<?php
namespace Person\Barnes\David
class Class1
{
    public function __construct()
    {
        echo __CLASS__;
    }
}
?>
  • Make the sub directory for each namespace you are defined.

File: /ProjectRoot/test.php

define('BASE_PATH', realpath(dirname(__FILE__)));
function my_autoloader($class)
{
    $filename = BASE_PATH . '/lib/' . str_replace('\\', '/', $class) . '.php';
    include($filename);
}
spl_autoload_register('my_autoloader');

use Person\Barnes\David as MyPerson;
$class = new MyPerson\Class1();
  • I used php 5 recomendation for autoloader declaration. If you are still with PHP 4, replace it with the old syntax: function __autoload($class)

Add column with constant value to pandas dataframe

Super simple in-place assignment: df['new'] = 0

For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

Note for object columns

If you want to add an column of empty lists, here is my advice:

  • Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured.
  • Consider storing your data in a sparse data structure. More information: sparse data structures
  • If you must store a column of lists, ensure not to copy the same reference multiple times.

    # Wrong
    df['new'] = [[]] * len(df)
    # Right
    df['new'] = [[] for _ in range(len(df))]
    

Generating a copy: df.assign(new=0)

If you need a copy instead, use DataFrame.assign:

df.assign(new='y')

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple column assignment

Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

How do I import other TypeScript files?

I would avoid now using /// <reference path='moo.ts'/>but for external libraries where the definition file is not included into the package.

The reference path solves errors in the editor, but it does not really means the file needs to be imported. Therefore if you are using a gulp workflow or JSPM, those might try to compile separately each file instead of tsc -out to one file.

From Typescript 1.5

Just prefix what you want to export at the file level (root scope)

aLib.ts

{
export class AClass(){} // exported i.e. will be available for import
export valueZero = 0; // will be available for import
}

You can also add later in the end of the file what you want to export

{
class AClass(){} // not exported yet
valueZero = 0; // not exported yet
valueOne = 1; // not exported (and will not in this example)

export {AClass, valueZero} // pick the one you want to export
}

Or even mix both together

{
class AClass(){} // not exported yet
export valueZero = 0; // will be available for import
export {AClass} // add AClass to the export list
}

For the import you have 2 options, first you pick again what you want (one by one)

anotherFile.ts

{
import {AClass} from "./aLib.ts"; // you import only AClass
var test = new AClass();
}

Or the whole exports

{
import * as lib from "./aLib.ts"; // you import all the exported values within a "lib" object
var test = new lib.AClass();
}

Note regarding the exports: exporting twice the same value will raise an error { export valueZero = 0; export {valueZero}; // valueZero is already exported… }

Remove multiple items from a Python list in just one statement

You can do it in one line by converting your lists to sets and using set.difference:

item_list = ['item', 5, 'foo', 3.14, True]
list_to_remove = ['item', 5, 'foo']

final_list = list(set(item_list) - set(list_to_remove))

Would give you the following output:

final_list = [3.14, True]

Note: this will remove duplicates in your input list and the elements in the output can be in any order (because sets don't preserve order). It also requires all elements in both of your lists to be hashable.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

The new URL for the repository is now http://download.eclipse.org/tools/pdt/updates/release. In Eclipse: open Help -> install new sofware -> add. Then paste this URL in the location.

Mark the check boxes you want and click next.

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

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

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

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

overflow: auto;
overflow-y: hidden;

You may also need to add for IE8:

-ms-overflow-y: hidden;

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

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

How Stuff and 'For Xml Path' work in SQL Server?

SELECT ID, 
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               ) 
FROM temp1 GROUP BY id

Here in the above query STUFF function is used to just remove the first comma (,) from the generated xml string (,aaa,bbb,ccc,ddd,eee) then it will become (aaa,bbb,ccc,ddd,eee).

And FOR XML PATH('') simply converts column data into (,aaa,bbb,ccc,ddd,eee) string but in PATH we are passing '' so it will not create a XML tag.

And at the end we have grouped records using ID column.

When should I use Async Controllers in ASP.NET MVC?

is it good to use async action everywhere in ASP.NET MVC?

As usual in programming, it depends. There is always a trade-off when going down a certain path.

async-await shines in places where you know you'll receiving concurrent requests to your service and you want to be able to scale out well. How does async-await help with scaling out? In the fact that when you invoke a async IO call synchronously, such as a network call or hitting your database, the current thread which is responsible for the execution is blocked waiting for the request to finish. When you use async-await, you enable the framework to create a state machine for you which makes sure that after the IO call is complete, your method continues executing from where it left off.

A thing to note is that this state machine has a subtle overhead. Making a method asynchronous does not make it execute faster, and that is an important factor to understand and a misconception many people have.

Another thing to take under consideration when using async-await is the fact that it is async all the way, meaning that you'll see async penetrate your entire call stack, top to buttom. This means that if you want to expose synchronous API's, you'll often find yourself duplicating a certain amount of code, as async and sync don't mix very well.

Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?

If you choose to go down the path of using async IO calls, then yes, async-await will be a good choice, as more and more modern database providers expose async method implementing the TAP (Task Asynchronous Pattern).

How many times I can use await keywords to query database asynchronously in ONE single action method?

As many as you want, as long as you follow the rules stated by your database provider. There is no limit to the amount of async calls you can make. If you have queries which are independent of each other and can be made concurrently, you can spin a new task for each and use await Task.WhenAll to wait for both to complete.

Dark color scheme for Eclipse

This is the best place for Eclipse color themes:

http://www.eclipsecolorthemes.org/

Determine the line of code that causes a segmentation fault?

Lucas's answer about core dumps is good. In my .cshrc I have:

alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'

to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.

Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.

How to read until EOF from cin in C++

Wait, am I understanding you correctly? You're using cin for keyboard input, and you want to stop reading input when the user enters the EOF character? Why would the user ever type in the EOF character? Or did you mean you want to stop reading from a file at the EOF?

If you're actually trying to use cin to read an EOF character, then why not just specify the EOF as the delimiter?

// Needed headers: iostream

char buffer[256];
cin.get( buffer, '\x1A' );

If you mean to stop reading from a file at the EOF, then just use getline and once again specify the EOF as the delimiter.

// Needed headers: iostream, string, and fstream

string buffer;

    ifstream fin;
    fin.open("test.txt");
    if(fin.is_open()) {
        getline(fin,buffer,'\x1A');

        fin.close();
    }

`export const` vs. `export default` in ES6

From the documentation:

Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.

Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.

What is the proper way to check if a string is empty in Perl?

The very concept of a "proper" way to do anything, apart from using CPAN, is non existent in Perl.

Anyways those are numeric operators, you should use

if($foo eq "")

or

if(length($foo) == 0)

href="tel:" and mobile numbers

As an additional note, you may also add markup language for pausing or waiting, I learned this from the iPhone iOS which allows numbers to be stored with extension numbers in the same line. A semi-colon establishes a wait, which will show as a next step upon calling the number. This helps to simplify the workflow of calling numbers with extensions in their board. You press the button shown on the bottom left of the iPhone screen when prompted, and the iPhone will dial it automatically.

<a href="tel:+50225079227;1">Call Now</a>

The pause is entered with a comma ",", allowing a short pause of time for each comma. Once the time has passed, the number after the comma will be dialed automatically

<a href="tel:+50225079227,1">Call Now, you will be automaticlaly transferred</a>

Unzip files programmatically in .net

Standard zip files normally use the deflate algorithm.

To extract files without using third party libraries use DeflateStream. You'll need a bit more information about the zip file archive format as Microsoft only provides the compression algorithm.

You may also try using zipfldr.dll. It is Microsoft's compression library (compressed folders from the Send to menu). It appears to be a com library but it's undocumented. You may be able to get it working for you through experimentation.

Get an array of list element contents in jQuery

var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})

Add a properties file to IntelliJ's classpath

For those of you who migrate from Eclipse to IntelliJ or the other way around here is a tip when working with property files or other resource files.

Its maddening (cost my a whole evening to find out) but both IDE's work quite different when it comes to looking for resource/propertty files when you want to run locally from your IDE or during debugging. (Packaging to a .jar is also quite different, but thats documented better.)

Suppose you have a relative path referral like this in your code:

new FileInputStream("xxxx.properties");

(which is convenient if you work with env specific .properties files which you don't want to package along with your JAR)

INTELLIJ

(I use 13.1 , but could be valid for more versions)

The file xxxx.properties needs to be at the PARENT dir of the project ROOT in order to be picked up at runtime like this in IntelliJ. (The project ROOT is where the /src folder resides in)

ECLIPSE

Eclipse is just happy when the xxxx.properties file is at the project ROOT itself.

So IntelliJ expects .properties file to be 1 level higher then Eclipse when it is referenced like this !!

This also affects the way you have to execute your code when you have this same line of code ( new FileInputStream("xxxx.properties"); ) in your exported .jar. When you want to be agile and don't want to package the .properties file with your jar you'll have to execute the jar like below in order to reference the .properties file correctly from the command line:

INTELLIJ EXPORTED JAR

java -cp "/path/to_properties_file/:/path/to_jar/some.jar" com.bla.blabla.ClassContainingMainMethod

ECLIPSE EXPORTED JAR

java -jar some.jar

where the Eclipse exported executable jar will just expect the referenced .properties file to be on the same location as where the .jar file is

open a url on click of ok button in android

String url = "https://www.murait.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}else{
    Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}

You have to check that the URL is valid or not. If URL is invalid application may crash so that you have to check URL is valid or not by this method.

How to blur background images in Android

you can use Glide for load and transform into blur image, 1) for only one view,

val requestOptions = RequestOptions()
                requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
                        .load(imageUrl).into(view)

2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.

 if(isBlure){
  val requestOptions = RequestOptions()
                requestOptions.transform(BlurTransformation(50))
                Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
                        .load(imageUrl).into(view )
}else{
 val requestOptions = RequestOptions()
            Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

preventDefault() on an <a> tag

You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.

Returning the event when it's called:

<a href="" onclick="return false;"> ... </a>

Void case:

<a href="javascript:void(0);"> ... </a>

You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

How to set a value of a variable inside a template code?

This is not a good idea in general. Do all the logic in python and pass the data to template for displaying. Template should be as simple as possible to ensure those working on the design can focus on design rather than worry about the logic.

To give an example, if you need some derived information within a template, it is better to get it into a variable in the python code and then pass it along to the template.

How do I plot list of tuples in Python?

You could also use zip

import matplotlib.pyplot as plt

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x, y = zip(*l)

plt.plot(x, y)

How can I fill out a Python string with spaces?

As of Python 3.6 you can just do

>>> strng = 'hi'
>>> f'{strng: <10}'

with literal string interpolation.

Or, if your padding size is in a variable, like this (thanks @Matt M.!):

>>> to_pad = 10
>>> f'{strng: <{to_pad}}'

How to replace a string in multiple files in linux command line

I found this one from another post (can't remember which) and while not the most elegant, it's simple and as a novice Linux user has given me no trouble

for i in *old_str* ; do mv -v "$i" "${i/\old_str/new_str}" ; done

if you have spaces or other special characters use a \

for i in *old_str\ * ; do mv -v "$i" "${i/\old_str\ /new_str}" ; done

for strings in sub-directories use **

for i in *\*old_str\ * ; do mv -v "$i" "${i/\old_str\ /new_str}" ; done

JavaScript: How to find out if the user browser is Chrome?

If you want to detect Chrome's rendering engine (so not specific features in Google Chrome or Chromium), a simple option is:

var isChrome = !!window.chrome;

NOTE: this also returns true for many versions of Edge, Opera, etc that are based on Chrome (thanks @Carrm for pointing this out). Avoiding that is an ongoing battle (see window.opr below) so you should ask yourself if you're trying to detect the rendering engine (used by almost all major modern browsers in 2020) or some other Chrome (or Chromium?) -specific feature.

And you can probably skip !!

How to start new activity on button click

// In Kotlin , you can do as /* In First Activity, let in activity layout there is button which has id as button. Suppose I have to pass data as String type from one activity to another */

     val btn = findViewById<Button>(R.id.button)
     btn.setOnClickListener {
        val intent = Intent(baseContext, SecondActivity::class.java).apply {
             putExtra("KEY", data)
        }
        startActivity(intent)
     }

// In Second Activity, you can get data from another activity as

 val name = intent.getStringExtra("KEY")

/* Suppose you have to pass a Custom Object then it should be Parcelable. let there is class Collage type which I have to pass from one activity to another */

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
class Collage(val name: String, val mobile: String, val email: String) : Parcelable

/* Activity First , let here data is Collage type. which I have to pass to another activity. */

val btn = findViewById<Button>(R.id.button)
         btn.setOnClickListener {
            val intent = Intent(baseContext, SecondActivity::class.java).apply {
                 putExtra("KEY", data)
            }
            startActivity(intent)
         }

// then from second Activity we will get as

val item = intent.extras?.getParcelable<Collage>("KEY")

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

Add User to Role ASP.NET Identity

While I agree with the other answers regarding the RoleManager, I would advice to examine the possibility to implement Authorization through Claims (Expressing Roles as Claims).

Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.

In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When the IsInRole() method is called, there is a check made to see if the current user has that role.

The role claim type is expressed using the following URI: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"

So instead of using the RoleManager, you can "add a user to a role" from the UserManager, doing something like this:

var um = new UserManager();
um.AddClaimAsync(1, new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "administrator"));

With the above lines you have added a role claim with the value "administrator" to the user with the id "1"...

Claims authorization, as suggested by MSFT, can simplify and increase the performance of authentication and authorization processes eliminating some back-end queries every time authorization takes place.

Using Claims you may not need the RoleStore anymore. (AspNetRoles, AspNetUserRoles)

Div vertical scrollbar show

What browser are you testing in?

What DOCType have you set?

How exactly are you declaring your CSS?

Are you sure you haven't missed a ; before/after the overflow-y: scroll?

I've just tested the following in IE7 and Firefox and it works fine

_x000D_
_x000D_
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents -->        _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

React - clearing an input value after form submit

The answers above are incorrect, they will all run weather or not the submission is successful... You need to write an error component that will receive any errors then check if there are errors in state, if there are not then clear the form....

use .then()

example:

 const onSubmit =  e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
  setTicketData({
    ticketType: "IT",
    ticketSubject: "",
    ticketDescription: "",
    itHelpType: "",
    ticketPriority: ""
  })
})  

};

Apache - MySQL Service detected with wrong path. / Ports already in use

In my case this issue caused because my local machine used to the one MySQL service installed earlier at 3006 port. Thus I modified both my.ini (C:\xampp\mysql\bin\my.ini) and php.ini (C:\xampp\php\php.ini) files replaced port 3006 to 3008

After that I've created a new service running the command described above by Tommer:

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

How to get the current time in Python

import datetime
date_time = datetime.datetime.now()

date = date_time.date()  # Gives the date
time = date_time.time()  # Gives the time

print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond

Do dir(date) or any variables including the package. You can get all the attributes and methods associated with the variable.

When to use the different log levels

Would you want the message to get a system administrator out of bed in the middle of the night?

  • yes -> error
  • no -> warn

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

pythonic way to do something N times without an index variable?

since function is first-class citizen, you can write small wrapper (from Alex answers)

def repeat(f, N):
    for _ in itertools.repeat(None, N): f()

then you can pass function as argument.

Calling Scalar-valued Functions in SQL

Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

Check if a variable is a string in JavaScript

I can't honestly see why one would not simply use typeof in this case:

if (typeof str === 'string') {
  return 42;
}

Yes it will fail against object-wrapped strings (e.g. new String('foo')) but these are widely regarded as a bad practice and most modern development tools are likely to discourage their use. (If you see one, just fix it!)

The Object.prototype.toString trick is something that all front-end developers have been found guilty of doing one day in their careers but don't let it fool you by its polish of clever: it will break as soon as something monkey-patch the Object prototype:

_x000D_
_x000D_
const isString = thing => Object.prototype.toString.call(thing) === '[object String]';_x000D_
_x000D_
console.log(isString('foo'));_x000D_
_x000D_
Object.prototype.toString = () => 42;_x000D_
_x000D_
console.log(isString('foo'));
_x000D_
_x000D_
_x000D_

How do you get the index of the current iteration of a foreach loop?

Finally C#7 has a decent syntax for getting an index inside of a foreach loop (i. e. tuples):

foreach (var (item, index) in collection.WithIndex())
{
    Debug.WriteLine($"{index}: {item}");
}

A little extension method would be needed:

public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)       
   => self.Select((item, index) => (item, index)); 

WP -- Get posts by category?

'category_name'=>'this cat' also works but isn't printed in the WP docs

How to get base url with jquery or javascript?

I am surprised that non of the answers consider the base url if it was set in <base> tag. All current answers try to get the host name or server name or first part of address. This is the complete logic which also considers the <base> tag (which may refer to another domain or protocol):

function getBaseURL(){
  var elem=document.getElementsByTagName("base")[0];
  if (typeof(elem) != 'undefined' && elem != null){
     return elem.href;
  }
  return window.location.origin;
}

Jquery format:

function getBaseURL(){
  if ($("base").length){
     return $("base").attr("href");
  }
  return window.location.origin;
}

Without getting involved with the logic above, the shorthand solution which considers both <base> tag and window.location.origin:

Js:

var a=document.createElement("a");
a.href=".";
var baseURL= a.href;

Jquery:

var baseURL= $('<a href=".">')[0].href

Final note: for a local file in your computer (not on a host) the window.location.origin only returns the file:// but the sorthand solution above returns the complete correct path.

MySQL Results as comma separated list

Instead of using group concat() you can use just concat()

Select concat(Col1, ',', Col2) as Foo_Bar from Table1;

edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.

How to make primary key as autoincrement for Room Persistence lib

For example, if you have a users entity you want to store, with fields (firstname, lastname , email) and you want autogenerated id, you do this.

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

Room will then autogenerate and auto-increment the id field.

location.host vs location.hostname and cross-browser compatibility?

interactive link anatomy

As a little memo: the interactive link anatomy

--

In short (assuming a location of http://example.org:8888/foo/bar#bang):

  • hostname gives you example.org
  • host gives you example.org:8888

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

ReactNative: how to center text?

Set in Parent view

justifyContent:center

and in child view alignSelf:center

How do I tell Gradle to use specific JDK version?

As seen in Gradle (Eclipse plugin)

http://www.gradle.org/get-started

Gradle uses whichever JDK it finds in your path (to check, use java -version). Alternatively, you can set the JAVA_HOME environment variable to point to the install directory of the desired JDK.


If you are using this Eclipse plugin or Enide Studio 2014, alternative JAVA_HOME to use (set in Preferences) will be in version 0.15, see http://www.nodeclipse.org/history

How to get the number of characters in a std::string?

Simplest way to get length of string without bothering about std namespace is as follows

string with/without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    getline(cin,str);
    cout<<"Length of given string is"<<str.length();
    return 0;
}

string without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<"Length of given string is"<<str.length();
    return 0;
}

How to backup MySQL database in PHP?

While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.

I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.

The basic usage of mysqldump is

mysqldump -u user_name -p name-of-database >file_to_write_to.sql

You can then restore the backup with a command like

mysql -u user_name -p <file_to_read_from.sql

Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like

<?php

$filename='database_backup_'.date('G_a_m_d_y').'.sql';

$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);

if(empty($output)){/* no output is good */}
else {/* we have something to log the output here*/}

If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.

It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.

You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.

Remove all non-"word characters" from a String in Java, leaving accented characters?

I was trying to achieve the exact opposite when I bumped on this thread. I know it's quite old, but here's my solution nonetheless. You can use blocks, see here. In this case, compile the following code (with the right imports):

> String s = "äêìóblah"; 
> Pattern p = Pattern.compile("[\\p{InLatin-1Supplement}]+"); // this regex uses a block
> Matcher m = p.matcher(s);
> System.out.println(m.find());
> System.out.println(s.replaceAll(p.pattern(), "#"));

You should see the following output:

true

#blah

Best,

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

File changed listener in Java

Similar to the other answers, here's how I did it using File, Timer, and TimerTask to let this run as a background thread polling at set intervals.

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class FileModifiedWatcher
{
  private static File file;
  private static int pollingInterval;
  private static Timer fileWatcher;
  private static long lastReadTimeStamp = 0L;

  public static boolean init(String _file, int _pollingInterval)
  {
    file =  new File(_file);
    pollingInterval = _pollingInterval; // In seconds

    watchFile();

    return true;
  }

  private static void watchFile()
  {
    if ( null == fileWatcher )
    {
      System.out.println("START");

      fileWatcher = new Timer();

      fileWatcher.scheduleAtFixedRate(new TimerTask()
      {
        @Override
        public void run()
        {

          if ( file.lastModified() > lastReadTimeStamp )
          {
            System.out.println("File Modified");
          }

          lastReadTimeStamp = System.currentTimeMillis();
        }
      }, 0, 1000 * pollingInterval);
    }

  }
}

How should I do integer division in Perl?

int(x+.5) will round positive values toward the nearest integer. Rounding up is harder.

To round toward zero:

int($x)

For the solutions below, include the following statement:

use POSIX;

To round down: POSIX::floor($x)

To round up: POSIX::ceil($x)

To round away from zero: POSIX::floor($x) - int($x) + POSIX::ceil($x)

To round off to the nearest integer: POSIX::floor($x+.5)

Note that int($x+.5) fails badly for negative values. int(-2.1+.5) is int(-1.6), which is -1.

calling javascript function on OnClientClick event of a Submit button

The above solutions must work. However you can try this one:

OnClientClick="return SomeMethod();return false;"

and remove return statement from the method.

how to console.log result of this ajax call?

try something like this :

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function (textStatus, status) {
        console.log(textStatus);
        console.log(status);
    },
    error: function(xhr, textStatus, error) {
        console.log(xhr.responseText);
        console.log(xhr.statusText);
        console.log(textStatus);
        console.log(error);
    }
});

How can I compare time in SQL Server?

Use Datepart function: DATEPART(datepart, date)

E.g#

SELECT DatePart(@YourVar, hh)*60) + DatePart(@YourVar, mi)*60)

This will give you total time of day in minutes allowing you to compare more easily.

You can use DateDiff if your dates are going to be the same, otherwise you'll need to strip out the date as above

Using BeautifulSoup to search HTML for string

The following line is looking for the exact NavigableString 'Python':

>>> soup.body.findAll(text='Python')
[]

Note that the following NavigableString is found:

>>> soup.body.findAll(text='Python Jobs') 
[u'Python Jobs']

Note this behaviour:

>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]

So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

HashMap and int as key

If you are using Netty and want to use a map with primitive int type keys, you can use its IntObjectHashMap

Some of the reasons to use primitive type collections:

  • improve performance by having specialized code
  • reduce garbage that can put pressure on the GC

The question of specialized vs generalized collections can make or break programs with high throughput requirements.

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

Finding Android SDK on Mac and adding to PATH

If Android Studio shows you the path /Users/<name>/Library/Android/sdk but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.

Add to integers in a list

fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]

Variables within app.config/web.config

For rolling out products where we need to configure a lot of items with similar values, we use small console apps that read the XML and update based on the parameters passed in. These are then called by the installer after it has asked the user for the required information.

Why is `input` in Python 3 throwing NameError: name... is not defined

I'd say the code you need is:

test = input("enter the test")
print(test)

Otherwise it shouldn't run at all, due to a syntax error. The print function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?

Simplest way to serve static data from outside the application server in a Java web application

Add to server.xml :

 <Context docBase="c:/dirtoshare" path="/dir" />

Enable dir file listing parameter in web.xml :

    <init-param>
        <param-name>listings</param-name>
        <param-value>true</param-value>
    </init-param>

Timer for Python game

  1. Asks you when to stop [seconds]
  2. Adds '0' at starting [1-9]
import time
import sys

stop = int(input('> '))
second = 0
print('> Stopwatch Started.')

while stop > second:
    if second < 9:
        second = second + 1
        time.sleep(1)
        sys.stdout.write('\r> ' + '0' + str(second))
    else:
        second += 1
        time.sleep(1)
        sys.stdout.write('\r' + '> ' + str(second))

print('\n> Stopwatch Stopped.')

libz.so.1: cannot open shared object file

Check below link: Specially "Install 32 bit libraries (if you're on 64 bit)"

 https://github.com/meteor/meteor/wiki/Mobile-Dev-Install:-Android-on-Linux

Java Spring - How to use classpath to specify a file location?

Are we talking about standard java.io.FileReader? Won't work, but it's not hard without it.

/src/main/resources maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:

InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");

If the result is not null (resource not found), feel free to wrap it in a reader:

Reader reader = new InputStreamReader(is);

What is fastest children() or find() in jQuery?

None of the other answers dealt with the case of using .children() or .find(">") to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.

As it happens, even when using the extra ">" selector, .find() is still a lot faster than .children(); on my system, 10x so.

So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children() at all.

How to stop (and restart) the Rails Server?

Press Ctrl+C

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

How to print star pattern in JavaScript in a very simple manner?

This below code worked for me

for(i= 0; i< n; i++){

   col = i;
   for(j = 0; j< n- col;j++){
       process.stdout.write('');
   }
   for (j = 1;j< col+2;j ++){
       process.stdout.write('#');
   }
   process.stdout.write('\n');
}

What's the difference between TRUNCATE and DELETE in SQL

DELETE

DELETE is a DML command
DELETE you can rollback
Delete = Only Delete- so it can be rolled back
In DELETE you can write conditions using WHERE clause
Syntax – Delete from [Table] where [Condition]

TRUNCATE

TRUNCATE is a DDL command
You can't rollback in TRUNCATE, TRUNCATE removes the record permanently
Truncate = Delete+Commit -so we can't roll back
You can't use conditions(WHERE clause) in TRUNCATE
Syntax – Truncate table [Table]

For more details visit

http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

Android - default value in editText

You can do it in this way

private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "[email protected]";

and inside onCreate method

nameEdit = (EditText) findViewById(R.id.name);
    nameEdit.setText(nameDefaultValue); 
    nameEdit.setOnTouchListener( new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (nameEdit.getText().toString().equals(nameDefaultValue)){
                nameEdit.setText("");
            }
            return false;
        }
    });

    nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {               
            if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
                nameEdit.setText(nameDefaultValue);
            } else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
                nameEdit.setText("");
            }
        }
    });     

    emailEdit = (EditText)findViewById(R.id.email);
    emailEdit.setText(emailDefaultValue);   
    emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {               
            if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
                emailEdit.setText(emailDefaultValue);
            } else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
                emailEdit.setText("");
            }
        }
    });

How can I determine browser window size on server side C#

So here is how you will do it.

Write a javascript function which fires whenever the window is resized.

window.onresize = function(event) {
    var height=$(window).height();
    var width=$(window).width();
    $.ajax({
     url: "/getwindowsize.ashx",
     type: "POST",
     data : { Height: height, 
              Width:width, 
              selectedValue:selectedValue },
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (response) { 
           // do stuff
     }

}

Codebehind of Handler:

 public class getwindowsize : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
     string Height = context.Request.QueryString["Height"]; 
     string Width = context.Request.QueryString["Width"]; 
    }

How to run two jQuery animations simultaneously?

See this brilliant blog post about animating values in objects.. you can then use the values to animate whatever you like, 100% simultaneously!

http://www.josscrowcroft.com/2011/code/jquery-animate-increment-decrement-numeric-text-elements-value/

I've used it like this to slide in/out:

        slide : function(id, prop, from, to) {
            if (from < to) {
                // Sliding out
                var fromvals = { add: from, subtract: 0 };
                var tovals = { add: to, subtract: 0 };
            } else {
                // Sliding back in
                var fromvals = { add: from, subtract: to };
                var tovals = { add: from, subtract: from };
            }

            $(fromvals).animate(tovals, {
                duration: 200,
                easing: 'swing', // can be anything
                step: function () { // called on every step
                    // Slide using the entire -ms-grid-columns setting
                    $(id).css(prop, (this.add - this.subtract) + 'px 1.5fr 0.3fr 8fr 3fr 5fr 0.5fr');
                }
            });
        }

What uses are there for "placement new"?

We use it with custom memory pools. Just a sketch:

class Pool {
public:
    Pool() { /* implementation details irrelevant */ };
    virtual ~Pool() { /* ditto */ };

    virtual void *allocate(size_t);
    virtual void deallocate(void *);

    static Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ }
};

class ClusterPool : public Pool { /* ... */ };
class FastPool : public Pool { /* ... */ };
class MapPool : public Pool { /* ... */ };
class MiscPool : public Pool { /* ... */ };

// elsewhere...

void *pnew_new(size_t size)
{
   return Pool::misc_pool()->allocate(size);
}

void *pnew_new(size_t size, Pool *pool_p)
{
   if (!pool_p) {
      return Pool::misc_pool()->allocate(size);
   }
   else {
      return pool_p->allocate(size);
   }
}

void pnew_delete(void *p)
{
   Pool *hp = Pool::find_pool(p);
   // note: if p == 0, then Pool::find_pool(p) will return 0.
   if (hp) {
      hp->deallocate(p);
   }
}

// elsewhere...

class Obj {
public:
   // misc ctors, dtors, etc.

   // just a sampling of new/del operators
   void *operator new(size_t s)             { return pnew_new(s); }
   void *operator new(size_t s, Pool *hp)   { return pnew_new(s, hp); }
   void operator delete(void *dp)           { pnew_delete(dp); }
   void operator delete(void *dp, Pool*)    { pnew_delete(dp); }

   void *operator new[](size_t s)           { return pnew_new(s); }
   void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); }
   void operator delete[](void *dp)         { pnew_delete(dp); }
   void operator delete[](void *dp, Pool*)  { pnew_delete(dp); }
};

// elsewhere...

ClusterPool *cp = new ClusterPool(arg1, arg2, ...);

Obj *new_obj = new (cp) Obj(arg_a, arg_b, ...);

Now you can cluster objects together in a single memory arena, select an allocator which is very fast but does no deallocation, use memory mapping, and any other semantic you wish to impose by choosing the pool and passing it as an argument to an object's placement new operator.

Vertically aligning text next to a radio button

You could also try something like this:

_x000D_
_x000D_
input[type="radio"] {_x000D_
  margin-top: -1px;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
  <label  class="child"><input id = "warm" type="radio" name="weathertype" value="warm" checked> Warm<br></label>_x000D_
<label class="child1"><input id = "cold" type="radio" name="weathertype" value="cold" checked> Cold<br></label>
_x000D_
_x000D_
_x000D_

YouTube Autoplay not working

Remove the spaces before the autoplay=1:

src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"

jQuery ajax post file field

I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)

function verify1() {
    jQuery.ajax({
        type: 'POST',
        url:"functions.php",
        data: new FormData($("#infoForm1")[0]),
        processData: false, 
        contentType: false, 
        success: function(returnval) {
             $("#show1").html(returnval);
             $('#show1').show();
         }
    });
}

Just print the file details and check. You will get Output. If error let me know.

Plotting a 2D heatmap with Matplotlib

For a 2d numpy array, simply use imshow() may help you:

import matplotlib.pyplot as plt
import numpy as np


def heatmap2d(arr: np.ndarray):
    plt.imshow(arr, cmap='viridis')
    plt.colorbar()
    plt.show()


test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)

The heatmap of the example code

This code produces a continuous heatmap.

You can choose another built-in colormap from here.

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

The character encoding of the HTML document was not declared

Your initial page is a complete HTML page containing a form, the contents of which are posted to insert.php when the submit button is clicked, but insert.php needs to process the form's contents and do something with them, like add them to a database, or output them to a new page. Your current insert.php just outputs the contents of the title field, so your browser tries to interpret that as an HTML page, and fails, obviously, because it isn't valid HTML (i.e. it isn't contained in an 'HTML' tag, etc.).

Your insert.php needs to output the necessary HTML, and insert the form data in there somewhere.

For example:

<?php 

   $title = $_POST["title"];
   $price = $_POST["price"];

  echo '<html xmlns="http://www.w3.org/1999/xhtml">';
  echo '<head>';
  echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  echo '<title>';
  echo $title;
  echo '</title>';
  echo '</head>';
  echo '<body>';
  echo 'Hello, world.';
  echo '</body>';

 ?>

The difference between Classes, Objects, and Instances

Honestly, I feel more comfortable with Alfred blog definitions:

Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.

Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.

Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.

Given the next example:

public class Person {
    private int id;
    private String name;
    private int age;

    public Person (int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (id != other.id)
            return false;
        return true;
    }

    public static void main(String[] args) {
        //case 1
        Person p1 = new Person(1, "Carlos", 20);
        Person p2 = new Person(1, "Carlos", 20);

        //case 2
        Person p3 = new Person(2, "John", 15);
        Person p4 = new Person(3, "Mary", 17);
    }
}

For case 1, there are two instances of the class Person, but both instances represent the same object.

For case 2, there are two instances of the class Person, but each instance represent a different object.

So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.

How to avoid HTTP error 429 (Too Many Requests) python

Writing this piece of code fixed my problem:

requests.get(link, headers = {'User-agent': 'your bot 0.1'})

Document Root PHP

<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
    <br />
<a href="/hello.html">go to with html</a>

Try this yourself and find that they are not exactly the same.

$_SERVER['DOCUMENT_ROOT'] renders an actual file path (on my computer running as it's own server, C:/wamp/www/

HTML's / renders the root of the server url, in my case, localhost/

But C:/wamp/www/hello.html and localhost/hello.html are in fact the same file

How can I do a line break (line continuation) in Python?

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

Otherwise you can do something like this:

if (a == True and
    b == False):

or with explicit line break:

if a == True and \
   b == False:

Check the style guide for more information.

Using parentheses, your example can be written over multiple lines:

a = ('1' + '2' + '3' +
    '4' + '5')

The same effect can be obtained using explicit line break:

a = '1' + '2' + '3' + \
    '4' + '5'

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.

Is there a way of setting culture for a whole application? All current threads and new threads?

This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.

How can I use threading in Python?

None of the previous solutions actually used multiple cores on my GNU/Linux server (where I don't have administrator rights). They just ran on a single core.

I used the lower level os.fork interface to spawn multiple processes. This is the code that worked for me:

from os import fork

values = ['different', 'values', 'for', 'threads']

for i in range(len(values)):
    p = fork()
    if p == 0:
        my_function(values[i])
        break

Git keeps asking me for my ssh key passphrase

Try adding this to your ~/.ssh/config:

Host *
   AddKeysToAgent yes
   UseKeychain yes
   IdentityFile ~/.ssh/id_rsa

... assuming your private key is named id_rsa

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.