Programs & Examples On #Controllers

Controller provides a centralized entry point for handling requests. Usually is referred as a part of Model-View-Controller design pattern.

How to pass model attributes from one Spring MVC controller to another controller?

If you want just pass all attributes to redirect...

public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
    if(shouldIRedirect()) {
        redirectAttributes.addAllAttributes(request.getParameterMap());
        return "redirect:/newPage.html";
    }
}

Display a view from another controller in ASP.NET MVC

Yes its possible. Return a RedirectToAction() method like this:

return RedirectToAction("ActionOrViewName", "ControllerName");

Meaning of 'const' last in a function declaration of a class?

https://isocpp.org/wiki/faq/const-correctness#const-member-fns

What is a "const member function"?

A member function that inspects (rather than mutates) its object.

A const member function is indicated by a const suffix just after the member function’s parameter list. Member functions with a const suffix are called “const member functions” or “inspectors.” Member functions without a const suffix are called “non-const member functions” or “mutators.”

class Fred {
public:
  void inspect() const;   // This member promises NOT to change *this
  void mutate();          // This member function might change *this
};
void userCode(Fred& changeable, const Fred& unchangeable)
{
  changeable.inspect();   // Okay: doesn't change a changeable object
  changeable.mutate();    // Okay: changes a changeable object
  unchangeable.inspect(); // Okay: doesn't change an unchangeable object
  unchangeable.mutate();  // ERROR: attempt to change unchangeable object
}

The attempt to call unchangeable.mutate() is an error caught at compile time. There is no runtime space or speed penalty for const, and you don’t need to write test-cases to check it at runtime.

The trailing const on inspect() member function should be used to mean the method won’t change the object’s abstract (client-visible) state. That is slightly different from saying the method won’t change the “raw bits” of the object’s struct. C++ compilers aren’t allowed to take the “bitwise” interpretation unless they can solve the aliasing problem, which normally can’t be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn’t guarantee that the object won’t change; it merely promises that the object won’t change via that pointer.

Entity Framework - Include Multiple Levels of Properties

I'm going to add my solution to my particular problem. I had two collections at the same level I needed to include. The final solution looked like this.

var recipe = _bartendoContext.Recipes
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.Ingredient)
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.MeasurementQuantity)
    .FirstOrDefault(r => r.Id == recipeId);
if (recipe?.Ingredients == null) return 0m;
var abv = recipe.Ingredients.Sum(ingredient => ingredient.Ingredient.AlcoholByVolume * ingredient.MeasurementQuantity.Quantity);
return abv;

This is calculating the percent alcohol by volume of a given drink recipe. As you can see I just included the ingredients collection twice then included the ingredient and quantity onto that.

How do you get the length of a string?

HTML

<div class="selector">Text mates</div>

SCRIPT

alert(jQuery('.selector').text().length);

RESULT

10

How to scroll to an element inside a div?

browser does scrolling automatically to an element that gets focus, so what you can also do it to wrap the element that you need to be scrolled to into <a>...</a> and then when you need scroll just set the focus on that a

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

How to redirect page after click on Ok button on sweet alert?

I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:

<script>    
          sweetAlert({
                title:'Warning!',
                text: 'Invalid user or password!',
                type:'warning'
          },function(isConfirm){
                alert('ok');
          });
          $('.swal2-confirm').click(function(){
                window.location.href = 'index.php';
          });
</script>

The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...

So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...

Hope this helps you all !

PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

Creating email templates with Django

If you want dynamic email templates for your mail then save the email content in your database tables. This is what i saved as HTML code in database =

<p>Hello.. {{ first_name }} {{ last_name }}.  <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>

 <p style='color:red'> Good Day </p>

In your views:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template

def dynamic_email(request):
    application_obj = AppDetails.objects.get(id=1)
    subject = 'First Interview Call'
    email = request.user.email
    to_email = application_obj.email
    message = application_obj.message

    text_content = 'This is an important message.'
    d = {'first_name': application_obj.first_name,'message':message}
    htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code

    open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
    text_file = open("partner/templates/first_interview.html", "w") # opening my file
    text_file.write(htmly) #putting HTML content in file which i saved in DB
    text_file.close() #file close

    htmly = get_template('first_interview.html')
    html_content = htmly.render(d)  
    msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

This will send the dynamic HTML template what you have save in Db.

Create a sample login page using servlet and JSP?

You're comparing the message with the empty string using ==.

First, your comparison is wrong because the message will be null (and not the empty string).

Second, it's wrong because Objects must be compared with equals() and not with ==.

Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:

<c:id test="${!empty message}">
    <c:out value="${message}"/>
</c:if>

MAX function in where clause mysql

Do you want the first and last name of the row with the largest id?

If so (and you were missing a FROM clause):

SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;

SQL Server format decimal places with commas

SQL (or to be more precise, the RDBMS) is not meant to be the right choice for formatting the output. The database should deliver raw data which then should be formatted (or more general: processed) in the destination application.

However, depending on the specific system you use, you may write a UDF (user defined function) to achive what you want. But please bear in mind that you then are in fact returning a varchar, which you will not be able to further process (e.g. summarize).

How can I clear console

#include <cstdlib>

void cls(){
#if defined(_WIN32) //if windows
    system("cls");

#else
    system("clear");    //if other
#endif  //finish

}

The just call cls() anywhere

How to remove non UTF-8 characters from text file

Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.

how to rename an index in a cluster?

If you can't REINDEX a workaround is to use aliases. From the official documentation:

APIs in elasticsearch accept an index name when working against a specific index, and several indices when applicable. The index aliases API allow to alias an index with a name, with all APIs automatically converting the alias name to the actual index name. An alias can also be mapped to more than one index, and when specifying it, the alias will automatically expand to the aliases indices. An alias can also be associated with a filter that will automatically be applied when searching, and routing values. An alias cannot have the same name as an index.

Be aware that this solution does not work if you're using More Like This feature. https://github.com/elastic/elasticsearch/issues/16560

How to call function that takes an argument in a Django template?

if you have an object you can define it as @property so you can get results without a call, e.g.

class Item:
    @property
    def results(self):
        return something

then in the template:

<% for result in item.results %>
...
<% endfor %>

Are static methods inherited in Java?

Static members will not be inherited to subclass because inheritance is only for non-static members.. And static members will be loaded inside static pool by class loader. Inheritance is only for those members which are loaded inside the object

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

How to import RecyclerView for Android L-preview

import android.support.v7.widget.RecyclerView;

In Android Studio, importing is not as intuitive as one would hope. Try importing this bit and see how it helps!

How do getters and setters work?

Tutorial is not really required for this. Read up on encapsulation

private String myField; //"private" means access to this is restricted

public String getMyField()
{
     //include validation, logic, logging or whatever you like here
    return this.myField;
}
public void setMyField(String value)
{
     //include more logic
     this.myField = value;
}

How to read/write from/to file using Go?

The Read method takes a byte parameter because that is the buffer it will read into. It's a common Idiom in some circles and makes some sense when you think about it.

This way you can determine how many bytes will be read by the reader and inspect the return to see how many bytes actually were read and handle any errors appropriately.

As others have pointed in their answers bufio is probably what you want for reading from most files.

I'll add one other hint since it's really useful. Reading a line from a file is best accomplished not by the ReadLine method but the ReadBytes or ReadString method instead.

How to do a SOAP Web Service call from Java class?

I understand your problem boils down to how to call a SOAP (JAX-WS) web service from Java and get its returning object. In that case, you have two possible approaches:

  1. Generate the Java classes through wsimport and use them; or
  2. Create a SOAP client that:
    1. Serializes the service's parameters to XML;
    2. Calls the web method through HTTP manipulation; and
    3. Parse the returning XML response back into an object.


About the first approach (using wsimport):

I see you already have the services' (entities or other) business classes, and it's a fact that the wsimport generates a whole new set of classes (that are somehow duplicates of the classes you already have).

I'm afraid, though, in this scenario, you can only either:

  • Adapt (edit) the wsimport generated code to make it use your business classes (this is difficult and somehow not worth it - bear in mind everytime the WSDL changes, you'll have to regenerate and readapt the code); or
  • Give up and use the wsimport generated classes. (In this solution, you business code could "use" the generated classes as a service from another architectural layer.)

About the second approach (create your custom SOAP client):

In order to implement the second approach, you'll have to:

  1. Make the call:
    • Use the SAAJ (SOAP with Attachments API for Java) framework (see below, it's shipped with Java SE 1.6 or above) to make the calls; or
    • You can also do it through java.net.HttpUrlconnection (and some java.io handling).
  2. Turn the objects into and back from XML:
    • Use an OXM (Object to XML Mapping) framework such as JAXB to serialize/deserialize the XML from/into objects
    • Or, if you must, manually create/parse the XML (this can be the best solution if the received object is only a little bit differente from the sent one).

Creating a SOAP client using classic java.net.HttpUrlConnection is not that hard (but not that simple either), and you can find in this link a very good starting code.

I recommend you use the SAAJ framework:

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "https://www.w3schools.com/xml/tempconvert.asmx";
        String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "https://www.w3schools.com/xml/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="https://www.w3schools.com/xml/">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:CelsiusToFahrenheit>
                        <myNamespace:Celsius>100</myNamespace:Celsius>
                    </myNamespace:CelsiusToFahrenheit>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
        soapBodyElem1.addTextNode("100");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

About using JAXB for serializing/deserializing, it is very easy to find information about it. You can start here: http://www.mkyong.com/java/jaxb-hello-world-example/.

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

Calculating the area under a curve given a set of coordinates, without knowing the function

The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

from __future__ import print_function

import numpy as np
from scipy.integrate import simps
from numpy import trapz


# The y values.  A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)

Output:

area = 452.5
area = 460.0

How do I move files in node.js?

According to seppo0010 comment, I used the rename function to do that.

http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback

fs.rename(oldPath, newPath, callback)

Added in: v0.0.2

oldPath <String> | <Buffer>
newPath <String> | <Buffer>
callback <Function>

Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

Manually type in a value in a "Select" / Drop-down HTML list?

I love the Shadow Wizard answer, which accually answers the question pretty nicelly. My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/

After typing new value, the form is ready to send, just need to handle new values on the back end.

jQuery is:

(function ($) 
{
 $.fn.otherize = function (option_text, texts_placeholder_text) {
    oSel = $(this);
    option_id = oSel.attr('id') + '_other';
    textbox_id = option_id + "_tb";

    this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
    this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
    this.change(

    function () {
        oTbox = oSel.parent().children('#' + textbox_id);
        oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
    });

    $("#" + textbox_id).change(

    function () {
        $("#" + option_id).val($("#" + textbox_id).val());
    });
};
}(jQuery));

So you apply this to the below html:

<form>
    <select id="otherize_me">
        <option value=1>option 1</option>
        <option value=2>option 2</option>
        <option value=3>option 3</option>
    </select>
</form>

Just like this:

$(function () {

   $("#otherize_me").otherize("other..", "put new option vallue here");

});

How do I add multiple conditions to "ng-disabled"?

Wanny is correct. The && operator doesn't work in HTML. With Angular, you must use the double pipes (||)for multiple conditions.

Create Hyperlink in Slack

I feel like none of these messages quite answer the question still. See - https://api.slack.com/docs/message-attachments.

It requires you to put the link in an attachment. Hyperlinking is still not allowed in the body of the message.

{ "attachments": [ { ..., "text": " <https://honeybadger.io/path/to/event/|ReferenceError> - UI is not defined", ... ] }

ReferenceError will be a hyperlink.

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

center aligning a fixed position div

if you don't want to use the wrapper method. then you can do this:

.fixed_center_div {
  position: fixed;
  width: 200px;
  height: 200px;
  left: 50%;
  top: 50%;
  margin-left: -100px; /* 50% of width */
  margin-top: -100px; /* 50% of height */
}

ASP.NET GridView RowIndex As CommandArgument

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

Create an S3 client object with your credentials

AWS_S3_CREDS = {
    "aws_access_key_id":"your access key", # os.getenv("AWS_ACCESS_KEY")
    "aws_secret_access_key":"your aws secret key" # os.getenv("AWS_SECRET_KEY")
}
s3_client = boto3.client('s3',**AWS_S3_CREDS)

It is always good to get credentials from os environment

To set Environment variables run the following commands in terminal

if linux or mac

$ export AWS_ACCESS_KEY="aws_access_key"
$ export AWS_SECRET_KEY="aws_secret_key"

if windows

c:System\> set AWS_ACCESS_KEY="aws_access_key"
c:System\> set AWS_SECRET_KEY="aws_secret_key"

What port number does SOAP use?

There is no such thing as "SOAP protocol". SOAP is an XML schema.

It usually runs over HTTP (port 80), however.

Environment Specific application.properties file in Spring Boot application

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
  @PropertySource("application-${spring.profiles.active}.properties"),
  @PropertySource("my-special-${spring.profiles.active}.properties"),
  @PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

javascript function wait until another function to finish

Following answer can help in this and other similar situations like synchronous AJAX call -

Working example

waitForMe().then(function(intentsArr){
  console.log('Finally, I can execute!!!');
},
function(err){
  console.log('This is error message.');
})

function waitForMe(){
    // Returns promise
    console.log('Inside waitForMe');
    return new Promise(function(resolve, reject){
        if(true){ // Try changing to 'false'
            setTimeout(function(){
                console.log('waitForMe\'s function succeeded');
                resolve();
            }, 2500);
        }
        else{
            setTimeout(function(){
                console.log('waitForMe\'s else block failed');
                resolve();
            }, 2500);
        }
    });
}

How to check if an appSettings key exists?

Using the new c# syntax with TryParse worked well for me:

  // TimeOut
  if (int.TryParse(ConfigurationManager.AppSettings["timeOut"], out int timeOut))
  {
     this.timeOut = timeOut;
  }

Select arrow style change

I have referred this post, it worked like charm , except it did not hide the arrow in IE browser.

However adding following hides the arrow in IE:

_x000D_
_x000D_
&::-ms-expand {_x000D_
      display: none;_x000D_
    }
_x000D_
_x000D_
_x000D_

Complete solution ( sass )

_x000D_
_x000D_
$select-border-color: #ccc;_x000D_
$select-focus-color: green;_x000D_
_x000D_
select {_x000D_
_x000D_
    cursor: pointer;_x000D_
    /* styling */_x000D_
    background-color: white;_x000D_
    border: 1px solid $select-border-color;_x000D_
    border-radius: 4px;_x000D_
    display: inline-block;_x000D_
    font: inherit;_x000D_
    line-height: 1.5em;_x000D_
    padding: 0.5em 3.5em 0.5em 1em;_x000D_
_x000D_
    /* reset */_x000D_
    margin: 0;_x000D_
    -webkit-box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    box-sizing: border-box;_x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
_x000D_
    background-image: linear-gradient(45deg, transparent 50%, $select-border-color 50%),_x000D_
    linear-gradient(135deg, $select-border-color 50%, transparent 50%),_x000D_
    linear-gradient(to right, $select-border-color, $select-border-color);_x000D_
    background-position: calc(100% - 20px) calc(1em + 2px),_x000D_
    calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
    background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
    background-repeat: no-repeat;_x000D_
_x000D_
    /* Very imp: hide arrow in IE */_x000D_
    &::-ms-expand {_x000D_
      display: none;_x000D_
    }_x000D_
_x000D_
    &:-moz-focusring {_x000D_
      color: transparent;_x000D_
      text-shadow: none;_x000D_
    }_x000D_
_x000D_
    &:focus {_x000D_
      background-image: linear-gradient(45deg, $select-focus-color 50%, transparent 50%),_x000D_
      linear-gradient(135deg, transparent 50%, $select-focus-color 50%), linear-gradient(to right, $select-focus-color, $select-focus-color);_x000D_
      background-position: calc(100% - 15px) 1em, calc(100% - 20px) 1em, calc(100% - 2.5em) 0.5em;_x000D_
      background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
      background-repeat: no-repeat;_x000D_
      border-color: $select-focus-color;_x000D_
      outline: 0;_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

How do I load an url in iframe with Jquery

Try $(this).load("/file_name.html");. This method targets a local file.

You can also target remote files (on another domain) take a look at: http://en.wikipedia.org/wiki/Same_origin_policy

Enum Naming Convention - Plural

In general, the best practice recommendation is singular, except for those enums that have the [Flags] attribute attached to them, (and which therefore can contain bit fields), which should be plural.

After reading your edited question, I get the feeling you may think the property name or variable name has to be different from the enum type name... It doesn't. The following is perfectly fine...

  public enum Status { New, Edited, Approved, Cancelled, Closed }

  public class Order
  {
      private Status stat;
      public Status Status
      { 
         get { return stat; }
         set { stat = value; }
      }
  }

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

Parse String date in (yyyy-MM-dd) format

You are creating a Date object, which is a representation of a certain point in the timeline. This means that it will have all the parts necessary to represent it correctly, including minutes and seconds and so on. Because you initialize it from a string containing only a part of the date, the missing data will be defaulted.

I assume you are then "printing" this Date object, but without actually specifying a format like you did when parsing it. Use the same SimpleDateFormat but call the reverse method, format(Date) as Holger suggested

How do I parse JSON into an int?

Non of them worked for me. I did this and it worked:

To encode as a json:

JSONObject obj = new JSONObject();
obj.put("productId", 100);

To decode:

long temp = (Long) obj.get("productId");

How to get Git to clone into current directory

shopt -s dotglob
git clone ssh://[email protected]/home/user/private/repos/project_hub.git tmp && mv tmp/* . && rm -rf tmp

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

Comparing arrays in C#

For .NET 4.0 and higher, you can compare elements in array or tuples using the StructuralComparisons type:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
        
Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)
        
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

I'm seeing this in a VS2017 environment. My build script calls VsDevCmd.bat first, and to solve this problem I set the VCTargetsPath environment variable after VsDevCmd and before calling MSBuild:

set VCTargetsPath=%VCIDEInstallDir%VCTargets

Node.js: Python not found exception due to node-sass and node-gyp

After looking at all the answers, i notice this solution might be very helpful. It explains how to configure "npm" to find your installed python version while installing node-sass. Remember, node-sass requires node-gyp (an npm build-tool) which looks for your python path. Or just install python, and follow the same solution given (in the link). Thanks.

How to detect the end of loading of UITableView

Here is how you do it in Swift 3:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        // perform your logic here, for the first row in the table
    }

    // ....
}

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

Share data between AngularJS controllers

Not sure where I picked up this pattern but for sharing data across controllers and reducing the $rootScope and $scope this works great. It is reminiscent of a data replication where you have publishers and subscribers. Hope it helps.

The Service:

(function(app) {
    "use strict";
    app.factory("sharedDataEventHub", sharedDataEventHub);

    sharedDataEventHub.$inject = ["$rootScope"];

    function sharedDataEventHub($rootScope) {
        var DATA_CHANGE = "DATA_CHANGE_EVENT";
        var service = {
            changeData: changeData,
            onChangeData: onChangeData
        };
        return service;

        function changeData(obj) {
            $rootScope.$broadcast(DATA_CHANGE, obj);
        }

        function onChangeData($scope, handler) {
            $scope.$on(DATA_CHANGE, function(event, obj) {
                handler(obj);
            });
        }
    }
}(app));

The Controller that is getting the new data, which is the Publisher would do something like this..

var someData = yourDataService.getSomeData();

sharedDataEventHub.changeData(someData);

The Controller that is also using this new data, which is called the Subscriber would do something like this...

sharedDataEventHub.onChangeData($scope, function(data) {
    vm.localData.Property1 = data.Property1;
    vm.localData.Property2 = data.Property2;
});

This will work for any scenario. So when the primary controller is initialized and it gets data it would call the changeData method which would then broadcast that out to all the subscribers of that data. This reduces the coupling of our controllers to each other.

SQL Query to add a new column after an existing column in SQL Server 2005

Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.

MySQL does however:

ALTER TABLE mytable
ADD COLUMN  new_column <type>
AFTER       existing_column

How to use: while not in

The expression 'AND' and 'OR' and 'NOT' always evaluates to 'NOT', so you are effectively doing

while 'NOT' not in some_list:
    print 'No boolean operator'

You can either check separately for all of them

while ('AND' not in some_list and 
       'OR' not in some_list and 
       'NOT' not in some_list):
    # whatever

or use sets

s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
    # whatever

Using AND/OR in if else PHP statement

"AND" does not work in my PHP code.

Server's version maybe?

"&&" works fine.

How do you round UP a number in Python?

My share

I have tested print(-(-101 // 5)) = 21 given example above.

Now for rounding up:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:

(-(-101 //(1/0.19))) = 20

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

first-child and last-child with IE8

If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js

Determine installed PowerShell version

Use $PSVersionTable.PSVersion to determine the engine version. If the variable does not exist, it is safe to assume the engine is version 1.0.

Note that $Host.Version and (Get-Host).Version are not reliable - they reflect the version of the host only, not the engine. PowerGUI, PowerShellPLUS, etc. are all hosting applications, and they will set the host's version to reflect their product version — which is entirely correct, but not what you're looking for.

PS C:\> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

Missing styles. Is the correct theme chosen for this layout?

In my case the problem occurred while the default setting for Android Version in the Designer was set to 'Preview N'. Changed Android Version to '23' and the error notification went away.
Edit
And don't forget to uncheck 'Automatically Pick Best'.

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

how do I create an array in jquery?

I haven't been using jquery for a while but you might be looking for this:

jQuery.makeArray(obj)

"Error: Main method not found in class MyClass, please define the main method as..."

The name of the exception suggests that the program tried to call a method that doesn't exist. In this context, it sounds like the program does not have a main method, though it would help if you posted the code that caused the error and the context in which the code was run.

This might have happened if the user tried to run a .class file or a .jar file that has no main method - in Java, the main method is the entry point to begin executing the program.

Normally the compiler is supposed to prevent this from happening so if this does happen, it's usually because the name of the method being called is getting determined ar run-time, rather than compile-time.

To fix this problem, a new programmer must either add the midding method (assuming still that it's main that's missing) or change the method call to the name of a method that does exist.

Read more about the main method here: http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html

Unzip files (7-zip) via cmd command

Regarding Phil Street's post:

It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip is installed, and if it is in Program Files (x86) then try using this instead:

PATH=%PATH%;C:\Program Files (x86)\7-Zip

In Angular, I need to search objects in an array

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

Converting stream of int's to char's in java

Simple casting:

int a = 99;
char c = (char) a;

Is there any reason this is not working for you?

How to get all checked checkboxes

Get all the checked checkbox value in an array - one liner

_x000D_
_x000D_
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
    <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
    <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
    <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript: Class.method vs. Class.prototype.method

When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.

That's why prototypes save memory.

Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.

Finding current executable's path without /proc/self/exe

In addition to mark4o's answer, FreeBSD also has

const char* getprogname(void)

It should also be available in macOS. It's available in GNU/Linux through libbsd.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

PHP PDO returning single row

If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php

How to get just the responsive grid from Bootstrap 3?

Go to http://getbootstrap.com/customize/ and toggle just what you want from the BS3 framework and then click "Compile and Download" and you'll get the CSS and JS that you chose.

Bootstrap Customizer

Open up the CSS and remove all but the grid. They include some normalize stuff too. And you'll need to adjust all the styles on your site to box-sizing: border-box - http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

source command not found in sh shell

Bourne shell (sh) uses PATH to locate in source <file>. If the file you are trying to source is not in your path, you get the error 'file not found'.

Try:

source ./<filename>

DataTable, How to conditionally delete rows

I don't have a windows box handy to try this but I think you can use a DataView and do something like so:

DataView view = new DataView(ds.Tables["MyTable"]);
view.RowFilter = "MyValue = 42"; // MyValue here is a column name

// Delete these rows.
foreach (DataRowView row in view)
{
  row.Delete();
}

I haven't tested this, though. You might give it a try.

How do I launch a program from command line without opening a new cmd window?

In Windows 7+ the first quotations will be the title to the cmd window to open the program:

start "title" "C:\path\program.exe"

Formatting your command like the above will temporarily open a cmd window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.

Check if inputs form are empty jQuery

You can do it using simple jQuery loop.

Total code

<!DOCTYPE html>
 <html lang="en">
  <head>
   <meta charset="UTF-8">
   <title></title>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  <style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
     }
    });

    if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

return isFormValid;
}   
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

What's the difference between the 'ref' and 'out' keywords?

For those looking concise answer.

Both ref and out keywords are used to pass-by-reference.


A variable of ref keyword must have a value or must refer to an object or null before its passing.


Unlike ref, a variable of out keyword must have a value or must refer to an object or null after its passing as well as no need to have a value or refer to an object before passing.

How do I correctly detect orientation change using Phonegap on iOS?

here is what i did:

window.addEventListener('orientationchange', doOnOrientationChange);

function doOnOrientationChange()
{
      if (screen.height > screen.width) {
         console.log('portrait');
      } else {
         console.log('landscape');
      }
}

How to hide element using Twitter Bootstrap and show it using jQuery?

Another way to address this annoyance is to create your own CSS class that does not set the !important at the end of rule, like this:

.hideMe {
    display: none;
}

and used like so :

<div id="header-mask" class="hideMe"></div>

and now jQuery hiding works

$('#header-mask').show();

How can getContentResolver() be called in Android?

getContentResolver() is method of class android.content.Context, so to call it you definitely need an instance of Context ( Activity or Service for example).

Does the Java &= operator apply & or &&?

see 15.22.2 of the JLS. For boolean operands, the & operator is boolean, not bitwise. The only difference between && and & for boolean operands is that for && it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).

So in your case, if b is a primitive, a = a && b, a = a & b, and a &= b all do the same thing.

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

No need for cut or magic, in bash you can cut a string like so:

  ORGSTRING="123456"
  CUTSTRING=${ORGSTRING:0:-3}
  echo "The original string: $ORGSTRING"
  echo "The new, shorter and faster string: $CUTSTRING"

See http://tldp.org/LDP/abs/html/string-manipulation.html

How to add parameters into a WebRequest?

I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;

string data = "phone_number=19735559042"; 
byte[] dataStream = Encoding.UTF8.GetBytes(data);

request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();

How to get number of video views with YouTube API?

Using youtube-dl and jq:

views() {
    id=$1
    youtube-dl -j https://www.youtube.com/watch?v=$id |
        jq -r '.["view_count"]'
}

views fOX1EyHkQwc

Remove style attribute from HTML tags

$html = preg_replace('/\sstyle=("|\').*?("|\')/i', '', $html);

For replacing all style="" with blank.

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

Get text from pressed button

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

Assign a class name to <img> tag instead of write it in css file?

Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}

In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.

How can I multiply and divide using only bit shifting and adding?

Take two numbers, lets say 9 and 10, write them as binary - 1001 and 1010.

Start with a result, R, of 0.

Take one of the numbers, 1010 in this case, we'll call it A, and shift it right by one bit, if you shift out a one, add the first number, we'll call it B, to R.

Now shift B left by one bit and repeat until all bits have been shifted out of A.

It's easier to see what's going on if you see it written out, this is the example:

      0
   0000      0
  10010      1
 000000      0
1001000      1
 ------
1011010

How to use private Github repo as npm dependency

With git there is a https format

https://github.com/equivalent/we_demand_serverless_ruby.git

This format accepts User + password

https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git

So what you can do is create a new user that will be used just as a bot, add only enough permissions that he can just read the repository you want to load in NPM modules and just have that directly in your packages.json

 Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token

In Select Scopes part, check the on repo: Full control of private repositories

This is so that token can access private repos that user can see

Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)

You need to be sure to push this config only to private repo

Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)

// packages.json


{
  // ....
    "name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
  // ...
}

https://blog.eq8.eu/til/pull-git-private-repo-from-github-from-npm-modules-or-bundler.html

lvalue required as left operand of assignment error when using C++

It is just a typo(I guess)-

p+=1;

instead of p +1=p; is required .

As name suggest lvalue expression should be left-hand operand of the assignment operator.

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

ECMAScript 6 class destructor

"A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."

Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.

For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.

// Set event listeners, hanging onto the returned listener removal functions
function initialize() {
    $scope.listenerCleanup = [];
    $scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
}

// Remove event listeners when the controller is destroyed
function onDestroy(){
    $scope.listenerCleanup.forEach( remove => remove() );
}


ansible: lineinfile for several lines?

It's not ideal, but you're allowed multiple calls to lineinfile. Using that with insert_after, you can get the result you want:

- name: Set first line at EOF (1/3)
  lineinfile: dest=/path/to/file regexp="^string 1" line="string 1"
- name: Set second line after first (2/3)
  lineinfile: dest=/path/to/file regexp="^string 2" line="string 2" insertafter="^string 1"
- name: Set third line after second (3/3)
  lineinfile: dest=/path/to/file regexp="^string 3" line="string 3" insertafter="^string 2"

How to export a Hive table into a CSV file?

or use this

hive -e 'select * from your_Table' | sed 's/[\t]/,/g'  > /home/yourfile.csv

You can also specify property set hive.cli.print.header=true before the SELECT to ensure that header along with data is created and copied to file. For example:

hive -e 'set hive.cli.print.header=true; select * from your_Table' | sed 's/[\t]/,/g'  > /home/yourfile.csv

If you don't want to write to local file system, pipe the output of sed command back into HDFS using the hadoop fs -put command.

It may also be convenient to SFTP to your files using something like Cyberduck, or you can use scp to connect via terminal / command prompt.

How to read embedded resource text file

You can add a file as a resource using two separate methods.

The C# code required to access the file is different, depending on the method used to add the file in the first place.

Method 1: Add existing file, set property to Embedded Resource

Add the file to your project, then set the type to Embedded Resource.

NOTE: If you add the file using this method, you can use GetManifestResourceStream to access it (see answer from @dtb).

enter image description here

Method 2: Add file to Resources.resx

Open up the Resources.resx file, use the dropdown box to add the file, set Access Modifier to public.

NOTE: If you add the file using this method, you can use Properties.Resources to access it (see answer from @Night Walker).

enter image description here

How to trim a string in SQL Server before 2017?

I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.

ALTER TABLE Customer ADD
   CONSTRAINT customer_names__whitespace
      CHECK (
             Names NOT LIKE ' %'
             AND Names NOT LIKE '% '
             AND Names NOT LIKE '%  %'
            );

Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.

It may also be a good time to split those Names into family_name, first_name, etc :)

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

Copy/Paste from Excel to a web page

On OSX and Windows , there are multiple types of clipboards for different types of content. When you copy content in Excel, data is stored in the plaintext and in the html clipboard.

The right way (that doesn't get tripped up by delimiter issues) is to parse the HTML. http://jsbin.com/uwuvan/5 is a simple demo that shows how to get the HTML clipboard. The key is to bind to the onpaste event and read

event.clipboardData.getData('text/html')

jQuery - Detect value change on hidden input field

This example returns the draft field value every time the hidden draft field changes its value (chrome browser):

var h = document.querySelectorAll('input[type="hidden"][name="draft"]')[0];
//or jquery.....
//var h = $('input[type="hidden"][name="draft"]')[0];

observeDOM(h, 'n', function(draftValue){ 
  console.log('dom changed draftValue:'+draftValue);
});


var observeDOM = (function(){
var MutationObserver = window.MutationObserver || 
window.WebKitMutationObserver;

  return function(obj, thistime, callback){
    if(typeof obj === 'undefined'){
      console.log('obj is undefined');
      return;
    }

    if( MutationObserver ){

        // define a new observer
        var obs = new MutationObserver(function(mutations, observer){

            if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ){

               callback('pass other observations back...');

            }else if(mutations[0].attributeName == "value" ){

               // use callback to pass back value of hidden form field                            
               callback( obj.value );

            }

        });

        // have the observer observe obj for changes in children
        // note 'attributes:true' else we can't read the input attribute value
        obs.observe( obj, { childList:true, subtree:true, attributes:true  });

       }
  };
})();

How to compare pointers?

The == operator on pointers will compare their numeric address and hence determine if they point to the same object.

Play a Sound with Python

Definitely use Pyglet for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.

import pyglet

music = pyglet.resource.media('music.mp3')
music.play()

pyglet.app.run()

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

    <fb:visible-to-connection>
       Fans will see this content.
       <fb:else>
           Non-fans will see this content.
       </fb:else>
    </fb:visible-to-connection>

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

Correct way to push into state array

Using react hooks, you can do following way

const [countryList, setCountries] = useState([]);


setCountries((countryList) => [
        ...countryList,
        "India",
      ]);

Jenkins fails when running "service start jenkins"

Similar problem on Ubuntu 16.04.

Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
? jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)

Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....

To fix the issue manually install Java Runtime Environment:

JDK version 9:

sudo apt install openjdk-9-jre

JDK version 8:

sudo apt install openjdk-8-jre

Open Jenkins configuration file:

sudo vi /etc/init.d/jenkins

Finally, append path to the new java executable (line 16):

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How to get script of SQL Server data?

SqlPubWiz.exe (for me, it's in C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Publishing\1.2>)

Run it with no arguments for a wizard. Give it arguments to run on commandline.

SqlPubWiz.exe script -C "<ConnectionString>" <OutputFile>

What is the format specifier for unsigned short int?

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

ISO/IEC 9899:201x - 7.21.6.1-7

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.

Function ereg_replace() is deprecated - How to clear this bug?

http://php.net/ereg_replace says:

Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.

Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.

Why is a ConcurrentModificationException thrown and how to debug it

In Java 8, you can use lambda expression:

map.keySet().removeIf(key -> key condition);

JavaScript OOP in NodeJS: how?

I suggest to use the inherits helper that comes with the standard util module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

There is an example of how to use it on the linked page.

Pods stuck in Terminating status

Practical answer -- you can always delete a terminating pod by running:

kubectl delete pod NAME --grace-period=0

Historical answer -- There was an issue in version 1.1 where sometimes pods get stranded in the Terminating state if their nodes are uncleanly removed from the cluster.

How do you get AngularJS to bind to the title attribute of an A tag?

Look at the fiddle here for a quick answer

data-ng-attr-title="{{d.age > 5 ? 'My age is greater than threshold': ''}}"

Displays Title over elements conditionally using Angular JS

How can I find non-ASCII characters in MySQL?

In Oracle we can use below.

SELECT * FROM TABLE_A WHERE ASCIISTR(COLUMN_A) <> COLUMN_A;

How to change Hash values?

Ruby has the tap method (1.8.7, 1.9.3 and 2.1.0) that's very useful for stuff like this.

original_hash = { :a => 'a', :b => 'b' }
original_hash.clone.tap{ |h| h.each{ |k,v| h[k] = v.upcase } }
# => {:a=>"A", :b=>"B"}
original_hash # => {:a=>"a", :b=>"b"}

C# Switch-case string starting with

If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length))).
Another option is to have a function that will return categoryId based on the string and switch on the id.

Iterate over object attributes in python

class someclass:
        x=1
        y=2
        z=3
        def __init__(self):
           self.current_idx = 0
           self.items = ["x","y","z"]
        def next(self):
            if self.current_idx < len(self.items):
                self.current_idx += 1
                k = self.items[self.current_idx-1]
                return (k,getattr(self,k))
            else:
                raise StopIteration
        def __iter__(self):
           return self

then just call it as an iterable

s=someclass()
for k,v in s:
    print k,"=",v

How to get IntPtr from byte[] in C#

Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:

IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);

Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.

Edit: Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

How to Convert Int to Unsigned Byte and Back

in java 7

public class Main {
    public static void main(String[] args) {
        byte b =  -2;
        int i = 0 ;
        i = ( b & 0b1111_1111 ) ;
        System.err.println(i);
    }
}

result : 254

EXC_BAD_ACCESS signal received

Don't forget the @ symbol when creating strings, treating C-strings as NSStrings will cause EXC_BAD_ACCESS.

Use this:

@"Some String"

Rather than this:

"Some String"

PS - typically when populating contents of an array with lots of records.

What is the best way to insert source code examples into a Microsoft Word document?

If you are still looking for an simple way to add code snippets.

you can easily go to [Insert] > [Object] > [Opendocument Text] > paste your code > Save and Close.

You could also put this into a macro and add it to your easy access bar.

notes:

  • This will only take up to one page of code.
  • Your Code will not be autocorrected.
  • You can only interact with it by double-clicking it.

An invalid form control with name='' is not focusable

Adding a novalidate attribute to the form will help:

<form name="myform" novalidate>

How do I sort a VARCHAR column in SQL server that contains numbers?

you can always convert your varchar-column to bigint as integer might be too short...

select cast([yourvarchar] as BIGINT)

but you should always care for alpha characters

where ISNUMERIC([yourvarchar] +'e0') = 1

the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber

this would lead to your statement

SELECT
  *
FROM
  Table
ORDER BY
   ISNUMERIC([yourvarchar] +'e0') DESC
 , LEN([yourvarchar]) ASC

the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)

this leads to the second version:

SELECT
      *
    FROM
      Table
    ORDER BY
       ISNUMERIC([yourvarchar] +'e0') DESC
     , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC

the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)

so third version:

 SELECT
          *
        FROM
          Table
        ORDER BY
           ISNUMERIC([yourvarchar] +'e0') DESC
         , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
                THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
                ELSE LTRIM(RTRIM([yourvarchar]))
           END ASC

now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

System.currentTimeMillis() is obviously the most efficient since it does not even create an object, but new Date() is really just a thin wrapper about a long, so it is not far behind. Calendar, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).

It's generally a good idea to deal only with long timestamps or Date objects within your application, and only use Calendar when you actually need to perform date/time calculations, or to format dates for displaying them to the user. If you have to do a lot of this, using Joda Time is probably a good idea, for the cleaner interface and better performance.

Hide/Show components in react native

in render() you can conditionally show the JSX or return null as in:

render(){
    return({yourCondition ? <yourComponent /> : null});
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

i don't see any for loop to initalize the variables.you can do something like this.

for(i=0;i<50;i++){
 /* Code which is necessary with a simple if statement*/

   }

What does the keyword "transient" mean in Java?

Google is your friend - first hit - also you might first have a look at what serialization is.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

Example from there, slightly modified (thanks @pgras):

public class Foo implements Serializable
 {
   private String saveMe;
   private transient String dontSaveMe;
   private transient String password;
   //...
 }

VLook-Up Match first 3 characters of one column with another column

=VLOOKUP(Left(A1,1),B$2:B$22,2,FALSE)

Left is because you are starting the word/alphanumeric text from the left. the number "1" which i have placed is after lookup value in this case "A1" is because my search includes the formula for 1st character. If second character is asked it would be (A1,2) quite simple really :)

Remove sensitive files and their commits from Git history

You can use git forget-blob.

The usage is pretty simple git forget-blob file-to-forget. You can get more info here

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

It will disappear from all the commits in your history, reflog, tags and so on

I run into the same problem every now and then, and everytime I have to come back to this post and others, that's why I automated the process.

Credits to contributors from Stack Overflow that allowed me to put this together

How do I create test and train samples from one dataframe with pandas?

If your wish is to have one dataframe in and two dataframes out (not numpy arrays), this should do the trick:

def split_data(df, train_perc = 0.8):

   df['train'] = np.random.rand(len(df)) < train_perc

   train = df[df.train == 1]

   test = df[df.train == 0]

   split_data ={'train': train, 'test': test}

   return split_data

Java method to swap primitives

For integer types, you can do

a ^= b;
b ^= a;
a ^= b;

using the bit-wise xor operator ^. As all the other suggestions, you probably shouldn't use it in production code.

For a reason I don't know, the single line version a ^= b ^= a ^= b doesn't work (maybe my Java compiler has a bug). The single line worked in C with all compilers I tried. However, two-line versions work:

a ^= b ^= a;
b ^= a;

as well as

b ^= a;
a ^= b ^= a;

A proof that it works: Let a0 and b0 be the initial values for a and b. After the first line, a is a1 = a0 xor b0; after the second line, b is b1 = b0 xor a1 = b0 xor (a0 xor b0) = a0. After the third line, a is a2 = a1 xor b1 = a1 xor (b0 xor a1) = b0.

Passing an array of parameters to a stored procedure

I like this one, because it is suited to be passed as an XElement, which is suitable for SqlCommand

(Sorry it is VB.NET but you get the idea)

<Extension()>
Public Function ToXml(Of T)(array As IEnumerable(Of T)) As XElement
   Return XElement.Parse(
           String.Format("<doc>{0}</doc>", String.Join("", array.Select(Function(s) String.Concat("<d>", s.ToString(), "</d>")))), LoadOptions.None)
 End Function

This is the sql Stored proc, shortened, not complete!

CREATE PROCEDURE [dbo].[myproc] (@blah xml)
AS ... WHERE SomeID IN (SELECT doc.t.value('.','int') from @netwerkids.nodes(N'/doc/d') as doc(t))

How to change file encoding in NetBeans?

There is an old Bugreport concerning this issue.

In Python, how do you convert seconds since epoch to a `datetime` object?

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

Add and remove a class on click using jQuery?

Here is an article with live working demo Class Animation In JQuery

You can try this,

$(function () {
   $("#btnSubmit").click(function () {
   $("#btnClass").removeClass("btnDiv").addClass("btn");
   });
});

you can also use switchClass() method - it allows you to animate the transition of adding and removing classes at the same time.

$(function () {
        $("#btnSubmit").click(function () {
            $("#btnClass").switchClass("btn", "btnReset", 1000, "easeInOutQuad");
        });
    });

How to create global variables accessible in all views using Express / Node.JS?

One way to do this by updating the app.locals variable for that app in app.js

Set via following

var app = express();
app.locals.appName = "DRC on FHIR";

Get / Access

app.listen(3000, function () {
    console.log('[' + app.locals.appName + '] => app listening on port 3001!');
});

Elaborating with a screenshot from @RamRovi example with slight enhancement.

enter image description here

List of special characters for SQL LIKE clause

You should add that you have to add an extra ' to escape an exising ' in SQL Server:

smith's -> smith''s

How to make <input type="date"> supported on all browsers? Any alternatives?

I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905 but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.

if ($('[type="date"]').prop('type') !== 'date') {
    //for reloading/displaying the ISO format back into input again
    var val = $('[type="date"]').each(function () {
        var val = $(this).val();
        if (val !== undefined && val.indexOf('-') > 0) {
            var arr = val.split('-');
            $(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
        }
    });

    //add in the datepicker
    $('[type="date"]').datepicker(datapickeroptions);

    //stops the invalid date when validated in safari
    jQuery.validator.methods["date"] = function (value, element) {
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }
}

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

How to make html table vertically scrollable

Why don't you place your table in a div?

<div style="height:100px;overflow:auto;">

 ... Your code goes here ...

</div>

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

How to detect incoming calls, in an Android device?

@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded(). It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.

1: a pair of brackets is missing.

case TelephonyManager.CALL_STATE_IDLE: 
    // Went to idle-  this is the end of a call.  What type depends on previous state(s)
    if (lastState == TelephonyManager.CALL_STATE_RINGING) {
        // Ring but no pickup-  a miss
        onMissedCall(context, savedNumber, callStartTime);
    } else {
        // this one is missing
        if(isIncoming){
            onIncomingCallEnded(context, savedNumber, callStartTime, new Date());                       
        } else {
            onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());                                               
        }
    }
    // this one is missing
    break;

2: lastState is not updated by the state if it is at the end of the function. It should be replaced to the first line of this function by

public void onCallStateChanged(Context context, int state, String number) {
    int lastStateTemp = lastState;
    lastState = state;
    // todo replace all the "lastState" by lastStateTemp from here.
    if (lastStateTemp  == state) {
        //No change, debounce extras
        return;
    }
    //....
}

Additional I've put lastState and savedNumber into shared preference as you suggested.

Just tested it with above changes. Bug fixed at least on my phones.

How to load assemblies in PowerShell?

Most people know by now that System.Reflection.Assembly.LoadWithPartialName is deprecated, but it turns out that Add-Type -AssemblyName Microsoft.VisualBasic does not behave much better than LoadWithPartialName:

Rather than make any attempt to parse your request in the context of your system, [Add-Type] looks at a static, internal table to translate the "partial name" to a "full name".

If your "partial name" doesn't appear in their table, your script will fail.

If you have multiple versions of the assembly installed on your computer, there is no intelligent algorithm to choose between them. You are going to get whichever one appears in their table, probably the older, outdated one.

If the versions you have installed are all newer than the obsolete one in the table, your script will fail.

Add-Type has no intelligent parser of "partial names" like .LoadWithPartialNames.

What Microsoft's .Net teams says you're actually supposed to do is something like this:

Add-Type -AssemblyName 'Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

Or, if you know the path, something like this:

Add-Type -Path 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualBasic\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualBasic.dll'

That long name given for the assembly is known as the strong name, which is both unique to the version and the assembly, and is also sometimes known as the full name.

But this leaves a couple questions unanswered:

  1. How do I determine the strong name of what's actually being loaded on my system with a given partial name?

    [System.Reflection.Assembly]::LoadWithPartialName($TypeName).Location; [System.Reflection.Assembly]::LoadWithPartialName($TypeName).FullName;

These should also work:

Add-Type -AssemblyName $TypeName -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
  1. If I want my script to always use a specific version of a .dll but I can't be certain of where it's installed, how do I determine what the strong name is from the .dll?

    [System.Reflection.AssemblyName]::GetAssemblyName($Path).FullName;

Or:

Add-Type $Path -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
  1. If I know the strong name, how do I determine the .dll path?

    [Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a').Location;

  2. And, on a similar vein, if I know the type name of what I'm using, how do I know what assembly it's coming from?

    [Reflection.Assembly]::GetAssembly([Type]).Location [Reflection.Assembly]::GetAssembly([Type]).FullName

  3. How do I see what assemblies are available?

I suggest the GAC PowerShell module. Get-GacAssembly -Name 'Microsoft.SqlServer.Smo*' | Select Name, Version, FullName works pretty well.

  1. How can I see the list that Add-Type uses?

This is a bit more complex. I can describe how to access it for any version of PowerShell with a .Net reflector (see the update below for PowerShell Core 6.0).

First, figure out which library Add-Type comes from:

Get-Command -Name Add-Type | Select-Object -Property DLL

Open the resulting DLL with your reflector. I've used ILSpy for this because it's FLOSS, but any C# reflector should work. Open that library, and look in Microsoft.Powershell.Commands.Utility. Under Microsoft.Powershell.Commands, there should be AddTypeCommand.

In the code listing for that, there is a private class, InitializeStrongNameDictionary(). That lists the dictionary that maps the short names to the strong names. There's almost 750 entries in the library I've looked at.

Update: Now that PowerShell Core 6.0 is open source. For that version, you can skip the above steps and see the code directly online in their GitHub repository. I can't guarantee that that code matches any other version of PowerShell, however.

Update 2: Powershell 7+ does not appear to have the hash table lookup any longer. Instead they use a LoadAssemblyHelper() method which the comments call "the closest approximation possible" to LoadWithPartialName. Basically, they do this:

loadedAssembly = Assembly.Load(new AssemblyName(assemblyName));

Now, the comments also say "users can just say Add-Type -AssemblyName Forms (instead of System.Windows.Forms)". However, that's not what I see in Powershell v7.0.3 on Windows 10 2004.

# Returns an error
Add-Type -AssemblyName Forms

# Returns an error
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('Forms'))

# Works fine
Add-Type -AssemblyName System.Windows.Forms

# Works fine
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('System.Windows.Forms'))

So the comments appear to be a bit of a mystery.

I don't know exactly what the logic is in Assembly.Load(AssemblyName) when there is no version or public key token specified. I would expect that this has many of the same problems that LoadWithPartialName does like potentially loading the wrong version of the assembly if you have multiple installed.

How to resize the jQuery DatePicker control

Not sure whether some body has suggested following way, if yes, just ignore my comments. I tested this today and it works for me. By just resizing the font before the control gets displayed:

$('#event_date').datepicker({
    showButtonPanel: true,
    dateFormat: "mm/dd/yy",
    beforeShow: function(){    
           $(".ui-datepicker").css('font-size', 12) 
    }
});

Using the callback function beforeShow

Add new item in existing array in c#.net

Since this question not satisfied with provided answer, I would like to add this answer :)

public class CustomArrayList<T> 
 {  
   private T[] arr;  private int count;  

public int Count  
  {   
    get   
      {    
        return this.count;   
      }  
   }  
 private const int INITIAL_CAPACITY = 4;  

 public CustomArrayList(int capacity = INITIAL_CAPACITY) 
 {  
    this.arr = new T[capacity];   this.count = 0; 
  } 

 public void Add(T item) 
  {  
    GrowIfArrIsFull();  
   this.arr[this.count] = item;  this.count++; 
  }  

public void Insert(int index, T item) 
{  
 if (index > this.count || index < 0)  
    {   
      throw new IndexOutOfRangeException(    "Invalid index: " + index);  
     }  
     GrowIfArrIsFull();  
     Array.Copy(this.arr, index,   this.arr, index + 1, this.count - index);          
    this.arr[index] = item;  this.count++; }  

    private void GrowIfArrIsFull() 
    {  
    if (this.count + 1 > this.arr.Length)  
    {   
      T[] extendedArr = new T[this.arr.Length * 2];  
      Array.Copy(this.arr, extendedArr, this.count);  
      this.arr = extendedArr;  
    } 
  }
 }
}

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

AngularJS - value attribute for select

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):

HTML:

<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

Javascript:

App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>

and

<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.

Can you force Visual Studio to always run as an Administrator in Windows 8?

I know this is a little late, but I just figured out how to do this by modifying (read, "hacking") the manifest of the devenv.exe file. I should have come here first because the stated solutions seem a little easier, and probably more supported by Microsoft. :)

Here's how I did it:

  1. Create a project in VS called "Exe Manifests". (I think any version will work, but I used 2013 Pro. Also, it doesn't really matter what you name it.)
  2. "Add existing item" to the project, browse to the Visual Studio exe, and click Okay. In my case, it was "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe".
  3. Double-click on the "devenv.exe" file that should now be listed as a file in your project. It should bring up the exe in a resource editor.
  4. Expand the "RT_MANIFEST" node, then double-click on "1" under that. This will open up the executable's manifest in the binary editor.
  5. Find the requestedExecutionLevel tag and replace "asInvoker" with "requireAdministrator". A la: <requestedExecutionLevel level="requireAdministrator" uiAccess="false"></requestedExecutionLevel>
  6. Save the file.

You've just saved the copy of the executable that was added to your project. Now you need to back up the original and copy your modified exe to your installation directory.

As I said, this is probably not the right way to do it, but it seems to work. If anyone knows of any negative fallout or requisite wrist-slapping that needs to happen, please chime in!

The requested URL /about was not found on this server

**Solved Permalink Issue Wordpress ** 1) Login to wordpress dashboard > click on settings > premalinks > then select post name. 2) After that login to your hosting server goto .htaccess file and replace the code.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Can I stop 100% Width Text Boxes from extending beyond their containers?

This works:

<div>
    <input type="text" 
        style="margin: 5px; padding: 4px; border: 1px solid; 
        width: 200px; width: calc(100% - 20px);">
</div>

The first 'width' is a fallback rule for older browsers.

How do I read a response from Python Requests?

If you push for example image to some API and want the result address(response) back you could do:

import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Capturing count from an SQL query

Use SqlCommand.ExecuteScalar() and cast it to an int:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Using "If cell contains" in VBA excel

This will loop through all cells in a given range that you define ("RANGE TO SEARCH") and add dashes at the cell below using the Offset() method. As a best practice in VBA, you should never use the Select method.

Sub AddDashes()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("RANGE TO SEARCH")

For Each cel In SrchRng
    If InStr(1, cel.Value, "TOTAL") > 0 Then
        cel.Offset(1, 0).Value = "-"
    End If
Next cel

End Sub

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

How to download fetch response in react as file

Browser technology currently doesn't support downloading a file directly from an Ajax request. The work around is to add a hidden form and submit it behind the scenes to get the browser to trigger the Save dialog.

I'm running a standard Flux implementation so I'm not sure what the exact Redux (Reducer) code should be, but the workflow I just created for a file download goes like this...

  1. I have a React component called FileDownload. All this component does is render a hidden form and then, inside componentDidMount, immediately submit the form and call it's onDownloadComplete prop.
  2. I have another React component, we'll call it Widget, with a download button/icon (many actually... one for each item in a table). Widget has corresponding action and store files. Widget imports FileDownload.
  3. Widget has two methods related to the download: handleDownload and handleDownloadComplete.
  4. Widget store has a property called downloadPath. It's set to null by default. When it's value is set to null, there is no file download in progress and the Widget component does not render the FileDownload component.
  5. Clicking the button/icon in Widget calls the handleDownload method which triggers a downloadFile action. The downloadFile action does NOT make an Ajax request. It dispatches a DOWNLOAD_FILE event to the store sending along with it the downloadPath for the file to download. The store saves the downloadPath and emits a change event.
  6. Since there is now a downloadPath, Widget will render FileDownload passing in the necessary props including downloadPath as well as the handleDownloadComplete method as the value for onDownloadComplete.
  7. When FileDownload is rendered and the form is submitted with method="GET" (POST should work too) and action={downloadPath}, the server response will now trigger the browser's Save dialog for the target download file (tested in IE 9/10, latest Firefox and Chrome).
  8. Immediately following the form submit, onDownloadComplete/handleDownloadComplete is called. This triggers another action that dispatches a DOWNLOAD_FILE event. However, this time downloadPath is set to null. The store saves the downloadPath as null and emits a change event.
  9. Since there is no longer a downloadPath the FileDownload component is not rendered in Widget and the world is a happy place.

Widget.js - partial code only

import FileDownload from './FileDownload';

export default class Widget extends Component {
    constructor(props) {
        super(props);
        this.state = widgetStore.getState().toJS();
    }

    handleDownload(data) {
        widgetActions.downloadFile(data);
    }

    handleDownloadComplete() {
        widgetActions.downloadFile();
    }

    render() {
        const downloadPath = this.state.downloadPath;

        return (

            // button/icon with click bound to this.handleDownload goes here

            {downloadPath &&
                <FileDownload
                    actionPath={downloadPath}
                    onDownloadComplete={this.handleDownloadComplete}
                />
            }
        );
    }

widgetActions.js - partial code only

export function downloadFile(data) {
    let downloadPath = null;

    if (data) {
        downloadPath = `${apiResource}/${data.fileName}`;
    }

    appDispatcher.dispatch({
        actionType: actionTypes.DOWNLOAD_FILE,
        downloadPath
    });
}

widgetStore.js - partial code only

let store = Map({
    downloadPath: null,
    isLoading: false,
    // other store properties
});

class WidgetStore extends Store {
    constructor() {
        super();
        this.dispatchToken = appDispatcher.register(action => {
            switch (action.actionType) {
                case actionTypes.DOWNLOAD_FILE:
                    store = store.merge({
                        downloadPath: action.downloadPath,
                        isLoading: !!action.downloadPath
                    });
                    this.emitChange();
                    break;

FileDownload.js
- complete, fully functional code ready for copy and paste
- React 0.14.7 with Babel 6.x ["es2015", "react", "stage-0"]
- form needs to be display: none which is what the "hidden" className is for

import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';

function getFormInputs() {
    const {queryParams} = this.props;

    if (queryParams === undefined) {
        return null;
    }

    return Object.keys(queryParams).map((name, index) => {
        return (
            <input
                key={index}
                name={name}
                type="hidden"
                value={queryParams[name]}
            />
        );
    });
}

export default class FileDownload extends Component {

    static propTypes = {
        actionPath: PropTypes.string.isRequired,
        method: PropTypes.string,
        onDownloadComplete: PropTypes.func.isRequired,
        queryParams: PropTypes.object
    };

    static defaultProps = {
        method: 'GET'
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).submit();
        this.props.onDownloadComplete();
    }

    render() {
        const {actionPath, method} = this.props;

        return (
            <form
                action={actionPath}
                className="hidden"
                method={method}
            >
                {getFormInputs.call(this)}
            </form>
        );
    }
}

Skip a submodule during a Maven build

Sure, this can be done using profiles. You can do something like the following in your parent pom.xml.

  ...
   <modules>
      <module>module1</module>
      <module>module2</module>  
      ...
  </modules>
  ...
  <profiles>
     <profile>
       <id>ci</id>
          <modules>
            <module>module1</module>
            <module>module2</module>
            ...
            <module>module-integration-test</module>
          </modules> 
      </profile>
  </profiles>
 ...

In your CI, you would run maven with the ci profile, i.e. mvn -P ci clean install

How to get ID of the last updated row in MySQL?

This is the same method as Salman A's answer, but here's the code you actually need to do it.

First, edit your table so that it will automatically keep track of whenever a row is modified. Remove the last line if you only want to know when a row was initially inserted.

ALTER TABLE mytable
ADD lastmodified TIMESTAMP 
    DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP;

Then, to find out the last updated row, you can use this code.

SELECT id FROM mytable ORDER BY lastmodified DESC LIMIT 1;

This code is all lifted from MySQL vs PostgreSQL: Adding a 'Last Modified Time' Column to a Table and MySQL Manual: Sorting Rows. I just assembled it.

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>
  </div>
</div>

.relative-parent {
  position:relative;
}
.hiding-parent {
  overflow:hidden;
}
.child {
  position:absolute; 
}

Remove large .pack file created by git

I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/

Redirect after Login on WordPress

// add the code to your theme function.php
//for logout redirection
add_action('wp_logout','auto_redirect_after_logout');
function auto_redirect_after_logout(){
wp_redirect( home_url() );
exit();
}
//for login redirection
add_action('wp_login','auto_redirect_after_login');
function auto_redirect_after_login(){
wp_redirect( home_url() );
exit();
`enter code here`}

What is an Intent in Android?

In a broad view, we can define Intent as

When one Activity wants to start another activity it creates an Object called Intent that specifies which Activity it wants to start.

How to refresh an access form

I recommend that you use REQUERY the specific combo box whose data you have changed AND that you do it after the Cmd.Close statement. that way, if you were inputing data, that data is also requeried.

DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery

you might also want to point to the recently changed value

Dim id As Integer
id = Me.[Index_Field]
DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery
Forms![Form_Name]![Combo_Box_Name] = id

this example supposes that you opened a form to input data into a secondary table.

let us say you save School_Index and School_Name in a School table and refer to it in a Student table (which contains only the School_Index field). while you are editing a student, you need to associate him with a school that is not in your School table, etc etc

How to change angular port from 4200 to any other

you can also write this command: ng serve -p 5000

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How to search a Git repository by commit message?

git log --grep="Build 0051"

should do the trick

Find records with a date field in the last 24 hours

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)

How to create python bytes object from long hex string?

import binascii

binascii.a2b_hex(hex_string)

Thats the way I did it.

In C, how should I read a text file and print all strings

There are plenty of good answers here about reading it in chunks, I'm just gonna show you a little trick that reads all the content at once to a buffer and prints it.

I'm not saying it's better. It's not, and as Ricardo sometimes it can be bad, but I find it's a nice solution for the simple cases.

I sprinkled it with comments because there's a lot going on.

#include <stdio.h>
#include <stdlib.h>

char* ReadFile(char *filename)
{
   char *buffer = NULL;
   int string_size, read_size;
   FILE *handler = fopen(filename, "r");

   if (handler)
   {
       // Seek the last byte of the file
       fseek(handler, 0, SEEK_END);
       // Offset from the first to the last byte, or in other words, filesize
       string_size = ftell(handler);
       // go back to the start of the file
       rewind(handler);

       // Allocate a string that can hold it all
       buffer = (char*) malloc(sizeof(char) * (string_size + 1) );

       // Read it all in one operation
       read_size = fread(buffer, sizeof(char), string_size, handler);

       // fread doesn't set it so put a \0 in the last position
       // and buffer is now officially a string
       buffer[string_size] = '\0';

       if (string_size != read_size)
       {
           // Something went wrong, throw away the memory and set
           // the buffer to NULL
           free(buffer);
           buffer = NULL;
       }

       // Always remember to close the file.
       fclose(handler);
    }

    return buffer;
}

int main()
{
    char *string = ReadFile("yourfile.txt");
    if (string)
    {
        puts(string);
        free(string);
    }

    return 0;
}

Let me know if it's useful or you could learn something from it :)

Constants in Kotlin -- what's a recommended way to create them?

You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const.

So, in this case, it should be:

const val MY_CONST = "something"

and then you can import the constant using:

import package_name.MY_CONST

You can refer to this link

Gradle does not find tools.jar

Did you make sure that tools.jar made it on the compile class path? Maybe the path is incorrect.

task debug << {
    configurations.compile.each { println it }
}

Where does Chrome store extensions?

This link "Finding All Installed Browsers in Windows XP and Vista – beware 64bit!" may be useful for Windows as suggested by "How to find all the browsers installed on a machine".

The installed web browsers are saved in this registry,

HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet

HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Clients\StartMenuInternet.

How can I add new array elements at the beginning of an array in Javascript?

array operations image

_x000D_
_x000D_
var a = [23, 45, 12, 67];_x000D_
a.unshift(34);_x000D_
console.log(a); // [34, 23, 45, 12, 67]
_x000D_
_x000D_
_x000D_

How to store a command in a variable in a shell script?

First of all there are functions for this. But if you prefer vars then your task can be done like this:

$ cmd=ls

$ $cmd # works
file  file2  test

$ cmd='ls | grep file'

$ $cmd # not works
ls: cannot access '|': No such file or directory
ls: cannot access 'grep': No such file or directory
 file

$ bash -c $cmd # works
file  file2  test

$ bash -c "$cmd" # also works
file
file2

$ bash <<< $cmd
file
file2

$ bash <<< "$cmd"
file
file2

Or via tmp file

$ tmp=$(mktemp)
$ echo "$cmd" > "$tmp"
$ chmod +x "$tmp"
$ "$tmp"
file
file2

$ rm "$tmp"

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

And I simply got this error because I used a totally different DocumentRoot directory.

My main DocumentRoot was the default /var/www/html and on the VirtualHost I used /sites/example.com

I have created a link on /var/www/html/example.com (to /sites/example.com). DocumentRoot was set to /var/www/html/example.com

It worked like a charm.

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

This one helped for me

//System.Web.HttpContext.Current.Server.MapPath //        
FileStream fileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/File.txt"),
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

What does <T> denote in C#

This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

Child inside parent with min-height: 100% not inheriting height

This is a reported webkit (chrome/safari) bug, children of parents with min-height can't inherit the height property: https://bugs.webkit.org/show_bug.cgi?id=26559

Apparently Firefox is affected too (can't test in IE at the moment)

Possible workaround:

  • add position:relative to #containment
  • add position:absolute to #containment-shadow-left

The bug doesn't show when the inner element has absolute positioning.

See http://jsfiddle.net/xrebB/

Edit on April 10, 2014

Since I'm currently working on a project for which I really need parent containers with min-height, and child elements inheriting the height of the container, I did some more research.

First: I'm not so sure anymore whether the current browser behaviour really is a bug. CSS2.1 specs say:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

If I put a min-height on my container, I'm not explicitly specifying its height - so my element should get an auto height. And that's exactly what Webkit - and all other browsers - do.

Second, the workaround I found:

If I set my container element to display:table with height:inherit it acts exactly the same way as if I'd give it a min-height of 100%. And - more importantly - if I set the child element to display:table-cell it will perfectly inherit the height of the container element - whether it's 100% or more.

Full CSS:

html, body {
  height: 100%;
  margin: 0;
}

#container {
  background: green;
  display: table;
  height: inherit;
  width: 100%;
}

#content {
  background: red;
  display: table-cell;
}

The markup:

<div id="container">
  <div id="content">
      <p>content</p>
  </div>
</div>

See http://jsfiddle.net/xrebB/54/.

A full list of all the new/popular databases and their uses?

The SQLite database engine

With library for most popular languages

  • .Net
  • perl
  • Feel free to edit this and add more links

"for loop" with two variables?

for (i,j) in [(i,j) for i in range(x) for j in range(y)]

should do it.

Concat scripts in order with Gulp

I have used the gulp-order plugin but it is not always successful as you can see by my stack overflow post gulp-order node module with merged streams. When browsing through the Gulp docs I came across the streamque module which has worked quite well for specifying order of in my case concatenation. https://github.com/gulpjs/gulp/blob/master/docs/recipes/using-multiple-sources-in-one-task.md

Example of how I used it is below

var gulp         = require('gulp');
var concat       = require('gulp-concat');
var handleErrors = require('../util/handleErrors');
var streamqueue  = require('streamqueue');

gulp.task('scripts', function() {
    return streamqueue({ objectMode: true },
        gulp.src('./public/angular/config/*.js'),
        gulp.src('./public/angular/services/**/*.js'),
        gulp.src('./public/angular/modules/**/*.js'),
        gulp.src('./public/angular/primitives/**/*.js'),
        gulp.src('./public/js/**/*.js')
    )
        .pipe(concat('app.js'))
        .pipe(gulp.dest('./public/build/js'))
        .on('error', handleErrors);
});

Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

Simple way to compare 2 ArrayLists

This should check if two lists are equal, it does some basic checks first (i.e. nulls and lengths), then sorts and uses the collections.equals method to check if they are equal.

public  boolean equalLists(List<String> a, List<String> b){     
    // Check for sizes and nulls

    if (a == null && b == null) return true;


    if ((a == null && b!= null) || (a != null && b== null) || (a.size() != b.size()))
    {
        return false;
    }

    // Sort and compare the two lists          
    Collections.sort(a);
    Collections.sort(b);      
    return a.equals(b);
}

How to configure nginx to enable kinda 'file browser' mode?

1. List content of all directories

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default ) should be like this

location /{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

2. List content of only some specific directory

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default )
should be like this.
change path_of_your_directory to your directory path

location /path_of_your_directory{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

Hope it helps..

Android List View Drag and Drop sort

The DragListView lib does this really neat with very nice support for custom animations such as elevation animations. It is also still maintained and updated on a regular basis.

Here is how you use it:

1: Add the lib to gradle first

dependencies {
    compile 'com.github.woxthebox:draglistview:1.2.1'
}

2: Add list from xml

<com.woxthebox.draglistview.DragListView
    android:id="@+id/draglistview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

3: Set the drag listener

mDragListView.setDragListListener(new DragListView.DragListListener() {
    @Override
    public void onItemDragStarted(int position) {
    }

    @Override
    public void onItemDragEnded(int fromPosition, int toPosition) {
    }
});

4: Create an adapter overridden from DragItemAdapter

public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>
    public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
        super(dragOnLongPress);
        mLayoutId = layoutId;
        mGrabHandleId = grabHandleId;
        setHasStableIds(true);
        setItemList(list);
}

5: Implement a viewholder that extends from DragItemAdapter.ViewHolder

public class ViewHolder extends DragItemAdapter.ViewHolder {
    public TextView mText;

    public ViewHolder(final View itemView) {
        super(itemView, mGrabHandleId);
        mText = (TextView) itemView.findViewById(R.id.text);
    }

    @Override
    public void onItemClicked(View view) {
    }

    @Override
    public boolean onItemLongClicked(View view) {
        return true;
    }
}

For more detailed info go to https://github.com/woxblom/DragListView

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

JavaScript - cannot set property of undefined

d = {} is an empty object right now.

And d[a] is also an empty object.

It does not have any key values. So you should initialize the key values to this.

d[a] = {
greetings:'',
data:''
}

Python : List of dict, if exists increment a dict value, if not append a new dict

That is a very strange way to organize things. If you stored in a dictionary, this is easy:

# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
    if not url in urls_d:
        urls_d[url] = 1
    else:
        urls_d[url] += 1

This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict, created just to make this even easier:

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

If you access the defaultdict using a key, and the key is not already in the defaultdict, the key is automatically added with a default value. The defaultdict takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int; when Python calls int() it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.

But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter You just create a Counter instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:

from collections import Counter  # available in Python 2.7 and newer

urls_d = Counter(list_of_urls)

If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]

If you are using Python 2.7 or newer you can do it in a one-liner:

from collections import Counter

urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]

Is there a RegExp.escape function in JavaScript?

Most of the expressions here solve single specific use cases.

That's okay, but I prefer an "always works" approach.

function regExpEscape(literal_string) {
    return literal_string.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
}

This will "fully escape" a literal string for any of the following uses in regular expressions:

  • Insertion in a regular expression. E.g. new RegExp(regExpEscape(str))
  • Insertion in a character class. E.g. new RegExp('[' + regExpEscape(str) + ']')
  • Insertion in integer count specifier. E.g. new RegExp('x{1,' + regExpEscape(str) + '}')
  • Execution in non-JavaScript regular expression engines.

Special Characters Covered:

  • -: Creates a character range in a character class.
  • [ / ]: Starts / ends a character class.
  • { / }: Starts / ends a numeration specifier.
  • ( / ): Starts / ends a group.
  • * / + / ?: Specifies repetition type.
  • .: Matches any character.
  • \: Escapes characters, and starts entities.
  • ^: Specifies start of matching zone, and negates matching in a character class.
  • $: Specifies end of matching zone.
  • |: Specifies alternation.
  • #: Specifies comment in free spacing mode.
  • \s: Ignored in free spacing mode.
  • ,: Separates values in numeration specifier.
  • /: Starts or ends expression.
  • :: Completes special group types, and part of Perl-style character classes.
  • !: Negates zero-width group.
  • < / =: Part of zero-width group specifications.

Notes:

  • / is not strictly necessary in any flavor of regular expression. However, it protects in case someone (shudder) does eval("/" + pattern + "/");.
  • , ensures that if the string is meant to be an integer in the numerical specifier, it will properly cause a RegExp compiling error instead of silently compiling wrong.
  • #, and \s do not need to be escaped in JavaScript, but do in many other flavors. They are escaped here in case the regular expression will later be passed to another program.

If you also need to future-proof the regular expression against potential additions to the JavaScript regex engine capabilities, I recommend using the more paranoid:

function regExpEscapeFuture(literal_string) {
    return literal_string.replace(/[^A-Za-z0-9_]/g, '\\$&');
}

This function escapes every character except those explicitly guaranteed not be used for syntax in future regular expression flavors.


For the truly sanitation-keen, consider this edge case:

var s = '';
new RegExp('(choice1|choice2|' + regExpEscape(s) + ')');

This should compile fine in JavaScript, but will not in some other flavors. If intending to pass to another flavor, the null case of s === '' should be independently checked, like so:

var s = '';
new RegExp('(choice1|choice2' + (s ? '|' + regExpEscape(s) : '') + ')');

SQL Server procedure declare a list

If you want input comma separated string as input & apply in in query in that then you can make Function like:

create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
    returns @temptable TABLE (items varchar(MAX))       
    as       
    begin      
        declare @idx int       
        declare @slice varchar(8000)       

        select @idx = 1       
            if len(@String)<1 or @String is null  return       

        while @idx!= 0       
        begin       
            set @idx = charindex(@Delimiter,@String)       
            if @idx!=0       
                set @slice = left(@String,@idx - 1)       
            else       
                set @slice = @String       

            if(len(@slice)>0)  
                insert into @temptable(Items) values(@slice)       

            set @String = right(@String,len(@String) - @idx)       
            if len(@String) = 0 break       
        end   
    return 
    end;

You can use it like :

Declare @Values VARCHAR(MAX);

set @Values ='1,2,5,7,10';
Select * from DBTable
    Where id  in (select items from [dbo].[Split] (@Values, ',') )

Alternatively if you don't have comma-separated string as input, You can try Table variable OR TableType Or Temp table like: INSERT using LIST into Stored Procedure