Programs & Examples On #Texttemplate

Text::Template is a Perl library that allows to generate text from text containing Perl code that is evaluated.

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

Another simple approach:

package org.yourpackagename;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

      @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(PreferenceController.class);
        }


    public static void main(String[] args) {
        SpringApplication.run(PreferenceController.class, args);
    }
}

printing all contents of array in C#

In C# you can loop through the array printing each element. Note that System.Object defines a method ToString(). Any given type that derives from System.Object() can override that.

Returns a string that represents the current object.

http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

By default the full type name of the object will be printed, though many built-in types override that default to print a more meaningful result. You can override ToString() in your own objects to provide meaningful output.

foreach (var item in myArray)
{
    Console.WriteLine(item.ToString()); // Assumes a console application
}

If you had your own class Foo, you could override ToString() like:

public class Foo
{
    public override string ToString()
    {
        return "This is a formatted specific for the class Foo.";
    }
}

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

You may need to go to Window -> Android SDK Manager -> Packages -> Reload to fetch latest updates and then update the SDK.

Type safety: Unchecked cast

Well, first of all, you're wasting memory with the new HashMap creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:

private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

Secondly, the compiler is complaining that you cast the object to a HashMap without checking if it is a HashMap. But, even if you were to do:

if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}

You would probably still get this warning. The problem is, getBean returns Object, so it is unknown what the type is. Converting it to HashMap directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a HashMap<String, String>.

HashMaps are really maps that take an object as a key and have an object as a value, HashMap<Object, Object> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a HashMap<String, String> because you could have HashMap<Date, Calendar> because the non-generic representation that is returned can have any objects.

If the code compiles, and you can execute String value = map.get("thisString"); without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a ClassCastException at runtime, because the generics cannot block this from happening in this case.

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

Are members of a C++ struct initialized to 0 by default?

No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor

Snapshot() : x(0), y(0) {
}

This ensures that all uses of Snapshot will have initialized values.

Submit button not working in Bootstrap form

  • If you put type=submit it is a Submit Button
  • if you put type=button it is just a button, It does not submit your form inputs.

and also you don't want to use both of these

Check if textbox has empty value

Also You can use

$value = $("#txt").val();

if($value == "")
{
    //Your Code Here
}
else
{
   //Your code
}

Try it. It work.

How to find largest objects in a SQL Server database?

In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.

SELECT INTO Variable in MySQL DECLARE causes syntax error?

In the end a stored procedure was the solution for my problem. Here´s what helped:

DELIMITER //
CREATE PROCEDURE test ()
  BEGIN
  DECLARE myvar DOUBLE;
  SELECT somevalue INTO myvar FROM mytable WHERE uid=1;
  SELECT myvar;
  END
  //

DELIMITER ;

call test ();

Can't start Tomcat as Windows Service

All those mistakes are related to badly connected Apache and JDK.

  1. go to start>System>Advanced_system_settings>
  2. System Properties will pop-up go to Environment Variables
  3. in User variables you have to set variable: JAVA_HOME value: C:\Program_Files\Java\jdk1.8.0_161
  4. in System variables you need to put in the path: jdk/bin path & jre/bin path and also you need to have JAVA_HOME C:\Program_Files\Java\jdk1.8.0_161

people usually forget to setup JAVA_HOME in System variables.

if you still have an error try to think step by step

  1. Open Event viewer>Check Administrative Events and Windows Logs>System see the error. If that doesn't help
  2. go to C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs commons-daemon.XXXX-XX-XX.log and READ THE ERRORS AND WARNINGS... there should be nicely put down in words what's the problem.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

How to increase font size in a plot in R?

By trial and error, I've determined the following is required to set font size:

  1. cex doesn't work in hist(). Use cex.axis for the numbers on the axes, cex.lab for the labels.
  2. cex doesn't work in axis() either. Use cex.axis for the numbers on the axes.
  3. In place of setting labels using hist(), you can set them using mtext(). You can set the font size using cex, but using a value of 1 actually sets the font to 1.5 times the default!!! You need to use cex=2/3 to get the default font size. At the very least, this is the case under R 3.0.2 for Mac OS X, using PDF output.
  4. You can change the default font size for PDF output using pointsize in pdf().

I suppose it would be far too logical to expect R to (a) actually do what its documentation says it should do, (b) behave in an expected fashion.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %>

Executes the ruby code within the brackets.

<%= %>

Prints something into erb file.

<%== %>

Equivalent to <%= raw %>. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)

<% -%>

Avoids line break after expression.

<%# %>

Comments out code within brackets; not sent to client (as opposed to HTML comments).

Visit Ruby Doc for more infos about ERB.

Moment.js - two dates difference in number of days

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
  var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

Query-string encoding of a Javascript Object

A little bit look better

objectToQueryString(obj, prefix) {
    return Object.keys(obj).map(objKey => {
        if (obj.hasOwnProperty(objKey)) {
            const key = prefix ? `${prefix}[${objKey}]` : objKey;
            const value = obj[objKey];

            return typeof value === "object" ?
                this.objectToQueryString(value, key) :
                `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }

        return null;
    }).join("&");
}

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Why can't I inherit static classes?

When we create a static class that contains only the static members and a private constructor.The only reason is that the static constructor prevent the class from being instantiated for that we can not inherit a static class .The only way to access the member of the static class by using the class name itself.Try to inherit a static class is not a good idea.

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

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

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

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

How do I get the position selected in a RecyclerView?

Set your onClickListeners on onBindViewHolder() and you can access the position from there. If you set them in your ViewHolder you won't know what position was clicked unless you also pass the position into the ViewHolder

EDIT

As pskink pointed out ViewHolder has a getPosition() so the way you were originally doing it was correct.

When the view is clicked you can use getPosition() in your ViewHolder and it returns the position

Update

getPosition() is now deprecated and replaced with getAdapterPosition()

Update 2020

getAdapterPosition() is now deprecated and replaced with getAbsoluteAdapterPosition() or getBindingAdapterPosition()

Kotlin code:

override fun onBindViewHolder(holder: MyHolder, position: Int) {
        // - get element from your dataset at this position
        val item = myDataset.get(holder.absoluteAdapterPosition)
    }

How to replace url parameter with javascript/jquery?

If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:

urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);

Example:

let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q

jQuery click not working for dynamically created items

$("#container").delegate("span", "click", function (){
    alert(11);
});

What is Dispatcher Servlet in Spring?

The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.

I might have

  • a file /WEB-INF/jsp/pages/Home.jsp
  • and a method on a class

    @RequestMapping(value="/pages/Home.html")
    private ModelMap buildHome() {
        return somestuff;
    }
    

The Dispatcher servlet is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.

How it accomplishes this varies widely with configuration and Spring version.

There's also no reason the end result has to be web pages. It can do the same thing to locate RMI end points, handle SOAP requests, anything that can come into a servlet.

Decimal number regular expression, where digit after decimal is optional

^\d+(()|(\.\d+)?)$

Came up with this. Allows both integer and decimal, but forces a complete decimal (leading and trailing numbers) if you decide to enter a decimal.

java.lang.OutOfMemoryError: Java heap space

To increase the heap size you can use the -Xmx argument when starting Java; e.g.

-Xmx256M

Add support library to Android Studio project

This is way more simpler with Maven dependency feature:

  1. Open File -> Project Structure... menu.
  2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
  3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
  4. Enter "support-v4" into the search field and click the icon with magnifying glass.
  5. Select "com.google.android:support-v4:r7@jar" from the drop-down list.
  6. Click "OK".
  7. Clean and rebuild your project.

Hope this will help!

Java 8 Filter Array Using Lambda

even simpler, adding up to String[],

use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

import org.apache.commons.lang3.StringUtils;

    String test = "a\nb\n\nc\n";
    String[] lines = test.split("\\n", -1);


    String[]  result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
    System.out.println(Arrays.toString(lines));
    System.out.println(Arrays.toString(result));

and output: [a, b, , c, ] [a, b, c]

Is it possible to override / remove background: none!important with jQuery?

Why does not it work? Because the background CSS with background:none!important has one #ID

A CSS selector file that contains an #id will always have a higher value than one .class

If you want to work, you need add #id on your .image-list li like this:

#an-element .image-list li {
    display: inline-block;
    background-image: url("http://placekitten.com/150/50")!important;
    padding: 1em;
    border: 1px solid blue;
}

result here

Bootstrap 3 2-column form layout

You could use the bootstrap grid system :

<div class="col-md-6 form-group">
    <label for="textbox1">Label1</label>
    <input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
    <label for="textbox2">Label2</label>
    <input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">

http://getbootstrap.com/css/#grid

Is that what you want to achieve?

FileNotFoundException..Classpath resource not found in spring?

This is due to spring-config.xml is not in classpath.

Add complete path of spring-config.xml to your classpath.

Also write command you execute to run your project. You can check classpath in command.

How to Resize a Bitmap in Android?

Try this: This function resizes a bitmap proportionally. When the last parameter is set to "X" the newDimensionXorY is treated as s new width and when set to "Y" a new height.

public Bitmap getProportionalBitmap(Bitmap bitmap, 
                                    int newDimensionXorY, 
                                    String XorY) {
    if (bitmap == null) {
        return null;
    }

    float xyRatio = 0;
    int newWidth = 0;
    int newHeight = 0;

    if (XorY.toLowerCase().equals("x")) {
        xyRatio = (float) newDimensionXorY / bitmap.getWidth();
        newHeight = (int) (bitmap.getHeight() * xyRatio);
        bitmap = Bitmap.createScaledBitmap(
            bitmap, newDimensionXorY, newHeight, true);
    } else if (XorY.toLowerCase().equals("y")) {
        xyRatio = (float) newDimensionXorY / bitmap.getHeight();
        newWidth = (int) (bitmap.getWidth() * xyRatio);
        bitmap = Bitmap.createScaledBitmap(
            bitmap, newWidth, newDimensionXorY, true);
    }
    return bitmap;
}

'IF' in 'SELECT' statement - choose output value based on column values

SELECT CompanyName, 
    CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
         WHEN Country = 'Brazil' THEN 'South America'
         ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;

How to execute function in SQL Server 2008

It looks like there's something else called Afisho_rankimin in your DB so the function is not being created. Try calling your function something else. E.g.

CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
   BEGIN
       Declare @rankimi int
       Select @rankimi=dbo.RESTORANTET.Rankimi
       From RESTORANTET
       Where  dbo.RESTORANTET.ID_Rest=@emri_rest
       RETURN @rankimi
  END
  GO

Note that you need to call this only once, not every time you call the function. After that try calling

SELECT dbo.Afisho_rankimin1(5) AS Rankimi 

stopPropagation vs. stopImmediatePropagation

Here I am adding my JSfiddle example for stopPropagation vs stopImmediatePropagation. JSFIDDLE

_x000D_
_x000D_
let stopProp = document.getElementById('stopPropagation');_x000D_
let stopImmediate = document.getElementById('stopImmediatebtn');_x000D_
let defaultbtn = document.getElementById("defalut-btn");_x000D_
_x000D_
_x000D_
stopProp.addEventListener("click", function(event){_x000D_
 event.stopPropagation();_x000D_
  console.log('stopPropagation..')_x000D_
  _x000D_
})_x000D_
stopProp.addEventListener("click", function(event){_x000D_
  console.log('AnotherClick')_x000D_
  _x000D_
})_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
  event.stopImmediatePropagation();_x000D_
    console.log('stopimmediate')_x000D_
})_x000D_
_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
    console.log('ImmediateStop Another event wont work')_x000D_
})_x000D_
_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
    alert("Default Clik");_x000D_
})_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
    console.log("Second event defined will also work same time...")_x000D_
})
_x000D_
div{_x000D_
  margin: 10px;_x000D_
}
_x000D_
<p>_x000D_
The simple example for event.stopPropagation and stopImmediatePropagation?_x000D_
Please open console to view the results and click both button._x000D_
</p>_x000D_
<div >_x000D_
<button id="stopPropagation">_x000D_
stopPropagation-Button_x000D_
</button>_x000D_
</div>_x000D_
<div  id="grand-div">_x000D_
  <div class="new" id="parent-div">_x000D_
    <button id="stopImmediatebtn">_x000D_
    StopImmediate_x000D_
    </button>_x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
<button id="defalut-btn">_x000D_
Normat Button_x000D_
</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.

As separate files the script will load just fine but as one individual file you need the semicolons.

fatal: does not appear to be a git repository

This is typically because you have not set the origin alias on your Git repository.

Try

git remote add origin URL_TO_YOUR_REPO

This will add an alias in your .git/config file for the remote clone/push/pull site URL. This URL can be found on your repository Overview page.

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.

You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:

sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
  abstract erubis activesupport mime-types mail text-hyphen text-format   \
  thor i18n rake bundler arel railties rails --prerelease --force

How to set margin of ImageView using code, not xml

sample code is here ,its very easy

LayoutParams params1 = (LayoutParams)twoLetter.getLayoutParams();//twoletter-imageview
                params1.height = 70;
                params1.setMargins(0, 210, 0, 0);//top margin -210 here
                twoLetter.setLayoutParams(params1);//setting layout params
                twoLetter.setImageResource(R.drawable.oo);

Why is there no SortedList in Java?

List iterators guarantee first and foremost that you get the list's elements in the internal order of the list (aka. insertion order). More specifically it is in the order you've inserted the elements or on how you've manipulated the list. Sorting can be seen as a manipulation of the data structure, and there are several ways to sort the list.

I'll order the ways in the order of usefulness as I personally see it:

1. Consider using Set or Bag collections instead

NOTE: I put this option at the top because this is what you normally want to do anyway.

A sorted set automatically sorts the collection at insertion, meaning that it does the sorting while you add elements into the collection. It also means you don't need to manually sort it.

Furthermore if you are sure that you don't need to worry about (or have) duplicate elements then you can use the TreeSet<T> instead. It implements SortedSet and NavigableSet interfaces and works as you'd probably expect from a list:

TreeSet<String> set = new TreeSet<String>();
set.add("lol");
set.add("cat");
// automatically sorts natural order when adding

for (String s : set) {
    System.out.println(s);
}
// Prints out "cat" and "lol"

If you don't want the natural ordering you can use the constructor parameter that takes a Comparator<T>.

Alternatively, you can use Multisets (also known as Bags), that is a Set that allows duplicate elements, instead and there are third-party implementations of them. Most notably from the Guava libraries there is a TreeMultiset, that works a lot like the TreeSet.

2. Sort your list with Collections.sort()

As mentioned above, sorting of Lists is a manipulation of the data structure. So for situations where you need "one source of truth" that will be sorted in a variety of ways then sorting it manually is the way to go.

You can sort your list with the java.util.Collections.sort() method. Here is a code sample on how:

List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");

Collections.sort(strings);
for (String s : strings) {
    System.out.println(s);
}
// Prints out "cat" and "lol"

Using comparators

One clear benefit is that you may use Comparator in the sort method. Java also provides some implementations for the Comparator such as the Collator which is useful for locale sensitive sorting strings. Here is one example:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY); // ignores casing

Collections.sort(strings, usCollator);

Sorting in concurrent environments

Do note though that using the sort method is not friendly in concurrent environments, since the collection instance will be manipulated, and you should consider using immutable collections instead. This is something Guava provides in the Ordering class and is a simple one-liner:

List<string> sorted = Ordering.natural().sortedCopy(strings);

3. Wrap your list with java.util.PriorityQueue

Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the java.util.PriorityQueue class.

Nico Haase linked in the comments to a related question that also answers this.

In a sorted collection you most likely don't want to manipulate the internal data structure which is why PriorityQueue doesn't implement the List interface (because that would give you direct access to its elements).

Caveat on the PriorityQueue iterator

The PriorityQueue class implements the Iterable<E> and Collection<E> interfaces so it can be iterated as usual. However, the iterator is not guaranteed to return elements in the sorted order. Instead (as Alderath points out in the comments) you need to poll() the queue until empty.

Note that you can convert a list to a priority queue via the constructor that takes any collection:

List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");

PriorityQueue<String> sortedStrings = new PriorityQueue(strings);
while(!sortedStrings.isEmpty()) {
    System.out.println(sortedStrings.poll());
}
// Prints out "cat" and "lol"

4. Write your own SortedList class

NOTE: You shouldn't have to do this.

You can write your own List class that sorts each time you add a new element. This can get rather computation heavy depending on your implementation and is pointless, unless you want to do it as an exercise, because of two main reasons:

  1. It breaks the contract that List<E> interface has because the add methods should ensure that the element will reside in the index that the user specifies.
  2. Why reinvent the wheel? You should be using the TreeSet or Multisets instead as pointed out in the first point above.

However, if you want to do it as an exercise here is a code sample to get you started, it uses the AbstractList abstract class:

public class SortedList<E> extends AbstractList<E> {

    private ArrayList<E> internalList = new ArrayList<E>();

    // Note that add(E e) in AbstractList is calling this one
    @Override 
    public void add(int position, E e) {
        internalList.add(e);
        Collections.sort(internalList, null);
    }

    @Override
    public E get(int i) {
        return internalList.get(i);
    }

    @Override
    public int size() {
        return internalList.size();
    }

}

Note that if you haven't overridden the methods you need, then the default implementations from AbstractList will throw UnsupportedOperationExceptions.

How do I search for files in Visual Studio Code?

To search for specifil file types in visual studio code.
Type ctrl+p and then search for something like *.py.
Simple and easy

No Persistence provider for EntityManager named

The question has been answered already, but just wanted to post a tip that was holding me up. This exception was being thrown after previous errors. I was getting this:

property toplink.platform.class.name is deprecated, property toplink.target-database should be used instead.

Even though I had changed the persistence.xml to include the new property name:

<property name="toplink.target-database" value="oracle.toplink.platform.database.oracle.Oracle10Platform"/>

Following the message about the deprecated property name I was getting the same PersistenceException like above and a whole other string of exceptions. My tip: make sure to check the beginning of the exception sausage.

There seems to be a bug in Glassfish v2.1.1 where redeploys or undeploys and deploys are not updating the persistence.xml, which is being cached somewhere. I had to restart the server and then it worked.

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}

Go / golang time.Now().UnixNano() convert to milliseconds?

Simple-read but precise solution would be:

func nowAsUnixMilliseconds(){
    return time.Now().Round(time.Millisecond).UnixNano() / 1e6
}

This function:

  1. Correctly rounds the value to the nearest millisecond (compare with integer division: it just discards decimal part of the resulting value);
  2. Does not dive into Go-specifics of time.Duration coercion — since it uses a numerical constant that represents absolute millisecond/nanosecond divider.

P.S. I've run benchmarks with constant and composite dividers, they showed almost no difference, so feel free to use more readable or more language-strict solution.

Angular 6 Material mat-select change method removed

If you're using Reactive forms you can listen for changes to the select control like so..

this.form.get('mySelectControl').valueChanges.subscribe(value => { ... do stuff ... })

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer

Spring Data Rest - _links

Replace CRLF using powershell

You have not specified the version, I'm assuming you are using Powershell v3.

Try this:

$path = "C:\Users\abc\Desktop\File\abc.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force

Editor's note: As mike z points out in the comments, Set-Content appends a trailing CRLF, which is undesired. Verify with: 'hi' > t.txt; (Get-Content -Raw t.txt).Replace("`r`n","`n") | Set-Content t.txt; (Get-Content -Raw t.txt).EndsWith("`r`n"), which yields $True.

Note this loads the whole file in memory, so you might want a different solution if you want to process huge files.

UPDATE

This might work for v2 (sorry nowhere to test):

$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out

Editor's note: Note that this solution (now) writes to a different file and is therefore not equivalent to the (still flawed) v3 solution. (A different file is targeted to avoid the pitfall Ansgar Wiechers points out in the comments: using > truncates the target file before execution begins). More importantly, though: this solution too appends a trailing CRLF, which may be undesired. Verify with 'hi' > t.txt; (Get-Content t.txt) -join "`n" > t.NEW.txt; [io.file]::ReadAllText((Convert-Path t.NEW.txt)).endswith("`r`n"), which yields $True.

Same reservation about being loaded to memory though.

JQuery / JavaScript - trigger button click from another button click event

Add id's to both inputs, id="first" and id="second"

//trigger second button
$("#second").click()

adding css file with jquery

    var css_link = $("<link>", {
        rel: "stylesheet",
        type: "text/css",
        href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
    });
    css_link.appendTo('head');

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Both of these operations restore a set of files to a previous state and are essentially faster, safer ways of undoing mistakes than using the p4 obliterate command (and you don't need admin access to use them).

In the case of "Rollback...", this could be any number of files, even an entire depot. You can tell it to rollback to a specific revision, changelist, or label. The files are restored to the state they were in at the time of creation of that revision, changelist, or label.

In the case of "Back Out Submitted Changelist #####", the restore operation is restricted to the files that were submitted in changelist #####. Those files are restored to the state they were in before you submitted that changelist, provided no changes have been made to those files since. If subsequent changes have been made to any of those files, Perforce will tell you that those files are now out of date. You will have to sync to the head revision and then resolve the differences. This way you don't inadvertently clobber any changes that you actually want to keep.

Both operations work by essentially submitting old revisions as new revisions. When you perform a "Rollback...", you are restoring the files to the state they were in at a specific point in time, regardless of what has happened to them since. When you perform a "Back out...", you are attempting to undo the changes you made at a specific point in time, while maintaining the changes that have occurred since.

How to print a list with integers without the brackets, commas and no quotes?

Something like this should do it:

for element in list_:
   sys.stdout.write(str(element))

Set bootstrap modal body height by percentage

This worked for me

.modal-dialog,
.modal-content {
    /* 80% of window height */
    height: 80%;
}

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;
}

Fiddle: http://jsfiddle.net/mehmetatas/18dpgqpb/2/

How to increase the distance between table columns in HTML?

If I understand correctly, you want this fiddle.

_x000D_
_x000D_
table {_x000D_
  background: gray;_x000D_
}_x000D_
td {    _x000D_
  display: block;_x000D_
  float: left;_x000D_
  padding: 10px 0;_x000D_
  margin-right:50px;_x000D_
  background: white;_x000D_
}_x000D_
td:last-child {_x000D_
  margin-right: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Hello HTML!</td>_x000D_
    <td>Hello CSS!</td>_x000D_
    <td>Hello JS!</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to insert data to MySQL having auto incremented primary key?

I used something like this to type only values in my SQL request. There are too much columns in my case, and im lazy.

insert into my_table select max(id)+1, valueA, valueB, valueC.... from my_table; 

Bootstrap 3 - How to load content in modal body via AJAX?

create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.

 $.ajax({url: "registration.html", success: function(result){
            //alert("success"+result);
              $("#contentBody").html(result);
            $("#myModal").modal('show'); 

        }});

once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.

You can call controller and get the page content and you can show that in your modal.

below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...

index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script type="text/javascript">
function loadme(){
    //alert("loadig");

    $.ajax({url: "registration.html", success: function(result){
        //alert("success"+result);
          $("#contentBody").html(result);
        $("#myModal").modal('show'); 

    }});
}
</script>
</head>
<body>

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>


<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content" >
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body" id="contentBody">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</body>
</html>

registration.html
-------------------- 
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}

form {
    border: 3px solid #f1f1f1;
    font-family: Arial;
}

.container {
    padding: 20px;
    background-color: #f1f1f1;
    width: 560px;
}

input[type=text], input[type=submit] {
    width: 100%;
    padding: 12px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

input[type=checkbox] {
    margin-top: 16px;
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    border: none;
}

input[type=submit]:hover {
    opacity: 0.8;
}
</style>
<body>

<h2>CSS Newsletter</h2>

<form action="/action_page.php">
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
  </div>

  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>

  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>

</body>
</html>

Text in HTML Field to disappear when clicked?

To accomplish that, you can use the two events onfocus and onblur:

<input type="text" name="theName" value="DefaultValue"
  onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
  onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
  style="color:#BBB;" />

Change table header color using bootstrap

You could simply apply one of the bootstrap contextual background colors to the header row. In this case (blue background, white text): primary.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<table class="table" >_x000D_
  <tr class="bg-primary">_x000D_
    <th>_x000D_
        Firstname_x000D_
    </th>_x000D_
    <th>_x000D_
        Surname_x000D_
    </th>_x000D_
    <th></th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>John</td>_x000D_
    <td>Doe</td>_x000D_
  </tr>_x000D_
    <tr>_x000D_
      <td>Jane</td>_x000D_
      <td>Roe</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to combine multiple inline style objects?

Ways of inline styling:

<View style={[styles.red, {fontSize: 25}]}>
  <Text>Hello World</Text>
</View>

<View style={[styles.red, styles.blue]}>
  <Text>Hello World</Text>
</View>

  <View style={{fontSize:10,marginTop:10}}>
  <Text>Hello World</Text>
</View>

Print all key/value pairs in a Java ConcurrentHashMap

  //best and simple way to show keys and values

    //initialize map
    Map<Integer, String> map = new HashMap<Integer, String>();

   //Add some values
    map.put(1, "Hi");
    map.put(2, "Hello");

    // iterate map using entryset in for loop
    for(Entry<Integer, String> entry : map.entrySet())
    {   //print keys and values
         System.out.println(entry.getKey() + " : " +entry.getValue());
    }

   //Result : 
    1 : Hi
    2 : Hello

Which maven dependencies to include for spring 3.0?

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

Regular Expressions- Match Anything

<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>

http://sandbox.phpcode.eu/g/b2243.php

Online code beautifier and formatter

What language?? There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.

Good ol' indent is a nice, customizable, command-line utility to format C and C++ programs.

Best way to create a simple python web service

Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

For mine, Resetting content and settings of Simulator works. To reset the simulator follow the steps:

iOS Simulator -> Reset Content and Settings -> Press Reset (on the warning which will come)

HTML if image is not found

Well you can try this.

  <object data="URL_TO_Default_img.png" type="image/png">
   <img src="your_original_image.png" />
  </object>

this worked for me. let me know about you.

CodeIgniter Select Query

use Result Rows.
row() method returns a single result row.

$id = $this 
    -> db
    -> select('id')
    -> where('email', $email)
    -> limit(1)
    -> get('users')
    -> row();

then, you can simply use as you want. :)

echo "ID is" . $id;

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

How do I get my page title to have an icon?

They're called favicons, and are quite easy to make/use. Have a read of http://www.favicon.com/ for help.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.

Microsoft.ReportViewer.Common Version=12.0.0.0

First install SQLSysClrTypes for Ms SQL 2014 and secondly install ReportViewer for ms sql 2014

Restart your application or project, in my case its resolved.

How to locate the git config file in Mac

I use this function which is saved in .bash_profile and it works a treat for me.

function show_hidden () {
        { defaults write com.apple.finder AppleShowAllFiles $1; killall -HUP Finder; }
}

How to use:

show_hidden true|false 

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

Java Synchronized list

That should be fine as long as you don't require the "remove" method to be atomic.

In other words, if the "do something" checks that the item appears more than once in the list for example, it is possible that the result of that check will be wrong by the time you reach the next line.

Also, make sure you synchronize on the list when iterating:

synchronized(list) {
    for (Object o : list) {}
}

As mentioned by Peter Lawrey, CopyOnWriteArrayList can make your life easier and can provide better performance in a highly concurrent environment.

Closing Excel Application Process in C# after Data Access

Think of this, it kills the process:

System.Diagnostics.Process[] process=System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
    if (!string.IsNullOrEmpty(p.ProcessName))
    {
        try
        {
            p.Kill();
        }
        catch { }
    }
}

Also, did you try just close it normally?

myWorkbook.SaveAs(@"C:/pape.xltx", missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
excelBook.Close(null, null, null);                 // close your workbook
excelApp.Quit();                                   // exit excel application
excel = null;                                      // set to NULL

Generate a unique id

If you want to use sha-256 (guid would be faster) then you would need to do something like

SHA256 shaAlgorithm = new SHA256Managed();
byte[] shaDigest = shaAlgorithm.ComputeHash(ASCIIEncoding.ASCII.GetBytes(url));
return BitConverter.ToString(shaDigest);

Of course, it doesn't have to ascii and it can be any other kind of hashing algorithm as well

Split text with '\r\n'

Following code gives intended results.

string text="some interesting text\nsome text that should be in the same line\r\nsome 
text should be in another line"
var results = text.Split(new[] {"\n","\r\n"}, StringSplitOptions.None);

Sql Server trigger insert values from new row into another table

Create 
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
     --Sql logic
     print 'Hello world'     
 end 

Best way to convert strings to symbols in hash

This is not exactly a one-liner, but it turns all string keys into symbols, also the nested ones:

def recursive_symbolize_keys(my_hash)
  case my_hash
  when Hash
    Hash[
      my_hash.map do |key, value|
        [ key.respond_to?(:to_sym) ? key.to_sym : key, recursive_symbolize_keys(value) ]
      end
    ]
  when Enumerable
    my_hash.map { |value| recursive_symbolize_keys(value) }
  else
    my_hash
  end
end

Delete specific line from a text file?

No rocket scien code require .Hope this simple and short code will help.

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

OR use this

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Provide the path of the text file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }

Exporting data In SQL Server as INSERT INTO

After search a lot, it was my best shot:

If you have a lot of data and needs a compact and elegant script, try it: SSMS Tools Pack

It generates a union all select statements to insert items into target tables and handle transactions pretty well.

Screenshot

Possible reason for NGINX 499 error codes

For my part I had enabled ufw but I forgot to expose my upstreams ports ._.

How to echo out table rows from the db (php)

Nested loop to display all rows & columns of resulting table:

$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
   for( $j = 0; $j<$cols; $j++ ) {
     echo mysql_result($result, $i, $j)."<br>";
   }
}

Can be made more complex with data decryption/decoding, error checking & html formatting before display.

Tested in MS Edge & G Chrome, PHP 5.6

Google Colab: how to read data from my google drive?

You can't permanently store a file on colab. Though you can import files from your drive and everytime when you are done with file you can save it back.

To mount the google drive to your Colab session

from google.colab import drive
drive.mount('/content/gdrive')

you can simply write to google drive as you would to a local file system Now if you see your google drive will be loaded in the Files tab. Now you can access any file from your colab, you can write as well as read from it. The changes will be done real time on your drive and anyone having the access link to your file can view the changes made by you from your colab.

Example

with open('/content/gdrive/My Drive/filename.txt', 'w') as f:
   f.write('values')

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

How to determine if a number is positive or negative?

Well, taking advantage of casting (since we don't care what the actual value is) perhaps the following would work. Bear in mind that the actual implementations do not violate the API rules. I've edited this to make the method names a bit more obvious and in light of @chris' comment about the {-1,+1} problem domain. Essentially, this problem does not appear to solvable without recourse to API methods within Float or Double that reference the native bit structure of the float and double primitives.

As everybody else has said: Stupid interview question. Grr.

public class SignDemo {

  public static boolean isNegative(byte x) {
    return (( x >> 7 ) & 1) == 1;
  }

  public static boolean isNegative(short x) {
    return (( x >> 15 ) & 1) == 1;
  }

  public static boolean isNegative(int x) {
    return (( x >> 31 ) & 1) == 1;
  }

  public static boolean isNegative(long x) {
    return (( x >> 63 ) & 1) == 1;
  }

  public static boolean isNegative(float x) {
    return isNegative((int)x);
  }

  public static boolean isNegative(double x) {
    return isNegative((long)x);
  }

  public static void main(String[] args) {


    // byte
    System.out.printf("Byte %b%n",isNegative((byte)1));
    System.out.printf("Byte %b%n",isNegative((byte)-1));

    // short
    System.out.printf("Short %b%n",isNegative((short)1));
    System.out.printf("Short %b%n",isNegative((short)-1));

    // int
    System.out.printf("Int %b%n",isNegative(1));
    System.out.printf("Int %b%n",isNegative(-1));

    // long
    System.out.printf("Long %b%n",isNegative(1L));
    System.out.printf("Long %b%n",isNegative(-1L));

    // float
    System.out.printf("Float %b%n",isNegative(Float.MAX_VALUE));
    System.out.printf("Float %b%n",isNegative(Float.NEGATIVE_INFINITY));

    // double
    System.out.printf("Double %b%n",isNegative(Double.MAX_VALUE));
    System.out.printf("Double %b%n",isNegative(Double.NEGATIVE_INFINITY));

    // interesting cases
    // This will fail because we can't get to the float bits without an API and
    // casting will round to zero
    System.out.printf("{-1,1} (fail) %b%n",isNegative(-0.5f));

  }

}

"SyntaxError: Unexpected token < in JSON at position 0"

This might cause due to your javascript code is looking at some json response and you received something else like text.

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

beyond top level package error in relative import

Not sure in python 2.x but in python 3.6, assuming you are trying to run the whole suite, you just have to use -t

-t, --top-level-directory directory Top level directory of project (defaults to start directory)

So, on a structure like

project_root
  |
  |----- my_module
  |          \
  |           \_____ my_class.py
  |
  \ tests
      \___ test_my_func.py

One could for example use:

python3 unittest discover -s /full_path/project_root/tests -t /full_path/project_root/

And still import the my_module.my_class without major dramas.

GitHub "fatal: remote origin already exists"

In the special case that you are creating a new repository starting from an old repository that you used as template (Don't do this if this is not your case). Completely erase the git files of the old repository so you can start a new one:

rm -rf .git

And then restart a new git repository as usual:

git init
git add whatever.wvr ("git add --all" if you want to add all files)
git commit -m "first commit"
git remote add origin [email protected]:ppreyer/first_app.git
git push -u origin master

Convert JS date time to MySQL datetime

Simple: just Replace the T. Format that I have from my <input class="form-control" type="datetime-local" is : "2021-02-10T18:18"

So just replace the T, and it would look like this: "2021-02-10 18:18" SQL will eat that.

Here is my function:

var CreatedTime = document.getElementById("example-datetime-local-input").value;

var newTime = CreatedTime.replace("T", " ");

Reference: https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

Object cannot be cast from DBNull to other types

I suspect that the line

DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));

is causing the problem. Is it possible that the op_Id value is being set to null by the stored procedure?

To Guard against it use the Convert.IsDBNull method. For example:

if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, "op_Id"))
{
 DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
}
else 
{
 DataTO.Id = ...some default value or perform some error case management
}

How to check for palindrome using Python logic

Below the code will print 0 if it is Palindrome else it will print -1

Optimized Code

word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome

Output: 0

word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome

Output: -1

Explaination:

when searching the string the value that is returned is the value of the location that the string starts at.

So when you do word.find(word[::-1]) it finds nepalapen at location 0 and [::-1] reverses nepalapen and it still is nepalapen at location 0 so 0 is returned.

Now when we search for nepalapend and then reverse nepalapend to dnepalapen it renders a FALSE statement nepalapend was reversed to dnepalapen causing the search to fail to find nepalapend resulting in a value of -1 which indicates string not found.


Another method print true if palindrome else print false

word = "nepalapen"
print(word[::-1]==word[::1])

output: TRUE

How to convert string date to Timestamp in java?

tl;dr

java.sql.Timestamp                  
.valueOf(                           // Class-method parses SQL-style formatted date-time strings.
    "2007-11-11 12:13:14"
)                                   // Returns a `Timestamp` object.
.toInstant()                        // Converts from terrible legacy classes to modern *java.time* class.

java.sql.Timestamp.valueOf parses SQL format

If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.

The java.sql.Timestamp class has a valueOf method to directly parse such strings.

String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;

java.time

In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.

System.out.println( "Output: " + ts.toInstant().toString() );

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

How to embed a Facebook page's feed into my website

Correct me if I am wrong, but it seems that Facebook deprecated the Activity Feed plugin. Additionally there does not seem to be any substitute plugin for activity anymore.

Here is the link: https://developers.facebook.com/docs/plugins/activity

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

This happens to me when my view controller originally had an .xib file, but now is created programmatically.

Even though I have deleted the .xib file from this project. The users iPhone/iPad may contain an .xib files for this viewcontroller.

Attempting to load an .xib file usually causes this crash:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x18afe0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key welcomeLabel.'

Solution when creating it programmatically may be this:

-(void)loadView {
    // Ensure that we don't load an .xib file for this viewcontroller
    self.view = [UIView new];
}

How to install wkhtmltopdf on a linux based (shared hosting) web server

Debian 8 Jessie
This works sudo apt-get install wkhtmltopdf

boolean in an if statement

Also can be tested with Boolean object, if you need to test an object error={Boolean(errors.email)}

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Change column type in pandas

this below code will change datatype of column.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

in place of data type you can give your datatype .what do you want like str,float,int etc.

How to create JSON Object using String?

JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

How to convert an ArrayList containing Integers to primitive int array?

Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this.

import org.apache.commons.lang.ArrayUtils;
...
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(2));
    int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

However, as Jon showed, it is pretty easy to do this by yourself instead of using external libraries.

Inline SVG in CSS

Inline SVG coming from 3rd party sources (like Google charts) may not contain XML namespace attribute (xmlns="http://www.w3.org/2000/svg") in SVG element (or maybe it's removed once SVG is rendered - neither browser inspector nor jQuery commands from browser console show the namespace in SVG element).

When you need to re-purpose these svg snippets for your other needs (background-image in CSS or img element in HTML) watch out for the missing namespace. Without the namespace browsers may refuse to display SVG (regardless of the encoding utf8 or base64).

Can I update a JSF component from a JSF backing bean method?

I also tried to update a component from a jsf backing bean/class

You need to do the following after manipulating the UI component:

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())

It is important to use the clientId instead of the (server-side) componentId!!

How to display an alert box from C# in ASP.NET?

Hey Try This Code.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);

Cheers

C# adding a character in a string

string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
  newAlpha = alpha.Insert(i, "-");
  alpha = newAlpha;
}

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I was able to solve "ORA-00604: error" by Droping with purge.

DROP TABLE tablename PURGE

How to see the proxy settings on windows?

You can use a tool called: NETSH

To view your system proxy information via command line:

netsh.exe winhttp show proxy

Another way to view it is to open IE, then click on the "gear" icon, then Internet options -> Connections tab -> click on LAN settings

How to keep an iPhone app running on background fully operational

From ioS 7 onwards, there are newer ways for apps to run in background. Apple now recognizes that apps have to constantly download and process data constantly.

Here is the new list of all the apps which can run in background.

  1. Apps that play audible content to the user while in the background, such as a music player app
  2. Apps that record audio content while in the background.
  3. Apps that keep users informed of their location at all times, such as a navigation app
  4. Apps that support Voice over Internet Protocol (VoIP)
  5. Apps that need to download and process new content regularly
  6. Apps that receive regular updates from external accessories

You can declare app's supported background tasks in Info.plist using X Code 5+. For eg. adding UIBackgroundModes key to your app’s Info.plist file and adding a value of 'fetch' to the array allows your app to regularly download and processes small amounts of content from the network. You can do the same in the 'capabilities' tab of Application properties in XCode 5 (attaching a snapshot)

Capabilities tab in XCode 5 You can find more about this in Apple documentation

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

How to close activity and go back to previous activity in android

I believe your second activity is probably not linked to your main activity as a child activity. Check your AndroidManifest.xml file and see if the <activity> entry for your child activity includes a android:parentActivityName attribute. It should look something like this:

<?xml ...?>
...
<activity
    android:name=".MainActivity"
    ...>
</activity>
<activity
    android:name=".ChildActivity"
    android:parentActivityName=".MainActivity"
    ...>
</activity>
...

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

List passed by ref - help me explain this behaviour

Initially, it can be represented graphically as follow:

Init states

Then, the sort is applied myList.Sort(); Sort collection

Finally, when you did: myList' = myList2, you lost the one of the reference but not the original and the collection stayed sorted.

Lost reference

If you use by reference (ref) then myList' and myList will become the same (only one reference).

Note: I use myList' to represent the parameter that you use in ChangeList (because you gave the same name as the original)

How to delete Tkinter widgets from a window?

Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.

from tkinter import *

cnt = 0


def MsgClick(event):
    children = root.winfo_children()
    for child in children:
        # print("type of widget is : " + str(type(child)))
        if str(type(child)) == "<class 'tkinter.Message'>":
            # print("Here Message widget will destroy")
            child.destroy()
            return

def MsgMotion(event):
  print("Mouse position: (%s %s)" % (event.x, event.y))
  return


def ButtonClick(event):
    global cnt, msg
    cnt += 1
    msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
    msg.config(bg='lightgreen', font=('times', 24, 'italic'))
    msg.bind("<Button-1>", MsgClick)
    msg.bind("<Motion>", MsgMotion)
    msg.pack()
    #print(type(msg)) tkinter.Message


def ButtonDoubleClick(event):
    import sys; sys.exit()


root = Tk()

root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
    root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)

root.mainloop()

Hope it will help someone...

CSS: Set Div height to 100% - Pixels

Now with css3 you could try to use calc()

.main{
  height: calc(100% - 111px);
}

have a look at this answer: Div width 100% minus fixed amount of pixels

Disable scrolling in webview?

Here is my code for disabling all scrolling in webview:

  // disable scroll on touch
  webview.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      return (event.getAction() == MotionEvent.ACTION_MOVE);
    }
  });

To only hide the scrollbars, but not disable scrolling:

WebView.setVerticalScrollBarEnabled(false);
WebView.setHorizontalScrollBarEnabled(false);

or you can try using single column layout but this only works with simple pages and it disables horizontal scrolling:

   //Only disabled the horizontal scrolling:
   webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

You can also try to wrap your webview with vertically scrolling scrollview and disable all scrolling on the webview:

<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"    >
  <WebView
    android:id="@+id/mywebview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none" />
</ScrollView>

And set

webview.setScrollContainer(false);

Don't forget to add the webview.setOnTouchListener(...) code above to disable all scrolling in the webview. The vertical ScrollView will allow for scrolling of the WebView's content.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

1) I had to do the following with my configuration: (Add BackConnectionHostNames or Disable Loopback Check) http://support.microsoft.com/kb/896861

2) I was working off a dev system on an isolated dev network. I had gotten it working using the dev system's computer name in the URL to the web service, but when I modified the URL to the URL that would be used in production (rather than the computer name), I started getting the NTLM error.

3) I noticed the security log showed that the service account failing to login with an error similar to the one in the MSDN article.

4) Adding the BackConnectionHostNames made it so I could log into the server via a browser running on the server, but the service account still had NTLM errors when trying to authenticate for the web services. I wound up disabling the loop back check and that fixed it for me.

Meaning of *& and **& in C++

To understand those phrases let's look at the couple of things:

typedef double Foo;
void fooFunc(Foo &_bar){ ... }

So that's passing a double by reference.

typedef double* Foo;
void fooFunc(Foo &_bar){ ... }

now it's passing a pointer to a double by reference.

typedef double** Foo;
void fooFunc(Foo &_bar){ ... }

Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.

Convert char * to LPWSTR

The clean way to use mbstowcs is to call it twice to find the length of the result:

  const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;

Don't forget to call setlocale(LC_CTYPE, ""); at the beginning of your program!

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

Writing List of Strings to Excel CSV File in Python

The csv.writer writerow method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

Do either:

import csv
RESULTS = [
    ['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerows(RESULTS)

or:

import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writerow(RESULT)

How do I Set Background image in Flutter?

Other answers are great. This is another way it can be done.

  1. Here I use SizedBox.expand() to fill available space and for passing tight constraints for its children (Container).
  2. BoxFit.cover enum to Zoom the image and cover whole screen
 Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand( // -> 01
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
              fit: BoxFit.cover,    // -> 02
            ),
          ),
        ),
      ),
    );
  }

screenshot

How to get the function name from within that function?

Easy way to get function name from within fuction you are running.

_x000D_
_x000D_
function x(){alert(this.name)};x()
_x000D_
_x000D_
_x000D_

I need to get all the cookies from the browser

You can only access cookies for a specific site. Using document.cookie you will get a list of escaped key=value pairs seperated by a semicolon.

secret=do%20not%20tell%you;last_visit=1225445171794

To simplify the access, you have to parse the string and unescape all entries:

var getCookies = function(){
  var pairs = document.cookie.split(";");
  var cookies = {};
  for (var i=0; i<pairs.length; i++){
    var pair = pairs[i].split("=");
    cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
  }
  return cookies;
}

So you might later write:

var myCookies = getCookies();
alert(myCookies.secret); // "do not tell you"

regex pattern to match the end of a string

Use this Regex pattern: /([^/]*)$

Signed to unsigned conversion in C - is it always safe?

What implicit conversions are going on here,

i will be converted to an unsigned integer.

and is this code safe for all values of u and i?

Safe in the sense of being well-defined yes (see https://stackoverflow.com/a/50632/5083516 ).

The rules are written in typically hard to read standards-speak but essentially whatever representation was used in the signed integer the unsigned integer will contain a 2's complement representation of the number.

Addition, subtraction and multiplication will work correctly on these numbers resulting in another unsigned integer containing a twos complement number representing the "real result".

division and casting to larger unsigned integer types will have well-defined results but those results will not be 2's complement representations of the "real result".

(Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)

While conversions from signed to unsigned are defined by the standard the reverse is implementation-defined both gcc and msvc define the conversion such that you will get the "real result" when converting a 2's complement number stored in an unsigned integer back to a signed integer. I expect you will only find any other behaviour on obscure systems that don't use 2's complement for signed integers.

https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation https://msdn.microsoft.com/en-us/library/0eex498h.aspx

Calling C/C++ from Python?

The question is how to call a C function from Python, if I understood correctly. Then the best bet are Ctypes (BTW portable across all variants of Python).

>>> from ctypes import *
>>> libc = cdll.msvcrt
>>> print libc.time(None)
1438069008
>>> printf = libc.printf
>>> printf("Hello, %s\n", "World!")
Hello, World!
14
>>> printf("%d bottles of beer\n", 42)
42 bottles of beer
19

For a detailed guide you may want to refer to my blog article.

Generating sql insert into for Oracle

If you have an empty table the Export method won't work. As a workaround. I used the Table View of Oracle SQL Developer. and clicked on Columns. Sorted by Nullable so NO was on top. And then selected these non nullable values using shift + select for the range.

This allowed me to do one base insert. So that Export could prepare a proper all columns insert.

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

Function overloading in Javascript - Best practices

#Forwarding Pattern => the best practice on JS overloading Forward to another function which name is built from the 3rd & 4th points :

  1. Using number of arguments
  2. Checking types of arguments
window['foo_'+arguments.length+'_'+Array.from(arguments).map((arg)=>typeof arg).join('_')](...arguments)

#Application on your case :

 function foo(...args){
          return window['foo_' + args.length+'_'+Array.from(args).map((arg)=>typeof arg).join('_')](...args);

  }
   //------Assuming that `x` , `y` and `z` are String when calling `foo` . 
  
  /**-- for :  foo(x)*/
  function foo_1_string(){
  }
  /**-- for : foo(x,y,z) ---*/
  function foo_3_string_string_string(){
      
  }

#Other Complex Sample :

      function foo(...args){
          return window['foo_'+args.length+'_'+Array.from(args).map((arg)=>typeof arg).join('_')](...args);
       }

        /** one argument & this argument is string */
      function foo_1_string(){

      }
       //------------
       /** one argument & this argument is object */
      function foo_1_object(){

      }
      //----------
      /** two arguments & those arguments are both string */
      function foo_2_string_string(){

      }
       //--------
      /** Three arguments & those arguments are : id(number),name(string), callback(function) */
      function foo_3_number_string_function(){
                let args=arguments;
                  new Person(args[0],args[1]).onReady(args[3]);
      }
     
       //--- And so on ....   

Does GPS require Internet?

I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.

http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html

converting a base 64 string to an image and saving it

You can save Base64 directly into file:

string filePath = "MyImage.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(base64imageString));

What's a good way to extend Error in JavaScript?

Since JavaScript Exceptions are difficult to sub-class, I don't sub-class. I just create a new Exception class and use an Error inside of it. I change the Error.name property so that it looks like my custom exception on the console:

var InvalidInputError = function(message) {
    var error = new Error(message);
    error.name = 'InvalidInputError';
    return error;
};

The above new exception can be thrown just like a regular Error and it will work as expected, for example:

throw new InvalidInputError("Input must be a string");
// Output: Uncaught InvalidInputError: Input must be a string 

Caveat: the stack trace is not perfect, as it will bring you to where the new Error is created and not where you throw. This is not a big deal on Chrome because it provides you with a full stack trace directly in the console. But it's more problematic on Firefox, for example.

AngularJs: Reload page

Angular 2+

I found this while searching for Angular 2+, so here is the way:

$window.location.reload();

Using Custom Domains With IIS Express

Leaving this here just in case anyone needs...

I needed to have custom domains for a Wordpress Multisite setup in IIS Express but nothing worked until I ran Webmatrix/Visual Studio as an Administrator. Then I was able to bind subdomains to the same application.

<bindings> 
    <binding protocol="http" bindingInformation="*:12345:localhost" />
    <binding protocol="http" bindingInformation="*:12345:whatever.localhost" />
</bindings>

Then going to http://whatever.localhost:12345/ will run.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

You can use npm i y-websockets-server and then use the below command

y-websockets-server --port 11000

and here in my case, the port No is 11000.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

How do I use ROW_NUMBER()?

May not be related to the question here. But I found it could be useful when using ROW_NUMBER -

SELECT *,
ROW_NUMBER() OVER (ORDER BY (SELECT 100)) AS Any_ID 
FROM #Any_Table

How to populate a sub-document in mongoose after creating it?

In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: 'User' }).

Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate as usual (e.g. populate('comments.created_by'))

Proof of concept code:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

Finally note that populate works only for queries so you need to first pass your item into a query and then call it:

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

How do I center list items inside a UL element?

li{
    display:table;
    margin:0px auto 0px auto;
}

This should work.

How can I specify system properties in Tomcat configuration on startup?

Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.

cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.

That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.

(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)

EDIT: Also, another possibility is to go for JNDI Resources.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

This is another valid way to make a copy of a vector, just use its constructor:

std::vector<int> newvector(oldvector);

This is even simpler than using std::copy to walk the entire vector from start to finish to std::back_insert them into the new vector.

That being said, your .swap() one is not a copy, instead it swaps the two vectors. You would modify the original to not contain anything anymore! Which is not a copy.

How can one use multi threading in PHP applications

You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.

I can't quite remember the php CLI syntax, but you'd want something like:

exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");

I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.

Is there a way to @Autowire a bean that requires constructor arguments?

In this example, how do I specify the value of "constrArg" in MyBeanService with the @Autowire annotation? Is there any way to do this?

No, not in the way that you mean. The bean representing MyConstructorClass must be configurable without requiring any of its client beans, so MyBeanService doesn't get a say in how MyConstructorClass is configured.

This isn't an autowiring problem, the problem here is how does Spring instantiate MyConstructorClass, given that MyConstructorClass is a @Component (and you're using component-scanning, and therefore not specifying a MyConstructorClass explicitly in your config).

As @Sean said, one answer here is to use @Value on the constructor parameter, so that Spring will fetch the constructor value from a system property or properties file. The alternative is for MyBeanService to directly instantiate MyConstructorClass, but if you do that, then MyConstructorClass is no longer a Spring bean.

How do I check form validity with angularjs?

form

  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

How to set array length in c# dynamically

Or in C# 3.0 using System.Linq you can skip the intermediate list:

private Update BuildMetaData(MetaData[] nvPairs)
{
        Update update = new Update();
        var ip = from nv in nvPairs
                 select new InputProperty()
                 {
                     Name = "udf:" + nv.Name,
                     Val = nv.Value
                 };
        update.Items = ip.ToArray();
        return update;
}

PowerShell : retrieve JSON object by field value

David Brabant's answer led me to what I needed, with this addition:

x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

Dart: mapping a list (list.map)

Yes, You can do it this way too

 List<String> listTab = new List();
 map.forEach((key, val) {
  listTab.add(val);
 });

 //your widget//
 bottom: new TabBar(
  controller: _controller,
  isScrollable: true,
  tabs: listTab
  ,
),

How to POST JSON Data With PHP cURL?

Try this example.

<?php 
 $url = 'http://localhost/test/page2.php';
    $data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
    $ch=curl_init($url);
    $data_string = urlencode(json_encode($data));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));


    $result = curl_exec($ch);
    curl_close($ch);

    echo $result;
?>

Your page2.php code

<?php
$datastring = $_POST['customer'];
$data = json_decode( urldecode( $datastring));

?>

Paused in debugger in chrome?

Click on the Settings icon and then click on the Restore defaults and reload button. This worked for me whereas the accepted answer didn't. Google Chrome Restore Defaults and Reload

Redirecting 404 error with .htaccess via 301 for SEO etc

I came up with the solution and posted it on my blog

http://web.archive.org/web/20130310123646/http://onlinemarketingexperts.com.au/2013/01/how-to-permanently-redirect-301-all-404-missing-pages-in-htaccess/

here is the htaccess code also

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

but I posted other solutions on my blog too, it depends what you need really

What is declarative programming?

As far as I can tell, it started being used to describe programming systems like Prolog, because prolog is (supposedly) about declaring things in an abstract way.

It increasingly means very little, as it has the definition given by the users above. It should be clear that there is a gulf between the declarative programming of Haskell, as against the declarative programming of HTML.

How to get the CUDA version?

One can get the cuda version by typing the following in the terminal:

$ nvcc -V

# below is the result
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2017 NVIDIA Corporation
Built on Fri_Nov__3_21:07:56_CDT_2017
Cuda compilation tools, release 9.1, V9.1.85

Alternatively, one can manually check for the version by first finding out the installation directory using:

$ whereis -b cuda         
cuda: /usr/local/cuda

And then cd into that directory and check for the CUDA version.

How to run an application as "run as administrator" from the command prompt?

See this TechNet article: Runas command documentation

From a command prompt:

C:\> runas /user:<localmachinename>\administrator cmd

Or, if you're connected to a domain:

C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd

strcpy() error in Visual studio 2012

There's an explanation and solution for this on MSDN:

The function strcpy is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow.

Consequently, as it suggests in the error description, you can use strcpy_s instead of strcpy:

strcpy_s( char *strDestination, size_t numberOfElements,
const char *strSource );

and:

To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

http://social.msdn.microsoft.com/Forums/da-DK/vcgeneral/thread/c7489eef-b391-4faa-bf77-b824e9e8f7d2

Change location of log4j.properties

Yes, define log4j.configuration property

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

How to reverse an animation on mouse out after hover

I think that if you have a to, you must use a from. I would think of something like :

@keyframe in {
    from: transform: rotate(0deg);
    to: transform: rotate(360deg);
}

@keyframe out {
    from: transform: rotate(360deg);
    to: transform: rotate(0deg);
}

Of course must have checked it already, but I found strange that you only use the transform property since CSS3 is not fully implemented everywhere. Maybe it would work better with the following considerations :

  • Chrome uses @-webkit-keyframes, no particuliar version needed
  • Safari uses @-webkit-keyframes since version 5+
  • Firefox uses @keyframes since version 16 (v5-15 used @-moz-keyframes)
  • Opera uses @-webkit-keyframes version 15-22 (only v12 used @-o-keyframes)
  • Internet Explorer uses @keyframes since version 10+

EDIT :

I came up with that fiddle :

http://jsfiddle.net/JjHNG/35/

Using minimal code. Is it approaching what you were expecting ?

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

Here const means that at that function any variable's value can not change

class Test{
private:
    int a;
public:
    void test()const{
        a = 10;
    }
};

And like this example, if you try to change the value of a variable in the test function you will get an error.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Border Radius of Table is not working

It works, this is a problem with the tool used: normalized CSS by jsFiddle is causing the problem by hiding you the default of browsers...
See http://jsfiddle.net/XvdX9/5/

EDIT:
normalize.css stylesheet from jsFiddle adds the instruction border-collapse: collapse to all tables and it renders them completely differently in CSS2.1:

Differences between the 2 models can be seen in this other fiddle: http://jsfiddle.net/XvdX9/11/ (with some transparencies on cells and an enormous border-radius on the top-left one, in order to see what happens on table vs its cells)

In the same CSS2.1 page about HTML tables, there are also explanations about what browsers should/could do with empty-cells in the separated borders model, the difference between border-style: none and border-style: hidden in the collapsing borders model, how width is calculated and which border should display if both table, row and cell elements define 3 different styles on the same border.

How to add an element to a list?

I would do this:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in "data"

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

How to map and remove nil values in Ruby

Definitely compact is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:

[1, nil, 3, nil, nil] - [nil]
 => [1, 3]

What's the fastest way to delete a large folder in Windows?

Try Shift + Delete. Did 24.000 files in 2 minutes for me.

What is the syntax for an inner join in LINQ to SQL?

var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
   select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();

Write table names you want, and initialize the select to get the result of fields.

How can I get the source directory of a Bash script from within the script itself?

Here's a command that works under either Bash or zsh, and whether executed stand-alone or sourced:

[ -n "$ZSH_VERSION" ] && this_dir=$(dirname "${(%):-%x}") \
    || this_dir=$(dirname "${BASH_SOURCE[0]:-$0}")

How it works

The zsh current file expansion: ${(%):-%x}

${(%):-%x} in zsh expands to the path of the currently-executing file.

The fallback substitution operator :-

You know already that ${...} substitutes variables inside of strings. You might not know that certain operations are possible (in both Bash and zsh) on the variables during substitution, like the fallback expansion operator :-:

% x=ok
% echo "${x}"
ok

% echo "${x:-fallback}"
ok

% x=
% echo "${x:-fallback}"
fallback

% y=yvalue
% echo "${x:-$y}"
yvalue

The %x prompt escape code

Next, we'll introduce prompt escape codes, a zsh-only feature. In zsh, %x will expand to the path of the file, but normally this is only when doing expansion for prompt strings. To enable those codes in our substitution, we can add a (%) flag before the variable name:

% cat apath/test.sh
fpath=%x
echo "${(%)fpath}"

% source apath/test.sh
apath/test.sh

% cd apath
% source test.sh
test.sh

An unlikely match: the percent escape and the fallback

What we have so far works, but it would be tidier to avoid creating the extra fpath variable. Instead of putting %x in fpath, we can use :- and put %x in the fallback string:

% cat test.sh
echo "${(%):-%x}"

% source test.sh
test.sh

Note that we normally would put a variable name between (%) and :-, but we left it blank. The variable with a blank name can't be declared or set, so the fallback is always triggered.

Finishing up: what about print -P %x?

Now we almost have the directory of our script. We could have used print -P %x to get the same file path with fewer hacks, but in our case, where we need to pass it as an argument to dirname, that would have required the overhead of a starting a new subshell:

% cat apath/test.sh
dirname "$(print -P %x)"  # $(...) runs a command in a new process
dirname "${(%):-%x}"

% source apath/test.sh
apath
apath

It turns out that the hacky way is both more performant and succinct.

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

Extracting Nupkg files using command line

NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.

How to copy file from HDFS to the local file system

In Hadoop 2.0,

hdfs dfs -copyToLocal <hdfs_input_file_path> <output_path>

where,

  • hdfs_input_file_path maybe obtained from http://<<name_node_ip>>:50070/explorer.html

  • output_path is the local path of the file, where the file is to be copied to.

  • you may also use get in place of copyToLocal.

WPF Datagrid Get Selected Cell Value

If SelectionUnit="Cell" try this:

    string cellValue = GetSelectedCellValue();

Where:

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
        if (cellInfo == null) return null;

        DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
        if (column == null) return null;

        FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
        BindingOperations.SetBinding(element, TagProperty, column.Binding);

        return element.Tag.ToString();
    }

Seems like it shouldn't be that complicated, I know...

Edit: This doesn't seem to work on DataGridTemplateColumn type columns. You could also try this if your rows are made up of a custom class and you've assigned a sort member path:

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cells = MyDataGrid.SelectedCells[0];

        YourRowClass item = cells.Item as YourRowClass;
        string columnName = cells.Column.SortMemberPath;

        if (item == null || columnName == null) return null;

        object result = item.GetType().GetProperty(columnName).GetValue(item, null);

        if (result == null) return null;

        return result.ToString();
    }

How to move certain commits to be based on another branch in git?

This is a classic case of rebase --onto:

 # let's go to current master (X, where quickfix2 should begin)
 git checkout master

 # replay every commit *after* quickfix1 up to quickfix2 HEAD.
 git rebase --onto master quickfix1 quickfix2 

So you should go from

o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)
              \
               q2a--q2b (quickfix2 HEAD)

to:

      q2a'--q2b' (new quickfix2 HEAD)
     /
o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)

This is best done on a clean working tree.
See git config --global rebase.autostash true, especially after Git 2.10.

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

How to grep and replace

Another option would be to just use perl with globstar.

Enabling shopt -s globstar in your .bashrc (or wherever) allows the ** glob pattern to match all sub-directories and files recursively.

Thus using perl -pXe 's/SEARCH/REPLACE/g' -i ** will recursively replace SEARCH with REPLACE.

The -X flag tells perl to "disable all warnings" - which means that it won't complain about directories.

The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext if you wanted to replace SEARCH with REPLACE in all child files with the extension .ext.

Proper way to restrict text input values (e.g. only numbers)

I think a custom ControlValueAccessor is the best option.

Not tested but as far as I remember, this should work:

<input [(ngModel)]="value" pattern="[0-9]">

Is an empty href valid?

Try to do <a href="#" class="arrow"> instead. (Note the sharp # character).

assembly to compare two numbers

Compare two numbers. If it equals Yes "Y", it prints No "N" on the screen if it is not equal. I am using emu8086. You can use the SUB or CMP command.

MOV AX,5h
MOV BX,5h
SUB AX,BX 
JZ EQUALS
JNZ NOTEQUALS

EQUALS:
MOV CL,'Y'
JMP PRINT

NOTEQUALS:
MOV CL,'N'

PRINT:
MOV AH,2
MOV DL,CL
INT 21H

RET

enter image description here

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

Google Maps API: open url by clicking on marker

    function loadMarkers(){
          {% for location in object_list %}
              var point = new google.maps.LatLng({{location.latitude}},{{location.longitude}});
              var marker = new google.maps.Marker({
              position: point,
              map: map,
              url: {{location.id}},
          });

          google.maps.event.addDomListener(marker, 'click', function() {
              window.location.href = this.url; });

          {% endfor %}

Creating a ZIP archive in memory using System.IO.Compression

This is the way to convert a entity to XML File and then compress it:

private  void downloadFile(EntityXML xml) {

string nameDownloadXml = "File_1.xml";
string nameDownloadZip = "File_1.zip";

var serializer = new XmlSerializer(typeof(EntityXML));

Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=" + nameDownloadZip);

using (var memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        var demoFile = archive.CreateEntry(nameDownloadXml);
        using (var entryStream = demoFile.Open())
        using (StreamWriter writer = new StreamWriter(entryStream, System.Text.Encoding.UTF8))
        {
            serializer.Serialize(writer, xml);
        }
    }

    using (var fileStream = Response.OutputStream)
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

Response.End();

}

Set 4 Space Indent in Emacs in Text Mode

You may find it easier to set up your tabs as follows:

M-x customize-group

At the Customize group: prompt enter indent.

You'll see a screen where you can set all you indenting options and set them for the current session or save them for all future sessions.

If you do it this way you'll want to set up a customisations file.

Color a table row with style="color:#fff" for displaying in an email

you can easily do like this:-

    <table>
    <thead>
        <tr>
          <th bgcolor="#5D7B9D"><font color="#fff">Header 1</font></th>
          <th bgcolor="#5D7B9D"><font color="#fff">Header 2</font></th>
           <th bgcolor="#5D7B9D"><font color="#fff">Header 3</font></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>blah blah</td>
            <td>blah blah</td>
            <td>blah blah</td>
        </tr>
    </tbody>
</table>

Demo:- http://jsfiddle.net/VWdxj/7/

How to make an AlertDialog in Flutter?

I used similar approach, but I wanted to

  1. Keep the Dialog code as a widget in a separated file so I can reuse it.
  2. Blurr the background when the dialog is shown.

enter image description here

Code: 1. alertDialog_widget.dart

import 'dart:ui';
import 'package:flutter/material.dart';


class BlurryDialog extends StatelessWidget {

  String title;
  String content;
  VoidCallback continueCallBack;

  BlurryDialog(this.title, this.content, this.continueCallBack);
  TextStyle textStyle = TextStyle (color: Colors.black);

  @override
  Widget build(BuildContext context) {
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
      child:  AlertDialog(
      title: new Text(title,style: textStyle,),
      content: new Text(content, style: textStyle,),
      actions: <Widget>[
        new FlatButton(
          child: new Text("Continue"),
           onPressed: () {
            continueCallBack();
          },
        ),
        new FlatButton(
          child: Text("Cancel"),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
      ));
  }
}

You can call this in main (or wherever you want) by creating a new method like:

 _showDialog(BuildContext context)
{

  VoidCallback continueCallBack = () => {
 Navigator.of(context).pop(),
    // code on continue comes here

  };
  BlurryDialog  alert = BlurryDialog("Abort","Are you sure you want to abort this operation?",continueCallBack);


  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

How to push both value and key into PHP array

array_push($GET, $GET['one']=1);

It works for me.

How to program a delay in Swift 3

Try the below code for delay

//MARK: First Way

func delayForWork() {
    delay(3.0) {
        print("delay for 3.0 second")
    }
}

delayForWork()

// MARK: Second Way

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // your code here delayed by 0.5 seconds
}

How to manipulate arrays. Find the average. Beginner Java

Try this way

public void average(int[] data) {  
    int sum = 0;
    double average;

    for(int i=0; i < data.length; i++){
        sum = sum + data[i];
    }
    average = (double)sum/data.length;
    System.out.println("Average value of array element is " + average);    
}

if you need to return average value you need to use double key word Instead of the void key word and need to return value return average.

public double average(int[] data) {  
    int sum = 0;
    double average;

    for(int i=0; i < data.length; i++){
        sum = sum + data[i];
    }
    average = (double)sum/data.length;
    return average;    
}

connect to host localhost port 22: Connection refused

  1. Before installing/reinstalling anything check the status of sshd . . .
sudo systemctl status sshd
  1. You should see something like . . .
? sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; disabled; vendor prese>
   Active: inactive (dead)
     Docs: man:sshd(8)
           man:sshd_config(5)
  1. Just enable and start sshd
sudo systemctl enable sshd
sudo systemctl start sshd

how to read xml file from url using php

file_get_contents() usually has permission issues. To avoid them, use:

function get_xml_from_url($url){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

    $xmlstr = curl_exec($ch);
    curl_close($ch);

    return $xmlstr;
}

Example:

$xmlstr = get_xml_from_url('http://www.camara.gov.br/SitCamaraWS/Deputados.asmx/ObterDeputados');
$xmlobj = new SimpleXMLElement($xmlstr);
$xmlobj = (array)$xmlobj;//optional

How do I add a reference to the MySQL connector for .NET?

This is an older question, but I found it yesterday while struggling with getting the MySQL Connector reference working properly on examples I'd found on the web. I'm working with VS 2010 on Win7 64 bit but have to work with .NET 3.5.

As others have stated, you need to download the .Net & Mono versions (I don't know why this is true, but it's what I've found works). The link to the connectors is given above in the earlier answers.

  • Extract the connectors somewhere convenient.
  • Open the project in Visual Studio, then on the menu bar navigate to Solution Explorer (View > Solution Explorer), and choose Properties (first box on the far left of the toolbar. The Solution Explorer shows up in the top right pane for me, but YMMV).
  • In Properties, select References & locate the instance for mysql.data. It's likely to have a yellow bang on it (Yellow triangle with exclamation point in it). Remove it.
  • Then on the menu bar, navigate to Project > Add Reference... > Browse > point to where you downloaded the connectors. I have only been able to get the V2 version to work, but that may be a factor of my platform, not sure.
  • Clean & build your application. You should now be able to use the MySQL connectors to talk to your database.
  • You can also now downgrade your .NET instance if you need to (we're constrained to .NET 3.5, but mysql.data.dll wants 4.0 at the time of my writing this). On the menu bar, navigate to the properties of your project (Project > Properties). Choose the Application tab > Target framework > Choose which .NET framework you want to use. You have to build the application at least once before you can change the .NET framework. Once you built once the connector will no longer complain about the lower version of .NET.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.

//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";

I have concluded that setting the globalCompositeOperation works with images.

//works with images
ctx.globalCompositeOperation = "lighter";

I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.

EDIT:

After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:

//works with images
ctx.globalAlpha = 0.5

If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.

How to get logged-in user's name in Access vba?

Try this:

Function UserNameWindows() As String
     UserName = Environ("USERNAME")
End Function

typecast string to integer - Postgres

Common issue

Naively type casting any string into an integer like so

SELECT ''::integer

Often results to the famous error:

Query failed: ERROR: invalid input syntax for integer: ""

Problem

PostgreSQL has no pre-defined function for safely type casting any string into an integer.

Solution

Create a user-defined function inspired by PHP's intval() function.

CREATE FUNCTION intval(character varying) RETURNS integer AS $$

SELECT
CASE
    WHEN length(btrim(regexp_replace($1, '[^0-9]', '','g')))>0 THEN btrim(regexp_replace($1, '[^0-9]', '','g'))::integer
    ELSE 0
END AS intval;

$$
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;

Usage

/* Example 1 */
SELECT intval('9000');
-- output: 9000

/* Example 2 */
SELECT intval('9gag');
-- output: 9

/* Example 3 */
SELECT intval('the quick brown fox jumps over the lazy dog');
-- output: 0

How can I center text (horizontally and vertically) inside a div block?

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <div style ="text-align: center;">Center horizontal text</div>
        <div style ="position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%);">Center vertical text</div>
    </body>
</html>