Programs & Examples On #Openvg

Sending emails with Javascript

Here's the way doing it using jQuery and an "element" to click on :

$('#element').click(function(){
    $(location).attr('href', 'mailto:?subject='
                             + encodeURIComponent("This is my subject")
                             + "&body=" 
                             + encodeURIComponent("This is my body")
    );
});

Then, you can get your contents either by feeding it from input fields (ie. using $('#input1').val() or by a server side script with $.get('...'). Have fun

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

The fact that the same number of rows is returned is an after fact, the query optimizer cannot know in advance that every row in Accepts has a matching row in Marker, can it?

If you join two tables A and B, say A has 1 million rows and B has 1 row. If you say A LEFT INNER JOIN B it means only rows that match both A and B can result, so the query plan is free to scan B first, then use an index to do a range scan in A, and perhaps return 10 rows. But if you say A LEFT OUTER JOIN B then at least all rows in A have to be returned, so the plan must scan everything in A no matter what it finds in B. By using an OUTER join you are eliminating one possible optimization.

If you do know that every row in Accepts will have a match in Marker, then why not declare a foreign key to enforce this? The optimizer will see the constraint, and if is trusted, will take it into account in the plan.

How to get streaming url from online streaming radio station

not that hard,

if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.

this is the stream url

"StreamUrl": "http://stream.radiotime.com/listen.stream?streamIds=3244651&rti=c051HQVbfRc4FEMbKg5RRVMzRU9KUBw%2fVBZHS0dPF1VIExNzJz0CGQtRcX8OS0o0CUkYRFJDDW8LEVRxGAEOEAcQXko%2bGgwSBBZrV1pQZgQZZxkWCA4L%7e%7e%7e",

which returns a JSON like that:

{
    "Streams": [
        {
            "StreamId": 3244651,
            "Reliability": 92,
            "Bandwidth": 64,
            "HasPlaylist": false,
            "MediaType": "MP3",
            "Url": "http://mp3hdfm32.hala.jo:8132",
            "Type": "Live"
        }
    ]
}

i believe that's the url you need: http://mp3hdfm32.hala.jo:8132

this is the station WebSite

How do I script a "yes" response for installing programs?

You might not have the ability to install Expect on the target server. This is often the case when one writes, say, a Jenkins job.

If so, I would consider something like the answer to the following on askubuntu.com:

https://askubuntu.com/questions/338857/automatically-enter-input-in-command-line

printf 'y\nyes\nno\nmaybe\n' | ./script_that_needs_user_input

Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:

printf 'yyy' | ./script_that_needs_user_input

For sake of completeness you can also use a here document:

./script_that_needs_user_input << EOF
y
y
y
EOF

Or if your shell supports it a here string:

./script <<< "y
y
y
"

Or you can create a file with one input per line:

./script < inputfile

Again, all credit for this answer goes to the author of the answer on askubuntu.com, lesmana.

Why doesn't Java allow overriding of static methods?

Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.

There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do had the benefit of familiarity for C++ programmers and was also very fast, because there's no need to wait until runtime to figure out which method to call.

How could I create a list in c++?

Why reinvent the wheel. Just use the STL list container.

#include <list>

// in some function, you now do...
std::list<int> mylist; // integer list

More information...

Spring Boot: Cannot access REST Controller on localhost (404)

Sometimes spring boot behaves weird. I specified below in application class and it works:

@ComponentScan("com.seic.deliveryautomation.controller")

How do you push a Git tag to a branch using a refspec?

It is probably failing because 1.0.0 is an annotated tag. Perhaps you saw the following error message:

error: Trying to write non-commit object to branch refs/heads/master

Annotated tags have their own distinct type of object that points to the tagged commit object. Branches can not usefully point to tag objects, only commit objects. You need to “peel” the annotated tag back to commit object and push that instead.

git push production +1.0.0^{commit}:master
git push production +1.0.0~0:master          # shorthand

There is another syntax that would also work in this case, but it means something slightly different if the tag object points to something other than a commit (or a tag object that points to (a tag object that points to a …) a commit).

git push production +1.0.0^{}:master

These tag peeling syntaxes are described in git-rev-parse(1) under Specifying Revisions.

find all subsets that sum to a particular value

This my dynamical programming implementation in JS. It will return an array of arrays, each holding the subsequences summing to the provided target value.

_x000D_
_x000D_
function getSummingItems(a,t){_x000D_
  return a.reduce((h,n) => Object.keys(h)_x000D_
                                 .reduceRight((m,k) => +k+n <= t ? (m[+k+n] = m[+k+n] ? m[+k+n].concat(m[k].map(sa => sa.concat(n)))_x000D_
                                                                                      : m[k].map(sa => sa.concat(n)),m)_x000D_
                                                                 :  m, h), {0:[[]]})[t];_x000D_
}_x000D_
var arr = Array(20).fill().map((_,i) => i+1), // [1,2,..,20]_x000D_
    tgt = 42,_x000D_
    res = [];_x000D_
_x000D_
console.time("test");_x000D_
res = getSummingItems(arr,tgt);_x000D_
console.timeEnd("test");_x000D_
console.log("found",res.length,"subsequences summing to",tgt);_x000D_
console.log(JSON.stringify(res));
_x000D_
_x000D_
_x000D_

How to replace substrings in windows batch file

SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%

EDIT

Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.

Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:

@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
  SET "line=%%L"
  SETLOCAL ENABLEDELAYEDEXPANSION
  ECHO !line:bath=hello!
  ENDLOCAL
)
ENDLOCAL

You can add a redirection to a file:

  ECHO !line:bath=hello!>>file2.txt

Or you can apply the redirection to the batch file. It must be a different file.

EDIT 2

Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !, ^ et al. (Thanks, jeb!)

C++ queue - simple example

std::queue<myclass*> that's it

ssh remote host identification has changed

I had this problem, and the reason is very simple, I have a duplicated IP address to ssh login, so after modify this problem, everthing is solved.

How do I change selected value of select2 dropdown with JqGrid?

For V4 Select2 if you want to change both the value of the select2 and the text representation of the drop down.

var intValueOfFruit = 1;
var selectOption = new Option("Fruit", intValueOfFruit, true, true);
$('#select').append(selectOption).trigger('change');

This will set not only the value behind the scenes but also the text display for the select2.

Pulled from https://select2.github.io/announcements-4.0.html#removed-methods

CMAKE_MAKE_PROGRAM not found

It seems everybody has different solution. I solved my problem like:

When I install 64bit mingw it installed itself to : "C:\Program Files\mingw-w64\x86_64-5.1.0-posix-seh-rt_v4-rev0\mingw64\bin"

Eventhough mingw-make.exe was under the path above, one invalid charecter or long path name confused CMake. I try to add path to environment path, try to give CMAKE as paramater it didn't work for me .

Finally I moved complex path of mingw-w64 to "C:/mingw64", than set the environment path, restarted CMake. Problem solved for me .

Fixed width buttons with Bootstrap

For your buttons, you can create another CSS selector for those special classes of buttons with a specified min-width and max-width. So if your button is

<button class="save_button">Save</button>

In your Bootstrap CSS file you can create something like

.save_button {
    min-width: 80px;
    max-width: 80px;
}

This way it should always stay 80px even if you have a responsive design.

As far as the right way of extending Bootstrap goes, Take a look at this thread:

Extending Bootstrap

How to find out if you're using HTTPS without $_SERVER['HTTPS']

What do you think of this?

if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
    $scheme = 'https';
else
    $scheme = 'http';

How to Make A Chevron Arrow Using CSS?

You can use the before or after pseudo-element and apply some CSS to it. There are various ways. You can add both before and after, and rotate and position each of them to form one of the bars. An easier solution is adding two borders to just the before element and rotate it using transform: rotate.

Scroll down for a different solution that uses an actual element instead of the pseuso elements

In this case, I've added the arrows as bullets in a list and used em sizes to make them size properly with the font of the list.

_x000D_
_x000D_
ul {_x000D_
    list-style: none;_x000D_
}_x000D_
_x000D_
ul.big {_x000D_
    list-style: none;_x000D_
    font-size: 300%_x000D_
}_x000D_
_x000D_
li::before {_x000D_
    position: relative;_x000D_
    /* top: 3pt; Uncomment this to lower the icons as requested in comments*/_x000D_
    content: "";_x000D_
    display: inline-block;_x000D_
    /* By using an em scale, the arrows will size with the font */_x000D_
    width: 0.4em;_x000D_
    height: 0.4em;_x000D_
    border-right: 0.2em solid black;_x000D_
    border-top: 0.2em solid black;_x000D_
    transform: rotate(45deg);_x000D_
    margin-right: 0.5em;_x000D_
}_x000D_
_x000D_
/* Change color */_x000D_
li:hover {_x000D_
  color: red; /* For the text */_x000D_
}_x000D_
li:hover::before {_x000D_
  border-color: red; /* For the arrow (which is a border) */_x000D_
}
_x000D_
<ul>_x000D_
    <li>Item1</li>_x000D_
    <li>Item2</li>_x000D_
    <li>Item3</li>_x000D_
    <li>Item4</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="big">_x000D_
    <li>Item1</li>_x000D_
    <li>Item2</li>_x000D_
    <li>Item3</li>_x000D_
    <li>Item4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Of course you don't need to use before or after, you can apply the same trick to a normal element as well. For the list above it is convenient, because you don't need additional markup. But sometimes you may want (or need) the markup anyway. You can use a div or span for that, and I've even seen people even recycle the i element for 'icons'. So that markup could look like below. Whether using <i> for this is right is debatable, but you can use span for this as well to be on the safe side.

_x000D_
_x000D_
/* Default icon formatting */_x000D_
i {_x000D_
  display: inline-block;_x000D_
  font-style: normal;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
/* Additional formatting for arrow icon */_x000D_
i.arrow {_x000D_
    /* top: 2pt; Uncomment this to lower the icons as requested in comments*/_x000D_
    width: 0.4em;_x000D_
    height: 0.4em;_x000D_
    border-right: 0.2em solid black;_x000D_
    border-top: 0.2em solid black;_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
And so you can have an <i class="arrow" title="arrow icon"></i> in your text._x000D_
This arrow is <i class="arrow" title="arrow icon"></i> used to be deliberately lowered slightly on request._x000D_
I removed that for the general public <i class="arrow" title="arrow icon"></i> but you can uncomment the line with 'top' <i class="arrow" title="arrow icon"></i> to restore that effect.
_x000D_
_x000D_
_x000D_

If you seek more inspiration, make sure to check out this awesome library of pure CSS icons by Nicolas Gallagher. :)

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

How to set the env variable for PHP?

You need to add the PHP directory to your path. On the command line (e.g. in a batch file), it would look like this:

SET PATH=%PATH%;C:\your\wamp\path\php

if in doubt, it's the directory containing the php.exe.

You can also pre-set the path in Windows' control panel. See here on how to do this in Windows 7 for example.

Be aware that if you call the PHP executable from an arbitrary directory, that directory will be the working directory. You may need to adjust your scripts so they use the proper directories for their file operations (if there are any).

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

How can I force a long string without any blank to be wrapped?

For word-wrap:break-word; to work for me, I had to make sure the display was set to block, and that the width was set on the element. In Safari, it had to have a p tag and the width had to be set in ex.

Using getResources() in non-activity class

I am late but complete solution;: Example Class, Use Context like this :-

public class SingletonSampleClass {

    // Your cute context
    private Context context;
    private static SingletonSampleClass instance;

  // Pass as Constructor
    private SingletonSampleClass(Context context) {
        this.context = context;
    }

    public synchronized static SingletonSampleClass getInstance(Context context) {
        if (instance == null) instance = new SingletonSampleClass(context);
        return instance;
    }

//At end, don't forgot to relase memory
    public void onDestroy() {
       if(context != null) {
          context = null; 
       }
    }
}

Warning (Memory Leaks)

How to solve this?

Option 1: Instead of passing activity context i.e. this to the singleton class, you can pass applicationContext().

Option 2: If you really have to use activity context, then when the activity is destroyed, ensure that the context you passed to the singleton class is set to null.

Hope it helps..????

Google Maps JavaScript API RefererNotAllowedMapError

This worked for me. There are 2 major categories of restrictions under api key settings:

  • Application restrictions
  • API restrictions

Application restrictions:

At the bottom in the Referrer section add your website url " http://www.grupocamaleon.com/boceto/aerial-simple.html " .There are example rules on the right hand side of the section based on various requirements.

Application restrictions

API restrictions:

Under API restrictions you have to explicitly select 'Maps Javascript API' from the dropdown list since our unique key will only be used for calling the Google maps API(probably) and save it as you can see in the below snap. I hope this works for you.....worked for me

enter image description here

Check your Script:

Also the issue may arise due to improper key feeding inside the script tag. It should be something like:

  <script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap"
  type="text/javascript"></script>

Can you write virtual functions / methods in Java?

All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

RecyclerView - How to smooth scroll to top of item on a certain position?

Probably @droidev approach is the correct one, but I just want to publish something a little bit different, which does basically the same job and doesn't require extension of the LayoutManager.

A NOTE here - this is gonna work well if your item (the one that you want to scroll on the top of the list) is visible on the screen and you just want to scroll it to the top automatically. It is useful when the last item in your list has some action, which adds new items in the same list and you want to focus the user on the new added items:

int recyclerViewTop = recyclerView.getTop();
int positionTop = recyclerView.findViewHolderForAdapterPosition(positionToScroll) != null ? recyclerView.findViewHolderForAdapterPosition(positionToScroll).itemView.getTop() : 200;
final int calcOffset = positionTop - recyclerViewTop; 
//then the actual scroll is gonna happen with (x offset = 0) and (y offset = calcOffset)
recyclerView.scrollBy(0, offset);

The idea is simple: 1. We need to get the top coordinate of the recyclerview element; 2. We need to get the top coordinate of the view item that we want to scroll to the top; 3. At the end with the calculated offset we need to do

recyclerView.scrollBy(0, offset);

200 is just example hard coded integer value that you can use if the viewholder item doesn't exist, because that is possible as well.

How to bring a window to the front?

Here's a method that REALLY works (tested on Windows Vista) :D

   frame.setExtendedState(JFrame.ICONIFIED);
   frame.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);

The fullscreen variable indicates if you want the app to run full screen or windowed.

This does not flash the task bar, but bring the window to front reliably.

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

So here is how you will do it.

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

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

}

Codebehind of Handler:

 public class getwindowsize : IHttpHandler {

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

HTML table: keep the same width for columns

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your <thead> to <caption> and remove the <td> inside of it, and then set fixed widths for the cells in <tbody>.

How to change the decimal separator of DecimalFormat from comma to dot/point?

This worked in my case:

DecimalFormat df2 = new DecimalFormat("#.##");           
df2.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));

Java: convert seconds to minutes, hours and days

You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
        : "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
        secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
        : "hours"));
sb.append(String.format("%d %s and ", minutesCount,
        (minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
        (secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
        new DecimalFormat("#,###").format(secondsIn), sb, sb2);

Which, when I enter 500000 outputs the requested (manual line break added for post) -

You entered 500,000 seconds, which is 5 days, 18 hours, 
53 minutes and 20 seconds. (5 days, 18:53:20 hours)

Better way to convert file sizes in Python

Instead of a size divisor of 1024 * 1024 you could use the << bitwise shifting operator, i.e. 1<<20 to get megabytes, 1<<30 to get gigabytes, etc.

In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20) which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR.

Megabytes are usually all that you need, or otherwise something like this can be used:

# bytes pretty-printing
UNITS_MAPPING = [
    (1<<50, ' PB'),
    (1<<40, ' TB'),
    (1<<30, ' GB'),
    (1<<20, ' MB'),
    (1<<10, ' KB'),
    (1, (' byte', ' bytes')),
]


def pretty_size(bytes, units=UNITS_MAPPING):
    """Get human-readable file sizes.
    simplified version of https://pypi.python.org/pypi/hurry.filesize/
    """
    for factor, suffix in units:
        if bytes >= factor:
            break
    amount = int(bytes / factor)

    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    return str(amount) + suffix

print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))

## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB

<embed> vs. <object>

You could also use the iframe method, although this is not cross browser compatible (eg. not working in chromium or android and probably others -> instead prompts to download). It works with dataURL's and normal URLS, not sure if the other examples work with dataURLS (please let me know if the other examples work with dataURLS?)

 <iframe class="page-icon preview-pane" frameborder="0" height="352" width="396" src="data:application/pdf;base64, ..DATAURLHERE!... "></iframe>

How to config routeProvider and locationProvider in angularJS?

Following is how one can configure $locationProvider using requireBase=false flag to avoid setting base href <head><base href="/"></head>:

var app = angular.module("hwapp", ['ngRoute']);

app.config(function($locationProvider){
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    }) 
});

How to split a string in Java

Assuming, that

  • you don't really need regular expressions for your split
  • you happen to already use apache commons lang in your app

The easiest way is to use StringUtils#split(java.lang.String, char). That's more convenient than the one provided by Java out of the box if you don't need regular expressions. Like its manual says, it works like this:

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]

I would recommend using commong-lang, since usually it contains a lot of stuff that's usable. However, if you don't need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.

Why am I seeing "TypeError: string indices must be integers"?

TypeError for Slice Notation str[a:b]

tl;dr: use a colon : instead of a comma in between the two indices a and b in str[a:b]


When working with strings and slice notation (a common sequence operation), it can happen that a TypeError is raised, pointing out that the indices must be integers, even if they obviously are.

Example

>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers

We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?

This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.

Explanation

We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5] because 0,5 (even without the parentheses) evaluates to the same tuple as (0,5) would do.

A comma , is actually enough for Python to evaluate something as a tuple:

>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>

So what we did there, this time explicitly:

>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers

Now, at least, the error message makes sense.

Solution

We need to replace the comma , with a colon : to separate the two integers correctly:

>>> my_string = "hello world"
>>> my_string[0:5]
'hello'

A clearer and more helpful error message could have been something like:

TypeError: string indices must be integers (not tuple)

A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.

[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]

Lessons learned

  • slice notation uses colons : to separate its indices (and step range, e.g. str[from:to:step])
  • tuples are defined by commas , (e.g. t = 1,)
  • add some information to error messages for users to understand what went wrong

Cheers and happy programming
winklerrr


[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.

So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]

How to sum the values of a JavaScript object?

Sum the object key value by parse Integer. Converting string format to integer and summing the values

_x000D_
_x000D_
var obj = {
  pay: 22
};
obj.pay;
console.log(obj.pay);
var x = parseInt(obj.pay);
console.log(x + 20);
_x000D_
_x000D_
_x000D_

How to rename HTML "browse" button of an input type=file?

  1. Wrap the <input type="file"> with a <label> tag;
  2. Add a tag (with the text that you need) inside the label, like a <span> or <a>;
  3. Make this tag look like a button;
  4. Make input[type="file"] invisible via display: none.

Mongoose: Find, modify, save

findOne, modify fields & save

User.findOne({username: oldUsername})
  .then(user => {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.markModified('username');
    user.markModified('password');
    user.markModified('rights');

    user.save(err => console.log(err));
});

OR findOneAndUpdate

User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }
    console.log(doc);
});

Also see updateOne

How do I resolve "Cannot find module" error using Node.js?

This happens when a first npm install has crashed for some reason (SIGINT of npm), or that the delay was too long, or data is corrupted. Trying an npm install again won't save the problem.

Something got wrong on the npm first check, so the best choice is to remove the file and to restart npm install.

Renaming columns in Pandas

Renaming columns in Pandas is an easy task.

df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)

Where can I find error log files?

For unix cli users:

Most probably the error_log ini entry isn't set. To verify:

php -i | grep error_log
// error_log => no value => no value

You can either set it in your php.ini cli file, or just simply quickly pipe all STDERR yourself to a file:

./myprog 2> myerror.log

Then quickly:

tail -f myerror.log

how to make UITextView height dynamic according to text length?

1 Add an observer to the content length of textfield

   yourTextView.addObserver(self, forKeyPath: "contentSize", options: (NSKeyValueObservingOptions.new), context: nil);

2 Implement observer

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let tv = object as! UITextView;
        var topCorrect = (tv.bounds.size.height - tv.contentSize.height * tv.zoomScale)/2.0;
        topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
        tv.contentOffset.x = 0;
        tv.contentOffset.y = -topCorrect;
        self.yourTextView.contentSize.height = tv.contentSize.height;
        UIView.animate(withDuration: 0.2, animations: {
            self.view.layoutIfNeeded();
        });
    }

Change header background color of modal of twitter bootstrap

All the other answersoverflow:hidden?alert-danger not work for me in Bootstrap 4, but I found a simple solution in Bootstrap 4. Since the white trim comes from modal-content, just add border-0 class to it and the white trim disappear.

Example: https://codepen.io/eric1214/pen/BajLwzE?editors=1010

Field 'id' doesn't have a default value?

As id is the primary key, you cannot have different rows with the same value. Try to change your table so that the id is auto incremented:

id int NOT NULL AUTO_INCREMENT

and then set the primary key as follows:

PRIMARY KEY (id)

All together:

CREATE TABLE card_games (
   id int(11) NOT NULL AUTO_INCREMENT,
   nafnleiks varchar(50),
   leiklysing varchar(3000), 
   prentadi varchar(1500), 
   notkunarheimildir varchar(1000),
   upplysingar varchar(1000),
   ymislegt varchar(500),
   PRIMARY KEY (id));

Otherwise, you can indicate the id in every insertion, taking care to set a different value every time:

insert into card_games (id, nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values(1, 'Svartipétur', 'Leiklýsingu vantar', 'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.', 'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum', 'Aðrar upplýsingar', 'ekkert hér sem stendur' );

Change default icon

Go to the Project properties Build the project Locate the .exe file in your favorite file explorer.

Git: "please tell me who you are" error

I had this as a faulty error message:
git pull worked fine on the cmd line
git pull failed in a Perl CGI process (a webhook to auto-deploy from github) with the above error.

Doing a git status identified a clashing file. Sorting it fixed the problem.

Problem reoccurred later when I changed some config settings.

This time, setting $HOME and $USER env vars fixed it (are unset by default in a CGI process)

How to delete multiple pandas (python) dataframes from memory to save RAM?

This will delete the dataframe and will release the RAM/memory

del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()

the data-frame will be explicitly set to null

in the above statements

Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.

more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/

Transfer data between databases with PostgreSQL

  1. If your source and target database resides in the same local machine, you can use:

Note:- Sourcedb already exists in your database.

CREATE DATABASE targetdb WITH TEMPLATE sourcedb;

This statement copies the sourcedb to the targetdb.

  1. If your source and target databases resides on different servers, you can use following steps:

Step 1:- Dump the source database to a file.

pg_dump -U postgres -O sourcedb sourcedb.sql

Note:- Here postgres is the username so change the name accordingly.

Step 2:- Copy the dump file to the remote server.

Step 3:- Create a new database in the remote server

CREATE DATABASE targetdb;

Step 4:- Restore the dump file on the remote server

psql -U postgres -d targetdb -f sourcedb.sql

(pg_dump is a standalone application (i.e., something you run in a shell/command-line) and not an Postgres/SQL command.)

This should do it.

Bootstrap fullscreen layout with 100% height

_x000D_
_x000D_
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
  <div class="container">
    <div class="row justify-content-between align-items-center">
    x
    x
    x
    </div>
  </div>
</section>
_x000D_
_x000D_
_x000D_

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

Renaming a branch in GitHub

I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

If you need step-by-step you can read this great article:

How to Rename Git Local and Remote Branches

angular 2 ngIf and CSS transition/animation

One way is to use a setter for the ngIf property and set the state as part of updating the value.

StackBlitz example

fade.component.ts

 import {
    animate,
    AnimationEvent,
    state,
    style,
    transition,
    trigger
  } from '@angular/animations';
  import { ChangeDetectionStrategy, Component, Input } from '@angular/core';

  export type FadeState = 'visible' | 'hidden';

  @Component({
    selector: 'app-fade',
    templateUrl: './fade.component.html',
    styleUrls: ['./fade.component.scss'],
    animations: [
      trigger('state', [
        state(
          'visible',
          style({
            opacity: '1'
          })
        ),
        state(
          'hidden',
          style({
            opacity: '0'
          })
        ),
        transition('* => visible', [animate('500ms ease-out')]),
        transition('visible => hidden', [animate('500ms ease-out')])
      ])
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
  })
  export class FadeComponent {
    state: FadeState;
    // tslint:disable-next-line: variable-name
    private _show: boolean;
    get show() {
      return this._show;
    }
    @Input()
    set show(value: boolean) {
      if (value) {
        this._show = value;
        this.state = 'visible';
      } else {
        this.state = 'hidden';
      }
    }

    animationDone(event: AnimationEvent) {
      if (event.fromState === 'visible' && event.toState === 'hidden') {
        this._show = false;
      }
    }
  }

fade.component.html

 <div
    *ngIf="show"
    class="fade"
    [@state]="state"
    (@state.done)="animationDone($event)"
  >
    <button mat-raised-button color="primary">test</button>
  </div>

example.component.css

:host {
  display: block;
}
.fade {
  opacity: 0;
}

What's the difference between an Angular component and module

Component is the template(view) + a class (Typescript code) containing some logic for the view + metadata(to tell angular about from where to get data it needs to display the template).

Modules basically group the related components, services together so that you can have chunks of functionality which can then run independently. For example, an app can have modules for features, for grouping components for a particular feature of your app, such as a dashboard, which you can simply grab and use inside another application.

Can you require two form fields to match with HTML5?

Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:

<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
    function check(input) {
        if (input.value != document.getElementById('password').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            // input is valid -- reset the error message
            input.setCustomValidity('');
        }
    }
</script>
<br /><br />
<input type="submit" />

Reducing the gap between a bullet and text in a list item

This is one way.

    li span {
        margin-left: -11px;
    }

<ul>
    <li><span>1</span></li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

Understanding colors on Android (six characters)

Going off the answer from @BlondeFurious, here is some Java code to get each hexadecimal value from 100% to 0% alpha:

for (double i = 1; i >= 0; i -= 0.01) {
    i = Math.round(i * 100) / 100.0d;
    int alpha = (int) Math.round(i * 255);
    String hex = Integer.toHexString(alpha).toUpperCase();
    if (hex.length() == 1)
        hex = "0" + hex;
    int percent = (int) (i * 100);
    System.out.println(String.format("%d%% — %s", percent, hex));
}

Output:

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

A JavaScript version is below:

_x000D_
_x000D_
var text = document.getElementById('text');_x000D_
for (var i = 1; i >= 0; i -= 0.01) {_x000D_
    i = Math.round(i * 100) / 100;_x000D_
    var alpha = Math.round(i * 255);_x000D_
    var hex = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();_x000D_
    var perc = Math.round(i * 100);_x000D_
    text.innerHTML += perc + "% — " + hex + " (" + alpha + ")</br>";_x000D_
}
_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_


You can also just Google "number to hex" where 'number' is any value between 0 and 255.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Here's what I did, for stamping the AssemblyFileVersion attribute.

Removed the AssemblyFileVersion from AssemblyInfo.cs

Add a new, empty, file called AssemblyFileInfo.cs to the project.

Install the MSBuild community tasks toolset on the hudson build machine or as a NuGet dependency in your project.

Edit the project (csproj) file , it's just an msbuild file, and add the following.

Somewhere there'll be a <PropertyGroup> stating the version. Change that so it reads e.g.

 <Major>1</Major>
 <Minor>0</Minor>
 <!--Hudson sets BUILD_NUMBER and SVN_REVISION -->
 <Build>$(BUILD_NUMBER)</Build>
 <Revision>$(SVN_REVISION)</Revision>

Hudson provides those env variables you see there when the project is built on hudson (assuming it's fetched from subversion).

At the bottom of the project file, add

 <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')" />
  <Target Name="BeforeBuild" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')">
    <Message Text="Version: $(Major).$(Minor).$(Build).$(Revision)" />
    <AssemblyInfo CodeLanguage="CS" OutputFile="AssemblyFileInfo.cs" AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" AssemblyConfiguration="$(Configuration)" Condition="$(Revision) != '' " />
  </Target>

This uses the MSBuildCommunityTasks to generate the AssemblyFileVersion.cs to include an AssemblyFileVersion attribute before the project is built. You could do this for any/all of the version attributes if you want.

The result is, whenever you issue a hudson build, the resulting assembly gets an AssemblyFileVersion of 1.0.HUDSON_BUILD_NR.SVN_REVISION e.g. 1.0.6.2632 , which means the 6'th build # in hudson, buit from the subversion revision 2632.

RunAs A different user when debugging in Visual Studio

As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:

  • Hold Shift + right-click to open a new instance of Visual Studio.
  • Click "Run as different user"

    Run as Different user

  • Enter credentials of the other user in the next pop-up window

  • Open the same solution you are working with

Now when you debug the solution it will be with the other user's permissions.

Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).

How to get a value inside an ArrayList java

The list may contain several elements, so the get method takes an argument : the index of the element you want to retrieve. If you want the first one, then it's 0.

The list contains Car instances, so you just have to do

Car firstCar = car.get(0);
String price = firstCar.getPrice();

or just

String price = car.get(0).getPrice();

The car variable should be named cars, since it's a list and thus contains several cars.

Read the tutorial about collections. And learn to use the javadoc: all the classes and methods are documented.

How do I restart a program based on user input?

You can do this simply with a function. For example:

def script():
    # program code here...
    restart = raw_input("Would you like to restart this program?")
    if restart == "yes" or restart == "y":
        script()
    if restart == "n" or restart == "no":
        print "Script terminating. Goodbye."
script()

Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.

ASP.NET MVC ActionLink and post method

This is taken from the MVC sample project

@if (ViewBag.ShowRemoveButton)
      {
         using (Html.BeginForm("RemoveLogin", "Manage"))
           {
              @Html.AntiForgeryToken()
                  <div>
                     @Html.Hidden("company_name", account)
                     @Html.Hidden("returnUrl", Model.returnUrl)
                     <input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
                  </div>
            }
        }

popup form using html/javascript/css

There are plenty available. Try using Modal windows of Jquery or DHTML would do good. Put the content in your div or Change your content in div dynamically and show it to the user. It won't be a popup but a modal window.
Jquery's Thickbox would clear your problem.

<Django object > is not JSON serializable

Our js-programmer asked me to return the exact JSON format data instead of a json-encoded string to her.

Below is the solution.(This will return an object that can be used/viewed straightly in the browser)

import json
from xxx.models import alert
from django.core import serializers

def test(request):
    alert_list = alert.objects.all()

    tmpJson = serializers.serialize("json",alert_list)
    tmpObj = json.loads(tmpJson)

    return HttpResponse(json.dumps(tmpObj))

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

C++ preprocessor __VA_ARGS__ number of arguments

I'm assuming that each argument to VA_ARGS will be comma separated. If so I think this should work as a pretty clean way to do this.

#include <cstring>

constexpr int CountOccurances(const char* str, char c) {
    return str[0] == char(0) ? 0 : (str[0] == c) + CountOccurances(str+1, c);
}

#define NUMARGS(...) (CountOccurances(#__VA_ARGS__, ',') + 1)

int main(){
    static_assert(NUMARGS(hello, world) == 2, ":(")  ;
    return 0;
}

Worked for me on godbolt for clang 4 and GCC 5.1. This will compute at compile time, but won't evaluate for the preprocessor. So if you are trying to do something like making a FOR_EACH, then this won't work.

Using SSH keys inside docker container

In a running docker container, you can issue ssh-keygen with the docker -i (interactive) option. This will forward the container prompts to create the key inside the docker container.

check if jquery has been loaded, then load it if false

Old post but I made an good solution what is tested on serval places.

https://github.com/CreativForm/Load-jQuery-if-it-is-not-already-loaded

CODE:

(function(url, position, callback){
    // default values
    url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
    position = position || 0;

    // Check is jQuery exists
    if (!window.jQuery) {
        // Initialize <head>
        var head = document.getElementsByTagName('head')[0];
        // Create <script> element
        var script = document.createElement("script");
        // Append URL
        script.src = url;
        // Append type
        script.type = 'text/javascript';
        // Append script to <head>
        head.appendChild(script);
        // Move script on proper position
        head.insertBefore(script,head.childNodes[position]);

        script.onload = function(){
            if(typeof callback == 'function') {
                callback(jQuery);
            }
        };
    } else {
        if(typeof callback == 'function') {
            callback(jQuery);
        }
    }
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){ 
    console.log($);
}));

At GitHub is better explanation but generaly this function you can add anywhere in your HTML code and you will initialize jquery if is not already loaded.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

Style

svg path {
    fill: #000;
}

Script

$(document).ready(function() {
    $('img[src$=".svg"]').each(function() {
        var $img = jQuery(this);
        var imgURL = $img.attr('src');
        var attributes = $img.prop("attributes");

        $.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Remove any invalid XML tags
            $svg = $svg.removeAttr('xmlns:a');

            // Loop through IMG attributes and apply on SVG
            $.each(attributes, function() {
                $svg.attr(this.name, this.value);
            });

            // Replace IMG with SVG
            $img.replaceWith($svg);
        }, 'xml');
    });
});

Print PHP Call Stack

Walltearer's solution is excellent, particularly if enclosed in a 'pre' tag:

<pre>
<?php debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); ?>
</pre>

- which sets out the calls on separate lines, neatly numbered

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

How to get the body's content of an iframe in Javascript?

use content in iframe with JS:

document.getElementById('id_iframe').contentWindow.document.write('content');

Removing pip's cache?

If using pip 6.0 or newer, try adding the --no-cache-dir option (source).

If using pip older than pip 6.0, upgrade it with pip install -U pip.

Searching for UUIDs in text with regex

So, I think Richard Bronosky actually has the best answer to date, but I think you can do a bit to make it somewhat simpler (or at least terser):

re_uuid = re.compile(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', re.I)

Setting up FTP on Amazon Cloud Server

FileZila is good FTP tool to setup with Amazon Cloud.

  1. Download FileZila client from https://filezilla-project.org/
  2. Click on File -> Site Manager - >
  3. New Site
  4. Provide Host Name IP address of your amazon cloud location (Port if any)
  5. Protocol - SFTP (May change based on your requirement)
  6. Login Type - Normal (So system will not ask for password each time)
  7. Provide user name and password.
  8. Connect.

You need to do these step only 1 time, later it will upload content to the same IP address and same site.

ImportError: No module named 'django.core.urlresolvers'

use this one:

from django.urls import reverse

iPhone X / 8 / 8 Plus CSS media queries

It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...

padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);

Here's a link describing this:

https://css-tricks.com/the-notch-and-css/

Babel 6 regeneratorRuntime is not defined

There are so many answers up there, I will post my answer for my reference. I use webpack and react, here is my solution without the .babelrc file

I am working on this in Aug 2020

Install react and babel

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react react react-dom @babel/plugin-transform-runtime --save-dev

Then in my webpack.config.js

// other stuff
module.exports = {
// other stuff

   module: {
   rules: [
  
   {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env',"@babel/preset-react"],
        plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime'],
        //npm install --save-dev @babel/plugin-transform-runtime
          }
        }
      },
    ],
  },

};

I just don't know why I dont need to install the async package for the moment

What is the instanceof operator in JavaScript?

instanceof

The Left Hand Side (LHS) operand is the actual object being tested to the Right Hand Side (RHS) operand which is the actual constructor of a class. The basic definition is:

Checks the current object and returns true if the object
is of the specified object type.

Here are some good examples and here is an example taken directly from Mozilla's developer site:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)

One thing worth mentioning is instanceof evaluates to true if the object inherits from the classe's prototype:

var p = new Person("Jon");
p instanceof Person

That is p instanceof Person is true since p inherits from Person.prototype.

Per the OP's request

I've added a small example with some sample code and an explanation.

When you declare a variable you give it a specific type.

For instance:

int i;
float f;
Customer c;

The above show you some variables, namely i, f, and c. The types are integer, float and a user defined Customer data type. Types such as the above could be for any language, not just JavaScript. However, with JavaScript when you declare a variable you don't explicitly define a type, var x, x could be a number / string / a user defined data type. So what instanceof does is it checks the object to see if it is of the type specified so from above taking the Customer object we could do:

var c = new Customer();
c instanceof Customer; //Returns true as c is just a customer
c instanceof String; //Returns false as c is not a string, it's a customer silly!

Above we've seen that c was declared with the type Customer. We've new'd it and checked whether it is of type Customer or not. Sure is, it returns true. Then still using the Customer object we check if it is a String. Nope, definitely not a String we newed a Customer object not a String object. In this case, it returns false.

It really is that simple!

Access parent URL from iframe

The problem with the PHP $_SERVER['HTTP_REFFERER'] is that it gives the fully qualified page url of the page that brought you to the parent page. That's not the same as the parent page, itself. Worse, sometimes there is no http_referer, because the person typed in the url of the parent page. So, if I get to your parent page from yahoo.com, then yahoo.com becomes the http_referer, not your page.

How to write a simple Java program that finds the greatest common divisor between two numbers?

private static void GCD(int a, int b) {

    int temp;
    // make a greater than b
    if (b > a) {
         temp = a;
         a = b;
         b = temp;
    }

    while (b !=0) {
        // gcd of b and a%b
        temp = a%b;
        // always make a greater than bf
        a =b;
        b =temp;

    }
    System.out.println(a);
}

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

WPF MVVM: How to close a window

I found myself having to do this on a WPF application based on .Net Core 3.0, where unfortunately behaviour support was not yet officially available in the Microsoft.Xaml.Behaviors.Wpf NuGet package.

Instead, I went with a solution that made use of the Façade design pattern.

Interface:

public interface IWindowFacade
{
    void Close();
}

Window:

public partial class MainWindow : Window, IWindowFacade
…

Standard command property on the view model:

public ICommand ExitCommand
…

Control binding:

<MenuItem Header="E_xit" Command="{Binding ExitCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>

Command:

public class ExitCommand : ICommand
{
    …
    public void Execute(object parameter)
    {
        var windowFacade = parameter as IWindowFacade;
        windowFacade?.Close();
    }
    …
}

Because the Close() method is already implemented by the Window class, applying the façade interface to the window is the only required code behind in the UI layer (for this simple example). The command in the presentation layer avoids any dependencies on the view/UI layer as it has no idea what it is talking to when it calls the Close method on the façade.

Display more Text in fullcalendar

I personally use a tooltip to display additional information, so when someone hovers over the event they can view a longer descriptions. This example uses qTip, but any tooltip implementation would work.

$(document).ready(function() {
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    $('#calendar').fullCalendar({
        header: {
            left: 'prev, next today',
            center: 'title',
            right: 'month, basicWeek, basicDay'
        },
        //events: "Calendar.asmx/EventList",
        //defaultView: 'dayView',
        events: [
        {
            title: 'All Day Event',
            start: new Date(y, m, 1),
            description: 'long description',
            id: 1
        },
        {
            title: 'Long Event',
            start: new Date(y, m, d - 5),
            end: new Date(y, m, 1),
            description: 'long description3',
            id: 2
        }],
        eventRender: function(event, element) {
            element.qtip({
                content: event.description + '<br />' + event.start,
                style: {
                    background: 'black',
                    color: '#FFFFFF'
                },
                position: {
                    corner: {
                        target: 'center',
                        tooltip: 'bottomMiddle'
                    }
                }
            });
        }
    });
});

link button property to open in new tab?

try by Adding following onClientClick event.

OnClientClick="aspnetForm.target ='_blank';"

so on click it will call Javascript function an will open respective link in News tab.

<asp:LinkButton id="lbnkVidTtile1" OnClientClick="aspnetForm.target ='_blank';" runat="Server" CssClass="bodytext" Text='<%# Eval("newvideotitle") %>'  />

How do you use youtube-dl to download live streams (that are live)?

There is no need to pass anything to ffmpeg you can just grab the desired format, in this example, it was the "95" format.

So once you know that it is the 95, you just type:

youtube-dl -f 95  https://www.youtube.com/watch\?v\=6aXR-SL5L2o

that is to say:

youtube-dl -f <format number> <url>

It will begin generating on the working directory a <somename>.<probably mp4>.part which is the partially downloaded file, let it go and just press <Ctrl-C> to stop the capture.

The file will still be named <something>.part, rename it to <whatever>.mp4 and there it is...

The ffmpeg code:

ffmpeg -i $(youtube-dl -f <format number> -g <url>) -copy <file_name>.ts

also worked for me, but sound and video got out of sync, using just youtube-dl seemed to yield a better result although it too uses ffmpeg.

The downside of this approach is that you cannot watch the video while downloading, well you can open yet another FF or Chrome, but it seems that mplayer cannot process the video output till youtube-dl/ffmpeg are running.

How to test if parameters exist in rails

Here's what I do,

before_action :validate_presence

and then following methods:

    def check_presence
  params[:param1].present? && params[:param2].present?
 end

 def validate_presence
  if !check_presence
    render json:  {
                      error:  {
                                message: "Bad Request, parameters missing.",
                                status: 500
                              }
                    }
  end
 end

Call method when home button pressed

I also struggled with HOME button for awhile. I wanted to stop/skip a background service (which polls location) when user clicks HOME button.

here is what I implemented as "hack-like" solution;

keep the state of the app on SharedPreferences using boolean value

on each activity

onResume() -> set appactive=true

onPause() -> set appactive=false

and the background service checks the appstate in each loop, skips the action

IF appactive=false

it works well for me, at least not draining the battery anymore, hope this helps....

word-wrap break-word does not work in this example

This code is also working:

_x000D_
_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<table style="table-layout:fixed;">_x000D_
<tr>_x000D_
<td style="word-break: break-all; width:100px;">ThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrap</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:

1: direct opening the sql server import and export wizard.

if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.

Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.

If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet

or check in the Addition Information content from the link below,

https://www.microsoft.com/en-us/download/details.aspx?id=54920

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

In your $CATALINA_BASE/conf/context.xml add block below before </Context>

<Resources cachingAllowed="true" cacheMaxSize="100000" />

For more information: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html

RSA encryption and decryption in Python

Watch out using Crypto!!! It is a wonderful library but it has an issue in python3.8 'cause from the library time was removed the attribute clock(). To fix it just modify the source in /usr/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.pyline 77 changing t = time.clock() int t = time.perf_counter()

Why does this code using random strings print "hello world"?

Derived from Denis Tulskiy's answer, this method generates the seed.

public static long generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
        for (long seed = start; seed < finish; seed++) {
            Random random = new Random(seed);

            for (int i = 0; i < input.length; i++)
                pool[i] = (char) (random.nextInt(27)+'`');

            if (random.nextInt(27) == 0) {
                for (int i = 0; i < input.length; i++) {
                    if (input[i] != pool[i])
                        continue label;
                }
                return seed;
            }

        }

    throw new NoSuchElementException("Sorry :/");
}

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

.aspx vs .ashx MAIN difference

Page is a special case handler.

Generic Web handler (*.ashx, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler directive.

ASP.NET page handler (*.aspx) is the default HTTP handler for all ASP.NET pages.

Among the built-in HTTP handlers there are also Web service handler (*.asmx) and Trace handler (trace.axd)

MSDN says:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

The image below illustrates this: request pipe line

As to your second question:

Does ashx handle more connections than aspx?

Don't think so (but for sure, at least not less than).

How to convert float number to Binary?

x = float(raw_input("enter number between 0 and 1: "))

p = 0
while ((2**p)*x) %1 != 0:
    p += 1
    # print p

    num = int (x * (2 ** p))
    # print num

    result = ''
    if num == 0:
        result = '0'
    while num > 0:
        result = str(num%2) + result
        num = num / 2

    for i in range (p - len(result)):
        result = '0' + result
    result = result[0:-p] + '.' + result[-p:]

print result #this will print result for the decimal portion

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

Convert an array into an ArrayList

This will give you a list.

List<Card> cardsList = Arrays.asList(hand);

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));

Get free disk space

As this answer and @RichardOD suggested , you should do like this:

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
   out ulong lpFreeBytesAvailable,
   out ulong lpTotalNumberOfBytes,
   out ulong lpTotalNumberOfFreeBytes);

ulong FreeBytesAvailable;
ulong TotalNumberOfBytes;
ulong TotalNumberOfFreeBytes;

bool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder",
                                  out FreeBytesAvailable,
                                  out TotalNumberOfBytes,
                                  out TotalNumberOfFreeBytes);
if(!success)
    throw new System.ComponentModel.Win32Exception();

Console.WriteLine("Free Bytes Available:      {0,15:D}", FreeBytesAvailable);
Console.WriteLine("Total Number Of Bytes:     {0,15:D}", TotalNumberOfBytes);
Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);

Converting milliseconds to a date (jQuery/JavaScript)

/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

What is a void pointer in C++?

A void* pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.

How to apply filters to *ngFor?

For this requirement, I implement and publish a generic component. See

https://www.npmjs.com/package/w-ng5

For use this components, before, install this package with npm:

npm install w-ng5 --save

After, import module in app.module

...
import { PipesModule } from 'w-ng5';

In the next step, add in declare section of app.module:

imports: [
  PipesModule,
  ...
]

Sample use

Filtering simple string

<input type="text"  [(ngModel)]="filtroString">
<ul>
  <li *ngFor="let s of getStrings() | filter:filtroString">
    {{s}}
  </li>
</ul>

Filtering complex string - field 'Value' in level 2

<input type="text"  [(ngModel)]="search">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtering complex string - middle field - 'Value' in level 1

<input type="text"  [(ngModel)]="search3">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.valor1', value: search3}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtering complex array simple - field 'Nome' level 0

<input type="text"  [(ngModel)]="search2">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'nome', value: search2}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtering in tree fields - field 'Valor' in level 2 or 'Valor' in level 1 or 'Nome' in level 0

<input type="text"  [(ngModel)]="search5">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search5}, {field:'n1.valor1', value: search5}, {field:'nome', value: search5}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtering nonexistent field - 'Valor' in nonexistent level 3

<input type="text"  [(ngModel)]="search4">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.n3.valor3', value: search4}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

This component work with infinite attribute level...

#define in Java

Java doesn't have a general purpose define preprocessor directive.

In the case of constants, it is recommended to declare them as static finals, like in

private static final int PROTEINS = 100;

Such declarations would be inlined by the compilers (if the value is a compile-time constant).

Please note also that public static final constant fields are part of the public interface and their values shouldn't change (as the compiler inlines them). If you do change the value, you would need to recompile all the sources that referenced that constant field.

SQL Server : How to test if a string has only digit characters

Method that will work. The way it is used above will not work.

declare @str varchar(50)='79136'

select 
  case 
    when  @str LIKE replicate('[0-9]',LEN(@str)) then 1 
    else 0 
  end

declare @str2 varchar(50)='79D136'

select 
  case 
    when  @str2 LIKE replicate('[0-9]',LEN(@str)) then 1 
    else 0 
  end

Error CS2001: Source file '.cs' could not be found

I had this problem, too.

Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.

  1. I checked all of the solutions mentioned on this question. The class name and build action were correct.
  2. I Cleaned my Solution and rebuilt. Another error appeared. "Error CS2001: Source file '.cs' could not be found"
  3. I found this answer and followed the steps.
  4. I reloaded the project and cleaned/rebuilt again.
  5. My solution builds without errors and my application works now.

How to use onSavedInstanceState example please

One major note that all new Android developers should know is that any information in Widgets (TextView, Buttons, etc.) will be persisted automatically by Android as long as you assign an ID to them. So that means most of the UI state is taken care of without issue. Only when you need to store other data does this become an issue.

From Android Docs:

The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then it cannot save its state

Regex to extract substring, returning 2 results for some reason

match returns an array.

The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);

go get results in 'terminal prompts disabled' error for github private repo

It complains because it needs to use ssh instead of https but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh instead of https. a simple way to do this by running the following:

git config --global --add url."[email protected]:".insteadOf "https://github.com/"

or if you already use ssh with git in your machine, you can safely edit ~/.gitconfig and add the following line at the very bottom

Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
        insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/
  • If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.

  • For more information on how to add ssh to your github account, please visit this page.

Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.

To do this, you need to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.

The variable is a comma-separated list of patterns (same syntax of Go's path.Match) of module path prefixes. For example,

export GOPRIVATE=*.corp.example.com,github.com/mycompany/*

Or

go env -w GOPRIVATE=github.com/mycompany/*
  • For more information on how to solve private packages/modules checksum validation issues, please read this article.
  • For more information about go 13 modules and new enhancements, please check out Go 1.13 Modules Release notes.

One last thing not to forget to mention, you can still configure go get to authenticate and fetch over https, all you need to do is to add the following line to $HOME/.netrc

machine github.com login USERNAME password APIKEY
  • For GitHub accounts, the password can be a personal access tokens.
  • For more information on how to do this, please check Go FAQ page.

I hope this helps the community and saves others' time to solve described issues quickly. please feel free to leave a comment in case you want more support or help.

CodeIgniter -> Get current URL relative to base url

In CI v3, you can try:

function partial_uri($start = 0) {
    return join('/',array_slice(get_instance()->uri->segment_array(), $start));
}

This will drop the number of URL segments specified by the $start argument. If your URL is http://localhost/dropbox/derrek/shopredux/ahahaha/hihihi, then:

partial_uri(3);  # returns "ahahaha/hihihi"

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

How to specify a multi-line shell variable?

Use read with a heredoc as shown below:

read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF

echo "$sql"

How to customize the configuration file of the official PostgreSQL Docker image?

With Docker Compose

When working with Docker Compose, you can use command: postgres -c option=value in your docker-compose.yml to configure Postgres.

For example, this makes Postgres log to a file:

command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs

Adapting Vojtech Vitek's answer, you can use

command: postgres -c config_file=/etc/postgresql.conf

to change the config file Postgres will use. You'd mount your custom config file with a volume:

volumes:
   - ./customPostgresql.conf:/etc/postgresql.conf

Here's the docker-compose.yml of my application, showing how to configure Postgres:

# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
  myApp:
    image: registry.gitlab.com/bullbytes/myApp:latest
    networks:
      - myApp-network
  db:
     image: postgres:9.6.1
     # Make Postgres log to a file.
     # More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
     command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
     environment:
       # Provide the password via an environment variable. If the variable is unset or empty, use a default password
       - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
     # If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
     volumes:
       # Persist the data between container invocations
       - postgresVolume:/var/lib/postgresql/data
       - ./logs:/logs
     networks:
       myApp-network:
         # Our application can communicate with the database using this hostname
         aliases:
           - postgresForMyApp
networks:
  myApp-network:
    driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
  postgresVolume:

Permission to write to the log directory

Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error

FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied

I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.

To fix this, I set the correct permissions on the host using

chgroup ./logs docker && chmod 770 ./logs

Why can't I declare static methods in an interface?

There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between

public interface Foo {
  public static int bar();
}

and

public interface Foo {
  public static int bar() {
    ...
  }
}

The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.

Java could allow the latter; and in fact, starting in Java 8, it does!

MVC razor form with multiple different submit buttons?

This elegant solution works for number of submit buttons:

@Html.Begin()
{
  // Html code here
  <input type="submit" name="command" value="submit1" />
  <input type="submit" name="command" value="submit2" />

}

And in your controllers' action method accept it as a parameter.

public ActionResult Create(Employee model, string command)
{
    if(command.Equals("submit1"))
    {
      // Call action here...
    }
    else
    {
      // Call another action here...
    }
}

Does return stop a loop?

Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.

It is easily verified for yourself:

_x000D_
_x000D_
function returnMe() {
  for (var i = 0; i < 2; i++) {
    if (i === 1) return i;
  }
}

console.log(returnMe());
_x000D_
_x000D_
_x000D_

** Notes: See this other answer about the special case of try/catch/finally and this answer about how forEach loops has its own function scope will not break out of the containing function.

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

ArrayList of String Arrays

I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:

List<List<String>> addresses = new ArrayList<List<String>>();

But honestly for addresses, I'd create a class to model them.

If you were to use arrays it would be:

List<String[]> addresses = new ArrayList<String[]>();

ie you can't declare the size of the array.

Lastly, don't declare your types as concrete types in instances like this (ie for addresses). Use the interface as I've done above. This applies to member variables, return types and parameter types.

Get protocol, domain, and port from URL

None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.

Method 1: Use the URL API (caveat: no IE11 support)

You can use the URL API (not supported by IE11, but available everywhere else).

This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

Method 2 (old way): Use the browser's built-in parser in the DOM

Use this if you need this to work on older browsers as well.

//  Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
//  Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

That's it!

The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):

//  Get any piece of the url you're interested in
url.hostname;  //  'example.com'
url.port;      //  12345
url.search;    //  '?startIndex=1&pageSize=10'
url.pathname;  //  '/blog/foo/bar'
url.protocol;  //  'http:'

Bonus: Search params

Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.

If you used Method 1 (URL API) above, you simply use the searchParams getters:

url.searchParams.get('startIndex');  // '1'

Or to get all parameters:

function searchParamsToObj(searchParams) {
  const paramsMap = Array
    .from(url.searchParams)
    .reduce((params, [key, val]) => params.set(key, val), new Map());
  return Object.fromEntries(paramsMap);
}
searchParamsToObj(url.searchParams);
// -> { startIndex: '1', pageSize: '10' }

If you used Method 2 (the old way), you can use something like this:

// Simple object output (note: does NOT preserve duplicate keys).
var params = url.search.substr(1); // remove '?' prefix
params
    .split('&')
    .reduce((accum, keyval) => {
        const [key, val] = keyval.split('=');
        accum[key] = val;
        return accum;
    }, {});
// -> { startIndex: '1', pageSize: '10' }

How to add new DataRow into DataTable?

I found dotnetperls examples on DataRow very helpful. Code snippet for new DataTable from there:

static DataTable GetTable()
{
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("Weight", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Breed", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
    table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
    table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
    table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
    table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);

    return table;
}

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

Center the nav in Twitter Bootstrap

Code used basic nav bootstrap

_x000D_
_x000D_
<!--MENU CENTER`enter code here` RESPONSIVE -->_x000D_
_x000D_
  <div class="container-fluid">_x000D_
        <div class="container logo"><h1>LOGO</h1></div>_x000D_
      <nav class="navbar navbar-default menu">_x000D_
        <div class="container-fluid">_x000D_
          <!-- Brand and toggle get grouped for better mobile display -->_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar2"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>_x000D_
           </div>_x000D_
          <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
          <div class="collapse navbar-collapse" id="defaultNavbar2">_x000D_
            <ul class="nav nav-justified" >_x000D_
              <li><a href="#">Home</a></li>_x000D_
              <li><a href="#">Link</a></li>_x000D_
              <li><a href="#">Link</a></li>_x000D_
              <li><a href="#">Link</a></li>_x000D_
              <li><a href="#">Link</a></li>_x000D_
              <li><a href="#">Link</a></li>_x000D_
              <li><a href="#">Link</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!-- /.navbar-collapse -->_x000D_
        </div>_x000D_
        <!-- /.container-fluid -->_x000D_
      </nav>_x000D_
    </div>_x000D_
  <!-- END MENU-->
_x000D_
_x000D_
_x000D_

Where is the list of predefined Maven properties

I think the best place to look is the Super POM.

As an example, at the time of writing, the linked reference shows some of the properties between lines 32 - 48.

The interpretation of this is to follow the XPath as a . delimited property.

So, for example:

${project.build.testOutputDirectory} == ${project.build.directory}/test-classes

And:

${project.build.directory} == ${project.basedir}/target

Thus combining them, we find:

${project.build.testOutputDirectory} == ${project.basedir}/target/test-classes

(To reference the resources directory(s), see this stackoverflow question)


<project>
    <modelVersion>4.0.0</modelVersion>
    .
    .
    .
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        .
        .
        .
    </build>
    .
    .
    .
</project>

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

Re-assign host access permission to MySQL user

I received the same error with RENAME USER and GRANTS aren't covered by the currently accepted solution:

The most reliable way seems to be to run SHOW GRANTS for the old user, find/replace what you want to change regarding the user's name and/or host and run them and then finally DROP USER the old user. Not forgetting to run FLUSH PRIVILEGES (best to run this after adding the new users' grants, test the new user, then drop the old user and flush again for good measure).

    > SHOW GRANTS FOR 'olduser'@'oldhost';
    +-----------------------------------------------------------------------------------+
    | Grants for olduser@oldhost                                                        |
    +-----------------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'olduser'@'oldhost' IDENTIFIED BY PASSWORD '*PASSHASH'      |
    | GRANT SELECT ON `db`.* TO 'olduser'@'oldhost'                                     |
    +-----------------------------------------------------------------------------------+
    2 rows in set (0.000 sec)

    > GRANT USAGE ON *.* TO 'newuser'@'newhost' IDENTIFIED BY PASSWORD '*SAME_PASSHASH';
    Query OK, 0 rows affected (0.006 sec)

    > GRANT SELECT ON `db`.* TO 'newuser'@'newhost';
    Query OK, 0 rows affected (0.007 sec)

    > DROP USER 'olduser'@'oldhost';
    Query OK, 0 rows affected (0.016 sec)

Email Address Validation in Android on EditText

To perform Email Validation we have many ways,but simple & easiest way are two methods.

1- Using EditText(....).addTextChangedListener which keeps triggering on every input in an EditText box i.e email_id is invalid or valid

/**
 * Email Validation ex:- [email protected]
*/


final EditText emailValidate = (EditText)findViewById(R.id.textMessage); 

final TextView textView = (TextView)findViewById(R.id.text); 

String email = emailValidate.getText().toString().trim();

String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

emailValidate .addTextChangedListener(new TextWatcher() { 
    public void afterTextChanged(Editable s) { 

    if (email.matches(emailPattern) && s.length() > 0)
        { 
            Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
            // or
            textView.setText("valid email");
        }
        else
        {
             Toast.makeText(getApplicationContext(),"Invalid email address",Toast.LENGTH_SHORT).show();
            //or
            textView.setText("invalid email");
        }
    } 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // other stuffs 
    } 
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    // other stuffs 
    } 
}); 

2- Simplest method using if-else condition. Take the EditText box string using getText() and compare with pattern provided for email. If pattern doesn't match or macthes, onClick of button toast a message. It ll not trigger on every input of an character in EditText box . simple example shown below.

final EditText emailValidate = (EditText)findViewById(R.id.textMessage); 

final TextView textView = (TextView)findViewById(R.id.text); 

String email = emailValidate.getText().toString().trim();

String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

// onClick of button perform this simplest code.
if (email.matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else 
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}

How to test that a registered variable is not empty?

You can check for empty string (when stderr is empty)

- name: Check script
  shell: . {{ venv_name }}/bin/activate && myscritp.py
  args:
    chdir: "{{ home }}"
  sudo_user: "{{ user }}"
  register: test_myscript

- debug: msg='myscritp is Ok'
  when: test_myscript.stderr == ""

If you want to check for fail:

- debug: msg='myscritp has error: {{test_myscript.stderr}}'
  when: test_myscript.stderr != ""

Also look at this stackoverflow question

What is the difference between using constructor vs getInitialState in React / React Native?

The big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React . The constructor method is a special method for creating and initializing an object created with a class.

how to detect search engine bots with php?

I use the following code which seems to be working fine:

function _bot_detected() {

  return (
    isset($_SERVER['HTTP_USER_AGENT'])
    && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])
  );
}

update 16-06-2017 https://support.google.com/webmasters/answer/1061943?hl=en

added mediapartners

Correct way to use Modernizr to detect IE?

You can use the < !-- [if IE] > hack to set a global js variable that then gets tested in your normal js code. A bit ugly but has worked well for me.

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

Eloquent ->first() if ->exists()

Try it this way in a simple manner it will work

$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";

SonarQube Exclude a directory

Add comma separated folder paths sonar.exclusions=**/abc/**,**/def/**

This worked in an angular project

base_url() function not working in codeigniter

First of all load URL helper. you can load in "config/autoload.php" file and add following code $autoload['helper'] = array('url');

or in controller add following code

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

then go to config.php in cofig folder and set

$config['base_url'] = 'http://urlbaseurl.com/';

hope this will help thanks

What is the significance of load factor in HashMap?

I would pick a table size of n * 1.5 or n + (n >> 1), this would give a load factor of .66666~ without division, which is slow on most systems, especially on portable systems where there is no division in the hardware.

PHP json_encode encoding numbers as strings

Like oli_arborum said, I think you can use a preg_replace for doing the job. Just change the command like this :

$json = preg_replace('#:"(\d+)"#', ':$1', $json);

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Why I can't change directories using "cd"?

You can do following:

#!/bin/bash
cd /your/project/directory
# start another shell and replacing the current
exec /bin/bash

EDIT: This could be 'dotted' as well, to prevent creation of subsequent shells.

Example:

. ./previous_script  (with or without the first line)

Any way to break if statement in PHP?

Don't worry about other users comments, I can understand you, SOMETIMES when developing this "fancy" things are required. If we can break an if, a lot of nested ifs won't be necessary, making the code much more clean and aesthetic.

This sample code illustrate that CERTAINS SITUATIONS where breaked if can be much more suitable than a lot of ugly nested ifs... if you haven't faced that certain situation does not mean it doesn't exists.

Ugly code

if(process_x()) {

    /* do a lot of other things */

    if(process_y()) {

         /* do a lot of other things */

         if(process_z()) {

              /* do a lot of other things */
              /* SUCCESS */

         }
         else {

              clean_all_processes();

         }

    }
    else {

         clean_all_processes();

    }

}
else {

    clean_all_processes();

}

Good looking code

do {

  if( !process_x() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_y() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_z() )
    { clean_all_processes();  break; }

  /* do a lot of other things */
  /* SUCCESS */

} while (0);

As @NiematojakTomasz says, the use of goto is an alternative, the bad thing about this is you always need to define the label (point target).

Could not load file or assembly 'System.Data.SQLite'

Make sure that "Enable 32 - Bit Applications" is set to false for the app pool.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Guava Documentation

The JDK provides Collections.unmodifiableXXX methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

Strip Leading and Trailing Spaces From Java String

With Java-11 and above, you can make use of the String.strip API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same reads :

/**
 * Returns a string whose value is this string, with all leading
 * and trailing {@link Character#isWhitespace(int) white space}
 * removed.
 * <p>
 * If this {@code String} object represents an empty string,
 * or if all code points in this string are
 * {@link Character#isWhitespace(int) white space}, then an empty string
 * is returned.
 * <p>
 * Otherwise, returns a substring of this string beginning with the first
 * code point that is not a {@link Character#isWhitespace(int) white space}
 * up to and including the last code point that is not a
 * {@link Character#isWhitespace(int) white space}.
 * <p>
 * This method may be used to strip
 * {@link Character#isWhitespace(int) white space} from
 * the beginning and end of a string.
 *
 * @return  a string whose value is this string, with all leading
 *          and trailing white space removed
 *
 * @see Character#isWhitespace(int)
 *
 * @since 11
 */
public String strip()

The sample cases for these could be:--

System.out.println("  leading".strip()); // prints "leading"
System.out.println("trailing  ".strip()); // prints "trailing"
System.out.println("  keep this  ".strip()); // prints "keep this"

How to install python3 version of package via pip on Ubuntu?

Another way to install python3 is using wget. Below are the steps for installation.

wget http://www.python.org/ftp/python/3.3.5/Python-3.3.5.tar.xz
tar xJf ./Python-3.3.5.tar.xz
cd ./Python-3.3.5
./configure --prefix=/opt/python3.3
make && sudo make install

Also,one can create an alias for the same using

echo 'alias py="/opt/python3.3/bin/python3.3"' >> ~/.bashrc

Now open a new terminal and type py and press Enter.

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

Is it a good practice to use try-except-else in Python?

Is it a good practice to use try-except-else in python?

The answer to this is that it is context dependent. If you do this:

d = dict()
try:
    item = d['item']
except KeyError:
    item = 'default'

It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get method:

item = d.get('item', 'default')

The try/except block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.

However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.

Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.

Apple Mach-O Linker Error when compiling for device

If you have defined NSObject with the same name like:

NSObject *notUniqueObj;

even in 2 different files ( if you are importing one in another ), it will give you an error. Give different names for those.

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

OpenCV - DLL missing, but it's not?

Copy all .dll from /bin in System32

How to enable Logger.debug() in Log4j

You need to set the logger level to the lowest you want to display. For example, if you want to display DEBUG messages, you need to set the logger level to DEBUG.

The Apache log4j manual has a section on Configuration.

Where is Developer Command Prompt for VS2013?

I'm using VS 2012, so I navigated to "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Visual Studio 2012\Visual Studio Tools" and ran as administrator this "Developer Command Prompt for VS2012" shortcut. In command shell I pasted the suggested

aspnet_regiis -i

and as I suspected this did not yield any success on Windows 10: enter image description here

So all I needed to do was "Turn Windows Features On/Off" at Control Panel and restart my machine to effect the changes. That did resolve the issue. Thanks.

What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

Is there anyway to exclude artifacts inherited from a parent POM?

When you call a package but do not want some of its dependencies you can do a thing like this (in this case I did not want the old log4j to be added because I needed to use the newer one):

<dependency>
  <groupId>package</groupId>
  <artifactId>package-pk</artifactId>
  <version>${package-pk.version}</version>

  <exclusions>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
    </exclusion>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<!-- LOG4J -->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.5</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.5</version>
</dependency>

This works for me... but I am pretty new to java/maven so it is maybe not optimum.

Python Binomial Coefficient

What about this one? :) It uses correct formula, avoids math.factorial and takes less multiplication operations:

import math
import operator
product = lambda m,n: reduce(operator.mul, xrange(m, n+1), 1)
x = max(0, int(input("Enter a value for x: ")))
y = max(0, int(input("Enter a value for y: ")))
print product(y+1, x) / product(1, x-y)

Also, in order to avoid big-integer arithmetics you may use floating point numbers, convert product(a[i])/product(b[i]) to product(a[i]/b[i]) and rewrite the above program as:

import math
import operator
product = lambda iterable: reduce(operator.mul, iterable, 1)
x = max(0, int(input("Enter a value for x: ")))
y = max(0, int(input("Enter a value for y: ")))
print product(map(operator.truediv, xrange(y+1, x+1), xrange(1, x-y+1)))

Convert string to ASCII value python

you can actually do it with numpy:

import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)

document.createElement("script") synchronously

This looks like a decent overview of dynamic script loading: http://unixpapa.com/js/dyna.html

Find closest previous element jQuery

I know this is old, but was hunting for the same thing and ended up coming up with another solution which is fairly concise andsimple. Here's my way of finding the next or previous element, taking into account traversal over elements that aren't of the type we're looking for:

var ClosestPrev = $( StartObject ).prevAll( '.selectorClass' ).first();
var ClosestNext = $( StartObject ).nextAll( '.selectorClass' ).first();

I'm not 100% sure of the order that the collection from the nextAll/prevAll functions return, but in my test case, it appears that the array is in the direction expected. Might be helpful if someone could clarify the internals of jquery for that for a strong guarantee of reliability.

Select DISTINCT individual columns in django?

The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

or

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.

How can I add comments in MySQL?

From here you can use

#  For single line comments
-- Also for single line, must be followed by space/control character
/*
    C-style multiline comment
*/

How can I "reset" an Arduino board?

Here is the best way that works out if you are trying to program through the USB cable:

  1. Ground the Tx signal on the board (connect digital I/O #1 to GND)
  2. Plug the USB cable
  3. Upload a new program
  4. Remove the USB cable
  5. Remove Tx grounding

You are all set!

How to replace a hash key with another key

rails Hash has standard method for it:

hash.transform_keys{ |key| key.to_s.upcase }

http://api.rubyonrails.org/classes/Hash.html#method-i-transform_keys

UPD: ruby 2.5 method

Docker Error bind: address already in use

maybe it is too rude, but works for me. restart docker service itself

sudo service docker restart

hope it works for you also!

GitHub relative link in Markdown file

Just follow the format below.

[TEXT TO SHOW](actual URL to navigate)

How to get these two divs side-by-side?

#parent_div_1, #parent_div_2, #parent_div_3 {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin-right: 10px;
  float: left;
}
.child_div_1 {
  float: left;
  margin-right: 5px;
}

Check working example at http://jsfiddle.net/c6242/1/

Basic http file downloading and saving to disk in python?

I started down this path because ESXi's wget is not compiled with SSL and I wanted to download an OVA from a vendor's website directly onto the ESXi host which is on the other side of the world.

I had to disable the firewall(lazy)/enable https out by editing the rules(proper)

created the python script:

import ssl
import shutil
import tempfile
import urllib.request
context = ssl._create_unverified_context()

dlurl='https://somesite/path/whatever'
with urllib.request.urlopen(durl, context=context) as response:
    with open("file.ova", 'wb') as tmp_file:
        shutil.copyfileobj(response, tmp_file)

ESXi libraries are kind of paired down but the open source weasel installer seemed to use urllib for https... so it inspired me to go down this path

Why use multiple columns as primary keys (composite primary key)

We create composite primary keys to guarantee the uniqueness column values which compose a single record. It is a constraint which helps prevent insertion of data which should not be duplicated.

i.e: If all student Ids and birth certificate numbers are uniquely assigned to a single person. Then it would be a good idea to make the primary key for a person a composition of student id and birth certificate number because it would prevent you from accidentally inserting two people who have different student ids and the same birth certificate.

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

How to reshape data from long to wide format

With the devel version of tidyr ‘0.8.3.9000’, there is pivot_wider and pivot_longer which is generalized to do the reshaping (long -> wide, wide -> long, respectively) from 1 to multiple columns. Using the OP's data

-single column long -> wide

library(dplyr)
library(tidyr)
dat1 %>% 
    pivot_wider(names_from = numbers, values_from = value)
# A tibble: 2 x 5
#  name          `1`    `2`    `3`    `4`
#  <fct>       <dbl>  <dbl>  <dbl>  <dbl>
#1 firstName   0.341 -0.703 -0.380 -0.746
#2 secondName -0.898 -0.335 -0.501 -0.175

-> created another column for showing the functionality

dat1 %>% 
    mutate(value2 = value * 2) %>% 
    pivot_wider(names_from = numbers, values_from = c("value", "value2"))
# A tibble: 2 x 9
#  name       value_1 value_2 value_3 value_4 value2_1 value2_2 value2_3 value2_4
#  <fct>        <dbl>   <dbl>   <dbl>   <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
#1 firstName    0.341  -0.703  -0.380  -0.746    0.682   -1.41    -0.759   -1.49 
#2 secondName  -0.898  -0.335  -0.501  -0.175   -1.80    -0.670   -1.00    -0.349

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

When I drag files in, the "Add to targets" box seems to be un-ticked by default. If I leave it un-ticked then I have the problem described. Fix it by deleting the files then dragging them back in but making sure to tick "Add to targets". enter image description here

What happens if you don't commit a transaction to a database (say, SQL Server)?

As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks.

If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.

How to increment a number by 2 in a PHP For Loop

<?php    
     $x = 1;

     for($x = 1; $x < 8; $x++) {
       $x = $x + 2;
       echo $x;
     };
?>

How can I add new item to the String array?

String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

Storing money in a decimal column - what precision and scale?

I would think that for a large part your or your client's requirements should dictate what precision and scale to use. For example, for the e-commerce website I am working on that deals with money in GBP only, I have been required to keep it to Decimal( 6, 2 ).

How to deploy a Java Web Application (.war) on tomcat?

As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webappdirectory.

Now, if Tomcat is installed and running on bilgin.ath.cx (as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80 on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk?, mod_proxy?). You should either give us more details or discuss this with your hosting provider.

Update: As expected, the bilgin.ath.cx is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties file to configure the workers and the httpd.conf for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount directive in Apache httpd.conf for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.

1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)

What's the difference between lists and tuples?

Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures.

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

Is there a way to get a list of all current temporary tables in SQL Server?

You can get list of temp tables by following query :

select left(name, charindex('_',name)-1) 
from tempdb..sysobjects
where charindex('_',name) > 0 and
xtype = 'u' and not object_id('tempdb..'+name) is null

Jquery validation plugin - TypeError: $(...).validate is not a function

You didn't include the base jQuery Validation library:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

Put that before the additional methods library. (BTW this is a hosted version, download your own if you want)

How can I show and hide elements based on selected option with jQuery?

You're running the code before the DOM is loaded.

Try this:

Live example:

http://jsfiddle.net/FvMYz/

$(function() {    // Makes sure the code contained doesn't run until
                  //     all the DOM elements have loaded

    $('#colorselector').change(function(){
        $('.colors').hide();
        $('#' + $(this).val()).show();
    });

});

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

How to set environment variable for everyone under my linux system?

If your LinuxOS has this file:

/etc/environment

You can use it to permanently set environmental variables for all users.

Extracted from: http://www.sysadmit.com/2016/04/linux-variables-de-entorno-permanentes.html

Get Android Device Name

Following works for me.

String deviceName = Settings.Global.getString(.getContentResolver(), Settings.Global.DEVICE_NAME);

I don't think so its duplicate answer. The above ppl are talking about Setting Secure, for me setting secure is giving null, if i use setting global it works. Thanks anyways.

C# MessageBox dialog result

Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.

var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
    case DialogResult.Yes:
        SaveChanges();
        break;
    case DialogResult.No:
        Rollback();
        break;
    default:
        break;
}

How to group subarrays by a column value?

I think this works better in PHP 5.5+

$IdVar = array_column($data, 'id');

CSS3 Transparency + Gradient

New syntax has been supported for a while by all modern browsers (starting from Chrome 26, Opera 12.1, IE 10 and Firefox 16): http://caniuse.com/#feat=css-gradients

background: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));

This renders a gradient, starting from solid black at the top, to fully transparent at the bottom.

Documentation on MDN.

Delete forked repo from GitHub

I had also faced this issue. NO it will not affect your original repo by anyway. just simply delete it by entering the name of forked repo

Ascii/Hex convert in bash

here a little script I wrote to convert ascii to hex. hope it helps:

echo '0x'"`echo 'ASCII INPUT GOES HERE' | hexdump -vC |  awk 'BEGIN {IFS="\t"} {$1=""; print }' | awk '{sub(/\|.*/,"")}1'  | tr -d '\n' | tr -d ' '`" | rev | cut -c 3- | rev

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

Check if returned value is not null and if so assign it, in one line, with one method call

Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.

You can use the result variable as your temporary, like this:

dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();

This, however, is hard to read.

Makefile ifeq logical or

You can introduce another variable. It doesnt consolidate both checks, but it at least avoids having to put the body in twice:

do_it = 
ifeq ($(GCC_MINOR), 4)
    do_it = yes
endif
ifeq ($(GCC_MINOR), 5)
    do_it = yes
endif
ifdef do_it
    CFLAGS += -fno-strict-overflow
endif

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)