Programs & Examples On #Formcollection

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

ASP.Net MVC - Read File from HttpPostedFileBase without save

An alternative is to use StreamReader.

public void FunctionName(HttpPostedFileBase file)
{
    string result = new StreamReader(file.InputStream).ReadToEnd();
}

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

How to convert List<string> to List<int>?

This may be overkill for this simple problem. But for Try-Do methods in connection with Linq, I tend to use anonymous classes for more expressive code. It is similar to the answers from Olivier Jacot-Descombes and BA TabNabber:

List<int> ints = strings
    .Select(idString => new { ParseSuccessful = Int32.TryParse(idString, out var id), Value = id })
    .Where(id => id.ParseSuccessful)
    .Select(id => id.Value)
    .ToList();

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

This code helped find my problem when I had issue with my Entity VAlidation Erros. It told me the exact problem with my Entity Definition. Try following code where you need to cover storeDB.SaveChanges(); in following try catch block.

  try
{
         if (TryUpdateModel(theEvent))
         {
             storeDB.SaveChanges();
             return RedirectToAction("Index");
         }
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
    Exception raise = dbEx;
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            string message = string.Format("{0}:{1}", 
                validationErrors.Entry.Entity.ToString(),
                validationError.ErrorMessage);
            // raise a new exception nesting
            // the current instance as InnerException
            raise = new InvalidOperationException(message, raise);
        }
    }
    throw raise;
}

How to handle checkboxes in ASP.NET MVC forms?

I know that this question was written when MVC3 wasn't out, but for anyone who comes to this question and are using MVC3, you may want the "correct" way to do this.

While I think that doing the whole

Contains("true");

thing is great and clean, and works on all MVC versions, the problem is that it doesn't take culture into account (as if it really matters in the case of a bool).

The "correct" way to figure out the value of a bool, at least in MVC3, is to use the ValueProvider.

var value = (bool)ValueProvider.GetValue("key").ConvertTo(typeof(bool));

I do this in one of my client's sites when I edit permissions:

var allPermissionsBase = Request.Params.AllKeys.Where(x => x.Contains("permission_")).ToList();
var allPermissions = new List<KeyValuePair<int, bool>>();

foreach (var key in allPermissionsBase)
{
     // Try to parse the key as int
     int keyAsInt;
     int.TryParse(key.Replace("permission_", ""), out keyAsInt);

     // Try to get the value as bool
     var value = (bool)ValueProvider.GetValue(key).ConvertTo(typeof(bool));
}

Now, the beauty of this is you can use this with just about any simple type, and it will even be correct based on the Culture (think money, decimals, etc).

The ValueProvider is what is used when you form your Actions like this:

public ActionResult UpdatePermissions(bool permission_1, bool permission_2)

but when you are trying to dynamically build these lists and check the values, you will never know the Id at compile time, so you have to process them on the fly.

Erase the current printed console line

You can use a \r (carriage return) to return the cursor to the beginning of the line:

printf("hello");
printf("\rbye");

This will print bye on the same line. It won't erase the existing characters though, and because bye is shorter than hello, you will end up with byelo. To erase it you can make your new print longer to overwrite the extra characters:

printf("hello");
printf("\rbye  ");

Or, first erase it with a few spaces, then print your new string:

printf("hello");
printf("\r          ");
printf("\rbye");

That will print hello, then go to the beginning of the line and overwrite it with spaces, then go back to the beginning again and print bye.

Should I URL-encode POST data?

General Answer

The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers.

A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string. A value of "multipart/form-data" means that you'll be using content delimiters and NOT url encoding the content.

This answer has a much more thorough explanation if you'd like more information.


Specific Answer

For an answer specific to the PHP libraries you're using (CURL), you should read the documentation here.

Here's the relevant information:

CURLOPT_POST

TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

Is it possible to interactively delete matching search pattern in Vim?

The best way is probably to use:

:%s/phrase//gc

c asks for confirmation before each deletion. g allows multiple replacements to occur on the same line.

You can also just search using /phrase, select the next match with gn, and delete it with d.

Restricting JTextField input to Integers

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

For example: using-documentfilter-filterbypass

Also for tutorial help, please look at: Implementing a DocumentFilter.

Edit

For instance:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
   public static void main(String[] args) {
      JTextField textField = new JTextField(10);

      JPanel panel = new JPanel();
      panel.add(textField);

      PlainDocument doc = (PlainDocument) textField.getDocument();
      doc.setDocumentFilter(new MyIntFilter());


      JOptionPane.showMessageDialog(null, panel);
   }
}

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

Why is this important?

  • What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?
  • You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?
  • What if you want to allow the user to later enter double data? In scientific notation?

Change Activity's theme programmatically

As docs say you have to call setTheme before any view output. It seems that super.onCreate() takes part in view processing.

So, to switch between themes dynamically you simply need to call setTheme before super.onCreate like this:

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}

Transposing a 1D NumPy array

Another solution.... :-)

import numpy as np

a = [1,2,4]

[1, 2, 4]

b = np.array([a]).T

array([[1], [2], [4]])

AttributeError: 'module' object has no attribute 'model'

I also got the same error but I noticed that I had typed in Foreign*k*ey and not Foreign*K*ey,(capital K) if there is a newbie out there, check out spelling and caps.

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

How to check if a column exists in a SQL Server table?

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'TableName'
             AND table_schema = 'SchemaName'
             AND column_name = 'ColumnName')  BEGIN

  ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';

END;

JavaScript/jQuery - How to check if a string contain specific words

An easy way to do it to use Regex match() method :-

For Example

var str ="Hi, Its stacks over flow and stackoverflow Rocks."

// It will check word from beginning to the end of the string

if(str.match(/(^|\W)stack($|\W)/)) {

        alert('Word Match');
}else {

        alert('Word not found');
}

Check the fiddle

NOTE: For adding case sensitiveness update the regex with /(^|\W)stack($|\W)/i

Thanks

Running stages in parallel with Jenkins workflow / pipeline

As @Quartz mentioned, you can do something like

stage('Tests') {
    parallel(
        'Unit Tests': {
            container('node') {
                sh("npm test --cat=unit")
            }
        },
        'API Tests': {
            container('node') {
                sh("npm test --cat=acceptance")
            }
        }
    )
}

What does LayoutInflater in Android do?

here is an example for geting a refrence for the root View of a layout , inflating it and using it with setContentView(View view)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater li=getLayoutInflater();
    View rootView=li.inflate(R.layout.activity_main,null);
    setContentView(rootView);


}

How to get length of a string using strlen function

Manually:

int strlen(string s)
{
    int len = 0;

    while (s[len])
        len++;

    return len;
}

datetime dtypes in pandas read_csv

I tried using the dtypes=[datetime, ...] option, but

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

I encountered the following error:

TypeError: data type not understood

The only change I had to make is to replace datetime with datetime.datetime

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime.datetime, datetime.datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

How to add days to the current date?

From the SQL Server 2017 official documentation:

SELECT DATEADD(day, 360, GETDATE());

If you would like to remove the time part of the GETDATE function, you can do:

SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));

How to vertically center content with variable height within a div?

Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered class name to elements I want to center:

_x000D_
_x000D_
.contentCentered {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.contentCentered::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
.contentCentered > * {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div class="contentCentered">_x000D_
  <div>_x000D_
    <h1>Some text</h1>_x000D_
    <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
      shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
      towards that ship a while ago?"</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Forked CodePen: http://codepen.io/dougli/pen/Eeysg

Getting Raw XML From SOAPMessage in Java

It is pretty old thread but recently i had a similar issue. I was calling a downstream soap service, from a rest service, and I needed to return the xml response coming from the downstream server as is.

So, i ended up adding a SoapMessageContext handler to get the XML response. Then i injected the response xml into servlet context as an attribute.

public boolean handleMessage(SOAPMessageContext context) {

            // Get xml response
            try {

                ServletContext servletContext =
                        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();

                SOAPMessage msg = context.getMessage();

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                msg.writeTo(out);
                String strMsg = new String(out.toByteArray());

                servletContext.setAttribute("responseXml", strMsg);

                return true;
            } catch (Exception e) {
                return false;
            }
        }

Then I have retrieved the xml response string in the service layer.

ServletContext servletContext =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();

        String msg = (String) servletContext.getAttribute("responseXml");

Didn't have chance to test it yet but this approach must be thread safe since it is using the servlet context.

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

Because python checks in the directories in sequential order starting at the first directory in sys.path list, till it find the .py file it was looking for.

Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So, most probably, you had a .py file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).

Also, a thing to note about ImportErrors , lets say the import error says - ImportError: No module named main - it doesn't mean the main.py is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py or some other file.

Example -

My directory structure looks like -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py

Now From testmain.py , I call from shared import phtest , it works fine.

Now lets say I introduce a shared.py in test directory` , example -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py 
  - shared.py

Now when I try to do from shared import phtest from testmain.py , I will get the error -

ImportError: cannot import name 'phtest'

As you can see above, the file that is causing the issue is shared.py , not phtest.py .

Defining a HTML template to append using JQuery

Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.

While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for), conditionals (<% if) and transforms (<%= myString | uppercase %>) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).

Templates Inside HTML

One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script> type, e.g. <script type="text/template">. For your case:

<script type="text/template" data-template="listitem">
    <a href="${url}" class="list-group-item">
        <table>
            <tr>
                <td><img src="${img}"></td>
                <td><p class="list-group-item-text">${title}</p></td>
            </tr>
        </table>
    </a>
</script>

On document load, read your template and tokenize it using a simple String#split

var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);

Notice that with our token, you get it in the alternating [text, property, text, property] format. This lets us nicely map it using an Array#map, with a mapping function:

function render(props) {
  return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}

Where props could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }.

Putting it all together assuming you've parsed and loaded your itemTpl as above, and you have an items array in-scope:

$('.search').keyup(function () {
  $('.list-items').append(items.map(function (item) {
    return itemTpl.map(render(item)).join('');
  }));
});

This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector and .innerHTML.

jsfiddle

Templates inside JS

A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.

In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html method above.

const Item = ({ url, img, title }) => `
  <a href="${url}" class="list-group-item">
    <div class="image">
      <img src="${img}" />
    </div>
    <p class="list-group-item-text">${title}</p>
  </a>
`;

Then you could easily render it, even mapped from an array, like so:

$('.list-items').html([
  { url: '/foo', img: 'foo.png', title: 'Foo item' },
  { url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));

Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.

How to connect from windows command prompt to mysql command line

If you're not on exact root of C:/ drive then first of all use cd../.. and then use query mysql -u username -p passsword

using the above lines you can access to mysql database.

How do I update a Python package?

Use pipupgrade!

$ pip install pipupgrade
$ pipupgrade --latest --interactive

pipupgrade helps you upgrade your system, local or packages from a requirements.txt file! It also selectively upgrades packages that don't break change. Compatible with Python2.7+, Python3.4+ and pip9+, pip10+, pip18+.

enter image description here

NOTE: I'm the author of the tool.

How to indent HTML tags in Notepad++

I have a solution for you.

Just you need to install a plugin named Indent By Fold.

You can install this by going through Plugins -> Plugin Manager -> Show Plugin Manager. OR Plugins -> Plugins Admin -> chekmark Indent By Fold from list than install

Then just select the list item and all you need is to type the first word then you got it.

you can use this plugin from a plugin in the menu bar.


How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

With $array being the contents of a PSCustomObject, this works:

$dataGridView1.DataSource=[collections.arraylist]($array)
$dataGridView1.Columns | Foreach-Object{$_.AutoSizeMode = [System.Windows.Forms.DataGridViewAutoSizeColumnMode]::AllCells}

How to convert date to string and to date again?

Use DateFormat#parse(String):

Date date = dateFormat.parse("2013-10-22");

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Swift 3 & Xcode 8.3.2

This code will help you, i add an explanation too

// Create custom class, this will make your life easier
class CustomDelay {

    static let cd = CustomDelay()

    // This is your custom delay function
    func runAfterDelay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}


// here how to use it (Example 1)
class YourViewController: UIViewController {

    // example delay time 2 second
    let delayTime = 2.0

    override func viewDidLoad() {
        super.viewDidLoad()

        CustomDelay.cd.runAfterDelay(delayTime) {
            // This func will run after 2 second
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
            self.runFunc()
        }
    }

    // example function 1
    func runFunc() {
        // do your method 1 here
    }
}

// here how to use it (Example 2)
class YourSecondViewController: UIViewController {

    // let say you want to user run function shoot after 3 second they tap a button

    // Create a button (This is programatically, you can create with storyboard too)
    let shootButton: UIButton = {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 15, y: 15, width: 40, height: 40) // Customize where do you want to put your button inside your ui
        button.setTitle("Shoot", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // create an action selector when user tap shoot button
        shootButton.addTarget(self, action: #selector(shoot), for: .touchUpInside)   
    }

    // example shoot function
    func shoot() {
        // example delay time 3 second then shoot
        let delayTime = 3.0

        // delay a shoot after 3 second
        CustomDelay.cd.runAfterDelay(delayTime) {
            // your shoot method here
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
        }
    }   
}

JavaScript global event mechanism

Try Atatus which provides Advanced Error Tracking and Real User Monitoring for modern web apps.

https://www.atatus.com/

Let me explain how to get stacktraces that are reasonably complete in all browsers.

Error handling in JavaScript

Modern Chrome and Opera fully support the HTML 5 draft spec for ErrorEvent and window.onerror. In both of these browsers you can either use window.onerror, or bind to the 'error' event properly:

// Only Chrome & Opera pass the error object.
window.onerror = function (message, file, line, col, error) {
    console.log(message, "from", error.stack);
    // You can send data to your server
    // sendError(data);
};
// Only Chrome & Opera have an error attribute on the event.
window.addEventListener("error", function (e) {
    console.log(e.error.message, "from", e.error.stack);
    // You can send data to your server
    // sendError(data);
})

Unfortunately Firefox, Safari and IE are still around and we have to support them too. As the stacktrace is not available in window.onerror we have to do a little bit more work.

It turns out that the only thing we can do to get stacktraces from errors is to wrap all of our code in a try{ }catch(e){ } block and then look at e.stack. We can make the process somewhat easier with a function called wrap that takes a function and returns a new function with good error handling.

function wrap(func) {
    // Ensure we only wrap the function once.
    if (!func._wrapped) {
        func._wrapped = function () {
            try{
                func.apply(this, arguments);
            } catch(e) {
                console.log(e.message, "from", e.stack);
                // You can send data to your server
                // sendError(data);
                throw e;
            }
        }
    }
    return func._wrapped;
};

This works. Any function that you wrap manually will have good error handling, but it turns out that we can actually do it for you automatically in most cases.

By changing the global definition of addEventListener so that it automatically wraps the callback we can automatically insert try{ }catch(e){ } around most code. This lets existing code continue to work, but adds high-quality exception tracking.

var addEventListener = window.EventTarget.prototype.addEventListener;
window.EventTarget.prototype.addEventListener = function (event, callback, bubble) {
    addEventListener.call(this, event, wrap(callback), bubble);
}

We also need to make sure that removeEventListener keeps working. At the moment it won't because the argument to addEventListener is changed. Again we only need to fix this on the prototype object:

var removeEventListener = window.EventTarget.prototype.removeEventListener;
window.EventTarget.prototype.removeEventListener = function (event, callback, bubble) {
    removeEventListener.call(this, event, callback._wrapped || callback, bubble);
}

Transmit error data to your backend

You can send error data using image tag as follows

function sendError(data) {
    var img = newImage(),
        src = 'http://yourserver.com/jserror&data=' + encodeURIComponent(JSON.stringify(data));

    img.crossOrigin = 'anonymous';
    img.onload = function success() {
        console.log('success', data);
    };
    img.onerror = img.onabort = function failure() {
        console.error('failure', data);
    };
    img.src = src;
}

Disclaimer: I am a web developer at https://www.atatus.com/.

Changing the URL in react-router v4 without using Redirect or Link

This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.

<GridTile
  key={video_id}
  title={video_title}
  containerElement={<Link to={`/player/${video_id}`}/>}
 >

ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )

Why is Node.js single threaded?

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

How to remove trailing whitespace in code, using another script?

fileinput seems to be for multiple input streams. This is what I would do:

with open("test.txt") as file:
    for line in file:
        line = line.rstrip()
        if line:
            print(line)

How to combine two strings together in PHP?

1.Concatenate the string (space between each string)

Code Snippet :

<?php
 $txt1 = "Sachin";
 $txt2 = "Tendulkar";

 $result = $txt1.$txt2 ;
 echo  $result. "\n";
 ?>  

Output: SachinTendulkar

2.Concatenate the string where space exists

Code Snippet :

<?php
 $txt1 = "Sachin";
 $txt2 = "Tendulkar";

 $result = $txt1." ".$txt2; 
 echo  $result. "\n";
?>  

Output : Sachin Tendulkar

  1. Concatenate the string using printf function.

Code Snippet :

  <?php
 $data1 = "Sachin";
 $data2 = "Tendulkar";
 printf("%s%s\n",$data1, $data2);
 printf("%s %s\n",$data1, $data2); 
?>

Output:
SachinTendulkar
Sachin Tendulkar

Counting number of words in a file

The below code supports in Java 8

//Read file into String

String fileContent=new String(Files.readAlBytes(Paths.get("MyFile.txt")),StandardCharacters.UFT_8);

//Keeping these into list of strings by splitting with a delimiter

List<String> words = Arrays.asList(contents.split("\\PL+"));

int count=0;
for(String x: words){
 if(x.length()>1) count++;
}

sop(x);

Get program execution time in the shell

You can get much more detailed information than the bash built-in time (which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time.

Editor's note: To ensure that you're invoking the external utility time rather than your shell's time keyword, invoke it as /usr/bin/time.
time is a POSIX-mandated utility, but the only option it is required to support is -p.
Specific platforms implement specific, nonstandard extensions: -v works with GNU's time utility, as demonstrated below (the question is tagged ); the BSD/macOS implementation uses -l to produce similar output - see man 1 time.

Example of verbose output:

$ /usr/bin/time -v sleep 1
       Command being timed: "sleep 1"
       User time (seconds): 0.00
       System time (seconds): 0.00
       Percent of CPU this job got: 1%
       Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
       Average shared text size (kbytes): 0
       Average unshared data size (kbytes): 0
       Average stack size (kbytes): 0
       Average total size (kbytes): 0
       Maximum resident set size (kbytes): 0
       Average resident set size (kbytes): 0
       Major (requiring I/O) page faults: 0
       Minor (reclaiming a frame) page faults: 210
       Voluntary context switches: 2
       Involuntary context switches: 1
       Swaps: 0
       File system inputs: 0
       File system outputs: 0
       Socket messages sent: 0
       Socket messages received: 0
       Signals delivered: 0
       Page size (bytes): 4096
       Exit status: 0

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

When running into this error and reviewing my dataset which appeared to have no missing data, I discovered that a few of my entries had the special character "#" which derailed importing the data. Once I removed the "#" from the offending cells, the data imported without issue.

What should I do if the current ASP.NET session is null?

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

Java Comparator class to sort arrays

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Entity Framework The underlying provider failed on Open

If you are using a local .mdf file, probably a sync software such Dropbox attempted to sync two log files (.ldf) in two different computers you can delete the log files from the bin Directory and make sure the .mdf properties->Copy to Output Directory ->Copy if newer that will copy the selected DB file and it's log to the bin Directory. !Alert- if your DB file has only changed in the bin Directory all the changes ill be discarded!

:not(:empty) CSS selector is not working?

_x000D_
_x000D_
.floating-label-input {_x000D_
  position: relative;_x000D_
  height:60px;_x000D_
}_x000D_
.floating-label-input input {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: transparent;_x000D_
  border: 0 none;_x000D_
  outline: none;_x000D_
  vertical-align: middle;_x000D_
  font-size: 20px;_x000D_
  font-weight: bold;_x000D_
  padding-top: 10px;_x000D_
}_x000D_
.floating-label-input label {_x000D_
  position: absolute;_x000D_
  top: calc(50% - 5px);_x000D_
  font-size: 22px;_x000D_
  left: 0;_x000D_
  color: #000;_x000D_
  transition: all 0.3s;_x000D_
}_x000D_
.floating-label-input input:focus ~ label, .floating-label-input input:focus ~ label, .floating-label-input input:valid ~ label {_x000D_
  top: 0;_x000D_
  font-size: 15px;_x000D_
  color: #33bb55;_x000D_
}_x000D_
.floating-label-input .line {_x000D_
  position: absolute;_x000D_
  height: 1px;_x000D_
  width: 100%;_x000D_
  bottom: 0;_x000D_
  background: #000;_x000D_
  left: 0;_x000D_
}_x000D_
.floating-label-input .line:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  width: 0;_x000D_
  background: #33bb55;_x000D_
  height: 1px;_x000D_
  transition: all 0.5s;_x000D_
}_x000D_
.floating-label-input input:focus ~ .line:after, .floating-label-input input:focus ~ .line:after, .floating-label-input input:valid ~ .line:after {_x000D_
  width: 100%;_x000D_
}
_x000D_
<div class="floating-label-input">_x000D_
      <input type="text" id="id" required/>_x000D_
      <label for="id" >User ID</label>_x000D_
      <span class="line"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Send email by using codeigniter library via localhost

$insert = $this->db->insert('email_notification', $data);
                $this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");

                //require ("plugins/mailer/PHPMailerAutoload.php");
                $mail = new PHPMailer;
                $mail->SMTPOptions = array(
                    'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ),
                );

                $message="
                     Your Account Has beed created successfully by Admin:
                    Username: ".$this->input->post('username')." <br><br>
                    Email: ".$this->input->post('sender_email')." <br><br>
                    Regargs<br>
                    <div class='background-color:#666;color:#fff;padding:6px;
                    text-align:center;'>
                         Bookly Admin.
                    </div>
                ";
                $mail->isSMTP(); // Set mailer to use SMTP
                $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
                $mail->SMTPAuth = true; 
                $subject = "Hello  ".$this->input->post('username');
                $mail->SMTDebug=2;
                $email = $this->input->post('sender_email'); //this email is user email
                $from_label = "Account Creation";
                $mail->Username = 'your email'; // SMTP username
                $mail->Password = 'password'; // SMTP password
                $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 465;
                $mail->setFrom($from_label);
                $mail->addAddress($email, 'Bookly Admin');
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
             if($mail->send()){

                  }

hadoop copy a local file system folder to HDFS

To copy a folder file from local to hdfs, you can the below command

hadoop fs -put /path/localpath  /path/hdfspath

or

hadoop fs -copyFromLocal /path/localpath  /path/hdfspath

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

raw vs. html_safe vs. h to unescape html

Considering Rails 3:

html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.

h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" an html_safe declaration, pretty unusual.

Prepending your expression with raw is actually equivalent to calling to_s chained with html_safe on it, but is declared on a helper, just like h, so it can only be used on controllers and views.

"SafeBuffers and Rails 3.0" is a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

OSError [Errno 22] invalid argument when use open() in Python

Add 'r' in starting of path:

path = r"D:\Folder\file.txt"

That works for me.

How do I catch a PHP fatal (`E_ERROR`) error?

PHP doesn't provide conventional means for catching and recovering from fatal errors. This is because processing should not typically be recovered after a fatal error. String matching an output buffer (as suggested by the original post the technique described on PHP.net) is definitely ill-advised. It's simply unreliable.

Calling the mail() function from within an error handler method prove to be problematic, too. If you had a lot of errors, your mail server would be loaded with work, and you could find yourself with a gnarly inbox. To avoid this, you might consider running a cron to scan error logs periodically and send notifications accordingly. You might also like to look into system monitoring software, such as Nagios.


To speak to the bit about registering a shutdown function:

It's true that you can register a shutdown function, and that's a good answer.

The point here is that we typically shouldn't try to recover from fatal errors, especially not by using a regular expression against your output buffer. I was responding to the accepted answer, which linked to a suggestion on php.net which has since been changed or removed.

That suggestion was to use a regex against the output buffer during exception handling, and in the case of a fatal error (detected by the matching against whatever configured error text you might be expecting), try to do some sort of recovery or continued processing. That would not be a recommended practice (I believe that's why I can't find the original suggestion, too. I'm either overlooking it, or the php community shot it down).

It might be worth noting that the more recent versions of PHP (around 5.1) seem to call the shutdown function earlier, before the output buffering callback is envoked. In version 5 and earlier, that order was the reverse (the output buffering callback was followed by the shutdown function). Also, since about 5.0.5 (which is much earlier than the questioner's version 5.2.3), objects are unloaded well before a registered shutdown function is called, so you won't be able to rely on your in-memory objects to do much of anything.

So registering a shutdown function is fine, but the sort of tasks that ought to be performed by a shutdown function are probably limited to a handful of gentle shutdown procedures.

The key take-away here is just some words of wisdom for anyone who stumbles upon this question and sees the advice in the originally accepted answer. Don't regex your output buffer.

How can I get the username of the logged-in user in Django?

request.user.get_username() will return a string of the users email.

request.user.username will return a method.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Selecting pandas column by location

The method .transpose() converts columns to rows and rows to column, hence you could even write

df.transpose().ix[3]

How to get Javascript Select box's selected text

this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

datatable jquery - table header width not aligned with body width

Found the solution :

Added table-layout:fixed to the table. And opened the application in IE mode.

Run JavaScript code on window close or page refresh?

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:

window.onbeforeunload = closingCode;
function closingCode(){
   // do something...
   return null;
}

Android: How can I print a variable on eclipse console?

System.out.println and Log.d both go to LogCat, not the Console.

How can I get the key value in a JSON object?

You can simply traverse through the object and return if a match is found.

Here is the code:

returnKeyforValue : function() {
    var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
        for (key in JsonObj) {
        if(JsonObj[key] === "Keyvalue") {
            return key;
        }
    }
}

How to use sed to remove the last n lines of a file

You could use head for this.

Use

$ head --lines=-N file > new_file

where N is the number of lines you want to remove from the file.

The contents of the original file minus the last N lines are now in new_file

Select multiple columns using Entity Framework

You can select to an anonymous type, for example

var dataset2 = 
    (from recordset in entities.processlists 
    where recordset.ProcessName == processname 
    select new
    {
        serverName = recordset.ServerName,
        processId = recordset.ProcessID, 
        username = recordset.Username
    }).ToList();

Or you can create a new class that will represent your selection, for example

public class MyDataSet
{
    public string ServerName { get; set; }
    public string ProcessId { get; set; }
    public string Username { get; set; }
}

then you can for example do the following

 var dataset2 = 
    (from recordset in entities.processlists 
    where recordset.ProcessName == processname 
    select new MyDataSet
    {
        ServerName = recordset.ServerName,
        ProcessId = recordset.ProcessID, 
        Username = recordset.Username
    }).ToList();

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

Deleting Elements in an Array if Element is a Certain value VBA

Sub DelEle(Ary, SameTypeTemp, Index As Integer) '<<<<<<<<< pass only not fixed sized array (i don't know how to declare same type temp array in proceder)
    Dim I As Integer, II As Integer
    II = -1
    If Index < LBound(Ary) And Index > UBound(Ary) Then MsgBox "Error.........."
    For I = 0 To UBound(Ary)
        If I <> Index Then
            II = II + 1
            ReDim Preserve SameTypeTemp(II)
            SameTypeTemp(II) = Ary(I)
        End If
    Next I
    ReDim Ary(UBound(SameTypeTemp))
    Ary = SameTypeTemp
    Erase SameTypeTemp
End Sub

Sub Test()
    Dim a() As Integer, b() As Integer
    ReDim a(3)
    Debug.Print "InputData:"
    For I = 0 To UBound(a)
        a(I) = I
        Debug.Print "    " & a(I)
    Next
    DelEle a, b, 1
    Debug.Print "Result:"
    For I = 0 To UBound(a)
        Debug.Print "    " & a(I)
    Next
End Sub

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

how to programmatically fake a touch event to a UIButton?

In this case, UIButton is derived from UIControl. This works for object derived from UIControl.

I wanted to reuse "UIBarButtonItem" action on specific use case. Here, UIBarButtonItem doesn't offer method sendActionsForControlEvents:

But luckily, UIBarButtonItem has properties for target & action.

 if(notHappy){        
         SEL exit = self.navigationItem.rightBarButtonItem.action;
         id  world = self.navigationItem.rightBarButtonItem.target;
         [world performSelector:exit];
 }

Here, rightBarButtonItem is of type UIBarButtonItem.

Is it possible to have placeholders in strings.xml for runtime values?

You can use MessageFormat:

<string name="customer_address">Wellcome: {0} {1}</string>

In Java code :

String text = MessageFormat(R.string.customer_address).format("Name","Family");

API level 1:

https://developer.android.com/reference/java/text/MessageFormat.html

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

In Android, how do I set margins in dp programmatically?

When you are in a custom View, you can use getDimensionPixelSize(R.dimen.dimen_value), in my case, I added the margin in LayoutParams created on init method.

In Kotlin

init {
    LayoutInflater.from(context).inflate(R.layout.my_layout, this, true)
    layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
    val margin = resources.getDimensionPixelSize(R.dimen.dimen_value)
    setMargins(0, margin, 0, margin)
}

in Java:

public class CustomView extends LinearLayout {

    //..other constructors

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        int margin = getResources().getDimensionPixelSize(R.dimen.spacing_dime);
        params.setMargins(0, margin, 0, margin);
        setLayoutParams(params);
    }
}

Map a 2D array onto a 1D array

It's important to store the data in a way that it can be retrieved in the languages used. C-language stores in row-major order (all of first row comes first, then all of second row,...) with every index running from 0 to it's dimension-1. So the order of array x[2][3] is x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2]. So in C language, x[i][j] is stored the same place as a 1-dimensional array entry x1dim[ i*3 +j]. If the data is stored that way, it is easy to retrieve in C language.

Fortran and MATLAB are different. They store in column-major order (all of first column comes first, then all of second row,...) and every index runs from 1 to it's dimension. So the index order is the reverse of C and all the indices are 1 greater. If you store the data in the C language order, FORTRAN can find X_C_language[i][j] using X_FORTRAN(j+1, i+1). For instance, X_C_language[1][2] is equal to X_FORTRAN(3,2). In 1-dimensional arrays, that data value is at X1dim_C_language[2*Cdim2 + 3], which is the same position as X1dim_FORTRAN(2*Fdim1 + 3 + 1). Remember that Cdim2 = Fdim1 because the order of indices is reversed.

MATLAB is the same as FORTRAN. Ada is the same as C except the indices normally start at 1. Any language will have the indices in one of those C or FORTRAN orders and the indices will start at 0 or 1 and can be adjusted accordingly to get at the stored data.

Sorry if this explanation is confusing, but I think it is accurate and important for a programmer to know.

call javascript function on hyperlink click

The simplest answer of all is...

_x000D_
_x000D_
<a href="javascript:alert('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

Or to answer the question of calling a javascript function:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
function myFunction(myMessage) {_x000D_
    alert(myMessage);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<a href="javascript:myFunction('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

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

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

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

void myMethod(Set<A> set)

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

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

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

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

void myMethod(Set<? extends A> set)

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

How do you change text to bold in Android?

Set the attribute

android:textStyle="bold"

Add 'x' number of hours to date

   $now = date("Y-m-d H:i:s");
   date("Y-m-d H:i:s", strtotime("+1 hours $now"));

How to send a POST request from node.js Express?

var request = require('request');
 function updateClient(postData){
            var clientServerOptions = {
                uri: 'http://'+clientHost+''+clientContext,
                body: JSON.stringify(postData),
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            request(clientServerOptions, function (error, response) {
                console.log(error,response.body);
                return;
            });
        }

For this to work, your server must be something like:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

var port = 9000;

app.post('/sample/put/data', function(req, res) {
    console.log('receiving data ...');
    console.log('body is ',req.body);
    res.send(req.body);
});

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

Using python's eval() vs. ast.literal_eval()?

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

MySQL SELECT LIKE or REGEXP to match multiple words in one record

I think that the best solution would be to use Regular expressions. It's cleanest and probably the most effective. Regular Expressions are supported in all commonly used DB engines.

In MySql there is RLIKE operator so your query would be something like:
SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus|2100'
I'm not very strong in regexp so I hope the expression is ok.

Edit
The RegExp should rather be:

SELECT * FROM buckets WHERE bucketname RLIKE '(?=.*Stylus)(?=.*2100)'

More on MySql regexp support:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp

MySQL Database won't start in XAMPP Manager-osx

Try this, sudo service mysql stop it will stop any other mysql services and then restart xampp

SQL order string as number

Another way to convert.

If you have string field, you can transform it or its numerical part the following way: add leading zeros to make all integer strings having equal length.

ORDER BY CONCAT( REPEAT(  "0", 18 - LENGTH( stringfield ) ) , stringfield ) 

or order by part of a field something like 'tensymbols13', 'tensymbols1222' etc.

ORDER BY CONCAT( REPEAT(  "0", 18 - LENGTH( LEFT( stringfield , 10 ) ) ) , LEFT( stringfield , 10 ) ) 

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

Generate Java class from JSON?

Thanks all who attempted to help.
For me this script was helpful. It process only flat JSON and don't take care of types, but automate some routine

  String str = 
        "{"
            + "'title': 'Computing and Information systems',"
            + "'id' : 1,"
            + "'children' : 'true',"
            + "'groups' : [{"
                + "'title' : 'Level one CIS',"
                + "'id' : 2,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Intro To Computing and Internet',"
                    + "'id' : 3,"
                    + "'children': 'false',"
                    + "'groups':[]"
                + "}]" 
            + "}]"
        + "}";



    JSONObject json = new JSONObject(str);
    Iterator<String> iterator =  json.keys();

    System.out.println("Fields:");
    while (iterator.hasNext() ){
       System.out.println(String.format("public String %s;", iterator.next()));
    }

    System.out.println("public void Parse (String str){");
    System.out.println("JSONObject json = new JSONObject(str);");

    iterator  = json.keys();
    while (iterator.hasNext() ){
       String key = iterator.next();
       System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));

    System.out.println("}");

Unable to find valid certification path to requested target - error even after cert imported

You need to configuring JSSE System Properties, specifically point to client certificate store.

Via command line:

java -Djavax.net.ssl.trustStore=truststores/client.ts com.progress.Client

or via Java code:

import java.util.Properties;
    ...
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.keyStorePassword","passwordForKeystore");
    systemProps.put("javax.net.ssl.keyStore","pathToKeystore.ks");
    systemProps.put("javax.net.ssl.trustStore", "pathToTruststore.ts");
    systemProps.put("javax.net.ssl.trustStorePassword","passwordForTrustStore");
    System.setProperties(systemProps);
    ...

For more refer to details on RedHat site.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.

Best way to understand the difference between orElse() and orElseGet() is that orElse() will always be executed if the Optional<T> is null or not, But orElseGet() will only be executed when Optional<T> is null.

The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:

    Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
    String value = nonEmptyOptional.orElse(iAmStillExecuted());

    public static String iAmStillExecuted(){
    System.out.println("nonEmptyOptional is not NULL,still I am being executed");
    return "I got executed";
    }

Output: nonEmptyOptional is not NULL,still I am being executed


    Optional<String> emptyOptional = Optional.ofNullable(null);
    String value = emptyOptional.orElse(iAmStillExecuted());
    public static String iAmStillExecuted(){
    System.out.println("emptyOptional is NULL, I am being executed, it is normal as 
    per dictionary");
    return "I got executed";
    }

Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary

For orElseGet() , The method goes as per dictionary meaning, The orElseGet() part will be executed only when the Optional is null.

Benchmarks:

+--------------------+------+-----+------------+-------------+-------+
| Benchmark          | Mode | Cnt | Score      | Error       | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark    | avgt | 20  | 60934.425  | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20  | 3.798      | ± 0.030     | ns/op |
+--------------------+------+-----+------------+-------------+-------+

Remarks: orElseGet() has clearly outperformed orElse() for our particular example.

Hope it clears the doubts of people like me who wants the very basic ground example :)

How to use sessions in an ASP.NET MVC 4 application?

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

Create Carriage Return in PHP String?

Carriage return is "\r". Mind the double quotes!

I think you want "\r\n" btw to put a line break in your text so it will be rendered correctly in different operating systems.

  • Mac: \r
  • Linux/Unix: \n
  • Windows: \r\n

xcopy file, rename, suppress "Does xxx specify a file name..." message

xcopy src dest /I

REM This assumes dest is a folder and will create it, if it doesnt exists

Remove all items from RecyclerView

public void clearData() {
    mylist.removeAll(mylist);
    mAdapter.notifyDataSetChanged();
    recyclerView.setAdapter(mAdapter);
}

Can I animate absolute positioned element with CSS transition?

You forgot to define the default value for left so it doesn't know how to animate.

.test {
    left: 0;
    transition:left 1s linear;
}

See here: http://jsfiddle.net/shomz/yFy5n/5/

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

+----------+
|       _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

Convert 4 bytes to int

try something like this:

a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];

this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).

basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.

Most efficient way to increment a Map value in Java

I think your solution would be the standard way, but - as you noted yourself - it is probably not the fastest way possible.

You may look at GNU Trove. That is a library which contains all sorts of fast primitive Collections. Your example would use a TObjectIntHashMap which has a method adjustOrPutValue which does exactly what you want.

How do I use the CONCAT function in SQL Server 2008 R2?

(city + ', ' + state + ' ' + zip) as ctstzip for select
(city + ', ' + state + ' ' + zip) for insert

Only cast or convert if any field type is different from others.

On insert the value needs to be in the correct spot you need it be inserted. Using "as" will give you an error.

i.e.

Insert into testtable (ctstzip) Values ((city + ', ' + state + ' ' + zip))

Displaying splash screen for longer than default seconds

Write sleep(5.0)

in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions for 5 seconds splash screen will be displayed

Getting the 'external' IP address in Java

I am not sure if you can grab that IP from code that runs on the local machine.

You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:

request.getRemoteAddr()

Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.

Use a webservice like AWS and others

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

How to parse a JSON string into JsonNode in Jackson?

Richard's answer is correct. Alternatively you can also create a MappingJsonFactory (in org.codehaus.jackson.map) which knows where to find ObjectMapper. The error you got was because the regular JsonFactory (from core package) has no dependency to ObjectMapper (which is in the mapper package).

But usually you just use ObjectMapper and do not worry about JsonParser or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.

What does the red exclamation point icon in Eclipse mean?

Make sure you don't have any undefined classpath variables (like M2_REPO).

How to append data to a json file?

this, work for me :

with open('file.json', 'a') as outfile:
    outfile.write(json.dumps(data))
    outfile.write(",")
    outfile.close()

Subtract two dates in Java

Assuming that you're constrained to using Date, you can do the following:

Date diff = new Date(d2.getTime() - d1.getTime());

Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

Swift GET request with parameters

I am using this, try it in playground. Define the base urls as Struct in Constants

struct Constants {

    struct APIDetails {
        static let APIScheme = "https"
        static let APIHost = "restcountries.eu"
        static let APIPath = "/rest/v1/alpha/"
    }
}

private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {

    var components = URLComponents()
    components.scheme = Constants.APIDetails.APIScheme
    components.host   = Constants.APIDetails.APIHost
    components.path   = Constants.APIDetails.APIPath
    if let paramPath = pathparam {
        components.path = Constants.APIDetails.APIPath + "\(paramPath)"
    }
    if !parameters.isEmpty {
        components.queryItems = [URLQueryItem]()
        for (key, value) in parameters {
            let queryItem = URLQueryItem(name: key, value: "\(value)")
            components.queryItems!.append(queryItem)
        }
    }

    return components.url!
}

let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")

//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true

How to allow only one radio button to be checked?

Just give them the same name throughout the form you are using.

<form><input type="radio" name="selection">
      <input type="radio" name="selection">
      ..
      ..
</form>

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

Update statement using with clause

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t
set z = (
  with comp as (
    select b.*, 42 as computed 
    from mytable t 
    where bs_id = 1
  )
  select c.computed
  from  comp c
  where c.id = t.id
)

Good luck,

GJ

keyCode values for numeric keypad?

The answer by @.A. Morel I find to be the best easy to understand solution with a small footprint. Just wanted to add on top if you want a smaller code amount this solution which is a modification of Morel works well for not allowing letters of any sort including inputs notorious 'e' character.

function InputTypeNumberDissallowAllCharactersExceptNumeric() {
  let key = Number(inputEvent.key);
  return !isNaN(key);
}

Renaming part of a filename

for file in *.dat ; do mv $file ${file//ABC/XYZ} ; done

No rename or sed needed. Just bash parameter expansion.

How to colorize diff on the command line?

I use grc (Generic Colouriser), which allows you to colour the output of a number of commands including diff.

It is a python script which can be wrapped around any command. So instead of invoking diff file1 file2, you would invoke grc diff file1 file2 to see colourised output. I have aliased diff to grc diff to make it easier.

Random string generation with upper case letters and digits

import string, random
lower = string.ascii_lowercase
upper = string.ascii_uppercase
digits = string.digits
special = '!"£$%^&*.,@#/?'

def rand_pass(l=4, u=4, d=4, s=4):
    p = []
    [p.append(random.choice(lower)) for x in range(l)]
    [p.append(random.choice(upper)) for x in range(u)]
    [p.append(random.choice(digits)) for x in range(d)]
    [p.append(random.choice(special)) for x in range(s)]
    random.shuffle(p)
    return "".join(p)

print(rand_pass())
# @5U,@A4yIZvnp%51

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.

Gantt chart for this ques will be:

| P3 | P2 | P4 | P5 | P1 |

1    4    5    7   11   14

Average waiting time=(0+2+2+3+3)/5=2

Average Turnaround time=(3+3+4+7+6)/5=4.6

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

If you can live without tools.jar and it's only included as a chained dependency, you can exclude it from the offending project:

<dependency>
    <groupId>org.apache.ambari</groupId>
    <artifactId>ambari-metrics-common</artifactId>
    <version>2.1.0.0</version>
    <exclusions>
        <exclusion>
            <artifactId>jdk.tools</artifactId>
            <groupId>jdk.tools</groupId>
        </exclusion>
    </exclusions>
</dependency>

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
    
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
    
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)


        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        Err.Clear
        On Error GoTo 0
    
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

printf a variable in C

Your printf needs a format string:

printf("%d\n", x);

This reference page gives details on how to use printf and related functions.

Convert string to int if string is a number

To put it on one line:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)

Changing the Git remote 'push to' default

You can easily change default remote for branches all at once simple using this command

git push -u <remote_name> --all

Shift column in pandas dataframe up by one?

First shift the column:

df['gdp'] = df['gdp'].shift(-1)

Second remove the last row which contains an NaN Cell:

df = df[:-1]

Third reset the index:

df = df.reset_index(drop=True)

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

From the help (if /?):

The ELSE clause must occur on the same line as the command after the IF.  For
example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

The following would NOT work because the del command needs to be terminated
by a newline:

    IF EXIST filename. del filename. ELSE echo filename. missing

Nor would the following work, since the ELSE command must be on the same line
as the end of the IF command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

How do I delete from multiple tables using INNER JOIN in SQL server

DELETE     TABLE1 LIN
FROM TABLE1 LIN
INNER JOIN TABLE2 LCS ON  CONDITION
WHERE CONDITION

How to Resize a Bitmap in Android?

Although the accepted answer is correct, it doesn't resize Bitmap by keeping the same Aspect Ratio. If you are looking for a method to resize Bitmap by keeping the same aspect ratio you can use the following utility function. The usage details and explanation of the function are present at this link.

public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
       try {
           if (source.getHeight() >= source.getWidth()) {
               int targetHeight = maxLength;
               if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
               int targetWidth = (int) (targetHeight * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;
           } else {
               int targetWidth = maxLength;

               if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
               int targetHeight = (int) (targetWidth * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;

           }
       }
       catch (Exception e)
       {
           return source;
       }
   }

Change the Blank Cells to "NA"

Call dplyr package by installing from cran in r

library(dplyr)

(file)$(colname)<-sub("-",NA,file$colname) 

It will convert all the blank cell in a particular column as NA

If the column contains "-", "", 0 like this change it in code according to the type of blank cell

E.g. if I get a blank cell like "" instead of "-", then use this code:

(file)$(colname)<-sub("", NA, file$colname)

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

How to input a path with a white space?

I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case

SOME_PATH="/$COMPANY/someProject/some path"

is one of possible solutions.

But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:

NEW_VAR="$SOME_PATH"

because if not, space will be expanded to command level, like this:

NEW_VAR=/YourCompany/someProject/some path

which is not what you want.

For more info you can check out my article about it http://www.cofoh.com/white-shell

Where Sticky Notes are saved in Windows 10 1607

It depends on the version of Windows 10 you're using. Starting with Windows 10 Anniversary Update version 1607, Sticky Notes is storing its data in the following directory:

%UserProfile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe

If your Windows 10 has an older version, it is storing the date in the following directory:

%UserProfile%\AppData\Roaming\Microsoft\StickyNotes\StickyNotes.snt

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Responsive iframe using Bootstrap

Please, Check this out, I hope it's help

<div class="row">
 <iframe class="col-lg-12 col-md-12 col-sm-12" src="http://www.w3schools.com">
 </iframe>
</div>

How to display .svg image using swift

To render SVG file you can use Macaw. Also Macaw supports transformations, user events, animation and various effects.

You can render SVG file with zero lines of code. For more info please check this article: Render SVG file with Macaw.

DISCLAIMER: I am affiliated with this project.

How to find minimum value from vector?

You can always use the stl:

auto min_value = *std::min_element(v.begin(),v.end());

How to style the option of an html "select" element?

It's 2017 and it IS possible to target specific select options. In my project I have a table with a class="variations", and the select options are in the table cell td="value", and the select has an ID select#pa_color. The option element also has a class option="attached" (among other class tags). If a user is logged in as a wholesale customer, they can see all of the color options. But retail customers are not allowed to purchase 2 color options, so I've disabled them

<option class="attached" disabled>color 1</option>
<option class="attached" disabled>color 2</option>

It took a little logic, but here is how I targeted the disabled select options.

CSS

table.variations td.value select#pa_color option.attached:disabled {
display: none !important;
}

With that, my color options are only visible to wholesale customers.

RestSharp JSON Parameter Posting

You might need to Deserialize your anonymous JSON type from the request body.

var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result;
ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody);

Insert line break in wrapped cell via code

You could also use vbCrLf which corresponds to Chr(13) & Chr(10).

How to get the error message from the error code returned by GetLastError()?

i'll leave this here since i will need to use it later. It's a source for a small binary compatible tool that will work equally well in assembly, C and C++.

GetErrorMessageLib.c (compiled to GetErrorMessageLib.dll)

#include <Windows.h>

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
__declspec(dllexport)
int GetErrorMessageA(DWORD dwErrorCode, LPSTR lpResult, DWORD dwBytes)
{    
    LPSTR tmp;
    DWORD result_len;

    result_len = FormatMessageA (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPSTR)&tmp,
        0,
        NULL
    );        

    if (result_len == 0) {
        return -1;
    }

    // FormatMessage's return is 1 character too short.
    ++result_len;

    strncpy(lpResult, tmp, dwBytes);

    lpResult[dwBytes - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_len <= dwBytes) {
        return 0;
    } else {
        return result_len;
    }
}

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
__declspec(dllexport)
int GetErrorMessageW(DWORD dwErrorCode, LPWSTR lpResult, DWORD dwBytes)
{   
    LPWSTR tmp;
    DWORD nchars;
    DWORD result_bytes;

    nchars = dwBytes >> 1;

    result_bytes = 2 * FormatMessageW (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPWSTR)&tmp,
        0,
        NULL
    );    

    if (result_bytes == 0) {
        return -1;
    } 

    // FormatMessage's return is 1 character too short.
    result_bytes += 2;

    wcsncpy(lpResult, tmp, nchars);
    lpResult[nchars - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_bytes <= dwBytes) {
        return 0;
    } else {
        return result_bytes * 2;
    }
}

inline version(GetErrorMessage.h):

#ifndef GetErrorMessage_H 
#define GetErrorMessage_H 
#include <Windows.h>    

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
static inline int GetErrorMessageA(DWORD dwErrorCode, LPSTR lpResult, DWORD dwBytes)
{    
    LPSTR tmp;
    DWORD result_len;

    result_len = FormatMessageA (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPSTR)&tmp,
        0,
        NULL
    );        

    if (result_len == 0) {
        return -1;
    }

    // FormatMessage's return is 1 character too short.
    ++result_len;

    strncpy(lpResult, tmp, dwBytes);

    lpResult[dwBytes - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_len <= dwBytes) {
        return 0;
    } else {
        return result_len;
    }
}

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
static inline int GetErrorMessageW(DWORD dwErrorCode, LPWSTR lpResult, DWORD dwBytes)
{   
    LPWSTR tmp;
    DWORD nchars;
    DWORD result_bytes;

    nchars = dwBytes >> 1;

    result_bytes = 2 * FormatMessageW (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPWSTR)&tmp,
        0,
        NULL
    );    

    if (result_bytes == 0) {
        return -1;
    } 

    // FormatMessage's return is 1 character too short.
    result_bytes += 2;

    wcsncpy(lpResult, tmp, nchars);
    lpResult[nchars - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_bytes <= dwBytes) {
        return 0;
    } else {
        return result_bytes * 2;
    }
}

#endif /* GetErrorMessage_H */

dynamic usecase(assumed that error code is valid, otherwise a -1 check is needed):

#include <Windows.h>
#include <Winbase.h>
#include <assert.h>
#include <stdio.h>

int main(int argc, char **argv)
{   
    int (*GetErrorMessageA)(DWORD, LPSTR, DWORD);
    int (*GetErrorMessageW)(DWORD, LPWSTR, DWORD);
    char result1[260];
    wchar_t result2[260];

    assert(LoadLibraryA("GetErrorMessageLib.dll"));

    GetErrorMessageA = (int (*)(DWORD, LPSTR, DWORD))GetProcAddress (
        GetModuleHandle("GetErrorMessageLib.dll"),
        "GetErrorMessageA"
    );        
    GetErrorMessageW = (int (*)(DWORD, LPWSTR, DWORD))GetProcAddress (
        GetModuleHandle("GetErrorMessageLib.dll"),
        "GetErrorMessageW"
    );        

    GetErrorMessageA(33, result1, sizeof(result1));
    GetErrorMessageW(33, result2, sizeof(result2));

    puts(result1);
    _putws(result2);

    return 0;
}

regular use case(assumes error code is valid, otherwise -1 return check is needed):

#include <stdio.h>
#include "GetErrorMessage.h"
#include <stdio.h>

int main(int argc, char **argv)
{
    char result1[260];
    wchar_t result2[260];

    GetErrorMessageA(33, result1, sizeof(result1));
    puts(result1);

    GetErrorMessageW(33, result2, sizeof(result2));
    _putws(result2);

    return 0;
}

example using with assembly gnu as in MinGW32(again, assumed that error code is valid, otherwise -1 check is needed).

    .global _WinMain@16

    .section .text
_WinMain@16:
    // eax = LoadLibraryA("GetErrorMessageLib.dll")
    push $sz0
    call _LoadLibraryA@4 // stdcall, no cleanup needed

    // eax = GetProcAddress(eax, "GetErrorMessageW")
    push $sz1
    push %eax
    call _GetProcAddress@8 // stdcall, no cleanup needed

    // (*eax)(errorCode, szErrorMessage)
    push $200
    push $szErrorMessage
    push errorCode       
    call *%eax // cdecl, cleanup needed
    add $12, %esp

    push $szErrorMessage
    call __putws // cdecl, cleanup needed
    add $4, %esp

    ret $16

    .section .rodata
sz0: .asciz "GetErrorMessageLib.dll"    
sz1: .asciz "GetErrorMessageW"
errorCode: .long 33

    .section .data
szErrorMessage: .space 200

result: The process cannot access the file because another process has locked a portion of the file.

find a minimum value in an array of floats

If min value in array, you can try like:

>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44

Typescript: React event types

I have the following in a types.ts file for html input, select, and textarea:

export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>

Then import them:

import { InputChangeEventHandler } from '../types'

Then use them:


const updateName: InputChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}

Then apply the functions on your markup (replacing ... with other necessary props):

<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
  // ...
</select>

Why is it that "No HTTP resource was found that matches the request URI" here?

I had that problem, if you are calling your REST Methods from another Assembly you must be sure that all your references have the same version as your main project references, otherwise will never find your controllers.

Regards.

What is the difference between mocking and spying when using Mockito?

[Test double types]

Mock vs Spy

Mock is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null

Spy is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it

class A {
    String foo1() {
        foo2();
        return "RealString_1";
    }

    String foo2() {
        return "RealString_2";
    }

    void foo3() { foo4(); }

    void foo4() { }
}
@Test
public void testMockA() {
    //given
    A mockA = Mockito.mock(A.class);
    Mockito.when(mockA.foo1()).thenReturn("MockedString");

    //when
    String result1 = mockA.foo1();
    String result2 = mockA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals(null, result2);

    //Case 2
    //when
    mockA.foo3();

    //then
    verify(mockA).foo3();
    verify(mockA, never()).foo4();
}

@Test
public void testSpyA() {
    //given
    A spyA = Mockito.spy(new A());

    Mockito.when(spyA.foo1()).thenReturn("MockedString");

    //when
    String result1 = spyA.foo1();
    String result2 = spyA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals("RealString_2", result2);

    //Case 2
    //when
    spyA.foo3();

    //then
    verify(spyA).foo3();
    verify(spyA).foo4();
}

What to do with branch after merge

If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.

How can I trigger the click event of another element in ng-click using angularjs?

So it was a simple fix. Just had to move the ng-click to a scope click handler:

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="clickUpload()">Upload</button>



$scope.clickUpload = function(){
    angular.element('#upload').trigger('click');
};

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

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

It's similar to pass in Python.

One use would be to stub out a function until it gets written:

future_function () { :; }

How to check if an environment variable exists and get its value?

If you don't care about the difference between an unset variable or a variable with an empty value, you can use the default-value parameter expansion:

foo=${DEPLOY_ENV:-default}

If you do care about the difference, drop the colon

foo=${DEPLOY_ENV-default}

You can also use the -v operator to explicitly test if a parameter is set.

if [[ ! -v DEPLOY_ENV ]]; then
    echo "DEPLOY_ENV is not set"
elif [[ -z "$DEPLOY_ENV" ]]; then
    echo "DEPLOY_ENV is set to the empty string"
else
    echo "DEPLOY_ENV has the value: $DEPLOY_ENV"
fi

Format a message using MessageFormat.format() in Java

Add an extra apostrophe ' to the MessageFormat pattern String to ensure the ' character is displayed

String text = 
     java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
                                         ^

An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc

A single quote itself must be represented by doubled single quotes '' throughout a String.

The String You\\'re is equivalent to adding a backslash character to the String so the only difference will be that You\re will be produced rather than Youre. (before double quote solution '' applied)

'pip' is not recognized as an internal or external command

Go to control Panel >> Uninstall or change Program and double click on Python XXX to modify install. Make sure PIP component is checked and install.

enter image description here

Get value of a string after last slash in JavaScript

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }

How to change Rails 3 server default port in develoment?

I like to append the following to config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    alias :default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port => 3333)
    end    
  end
end

How do you access the value of an SQL count () query in a Java program

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");

Embedding DLLs in a compiled executable

If they're actually managed assemblies, you can use ILMerge. For native DLLs, you'll have a bit more work to do.

See also: How can a C++ windows dll be merged into a C# application exe?

onclick event function in JavaScript

Two observations:

  1. You should write

    <input type="button" value="button text" />
    

    instead of

    <input type="button">button text</input>
    
  2. You should rename your function. The function click() is already defined on a button (it simulates a click), and gets a higher priority then your method.

Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:

  • Do not use onclick="javascript:myfunc()". Only use the javascript: prefix inside the href attribute of a hyperlink: <a href="javascript:myfunc()">.
  • You don't have to end with a semicolon. onclick="foo()" and onclick="foo();" both work just fine.
  • Event attributes in HTML are not case sensitive, so onclick, onClick and ONCLICK all work. It is common practice to write attributes in lowercase: onclick. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ..., then it must be all lowercase.

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under ruby-doc.org:

http://www.ruby-doc.org/core/classes/Array.html#M000249

  • ary.collect {|item| block } ? new_ary
  • ary.map {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ary.map ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.

How to compile Tensorflow with SSE4.2 and AVX instructions?

These are SIMD vector processing instruction sets.

Using vector instructions is faster for many tasks; machine learning is such a task.

Quoting the tensorflow installation docs:

To be compatible with as wide a range of machines as possible, TensorFlow defaults to only using SSE4.1 SIMD instructions on x86 machines. Most modern PCs and Macs support more advanced instructions, so if you're building a binary that you'll only be running on your own machine, you can enable these by using --copt=-march=native in your bazel build command.

grep exclude multiple strings

egrep -v "Nopaging the limit is|keyword to remove is"

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

Get values from label using jQuery

Try this:

var label = $('#currentMonth').text()

How can I define colors as variables in CSS?

Do not use css3 variables due to support.

I would do the following if you want a pure css solution.

  1. Use color classes with semenatic names.

    .bg-primary   { background: #880000; }
    
    .bg-secondary { background: #008800; }
    
    .bg-accent    { background: #F5F5F5; }
    
  2. Separate the structure from the skin (OOCSS)

    /* Instead of */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
        color: #8000;
    }
    
    /* use this */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
    }
    
    .bg-primary {
        background: #880000;
    }
    
    /* This will allow you to reuse colors in your design */
    
  3. Put these inside a separate css file to change as needed.

How to convert a string to lower or upper case in Ruby

You can find strings method like "strings".methods You can define string as upcase, downcase, titleize. For Example,

"hii".downcase
"hii".titleize
"hii".upcase

Laravel Eloquent - Get one Row

Laravel 5.2

$sql = "SELECT * FROM users WHERE email = $email";

$user = collect(\User::select($sql))->first();

or

$user = User::table('users')->where('email', $email)->pluck();

What is the Eclipse shortcut for "public static void main(String args[])"?

As bmargulies mentioned:

Preferences>Java>Editor>Templates>New...

enter image description here

enter image description here

Now, type psvm then Ctrl + Space on Mac or Windows.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

Setting my RequestOperationManager Response Serializer to HTTPResponseSerializer fixed the issue.

Objective-C

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Swift

manager.responseSerializer = AFHTTPResponseSerializer()

Making this change means I don't need to add acceptableContentTypes to every request I make.

HTML5 LocalStorage: Checking if a key exists

Update:

if (localStorage.hasOwnProperty("username")) {
    //
}

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) {
    //
}

How do I change UIView Size?

Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.

questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264

and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141

eg:

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES

How to get file's last modified date on Windows command line?

Change % to %% for use in batch file, for %~ta syntax enter call /?

for %a in (MyFile.txt) do set FileDate=%~ta

Sample output:

for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM

for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:


IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

How to build minified and uncompressed bundle with webpack?

webpack entry.jsx ./output.js -p

works for me, with -p flag.

Creating a batch file, for simple javac and java command execution

@author MADMILK
@echo off
:getback1
set /p jump1=Do you want to compile? Write yes/no : 
if %jump1% = yes
goto loop
if %jump1% = no
goto getback2
:: Important part here
:getback2
set /p jump2=Do you want to run a java program? Write yes/no : 
if %jump2% = yes
goto loop2
if %jump2% = no
goto getback1
:: Make a folder anywhere what you want to use for scripts, for example i make one.
cd desktop
:: This is the folder where is gonna be your script(s)
mkdir My Scripts
cd My Scripts
title Java runner/compiler
echo REMEMBER! LOWER CASES AND UPPER CASES ARE IMPORTANT!
:loop
echo This is the java compiler program.
set /p jcVal=What java program do you want to compile? : 
javac %jcVal%
:loop2
echo This is the java code runner program.
set /p javaVal=What java program do you want to run? : 
java %javaVal%
pause >nul
echo Press NOTHING to leave

Call a PHP function after onClick HTML event

<div id="sample"></div>   
 <form>
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>

<script>

    $(document).ready(function(){
         $("#submitButton").click(function(){
            $("#sample").load(filenameofyourfunction?the the variable you need);
         });
    });

</script>

How can I test a PDF document if it is PDF/A compliant?

The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.

  • PDF/A1-a
  • PDF/A2-a
  • PDF/A2-b
  • PDF/A1-b
  • PDF/A2-u

How to make a dropdown readonly using jquery?

I'd make the field disabled. Then, when the form submits, make it not disabled. In my opinion, this is easier than having to deal with hidden fields.

//disable the field
$("#myFieldID").prop( "disabled", true );           

//right before the form submits, we re-enable the fields, to make them submit.
$( "#myFormID" ).submit(function( event ) {
    $("#myFieldID").prop( "disabled", false );
});     

What is the difference between . (dot) and $ (dollar sign)?

My rule is simple (I'm beginner too):

  • do not use . if you want to pass the parameter (call the function), and
  • do not use $ if there is no parameter yet (compose a function)

That is

show $ head [1, 2]

but never:

show . head [1, 2]

How do I remove the height style from a DIV using jQuery?

maybe something like

$('div#someDiv').css("height", "auto");

Allowed memory size of 536870912 bytes exhausted in Laravel

You can try editing /etc/php5/fpm/php.ini:

; Old Limit
; memory_limit = 512M

; New Limit
memory_limit = 2048M

You may need to restart nginx:

sudo systemctl restart nginx

You may also have an infinite loop somewhere. Can you post the code you're calling?

Convert int to a bit array in .NET

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

In my case, I forgot to add my component in the Declaration array of app.module.ts, and voila! the issue was fixed.

Websocket connections with Postman

Postman doesn't support websocket. Most of the extension and app I had ever seen were not working properly.

Solution which I found

Just login/ open your application in your browser, and open browser console. Then enter your socket event, and press enter.

socket.emit("event_name", {"id":"123"}, (res)=>{console.log(res); });

enter image description here

Executing periodic actions in Python

This will insert a 10 second sleep in between every call to foo(), which is approximately what you asked for should the call complete quickly.

import time

while True:
    foo()
    time.sleep(10)

To do other things while your foo() is being called in a background thread

import time
import sys
import threading

def foo():
    sys.stdout.write('({}) foo\n'.format(time.ctime()))

def foo_target():
    while True:
        foo()
        time.sleep(10)

t = threading.Thread(target=foo_target)
t.daemon = True
t.start()
print('doing other things...')

Visual Studio Error: (407: Proxy Authentication Required)

While running Visual Studio 2012 behind a proxy, I received the following error message when checking for extension updates in the Visual Studio Gallery:

The remote server returned an unexpected response: (417) Expectation failed

A look around Google finally revealed a solution here:

Visual Studio 2012 Proxy Settings

http://www.jlpaonline.com/?p=176

Basically, he's saying the fix is to edit your devenv.exe.config file and change this:

<settings>      
   <ipv6 enabled="true"/> 
</settings>

to this:

 <settings>
   <ipv6 enabled="true"/>      
   <servicePointManager expect100Continue="false"/> 
 </settings> 

How do I create a crontab through a script

It is an approach to incrementally add the cron job:

  ssh USER_NAME@$PRODUCT_IP nohup "echo '*/2 * * * * ping -c2 PRODUCT_NAME.com >> /var/www/html/test.html' | crontab -u USER_NAME -"

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

Player.cpp:

#include "Player.h"
#include "Ball.h"

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

formGroup expects a FormGroup instance

I was using reactive forms and ran into similar problems. What helped me was to make sure that I set up a corresponding FormGroup in the class. Something like this:

myFormGroup: FormGroup = this.builder.group({
    dob: ['', Validators.required]
});

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

The problem was I have 2 instances of Mysql installed and I didn't know the password for both instances.Just check if port 80 is used by any of the programs. This is what I did

1.Quit Skype because it was using port 80.(Please check if port 80 is used by any other program).

2.Search for Mysql services in task manager and stop it.

3.Now delete all the related mysql files.Make sure you delete all the files.

4.Reinstall

Test if numpy array contains only zeros

If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.

try: # removes output noise for empty slice 
    mean = np.mean(array)
except:
    mean = 0

What is the maximum characters for the NVARCHAR(MAX)?

The max size for a column of type NVARCHAR(MAX) is 2 GByte of storage.

Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters.

Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX) column.

Is that enough space for your needs? :-)

How to make a submit out of a <a href...>...</a> link?

What might be a handy addition to this is the possibility to change the post-url from the extra button so you can post to different urls with different buttons. This can be achieved by setting the form 'action' property. Here's the code for that when using jQuery:

$('#[href button name]').click(function(e) {
    e.preventDefault();
    $('#[form name]').attr('action', 'alternateurl.php');
    $('#[form name]').submit();
});

The action-attribute has some issues with older jQuery versions, but on the latest you'll be good to go.

css to make bootstrap navbar transparent

_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light fixed-top bg-transparent">
              <a class="navbar-brand" href="#">Navbar w/ text</a>
              <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
              </button>
              <div class="collapse navbar-collapse" id="navbarText">
                <ul class="navbar-nav mr-auto">
                  <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="#">Features</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="#">Pricing</a>
                  </li>
                </ul>
                <span class="navbar-text">
                  Navbar text with an inline element
                </span>
              </div>
            </nav>
_x000D_
_x000D_
_x000D_

Where is the web server root directory in WAMP?

In WAMP the files are served by the Apache component (the A in WAMP).

In Apache, by default the files served are located in the subdirectory htdocs of the installation directory. But this can be changed, and is actually changed when WAMP installs Apache.

The location from where the files are served is named the DocumentRoot, and is defined using a variable in Apache configuration file. The default value is the subdirectory htdocs relative to what is named the ServerRoot directory.

By default the ServerRoot is the installation directory of Apache. However this can also be redefined into the configuration file, or using the -d option of the command httpd which is used to launch Apache. The value in the configuration file overrides the -d option.

The configuration file is by default conf/httpd.conf relative to ServerRoot. But this can be changed using the -f option of command httpd.

When WAMP installs itself, it modify the default configuration file with DocumentRoot c:/wamp/www/. The files to be served need to be located here and not in the htdocs default directory.

You may change this location set by WAMP, either by modifying DocumentRoot in the default configuration file, or by using one of the two command line options -f or -d which point explicitly or implicity to a new configuration file which may hold a different value for DocumentRoot (in that case the new file needs to contain this definition, but also the rest of the configuration found in the default configuration file).

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

As the creator of ElasticSearch, maybe I can give you some reasoning on why I went ahead and created it in the first place :).

Using pure Lucene is challenging. There are many things that you need to take care for if you want it to really perform well, and also, its a library, so no distributed support, it's just an embedded Java library that you need to maintain.

In terms of Lucene usability, way back when (almost 6 years now), I created Compass. Its aim was to simplify using Lucene and make everyday Lucene simpler. What I came across time and time again is the requirement to be able to have Compass distributed. I started to work on it from within Compass, by integrating with data grid solutions like GigaSpaces, Coherence, and Terracotta, but it's not enough.

At its core, a distributed Lucene solution needs to be sharded. Also, with the advancement of HTTP and JSON as ubiquitous APIs, it means that a solution that many different systems with different languages can easily be used.

This is why I went ahead and created ElasticSearch. It has a very advanced distributed model, speaks JSON natively, and exposes many advanced search features, all seamlessly expressed through JSON DSL.

Solr is also a solution for exposing an indexing/search server over HTTP, but I would argue that ElasticSearch provides a much superior distributed model and ease of use (though currently lacking on some of the search features, but not for long, and in any case, the plan is to get all Compass features into ElasticSearch). Of course, I am biased, since I created ElasticSearch, so you might need to check for yourself.

As for Sphinx, I have not used it, so I can't comment. What I can refer you is to this thread at Sphinx forum which I think proves the superior distributed model of ElasticSearch.

Of course, ElasticSearch has many more features than just being distributed. It is actually built with a cloud in mind. You can check the feature list on the site.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

CSS Calc Viewport Units Workaround?

<div>It's working fine.....</div>

div
{
     height: calc(100vh - 8vw);
    background: #000;
    overflow:visible;
    color: red;
}

Check here this css code right now support All browser without Opera

just check this

Live

see Live preview by jsfiddle

See Live preview by codepen.io

finding and replacing elements in a list

a = [1,2,3,4,5,1,2,3,4,5,1,12]
for i in range (len(a)):
    if a[i]==2:
        a[i]=123

You can use a for and or while loop; however if u know the builtin Enumerate function, then it is recommended to use Enumerate.1

Angular 4 setting selected option in Dropdown

If you want to select a value based on true / false use

[selected]="opt.selected == true"

 <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>

checkit out

Angular 2 - Setting selected value on dropdown list

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How to avoid Sql Query Timeout

My team were experiencing these issues intermittently with long running SSIS packages. This has been happening since Windows server patching.

Our SSIS and SQL servers are on separate VM servers.

Working with our Wintel Servers team we rebooted both servers and for the moment, the problem appears to have gone away.

The engineer has said that they're unsure if the issue is the patches or new VMTools that they updated at the same time. We'll monitor for now and if the timeout problems recur, they'll try rolling back the VMXNET3 driver, first, then if that doesn't work, take off the June Rollup patches.

So for us the issue is nothing to do with our SQL Queries (we're loading billions of new rows so it has to be long running).

Push an associative item into an array in JavaScript

To make something like associative array in JavaScript you have to use objects. ?

_x000D_
_x000D_
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
_x000D_
_x000D_
_x000D_

DEMO: http://jsfiddle.net/bz8pK/1/

HTML Display Current date

Use Date::toLocaleDateString.

new Date().toLocaleDateString()
= "9/13/2015"

You don't need to set innerHTML, just by writing

<p>
<script> document.write(new Date().toLocaleDateString()); </script>
</p>

will work.

supportness

P.S.

new Date().toDateString()
= "Sun Sep 13 2015"

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

Change encoding in notepad++ UTF-8 with BOM. That is how it worked for me

What is the LD_PRELOAD trick?

As many people mentioned, using LD_PRELOAD to preload library. BTW, you can CHECK if the setting is available by ldd command.

Example: suppose you need to preload your own libselinux.so.1.

> ldd /bin/ls
    ...
    libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f3927b1d000)
    libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007f3927914000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f392754f000)
    libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f3927311000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f392710c000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f3927d65000)
    libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007f3926f07000)

Thus, set your preload environment:

  export LD_PRELOAD=/home/patric/libselinux.so.1

Check your library again:

>ldd /bin/ls
    ...
    libselinux.so.1 =>
    /home/patric/libselinux.so.1 (0x00007fb9245d8000)
    ...

Pass Javascript Variable to PHP POST

You can do this using Ajax. I have a function that I use for something like this:

function ajax(elementID,filename,str,post)
{
    var ajax;
    if (window.XMLHttpRequest)
    {
        ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
    }
    else if (ActiveXObject("Microsoft.XMLHTTP"))
    {
        ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
    }
    else if (ActiveXObject("Msxml2.XMLHTTP"))
    {
        ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
    }
    else
    {
        alert("Error: Your browser does not support AJAX.");
        return false;
    }
    ajax.onreadystatechange=function()
    {
        if (ajax.readyState==4&&ajax.status==200)
        {
            document.getElementById(elementID).innerHTML=ajax.responseText;
        }
    }
    if (post==false)
    {
        ajax.open("GET",filename+str,true);
        ajax.send(null);
    }
    else
    {
        ajax.open("POST",filename,true);
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        ajax.send(str);
    }
    return ajax;
}

The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.