Programs & Examples On #Noise generator

Anything related to software noise generators and noise generation techniques. Noise is a general term to indicate a signal with (pseudo)random characteristics. Noise generators are used, for example, in telecommunication or electronic systems simulation, in computer games and in virtual reality applications.

Hibernate: How to fix "identifier of an instance altered from X to Y"?

Problem can be also in different types of object's PK ("User" in your case) and type you ask hibernate to get session.get(type, id);.

In my case error was identifier of an instance of <skipped> was altered from 16 to 32. Object's PK type was Integer, hibernate was asked for Long type.

How to change angular port from 4200 to any other

The code worked for me was as follows

ng serve --port ABCD

For Example

ng serve --port 6300

How can I push a specific commit to a remote, and not previous commits?

The simplest way to accomplish this is to use two commands.

First, get the local directory into the state that you want. Then,

$ git push origin +HEAD^:someBranch

removes the last commit from someBranch in the remote only, not local. You can do this a few times in a row, or change +HEAD^ to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use

$ git push origin someBranch

as normal to update the remote.

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

JavaScript loop through json array?

A short solution using map and an arrow function

_x000D_
_x000D_
var data = [{_x000D_
  "id": "1",_x000D_
  "msg": "hi",_x000D_
  "tid": "2013-05-05 23:35",_x000D_
  "fromWho": "[email protected]"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "msg": "there",_x000D_
  "tid": "2013-05-05 23:45",_x000D_
  "fromWho": "[email protected]"_x000D_
}];_x000D_
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));
_x000D_
_x000D_
_x000D_

And to cover the cases when the property "id" is not present use filter:

_x000D_
_x000D_
var data = [{_x000D_
  "id": "1",_x000D_
  "msg": "hi",_x000D_
  "tid": "2013-05-05 23:35",_x000D_
  "fromWho": "[email protected]"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "msg": "there",_x000D_
  "tid": "2013-05-05 23:45",_x000D_
  "fromWho": "[email protected]"_x000D_
}, {_x000D_
  "msg": "abcde",_x000D_
  "tid": "2013-06-06 23:46",_x000D_
  "fromWho": "[email protected]"_x000D_
}];_x000D_
_x000D_
data.filter(item=>item.hasOwnProperty('id'))_x000D_
                .map((item, i) => console.log('Index:', i, 'Id:', item.id));
_x000D_
_x000D_
_x000D_

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Invoking Java main method with parameters from Eclipse

Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:

  1. Run your class once as is.
  2. Go to Run -> Run configurations...
  3. From the lefthand list, select your class from the list under Java Application or by typing its name to filter box.
  4. Select Arguments tab and write your arguments to Program arguments box. Just in case it isn't clear, they're whitespace-separated so "a b c" (without quotes) would mean you'd pass arguments a, b and c to your program.
  5. Run your class again just like in step 1.

I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

Why doesn't the Scanner class have a nextChar method?

I would imagine that it has to do with encoding. A char is 16 bytes and some encodings will use one byte for a character whereas another will use two or even more. When Java was originally designed, they assumed that any Unicode character would fit in 2 bytes, whereas now a Unicode character can require up to 4 bytes (UTF-32). There is no way for Scanner to represent a UTF-32 codepoint in a single char.

You can specify an encoding to Scanner when you construct an instance, and if not provided, it will use the platform character-set. But this still doesn't handle the issue with 3 or 4 byte Unicode characters, since they cannot be represented as a single char primitive (since char is only 16 bytes). So you would end up getting inconsistent results.

How to remove close button on the jQuery UI dialog?

the "best" answer will not be good for multiple dialogs. here is a better solution.

open: function(event, ui) { 
    //hide close button.
    $(this).parent().children().children('.ui-dialog-titlebar-close').hide();
},

How can I rename a field for all documents in MongoDB?

If ever you need to do the same thing with mongoid:

Model.all.rename(:old_field, :new_field)

UPDATE

There is change in the syntax in monogoid 4.0.0:

Model.all.rename(old_field: :new_field)

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need to go here https://security.google.com/settings/security/apppasswords

then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

Best XML Parser for PHP

This is a useful function for quick and easy xml parsing when an extension is not available:

<?php
/**
 * Convert XML to an Array
 *
 * @param string  $XML
 * @return array
 */
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close') {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete') {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while ($start_level < $x_level) {
            $php_stmt .= '[$level['.$start_level.']]';
            if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
            $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
            $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes', $xml_elem)) {
            if (isset($xml_elem['value'])) {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value) {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
    return $xml_array;
}
?>

mat-form-field must contain a MatFormFieldControl

If anyone got stuck with this error after attempting to nest a <mat-checkbox>, be of good cheer! It doesn't work inside a <mat-form-field> tag.

Saving lists to txt file

Framework 4: no need to use StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);

Whitespaces in java

For a non-regular expression approach, you can check Character.isWhitespace for each character.

boolean containsWhitespace(String s) {
    for (int i = 0; i < s.length(); ++i) {
        if (Character.isWhitespace(s.charAt(i)) {
            return true;
        }
    }
    return false;
}

Which are the white spaces in Java?

The documentation specifies what Java considers to be whitespace:

public static boolean isWhitespace(char ch)

Determines if the specified character is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\u0009', HORIZONTAL TABULATION.
  • It is '\u000A', LINE FEED.
  • It is '\u000B', VERTICAL TABULATION.
  • It is '\u000C', FORM FEED.
  • It is '\u000D', CARRIAGE RETURN.
  • It is '\u001C', FILE SEPARATOR.
  • It is '\u001D', GROUP SEPARATOR.
  • It is '\u001E', RECORD SEPARATOR.
  • It is '\u001F', UNIT SEPARATOR.

What does "async: false" do in jQuery.ajax()?

From

https://xhr.spec.whatwg.org/#synchronous-flag

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.

How to calculate an angle from three points?

Very Simple Geometric Solution with Explanation

Few days ago, a fell into the same problem & had to sit with the math book. I solved the problem by combining and simplifying some basic formulas.


Lets consider this figure-

angle

We want to know ?, so we need to find out a and ß first. Now, for any straight line-

y = m * x + c

Let- A = (ax, ay), B = (bx, by), and O = (ox, oy). So for the line OA-

oy = m1 * ox + c   ? c = oy - m1 * ox   ...(eqn-1)

ay = m1 * ax + c   ? ay = m1 * ax + oy - m1 * ox   [from eqn-1]
                   ? ay = m1 * ax + oy - m1 * ox
                   ? m1 = (ay - oy) / (ax - ox)
                   ? tan a = (ay - oy) / (ax - ox)   [m = slope = tan ?]   ...(eqn-2)

In the same way, for line OB-

tan ß = (by - oy) / (bx - ox)   ...(eqn-3)

Now, we need ? = ß - a. In trigonometry we have a formula-

tan (ß-a) = (tan ß + tan a) / (1 - tan ß * tan a)   ...(eqn-4)

After replacing the value of tan a (from eqn-2) and tan b (from eqn-3) in eqn-4, and applying simplification we get-

tan (ß-a) = ( (ax-ox)*(by-oy)+(ay-oy)*(bx-ox) ) / ( (ax-ox)*(bx-ox)-(ay-oy)*(by-oy) )

So,

? = ß-a = tan^(-1) ( ((ax-ox)*(by-oy)+(ay-oy)*(bx-ox)) / ((ax-ox)*(bx-ox)-(ay-oy)*(by-oy)) )

That is it!


Now, take following figure-

angle

This C# or, Java method calculates the angle (?)-

    private double calculateAngle(double P1X, double P1Y, double P2X, double P2Y,
            double P3X, double P3Y){

        double numerator = P2Y*(P1X-P3X) + P1Y*(P3X-P2X) + P3Y*(P2X-P1X);
        double denominator = (P2X-P1X)*(P1X-P3X) + (P2Y-P1Y)*(P1Y-P3Y);
        double ratio = numerator/denominator;

        double angleRad = Math.Atan(ratio);
        double angleDeg = (angleRad*180)/Math.PI;

        if(angleDeg<0){
            angleDeg = 180+angleDeg;
        }

        return angleDeg;
    }

What does PermGen actually stand for?

PermGen stands for Permanent Generation.

Here is a brief blurb on DDJ

Get all attributes of an element using jQuery

My suggestion:

$.fn.attrs = function (fnc) {
    var obj = {};
    $.each(this[0].attributes, function() {
        if(this.name == 'value') return; // Avoid someone (optional)
        if(this.specified) obj[this.name] = this.value;
    });
    return obj;
}

var a = $(el).attrs();

Find an element in DOM based on an attribute value

FindByAttributeValue("Attribute-Name", "Attribute-Value");   

p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");   

but at first, define this function:

function FindByAttributeValue(attribute, value, element_type)    {
  element_type = element_type || "*";
  var All = document.getElementsByTagName(element_type);
  for (var i = 0; i < All.length; i++)       {
    if (All[i].getAttribute(attribute) == value) { return All[i]; }
  }
}

p.s. updated per comments recommendations.

MySQL Like multiple values

More work examples:

SELECT COUNT(email) as count FROM table1 t1 
JOIN (
      SELECT company_domains as emailext FROM table2 WHERE company = 'DELL'
     ) t2 
ON t1.email LIKE CONCAT('%', emailext) WHERE t1.event='PC Global Conference";

Task was count participants at an event(s) with filter if email extension equal to multiple company domains.

How to set the focus for a particular field in a Bootstrap modal, once it appears

I had the same problem with the bootstrap 3 and solved like this:

$('#myModal').on('shown.bs.modal', function (e) {
    $(this).find('input[type=text]:visible:first').focus();
})

$('#myModal').modal('show').trigger('shown');

How to send post request to the below post method using postman rest client

1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.

How can I have linebreaks in my long LaTeX equations?

This worked for me while using mathtools package.

\documentclass{article}
\usepackage{mathtools}
\begin{document}
    \begin{equation}
        \begin{multlined}
            first term \\
            second term                 
        \end{multlined}
    \end{equation}
\end{document}

Is it possible to hide the cursor in a webpage using CSS or Javascript?

I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.

Coloring Buttons in Android with Material Design and AppCompat

One way to pull this off allows you to just point to a style and NOT theme ALL the buttons in your app the same.
In themes.xml add a theme

    <style name="Theme.MyApp.Button.Primary.Blue" parent="Widget.AppCompat.Button">
        <item name="colorButtonNormal">@color/someColor</item>
        <item name="android:textColorPrimary">@android:color/white</item>
    </style>

Now in styles.xml add

    <style name="MyApp.Button.Primary.Blue" parent="">
        <item name="android:theme">@style/Theme.MyApp.Button.Primary.Blue</item>
    </style>

Now in your layout simply point to the STYLE in your Button

    <Button
        ...
        style="@style/MyApp.Button.Primary.Blue"
        ...  />

How to use multiprocessing queue in Python?

A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.

from multiprocessing import Process, JoinableQueue
import time
import os

q = JoinableQueue()

def producer():
    for item in range(30):
        time.sleep(2)
        q.put(item)
    pid = os.getpid()
    print(f'producer {pid} done')


def worker():
    while True:
        item = q.get()
        pid = os.getpid()
        print(f'pid {pid} Working on {item}')
        print(f'pid {pid} Finished {item}')
        q.task_done()

for i in range(5):
    p = Process(target=worker, daemon=True).start()

# send thirty task requests to the worker
producers = []
for i in range(2):
    p = Process(target=producer)
    producers.append(p)
    p.start()

# make sure producers done
for p in producers:
    p.join()

# block until all workers are done
q.join()
print('All work completed')

Explanation:

  1. Two producers and five consumers in this example.
  2. JoinableQueue is used to make sure all elements stored in queue will be processed. 'task_done' is for worker to notify an element is done. 'q.join()' will wait for all elements marked as done.
  3. With #2, there is no need to join wait for every worker.
  4. But it is important to join wait for every producer to store element into queue. Otherwise, program exit immediately.

How to check visibility of software keyboard in Android?

Wow, We have Good news Android Geeks. And its time to say goodbye to the old way. First I will add official release note to read and know more about these methods/ classes, and then we will see these amazing methods/ classes

Breaking Note: Do not add these into your release apps, until these classes/ methods are released

How to check keyboard visibility

val insets = ViewCompat.getRootWindowInsets(view)
val isKeyboardVisible = insets.isVisible(Type.ime())

Few other utilities

How to get the height of Keyboard

val insets = ViewCompat.getRootWindowInsets(view)
val keyboardHeight = insets.getInsets(Type.ime()).bottom

How to show/ hide the keyboard

val controller = view.windowInsetsController

// Show the keyboard
controller.show(Type.ime())

// Hide the keyboard
controller.hide(Type.ime())

Note: WindowInsetsController added in API-30, so wait till backward compatible class is not available.

How to listen to keyboard hide/ show event

ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
    val isKeyboardVisible = insets.isVisible(Type.ime())
    if (isKeyboardVisible) {
        // Do it when keyboard is being shown
    } else {
        // Do it when keyboard is hidden
    }

    // Return the insets to keep going down this event to the view hierarchy
    insets
}

How to read values from the querystring with ASP.NET Core?

You can use [FromQuery] to bind a particular model to the querystring:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

e.g.

[HttpGet()]
public IActionResult Get([FromQuery(Name = "page")] string page)
{...}

Difference between style = "position:absolute" and style = "position:relative"

position: relative act as a parent element position: absolute act a child of relative position. you can see the below example

.postion-element{
   position:relative;
   width:200px;
   height:200px;
   background-color:green;
 }
.absolute-element{
  position:absolute;
  top:10px;
  left:10px;
  background-color:blue;
 }

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Web colors in an Android color xml resource file

I change all code to lower case for mono android

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <color name="white">#FFFFFF</color>
    <color name="ivory">#FFFFF0</color>
    <color name="lightyellow">#FFFFE0</color>
    <color name="yellow">#FFFF00</color>
    <color name="snow">#FFFAFA</color>
    <color name="floralwhite">#FFFAF0</color>
    <color name="lemonchiffon">#FFFACD</color>
    <color name="cornsilk">#FFF8DC</color>
    <color name="seashell">#FFF5EE</color>
    <color name="lavenderblush">#FFF0F5</color>
    <color name="papayawhip">#FFEFD5</color>
    <color name="blanchedalmond">#FFEBCD</color>
    <color name="mistyrose">#FFE4E1</color>
    <color name="bisque">#FFE4C4</color>
    <color name="moccasin">#FFE4B5</color>
    <color name="navajowhite">#FFDEAD</color>
    <color name="peachpuff">#FFDAB9</color>
    <color name="gold">#FFD700</color>
    <color name="pink">#FFC0CB</color>
    <color name="lightpink">#FFB6C1</color>
    <color name="orange">#FFA500</color>
    <color name="lightsalmon">#FFA07A</color>
    <color name="darkorange">#FF8C00</color>
    <color name="coral">#FF7F50</color>
    <color name="hotpink">#FF69B4</color>
    <color name="tomato">#FF6347</color>
    <color name="orangered">#FF4500</color>
    <color name="deeppink">#FF1493</color>
    <color name="fuchsia">#FF00FF</color>
    <color name="magenta">#FF00FF</color>
    <color name="red">#FF0000</color>
    <color name="oldlace">#FDF5E6</color>
    <color name="lightgoldenrodyellow">#FAFAD2</color>
    <color name="linen">#FAF0E6</color>
    <color name="antiquewhite">#FAEBD7</color>
    <color name="salmon">#FA8072</color>
    <color name="ghostwhite">#F8F8FF</color>
    <color name="mintcream">#F5FFFA</color>
    <color name="whitesmoke">#F5F5F5</color>
    <color name="beige">#F5F5DC</color>
    <color name="wheat">#F5DEB3</color>
    <color name="sandybrown">#F4A460</color>
    <color name="azure">#F0FFFF</color>
    <color name="honeydew">#F0FFF0</color>
    <color name="aliceblue">#F0F8FF</color>
    <color name="khaki">#F0E68C</color>
    <color name="lightcoral">#F08080</color>
    <color name="palegoldenrod">#EEE8AA</color>
    <color name="violet">#EE82EE</color>
    <color name="darksalmon">#E9967A</color>
    <color name="lavender">#E6E6FA</color>
    <color name="lightcyan">#E0FFFF</color>
    <color name="burlywood">#DEB887</color>
    <color name="plum">#DDA0DD</color>
    <color name="gainsboro">#DCDCDC</color>
    <color name="crimson">#DC143C</color>
    <color name="palevioletred">#DB7093</color>
    <color name="goldenrod">#DAA520</color>
    <color name="orchid">#DA70D6</color>
    <color name="thistle">#D8BFD8</color>
    <color name="lightgrey">#D3D3D3</color>
    <color name="tan">#D2B48C</color>
    <color name="chocolate">#D2691E</color>
    <color name="peru">#CD853F</color>
    <color name="indianred">#CD5C5C</color>
    <color name="mediumvioletred">#C71585</color>
    <color name="silver">#C0C0C0</color>
    <color name="darkkhaki">#BDB76B</color>
    <color name="rosybrown">#BC8F8F</color>
    <color name="mediumorchid">#BA55D3</color>
    <color name="darkgoldenrod">#B8860B</color>
    <color name="firebrick">#B22222</color>
    <color name="powderblue">#B0E0E6</color>
    <color name="lightsteelblue">#B0C4DE</color>
    <color name="paleturquoise">#AFEEEE</color>
    <color name="greenyellow">#ADFF2F</color>
    <color name="lightblue">#ADD8E6</color>
    <color name="darkgray">#A9A9A9</color>
    <color name="brown">#A52A2A</color>
    <color name="sienna">#A0522D</color>
    <color name="yellowgreen">#9ACD32</color>
    <color name="darkorchid">#9932CC</color>
    <color name="palegreen">#98FB98</color>
    <color name="darkviolet">#9400D3</color>
    <color name="mediumpurple">#9370DB</color>
    <color name="lightgreen">#90EE90</color>
    <color name="darkseagreen">#8FBC8F</color>
    <color name="saddlebrown">#8B4513</color>
    <color name="darkmagenta">#8B008B</color>
    <color name="darkred">#8B0000</color>
    <color name="blueviolet">#8A2BE2</color>
    <color name="lightskyblue">#87CEFA</color>
    <color name="skyblue">#87CEEB</color>
    <color name="gray">#808080</color>
    <color name="olive">#808000</color>
    <color name="purple">#800080</color>
    <color name="maroon">#800000</color>
    <color name="aquamarine">#7FFFD4</color>
    <color name="chartreuse">#7FFF00</color>
    <color name="lawngreen">#7CFC00</color>
    <color name="mediumslateblue">#7B68EE</color>
    <color name="lightslategray">#778899</color>
    <color name="slategray">#708090</color>
    <color name="olivedrab">#6B8E23</color>
    <color name="slateblue">#6A5ACD</color>
    <color name="dimgray">#696969</color>
    <color name="mediumaquamarine">#66CDAA</color>
    <color name="cornflowerblue">#6495ED</color>
    <color name="cadetblue">#5F9EA0</color>
    <color name="darkolivegreen">#556B2F</color>
    <color name="indigo">#4B0082</color>
    <color name="mediumturquoise">#48D1CC</color>
    <color name="darkslateblue">#483D8B</color>
    <color name="steelblue">#4682B4</color>
    <color name="royalblue">#4169E1</color>
    <color name="turquoise">#40E0D0</color>
    <color name="mediumseagreen">#3CB371</color>
    <color name="limegreen">#32CD32</color>
    <color name="darkslategray">#2F4F4F</color>
    <color name="seagreen">#2E8B57</color>
    <color name="forestgreen">#228B22</color>
    <color name="lightseagreen">#20B2AA</color>
    <color name="dodgerblue">#1E90FF</color>
    <color name="midnightblue">#191970</color>
    <color name="aqua">#00FFFF</color>
    <color name="cyan">#00FFFF</color>
    <color name="springgreen">#00FF7F</color>
    <color name="lime">#00FF00</color>
    <color name="mediumspringgreen">#00FA9A</color>
    <color name="darkturquoise">#00CED1</color>
    <color name="deepskyblue">#00BFFF</color>
    <color name="darkcyan">#008B8B</color>
    <color name="teal">#008080</color>
    <color name="green">#008000</color>
    <color name="darkgreen">#006400</color>
    <color name="blue">#0000FF</color>
    <color name="mediumblue">#0000CD</color>
    <color name="darkblue">#00008B</color>
    <color name="navy">#000080</color>
    <color name="black">#000000</color>
    </resources>

CSS selector for first element with class

This is one of the most well-known examples of authors misunderstanding how :first-child works. Introduced in CSS2, the :first-child pseudo-class represents the very first child of its parent. That's it. There's a very common misconception that it picks up whichever child element is the first to match the conditions specified by the rest of the compound selector. Due to the way selectors work (see here for an explanation), that is simply not true.

Selectors level 3 introduces a :first-of-type pseudo-class, which represents the first element among siblings of its element type. This answer explains, with illustrations, the difference between :first-child and :first-of-type. However, as with :first-child, it does not look at any other conditions or attributes. In HTML, the element type is represented by the tag name. In the question, that type is p.

Unfortunately, there is no similar :first-of-class pseudo-class for matching the first child element of a given class. One workaround that Lea Verou and I came up with for this (albeit totally independently) is to first apply your desired styles to all your elements with that class:

/* 
 * Select all .red children of .home, including the first one,
 * and give them a border.
 */
.home > .red {
    border: 1px solid red;
}

... then "undo" the styles for elements with the class that come after the first one, using the general sibling combinator ~ in an overriding rule:

/* 
 * Select all but the first .red child of .home,
 * and remove the border from the previous rule.
 */
.home > .red ~ .red {
    border: none;
}

Now only the first element with class="red" will have a border.

Here's an illustration of how the rules are applied:

<div class="home">
  <span>blah</span>         <!-- [1] -->
  <p class="red">first</p>  <!-- [2] -->
  <p class="red">second</p> <!-- [3] -->
  <p class="red">third</p>  <!-- [3] -->
  <p class="red">fourth</p> <!-- [3] -->
</div>
  1. No rules are applied; no border is rendered.
    This element does not have the class red, so it's skipped.

  2. Only the first rule is applied; a red border is rendered.
    This element has the class red, but it's not preceded by any elements with the class red in its parent. Thus the second rule is not applied, only the first, and the element keeps its border.

  3. Both rules are applied; no border is rendered.
    This element has the class red. It is also preceded by at least one other element with the class red. Thus both rules are applied, and the second border declaration overrides the first, thereby "undoing" it, so to speak.

As a bonus, although it was introduced in Selectors 3, the general sibling combinator is actually pretty well-supported by IE7 and newer, unlike :first-of-type and :nth-of-type() which are only supported by IE9 onward. If you need good browser support, you're in luck.

In fact, the fact that the sibling combinator is the only important component in this technique, and it has such amazing browser support, makes this technique very versatile — you can adapt it for filtering elements by other things, besides class selectors:

  • You can use this to work around :first-of-type in IE7 and IE8, by simply supplying a type selector instead of a class selector (again, more on its incorrect usage here in a later section):

    article > p {
        /* Apply styles to article > p:first-of-type, which may or may not be :first-child */
    }
    
    article > p ~ p {
        /* Undo the above styles for every subsequent article > p */
    }
    
  • You can filter by attribute selectors or any other simple selectors instead of classes.

  • You can also combine this overriding technique with pseudo-elements even though pseudo-elements technically aren't simple selectors.

Note that in order for this to work, you will need to know in advance what the default styles will be for your other sibling elements so you can override the first rule. Additionally, since this involves overriding rules in CSS, you can't achieve the same thing with a single selector for use with the Selectors API, or Selenium's CSS locators.

It's worth mentioning that Selectors 4 introduces an extension to the :nth-child() notation (originally an entirely new pseudo-class called :nth-match()), which will allow you to use something like :nth-child(1 of .red) in lieu of a hypothetical .red:first-of-class. Being a relatively recent proposal, there aren't enough interoperable implementations for it to be usable in production sites yet. Hopefully this will change soon. In the meantime, the workaround I've suggested should work for most cases.

Keep in mind that this answer assumes that the question is looking for every first child element that has a given class. There is neither a pseudo-class nor even a generic CSS solution for the nth match of a complex selector across the entire document — whether a solution exists depends heavily on the document structure. jQuery provides :eq(), :first, :last and more for this purpose, but note again that they function very differently from :nth-child() et al. Using the Selectors API, you can either use document.querySelector() to obtain the very first match:

var first = document.querySelector('.home > .red');

Or use document.querySelectorAll() with an indexer to pick any specific match:

var redElements = document.querySelectorAll('.home > .red');
var first = redElements[0];
var second = redElements[1];
// etc

Although the .red:nth-of-type(1) solution in the original accepted answer by Philip Daubmeier works (which was originally written by Martyn but deleted since), it does not behave the way you'd expect it to.

For example, if you only wanted to select the p in your original markup:

<p class="red"></p>
<div class="red"></div>

... then you can't use .red:first-of-type (equivalent to .red:nth-of-type(1)), because each element is the first (and only) one of its type (p and div respectively), so both will be matched by the selector.

When the first element of a certain class is also the first of its type, the pseudo-class will work, but this happens only by coincidence. This behavior is demonstrated in Philip's answer. The moment you stick in an element of the same type before this element, the selector will fail. Taking the updated markup:

<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

Applying a rule with .red:first-of-type will work, but once you add another p without the class:

<div class="home">
  <span>blah</span>
  <p>dummy</p>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

... the selector will immediately fail, because the first .red element is now the second p element.

Integrity constraint violation: 1452 Cannot add or update a child row:

I hope my decision will help. I had a similar error in Laravel. I added a foreign key to the wrong table.
Wrong code:

Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
    });


Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    ...
    });

Please note to the function on('comments') above. Correct code

 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

what innerHTML is doing in javascript?

The innerHTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website being displayed. Specifically, it allows reading and replacing everything within a given DOM element (HTML tag).

However, DOM manipulations using innerHTML are slower and more failure-prone than manipulations based on individual DOM objects.

X-Frame-Options Allow-From multiple domains

The RFC for the HTTP Header Field X-Frame-Options states that the "ALLOW-FROM" field in the X-Frame-Options header value can only contain one domain. Multiple domains are not allowed.

The RFC suggests a work around for this problem. The solution is to specify the domain name as a url parameter in the iframe src url. The server that hosts the iframe src url can then check the domain name given in the url parameters. If the domain name matches a list of valid domain names, then the server can send the X-Frame-Options header with the value: "ALLOW-FROM domain-name", where domain name is the name of the domain that is trying to embed the remote content. If the domain name is not given or is not valid, then the X-Frame-Options header can be sent with the value: "deny".

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

Update Jenkins from a war file

I didn't want to install the x11-common and other components that come bundled in the apt-get install approach, so I just downloaded the .war file and ran the command Francois mentioned. That worked nicely, but you have to write your own daemon script with that approach. Full details here: http://strem.in/stream/9488/Using-the-war-file-for-jenkins-ci

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.

JAVASCRIPT side:

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

Non-recursive depth first search algorithm

DFS:

list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
  currentnode = nodes_to_visit.take_first();
  nodes_to_visit.prepend( currentnode.children );
  //do something
}

BFS:

list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
  currentnode = nodes_to_visit.take_first();
  nodes_to_visit.append( currentnode.children );
  //do something
}

The symmetry of the two is quite cool.

Update: As pointed out, take_first() removes and returns the first element in the list.

In plain English, what does "git reset" do?

In general, git reset's function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. More concretely, if your master branch (currently checked out) is like this:

- A - B - C (HEAD, master)

and you realize you want master to point to B, not C, you will use git reset B to move it there:

- A - B (HEAD, master)      # - C is still here, but there's no branch pointing to it anymore

Digression: This is different from a checkout. If you'd run git checkout B, you'd get this:

- A - B (HEAD) - C (master)

You've ended up in a detached HEAD state. HEAD, work tree, index all match B, but the master branch was left behind at C. If you make a new commit D at this point, you'll get this, which is probably not what you want:

- A - B - C (master)
       \
        D (HEAD)

Remember, reset doesn't make commits, it just updates a branch (which is a pointer to a commit) to point to a different commit. The rest is just details of what happens to your index and work tree.

Use cases

I cover many of the main use cases for git reset within my descriptions of the various options in the next section. It can really be used for a wide variety of things; the common thread is that all of them involve resetting the branch, index, and/or work tree to point to/match a given commit.

Things to be careful of

  • --hard can cause you to really lose work. It modifies your work tree.

  • git reset [options] commit can cause you to (sort of) lose commits. In the toy example above, we lost commit C. It's still in the repo, and you can find it by looking at git reflog show HEAD or git reflog show master, but it's not actually accessible from any branch anymore.

  • Git permanently deletes such commits after 30 days, but until then you can recover C by pointing a branch at it again (git checkout C; git branch <new branch name>).

Arguments

Paraphrasing the man page, most common usage is of the form git reset [<commit>] [paths...], which will reset the given paths to their state from the given commit. If the paths aren't provided, the entire tree is reset, and if the commit isn't provided, it's taken to be HEAD (the current commit). This is a common pattern across git commands (e.g. checkout, diff, log, though the exact semantics vary), so it shouldn't be too surprising.

For example, git reset other-branch path/to/foo resets everything in path/to/foo to its state in other-branch, git reset -- . resets the current directory to its state in HEAD, and a simple git reset resets everything to its state in HEAD.

The main work tree and index options

There are four main options to control what happens to your work tree and index during the reset.

Remember, the index is git's "staging area" - it's where things go when you say git add in preparation to commit.

  • --hard makes everything match the commit you've reset to. This is the easiest to understand, probably. All of your local changes get clobbered. One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don't change the branch but get rid of all local changes. The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

  • --mixed is the default, i.e. git reset means git reset --mixed. It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status. Use this when you realize you made some bad commits, but you want to keep all the work you've done so you can fix it up and recommit. In order to commit, you'll have to add files to the index again (git add ...).

  • --soft doesn't touch the index or work tree. All your files are intact as with --mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you've made some bad commits, but the work's all good - all you need to do is recommit it differently. The index is untouched, so you can commit immediately if you want - the resulting commit will have all the same content as where you were before you reset.

  • --merge was added recently, and is intended to help you abort a failed merge. This is necessary because git merge will actually let you attempt a merge with a dirty work tree (one with local modifications) as long as those modifications are in files unaffected by the merge. git reset --merge resets the index (like --mixed - all changes show up as local modifications), and resets the files affected by the merge, but leaves the others alone. This will hopefully restore everything to how it was before the bad merge. You'll usually use it as git reset --merge (meaning git reset --merge HEAD) because you only want to reset away the merge, not actually move the branch. (HEAD hasn't been updated yet, since the merge failed)

    To be more concrete, suppose you've modified files A and B, and you attempt to merge in a branch which modified files C and D. The merge fails for some reason, and you decide to abort it. You use git reset --merge. It brings C and D back to how they were in HEAD, but leaves your modifications to A and B alone, since they weren't part of the attempted merge.

Want to know more?

I do think man git reset is really quite good for this - perhaps you do need a bit of a sense of the way git works for them to really sink in though. In particular, if you take the time to carefully read them, those tables detailing states of files in index and work tree for all the various options and cases are very very helpful. (But yes, they're very dense - they're conveying an awful lot of the above information in a very concise form.)

Strange notation

The "strange notation" (HEAD^ and HEAD~1) you mention is simply a shorthand for specifying commits, without having to use a hash name like 3ebe3f6. It's fully documented in the "specifying revisions" section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things:

  • HEAD~ is short for HEAD~1 and means the commit's first parent. HEAD~2 means the commit's first parent's first parent. Think of HEAD~n as "n commits before HEAD" or "the nth generation ancestor of HEAD".
  • HEAD^ (or HEAD^1) also means the commit's first parent. HEAD^2 means the commit's second parent. Remember, a normal merge commit has two parents - the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).
  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

caret and tilde

Amazon S3 boto - how to create a folder?

It's really easy to create folders. Actually it's just creating keys.

You can see my below code i was creating a folder with utc_time as name.

Do remember ends the key with '/' like below, this indicates it's a key:

Key='folder1/' + utc_time + '/'

client = boto3.client('s3')
utc_timestamp = time.time()


def lambda_handler(event, context):

    UTC_FORMAT = '%Y%m%d'
    utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
    utc_time = utc_time.strftime(UTC_FORMAT)
    print 'start to create folder for => ' + utc_time

    putResponse = client.put_object(Bucket='mybucketName',
                                    Key='folder1/' + utc_time + '/')

    print putResponse

What is a "cache-friendly" code?

It needs to be clarified that not only data should be cache-friendly, it is just as important for the code. This is in addition to branch predicition, instruction reordering, avoiding actual divisions and other techniques.

Typically the denser the code, the fewer cache lines will be required to store it. This results in more cache lines being available for data.

The code should not call functions all over the place as they typically will require one or more cache lines of their own, resulting in fewer cache lines for data.

A function should begin at a cache line-alignment-friendly address. Though there are (gcc) compiler switches for this be aware that if the the functions are very short it might be wasteful for each one to occupy an entire cache line. For example, if three of the most often used functions fit inside one 64 byte cache line, this is less wasteful than if each one has its own line and results in two cache lines less available for other usage. A typical alignment value could be 32 or 16.

So spend some extra time to make the code dense. Test different constructs, compile and review the generated code size and profile.

Pushing value of Var into an Array

jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:

$('#fruit').append(veggies);

or to append it to the end of a form value like in your example:

 $('#fruit').val($('#fruit').val()+veggies);

In your case, fruitvegbasket is a string that contains the current value of #fruit, not an array.

jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val() returns the value attribute of an input element as a string. You can't push something onto a string.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

The modular crypt format for bcrypt consists of

  • $2$, $2a$ or $2y$ identifying the hashing algorithm and format
  • a two digit value denoting the cost parameter, followed by $
  • a 53 characters long base-64-encoded value (they use the alphabet ., /, 09, AZ, az that is different to the standard Base 64 Encoding alphabet) consisting of:
    • 22 characters of salt (effectively only 128 bits of the 132 decoded bits)
    • 31 characters of encrypted output (effectively only 184 bits of the 186 decoded bits)

Thus the total length is 59 or 60 bytes respectively.

As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARYor BINARY(60) (see The _bin and binary Collations for information about the difference).

CHAR is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A is treated as equal to a. See The _bin and binary Collations for more information.

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

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

I came across this error by writing a Build script that would put MSBuild on the %PATH% after recursively digging through the C:\Windows\Microsoft.NET folder for any found MSBuild.exe files. The last found hit was the directory that was put on the path. Since the dir command would hit the Framework64 folder after Framework I was getting one of the 64bit MSBuilds put on my path. I was trying to build a Visual Studio 2010 solution and wound up altering my search string from C:\Windows\Microsoft.NET to C:\Windows\Microsoft.NET\Framework so that I would wind up with a 32bit MSBuild.exe. Now my solution file builds.

Pass multiple optional parameters to a C# function

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

Cygwin Make bash command not found

While instaling (updating) check 'Devel' to 'Install', it will install a lot of MB but helps. I don't have time to check which exacly I (we) need.

CYGWIN INSTALL STEP

Java best way for string find and replace?

Well, you can use a regular expression to find the cases where "Milan" isn't followed by "Vasic":

Milan(?! Vasic)

and replace that by the full name:

String.replaceAll("Milan(?! Vasic)", "Milan Vasic")

The (?!...) part is a negative lookahead which ensures that whatever matches isn't followed by the part in parentheses. It doesn't consume any characters in the match itself.

Alternatively, you can simply insert (well, technically replacing a zero-width match) the last name after the first name, unless it's followed by the last name already. This looks similar, but uses a positive lookbehind as well:

(?<=Milan)(?! Vasic)

You can replace this by just " Vasic" (note the space at the start of the string):

String.replaceAll("(?<=Milan)(?! Vasic)", " Vasic")

You can try those things out here for example.

C# Macro definitions in Preprocessor

Since C# 7.0 supports using static directive and Local functions you don't need preprocessor macros for most cases.

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

how to prevent "directory already exists error" in a makefile when using mkdir

On UNIX Just use this:

mkdir -p $(OBJDIR)

The -p option to mkdir prevents the error message if the directory exists.

C++ convert hex string to signed integer

use std::stringstream

unsigned int x;   
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;

the following example produces -65538 as its result:

#include <sstream>
#include <iostream>

int main() {
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "fffefffe";
    ss >> x;
    // output it as a signed type
    std::cout << static_cast<int>(x) << std::endl;
}

In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string

So, the simplest answer for newer code would probably look like this:

std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);

NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).

It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.

Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:

try {
    unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
    // whatever you want to do...
}

If you don't feel like using boost, here's a light version of lexical cast which does no error checking:

template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
    T2 out;
    std::stringstream ss;
    ss << in;
    ss >> out;
    return out;
}

which you can use like this:

// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef"); 

Array inside a JavaScript Object?

_x000D_
_x000D_
var defaults = {_x000D_
_x000D_
  "background-color": "#000",_x000D_
  color: "#fff",_x000D_
  weekdays: [_x000D_
    {0: 'sun'},_x000D_
    {1: 'mon'},_x000D_
    {2: 'tue'},_x000D_
    {3: 'wed'},_x000D_
    {4: 'thu'},_x000D_
    {5: 'fri'},_x000D_
    {6: 'sat'}_x000D_
  ]_x000D_
_x000D_
};_x000D_
               _x000D_
console.log(defaults.weekdays[3]);
_x000D_
_x000D_
_x000D_

What's the difference between all the Selection Segues?

Here is a quick summary of the segues and an example for each type.

Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail

Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout

Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings

Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar

Custom - You may implement your own custom segue and have control over its behavior

The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.

For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.

How can I select the record with the 2nd highest salary in database Oracle?

select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))

so in our emp table(default provided by oracle) here is the output

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


  7698 BLAKE      MANAGER         7839 01-MAY-81       3000            30
  7788 SCOTT      ANALYST         7566 19-APR-87       3000            20
  7902 FORD       ANALYST         7566 03-DEC-81       3000            20

or just you want 2nd maximum salary to be displayed

select max(sal) from emp where sal<(select max(sal) from emp)

MAX(SAL)

  3000

Python: json.loads returns items prefixing with 'u'

The d3 print below is the one you are looking for (which is the combination of dumps and loads) :)

Having:

import json

d = """{"Aa": 1, "BB": "blabla", "cc": "False"}"""

d1 = json.loads(d)              # Produces a dictionary out of the given string
d2 = json.dumps(d)              # Produces a string out of a given dict or string
d3 = json.dumps(json.loads(d))  # 'dumps' gets the dict from 'loads' this time

print "d1:  " + str(d1)
print "d2:  " + d2
print "d3:  " + d3

Prints:

d1:  {u'Aa': 1, u'cc': u'False', u'BB': u'blabla'}
d2:  "{\"Aa\": 1, \"BB\": \"blabla\", \"cc\": \"False\"}"
d3:  {"Aa": 1, "cc": "False", "BB": "blabla"}

ASP.Net MVC - Read File from HttpPostedFileBase without save

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

Java Date - Insert into database

Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.

To answer your question, as others have mentioned, look into java.sql.PreparedStatement, and use java.sql.Date or java.sql.Timestamp. Something like (to use your original code as much as possible, you probably want to change it even more):

java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");

Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);

stmt.executeUpdate(); // optionally check the return value of this call

One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).

Pandas groupby month and year

You can use either resample or Grouper (which resamples under the hood).

First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime). It's easier if it's a DatetimeIndex:

In [11]: df1
Out[11]:
            abc  xyz
Date
2013-06-01  100  200
2013-06-03  -20   50
2013-08-15   40   -5
2014-01-20   25   15
2014-02-21   60   80

In [12]: g = df1.groupby(pd.Grouper(freq="M"))  # DataFrameGroupBy (grouped by Month)

In [13]: g.sum()
Out[13]:
            abc  xyz
Date
2013-06-30   80  250
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

In [14]: df1.resample("M", how='sum')  # the same
Out[14]:
            abc  xyz
Date
2013-06-30   40  125
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

Note: Previously pd.Grouper(freq="M") was written as pd.TimeGrouper("M"). The latter is now deprecated since 0.21.


I had thought the following would work, but it doesn't (due to as_index not being respected? I'm not sure.). I'm including this for interest's sake.

If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime), you can use the PeriodIndex:

In [21]: df
Out[21]:
        Date  abc  xyz
0 2013-06-01  100  200
1 2013-06-03  -20   50
2 2013-08-15   40   -5
3 2014-01-20   25   15
4 2014-02-21   60   80

In [22]: pd.DatetimeIndex(df.Date).to_period("M")  # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M

In [23]: per = df.Date.dt.to_period("M")  # new way to get the same

In [24]: g = df.groupby(per)

In [25]: g.sum()  # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
         abc  xyz
2013-06   80  250
2013-08   40   -5
2014-01   25   15
2014-02   60   80

To get the desired result we have to reindex...

Pick a random value from an enum?

I guess that this single-line-return method is efficient enough to be used in such a simple job:

public enum Day {
    SUNDAY,
    MONDAY,
    THURSDAY,
    WEDNESDAY,
    TUESDAY,
    FRIDAY;

    public static Day getRandom() {
        return values()[(int) (Math.random() * values().length)];
    }

    public static void main(String[] args) {
        System.out.println(Day.getRandom());
    }
}

Substitute a comma with a line break in a cell

You can also do this without VBA from the find/replace dialogue box. My answer was at https://stackoverflow.com/a/6116681/509840 .

ORA-00932: inconsistent datatypes: expected - got CLOB

I just ran over this one and I found by accident that CLOBs can be used in a like query:

   UPDATE IMS_TEST 
   SET TEST_Category  = 'just testing'  
 WHERE TEST_SCRIPT    LIKE '%something%'
   AND ID             = '10000239' 

This worked also for CLOBs greater than 4K

The Performance won't be great but that was no problem in my case.

How to extract a string between two delimiters

If you have just a pair of brackets ( [] ) in your string, you can use indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

How do I compare two variables containing strings in JavaScript?

You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.

<script>
    var to_check=$(this).val();
    var cur_string=$("#0").text();
    var to_chk = "that";
    var cur_str= "that";
    if(to_chk.localeCompare(cur_str) == 0){
        alert("both are equal");
        $("#0").attr("class","correct");    
    } else {
        alert("both are not equal");
        $("#0").attr("class","incorrect");
    }
</script>

How do I clone a single branch in Git?

git clone <url> --branch <branch> --single-branch

Just put in URL and branch name.

What is cardinality in Databases?

Definition: We have tables in database. In relational database, we have relations among the tables. These relations can be one-to-one, one-to-many or many-to-many. These relations are called 'cardinality'.

Significant of cardinality:

Many relational databases have been designed following stick business rules.When you design the database we define the cardinality based on the business rules. But every objects has its own nature as well.

When you define cardinality among object you have to consider all these things to define the correct cardinality.

Hidden TextArea

use

textarea{
  visibility:hidden;
}

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

General container requirements relating to iterator invalidation:

  • Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]

  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

swift UITableView set rowHeight

yourTableView.rowHeight = UITableViewAutomaticDimension

Try this.

html5: display video inside canvas

You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.

You can also use for ex. this plugin https://github.com/tstabla/stVideo

How to get share counts using graph API

when i used FQL I found the problem (but it is still problem) the documentation says that the number shown is the sum of:

  • number of likes of this URL
  • number of shares of this URL (this includes copy/pasting a link back to Facebook)
  • number of likes and comments on stories on Facebook about this URL
  • number of inbox messages containing this URL as an attachment.

but on my website the shown number is sum of these 4 counts + number of shares (again)

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

How to move all HTML element children to another parent using JavaScript?

Here's a simple function:

function setParent(el, newParent)
{
    newParent.appendChild(el);
}

el's childNodes are the elements to be moved, newParent is the element el will be moved to, so you would execute the function like:

var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
    setParent(a.childNodes[0], b);
}

Here is the Demo

How to pass props to {this.props.children}

Maybe you can also find useful this feature, though many people have considered this as an anti-pattern it still can be used if you're know what you're doing and design your solution well.

Function as Child Components

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Defining array with multiple types in TypeScript

Defining array with multiple types in TypeScript

Use a union type (string|number)[] demo:

const foo: (string|number)[] = [ 1, "message" ];

I have an array of the form: [ 1, "message" ].

If you are sure that there are always only two elements [number, string] then you can declare it as a tuple:

const foo: [number, string] = [ 1, "message" ];

FPDF utf-8 encoding (HOW-TO)

there is a really simple solution for this problem.

In the file fpdf.php go to the line that says:

if($txt!=='')
{

It is line 648 in my version of fpdf. Insert the following line of code:

$txt = iconv('utf-8', 'cp1252', $txt);

(above the line of code)

if($align=='R')

This works for all German special characters and should also work for Greek special characters. Otherwise simply replace cp1252 with the respective alphabet you require. You can see all supported characters here: http://en.wikipedia.org/wiki/Windows-1252

I saw the solution here: http://fudforum.org/forum/index.php?t=msg&goto=167345 Please use my example code above, as the original author forgot to insert a dash between utf and 8.

Hope the above was helpful.

Daan

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

"int cannot be dereferenced" in Java

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :

id.equals

Try replacing this:

        if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"

with

        if (id == list[pos].getItemNumber()){ //Getting error on "equals"

Is there a limit to the length of a GET request?

The specification does not limit the length of an HTTP Get request but the different browsers implement their own limitations. For example Internet Explorer has a limitation implemented at 2083 characters.

Can I use Homebrew on Ubuntu?

Because all previous answers doesn't work for me for ubuntu 14.04 here what I did, if any one get the same problem:

git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"

then

sudo apt-get install gawk
sudo yum install gawk
brew install hello

you can follow this link for more information.

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

Get the element triggering an onclick event in jquery?

If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:

$('#sendButton').click(function(e){
    var SendButton = $(e.target);
    var TheForm = SendButton.parents('form');
    TheForm.submit();

    return false;
});

How to capture Curl output to a file?

A tad bit late, but I think the OP was looking for something like:

curl -K myfile.txt --trace-asci output.txt

How do I clear all variables in the middle of a Python script?

In Spyder one can configure the IPython console for each Python file to clear all variables before each execution in the Menu Run -> Configuration -> General settings -> Remove all variables before execution.

How do I create a ListView with rounded corners in Android?

I'm using a custom view that I layout on top of the other ones and that just draws the 4 small corners in the same color as the background. This works whatever the view contents are and does not allocate much memory.

public class RoundedCornersView extends View {
    private float mRadius;
    private int mColor = Color.WHITE;
    private Paint mPaint;
    private Path mPath;

    public RoundedCornersView(Context context) {
        super(context);
        init();
    }

    public RoundedCornersView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.RoundedCornersView,
                0, 0);

        try {
            setRadius(a.getDimension(R.styleable.RoundedCornersView_radius, 0));
            setColor(a.getColor(R.styleable.RoundedCornersView_cornersColor, Color.WHITE));
        } finally {
            a.recycle();
        }
    }

    private void init() {
        setColor(mColor);
        setRadius(mRadius);
    }

    private void setColor(int color) {
        mColor = color;
        mPaint = new Paint();
        mPaint.setColor(mColor);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);

        invalidate();
    }

    private void setRadius(float radius) {
        mRadius = radius;
        RectF r = new RectF(0, 0, 2 * mRadius, 2 * mRadius);
        mPath = new Path();
        mPath.moveTo(0,0);
        mPath.lineTo(0, mRadius);
        mPath.arcTo(r, 180, 90);
        mPath.lineTo(0,0);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        /*Paint paint = new Paint();
        paint.setColor(Color.RED);
        canvas.drawRect(0, 0, mRadius, mRadius, paint);*/

        int w = getWidth();
        int h = getHeight();
        canvas.drawPath(mPath, mPaint);
        canvas.save();
        canvas.translate(w, 0);
        canvas.rotate(90);
        canvas.drawPath(mPath, mPaint);
        canvas.restore();
        canvas.save();
        canvas.translate(w, h);
        canvas.rotate(180);
        canvas.drawPath(mPath, mPaint);
        canvas.restore();
        canvas.translate(0, h);
        canvas.rotate(270);
        canvas.drawPath(mPath, mPaint);
    }
}

When to use "ON UPDATE CASCADE"

  1. Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10 all children parent_id's of 10 will also be updated to 20

  2. If you don't update the field the foreign key refers to, this setting is not needed

  3. Can't think of any other use.

  4. You can't do that as the foreign key constraint would fail.

Setting Remote Webdriver to run tests in a remote computer using Java

You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

You can have a look at here for more information.

How to get Selected Text from select2 when using <input>

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via ajax

 $("#vendor-brands").select2({
   ajax: {
   url:site_url('general/get_brand_ajax_json'),
  dataType: 'json',
  delay: 250,
  data: function (params) {
  return {
    q: params.term, // search term
    page: params.page
  };
},
processResults: function (data, params) {
  // parse the results into the format expected by Select2
  // since we are using custom formatting functions we do not need to
  // alter the remote JSON data, except to indicate that infinite
  // scrolling can be used
  params.page = params.page || 1;

  return {
    results: data,
    pagination: {
      more: (params.page * 30) < data.total_count
    }
  };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom    formatter work
minimumInputLength: 1,
}).on("change", function(e) {


  var lastValue = $("#vendor-brands option:last-child").val();
  var lastText = $("#vendor-brands option:last-child").text();

  alert(lastValue+' '+lastText);
 });

Android - Share on Facebook, Twitter, Mail, ecc

I think you want to give Share button, clicking on which the suitable media/website option should be there to share with it. In Android, you need to create createChooser for the same.

Sharing Text:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Sharing binary objects (Images, videos etc.)

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);

sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

FYI, above code are referred from Sharing content in Android using ACTION_SEND Intent

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

Well, it'd still be convenient (syntactically) if we could declare usual values inside the if's condition. So, here's a trick: you can make the compiler think there is an assignment of Optional.some(T) to a value like so:

    if let i = "abc".firstIndex(of: "a"),
        let i_int = .some(i.utf16Offset(in: "abc")),
        i_int < 1 {
        // Code
    }

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter. http://php.net/manual/en/function.json-decode.php

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

2D array values C++

Just want to point out you do not need to specify all dimensions of the array.

The leftmost dimension can be 'guessed' by the compiler.

#include <stdio.h>
int main(void) {
  int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
  printf("sizeof arr is %d bytes\n", (int)sizeof arr);
  printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
  return 0;
}

How do I format a number with commas in T-SQL?

Here is a scalar function I am using that fixes some bugs in a previous example (above) and also handles decimal values (to the specified # of digits) (EDITED to also work with 0 & negative numbers). One other note, the cast as money method above is limited to the size of the MONEY data type, and doesn't work with 4 (or more) digits decimals. That method is definitely simpler but less flexible.

CREATE FUNCTION [dbo].[fnNumericWithCommas](@num decimal(38, 18), @decimals int = 4) RETURNS varchar(44) AS
BEGIN
    DECLARE @ret varchar(44)

    DECLARE @negative bit; SET @negative = CASE WHEN @num < 0 THEN 1 ELSE 0 END

    SET @num = abs(round(@num, @decimals)) -- round the value to the number of decimals desired
    DECLARE @decValue varchar(18); SET @decValue = substring(ltrim(@num - round(@num, 0, 1)) + '000000000000000000', 3, @decimals)
    SET @num = round(@num, 0, 1) -- truncate the incoming number of any decimals
    WHILE @num > 0 BEGIN
        SET @ret = str(@num % 1000, 3, 0) + isnull(','+@ret, '')
        SET @num = round(@num / 1000, 0, 1)
    END
    SET @ret = isnull(replace(ltrim(@ret), ' ', '0'), '0') + '.' + @decValue
    IF (@negative = 1) SET @ret = '-' + @ret

    RETURN @ret
END

GO

How to print object array in JavaScript?

There is a wonderful print_r implementation for JavaScript in php.js library.

Note, you should also add echo support in the code.

DEMO: http://jsbin.com/esexiw/1

How do I concatenate multiple C++ strings on one line?

In 5 years nobody has mentioned .append?

#include <string>

std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");

Python convert decimal to hex

A version using iteration:

def toHex(decimal):
    hex_str = ''
    digits = "0123456789ABCDEF"
    if decimal == 0:
       return '0'

    while decimal != 0:
        hex_str += digits[decimal % 16]
        decimal = decimal // 16

    return hex_str[::-1] # reverse the string

numbers = [0, 16, 20, 45, 255, 456, 789, 1024]
print([toHex(x) for x in numbers])
print([hex(x) for x in numbers])

Is the Javascript date object always one day off?

Storing yyyy-mm-dd in MySql Date format you must do the following:

const newDate = new Date( yourDate.getTime() + Math.abs(yourDate.getTimezoneOffset()*60000) );
console.log(newDate.toJSON().slice(0, 10)); // yyyy-mm-dd

Remove/ truncate leading zeros by javascript/jquery

One another way without regex:

function trimLeadingZerosSubstr(str) {
    var xLastChr = str.length - 1, xChrIdx = 0;
    while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
        xChrIdx++;
    }
    return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}

With short string it will be more faster than regex (jsperf)

setting multiple column using one update

UPDATE some_table 
   SET this_column=x, that_column=y 
   WHERE something LIKE 'them'

How to clear a textbox once a button is clicked in WPF?

There is one possible pitfall with using textBoxName.Text = string.Empty; and that is if you are using Text binding for your TextBox (i.e. <TextBox Text="{Binding Path=Description}"></TextBox>). In this case, setting an empty string will actually override and break your binding.

To prevent this behavior you have to use the Clear method:

textBoxName.Clear();

This way the TextBox will be cleared, but the binding will be kept intact.

How to redirect output of an already running process

Dupx

Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.

Motivation

I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a

bg %1 >/tmp/stdout 2>/tmp/stderr 

Unfortunately this will not work (in shells I know).

http://www.isi.edu/~yuri/dupx/

if else in a list comprehension

Here is another illustrative example:

>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!

It exploits the fact that if i evaluates to False for 0 and to True for all other values generated by the function range(). Therefore the list comprehension evaluates as follows:

>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']

Append a dictionary to a dictionary

Assuming that you do not want to change orig, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

Or without itertools:

dest = dict(list(orig.items()) + list(extra.items()))

Note that you only need to pass the result of items() into list() on Python 3, on 2.x dict.items() already returns a list so you can just do dict(orig.items() + extra.items()).

As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

List Git aliases

If you know the name of the alias, you can use the --help option to describe it. For example:

$ git sa --help
`git sa' is aliased to `stash'

$ git a --help
`git a' is aliased to `add'

twitter bootstrap 3.0 typeahead ajax example

I'm using this https://github.com/biggora/bootstrap-ajax-typeahead

The result of code using Codeigniter/PHP

<pre>

$("#produto").typeahead({
        onSelect: function(item) {
            console.log(item);
            getProductInfs(item);
        },
        ajax: {
            url: path + 'produto/getProdName/',
            timeout: 500,
            displayField: "concat",
            valueField: "idproduto",
            triggerLength: 1,
            method: "post",
            dataType: "JSON",
            preDispatch: function (query) {
                showLoadingMask(true);
                return {
                    search: query
                }
            },
            preProcess: function (data) {

                if (data.success === false) {
                    return false;
                }else{
                    return data;    
                }                
            }               
        }
    });
</pre>   

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

Invoking a jQuery function after .each() has completed

If you're willing to make it a couple of steps, this might work. It's dependent on the animations finishing in order, though. I don't think that should be a problem.

var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;

elems.each( function(i) {
    $(this).fadeOut(200, function() { 
        $(this).remove(); 
        if (i == lastID) {
           doMyThing();
        }
    });
});

How to enable LogCat/Console in Eclipse for Android?

Write "LogCat" in Quick Access edit box in your eclipse window (top right corner, just before Open Prospective button). And just select LogCat it will open-up the LogCat window in your current prospect

enter image description here

Jquery UI tooltip does not support html content

Instead of this:

$(document).tooltip({
    content: function () {
        return $(this).prop('title');
    }
});

use this for better performance

$(selector).tooltip({
    content: function () {
        return this.getAttribute("title");
    },
});

PHP cURL GET request and request's body

  <?php
  $post = ['batch_id'=> "2"];
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  $response = curl_exec($ch);
  $result = json_decode($response);
  curl_close($ch); // Close the connection
  $new=   $result->status;
  if( $new =="1")
  {
    echo "<script>alert('Student list')</script>";
  }
  else 
  {
    echo "<script>alert('Not Removed')</script>";
  }

  ?>

How to establish a connection pool in JDBC?

Don't reinvent the wheel.

Try one of the readily available 3rd party components:

  • Apache DBCP - This one is used internally by Tomcat, and by yours truly.
  • c3p0

Apache DBCP comes with different example on how to setup a pooling javax.sql.DataSource. Here is one sample that can help you get started.

Specify the from user when sending email using the mail command

echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"

or

echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"

How to update a single pod without touching other dependencies

Just a small notice.

pod update POD_NAME

will work only if this pod was already installed. Otherwise you will have to update all of them with

pod update

command

How to check if a variable is not null?

  • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

Here you have all (src)

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Using comma as list separator with AngularJS

I think it's better to use ng-if. ng-show creates an element in the dom and sets it's display:none. The more dom elements you have the more resource hungry your app becomes, and on devices with lower resources the less dom elements the better.

TBH <span ng-if="!$last">, </span> seems like a great way to do it. It's simple.

How can I deploy an iPhone application from Xcode to a real iPhone device?

This really all depends on what version of Xcode you are using as different versions use different methods to deploy to your iPhone without a provisioning profile.

Xcode 3.2.1 is a good version and is easy to sort out, but we need to know what version you are using.

How to see the values of a table variable at debug time in T-SQL?

DECLARE @v XML = (SELECT * FROM <tablename> FOR XML AUTO)

Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add @v to the watches window.

enter image description here

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

OperationDataContext odDataContext = new OperationDataContext();    
        var studentInfo = from student in odDataContext.STUDENTs
                          join course in odDataContext.COURSEs
                          on student.course_id equals course.course_id
                          select new { student.student_name, student.student_city, course.course_name, course.course_desc };

Where student and course tables have primary key and foreign key relationship

How to add a set path only for that batch file executing?

That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:

setx ENV_VAR_NAME "DESIRED_PATH" /m

This will change it permanently and yes you can overwrite it by another batch script.

webpack: Module not found: Error: Can't resolve (with relative path)

I had a different problem. some of my includes were set to 'app/src/xxx/yyy' instead of '../xxx/yyy'

How can I display the users profile pic using the facebook graph api?

EDIT: So facebook has changed it again! No more searching by username - have amended the answer below...

https://graph.facebook.com/{{UID}}/picture?redirect=false&height=200&width=200
  • UID = the profile or page id
  • redirect either returns json (false) or redirects to the image (true)
  • height and width is the crop
  • does not require authentication

e.g. https://graph.facebook.com/4/picture?redirect=false&height=200&width=200

Facebook Graph picture doc

How to open SharePoint files in Chrome/Firefox

Installing the Chrome extension IE Tab did the job for me.

It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.

You can install IETab for FireFox too.

Express.js req.body undefined

Latest version of Express already has body-parser built-in. So you can use:

const express = require('express);
... 
app.use(express.urlencoded({ extended: false }))
.use(express.json());

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

If the element only has one handler, then simply use jQuery unbind.

$("#element").unbind();

Node.js: Difference between req.query[] and req.params

Suppose you have defined your route name like this:

https://localhost:3000/user/:userid

which will become:

https://localhost:3000/user/5896544

Here, if you will print: request.params

{
userId : 5896544
}

so

request.params.userId = 5896544

so request.params is an object containing properties to the named route

and request.query comes from query parameters in the URL eg:

https://localhost:3000/user?userId=5896544 

request.query

{

userId: 5896544

}

so

request.query.userId = 5896544

Assign a synthesizable initial value to a reg in Verilog

When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.

This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.

always @(posedge clk) begin
    if (reset == 1) begin // For an active high reset
        data_reg = 8'b10101011;
    end else begin
        data_reg = next_data_reg;
    end
end

Should I use window.navigate or document.location in JavaScript?

window.navigate is NOT supported in some browsers, so that one should be avoided. Any of the other methods using the location property are the most reliable and consistent approach

Streaming video from Android camera to server

Took me some time, but I finally manage do make an app that does just that. Check out the google code page if you're interested: http://code.google.com/p/spydroid-ipcamera/ I added loads of comments in my code (mainly, look at CameraStreamer.java), so it should be pretty self-explanatory. The hard part was actually to understand the RFC 3984 and implement a proper algorithm for the packetization process. (This algorithm actually turns the mpeg4/h.264 stream produced by the MediaRecorder into a nice rtp stream, according to the rfc)

Bye

What is considered a good response time for a dynamic, personalized web application?

It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.

Difference between frontend, backend, and middleware in web development

Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works

Checking if an object is a number in C#

If your requirement is really

.ToString() would result in a string containing digits and +,-,.

and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.

For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:

NumberStyles style = 
   NumberStyles.AllowLeadingSign | 
   NumberStyles.AllowDecimalPoint | 
double.TryParse(input, style, CultureInfo.InvariantCulture, out result);

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

Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:

todos = [do_something] * N  
for doit in todos:  
    doit()

POSTing JsonObject With HttpClient From Web API

the code over it in vbnet:

dim FeToSend as new (object--> define class)

Dim client As New HttpClient
Dim content = New StringContent(FeToSend.ToString(), Encoding.UTF8,"application/json")
content.Headers.ContentType = New MediaTypeHeaderValue( "application/json" )
Dim risp = client.PostAsync(Chiamata, content).Result

msgbox(risp.tostring)

Hope this help

How do I do redo (i.e. "undo undo") in Vim?

Vim documentation

<Undo>      or                  *undo* *<Undo>* *u*
u           Undo [count] changes.  {Vi: only one level}

                            *:u* *:un* *:undo*
:u[ndo]         Undo one change.  {Vi: only one level}

                            *CTRL-R*
CTRL-R          Redo [count] changes which were undone.  {Vi: redraw screen}

                            *:red* *:redo* *redo*
:red[o]         Redo one change which was undone.  {Vi: no redo}

                            *U*
U           Undo all latest changes on one line.  {Vi: while not
            moved off of it}

How to plot all the columns of a data frame in R

In case the column names in the .csv file file are not valid R name:

data <- read.csv("sample.csv",sep=";",head=TRUE)
data2 <- read.csv("sample.csv",sep=";",head=FALSE,nrows=1)

for ( i in seq(1,length( data ),1) ) plot(data[,i],ylab=data2[1,i],type="l")

Oracle SQL Developer - tables cannot be seen

I had this problem on my Mac. Fixed it by uninstalling it AND removing the /Users/aa77686/.sqldeveloper folder. Uninstalling without deleting that folder did not fix it.
Then redownloaded and reinstalled.
Started it up, added connections and it worked fine.
Quit it, restarted it several times and it shows the tables, etc. correctly each time so far.

WebView and HTML5 <video>

This question is years old, but maybe my answer will help people like me who have to support old Android version. I tried a lot of different approaches which worked on some Android versions, however not on all. The best solution I found is to use the Crosswalk Webview which is optimized for HTML5 feature support and works on Android 4.1 and higher. It is as simple to use as the default Android WebView. You just have to include the library. Here you can find a simple tutorial on how to use it: https://diego.org/2015/01/07/embedding-crosswalk-in-android-studio/

How to add rows dynamically into table layout

The way you have added a row into the table layout you can add multiple TableRow instances into your tableLayout object

tl.addView(row1);
tl.addView(row2);

etc...

Python Sets vs Lists

from datetime import datetime
listA = range(10000000)
setA = set(listA)
tupA = tuple(listA)
#Source Code

def calc(data, type):
start = datetime.now()
if data in type:
print ""
end = datetime.now()
print end-start

calc(9999, listA)
calc(9999, tupA)
calc(9999, setA)

Output after comparing 10 iterations for all 3 : Comparison

jQuery datepicker years shown

Adding to what @Shog9 posted, you can also restrict dates individually in the beforeShowDay: callback function.

You supply a function that takes a date and returns a boolean array:

"$(".selector").datepicker({ beforeShowDay: nationalDays}) 
natDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'], 
[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7, 
'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']]; 
function nationalDays(date) { 
    for (i = 0; i < natDays.length; i++) { 
      if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == 
natDays[i][1]) { 
        return [false, natDays[i][2] + '_day']; 
      } 
    } 
  return [true, '']; 
} 

adding multiple entries to a HashMap at once in one statement

Based on solution, presented by @Dakusan (the class defining to extend the HashMap), I did it this way:

  public static HashMap<String,String> SetHash(String...pairs) {
     HashMap<String,String> rtn = new HashMap<String,String>(pairs.length/2);
     for ( int n=0; n < pairs.length; n+=2 ) rtn.put(pairs[n], pairs[n + 1]);
    return rtn; 
  }

.. and using it this way:

HashMap<String,String> hm = SetHash( "one","aa", "two","bb", "tree","cc");

(Not sure if there is any disadvantages in that way (I am not a java developer, just has to do some task in java), but it works and seems to me comfortable.)

What's a good (free) visual merge tool for Git? (on windows)

What's wrong with using Git For Windows? From the repo view, there's an icon of the branch you're in (at the top), and if you click on manage you can drag&drop in a very visual and convenient way.

Spring Test & Security: How to mock authentication?

It turned out that the SecurityContextPersistenceFilter, which is part of the Spring Security filter chain, always resets my SecurityContext, which I set calling SecurityContextHolder.getContext().setAuthentication(principal) (or by using the .principal(principal) method). This filter sets the SecurityContext in the SecurityContextHolder with a SecurityContext from a SecurityContextRepository OVERWRITING the one I set earlier. The repository is a HttpSessionSecurityContextRepository by default. The HttpSessionSecurityContextRepository inspects the given HttpRequest and tries to access the corresponding HttpSession. If it exists, it will try to read the SecurityContext from the HttpSession. If this fails, the repository generates an empty SecurityContext.

Thus, my solution is to pass a HttpSession along with the request, which holds the SecurityContext:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

import eu.ubicon.webapp.test.WebappTestEnvironment;

public class Test extends WebappTestEnvironment {

    public static class MockSecurityContext implements SecurityContext {

        private static final long serialVersionUID = -1386535243513362694L;

        private Authentication authentication;

        public MockSecurityContext(Authentication authentication) {
            this.authentication = authentication;
        }

        @Override
        public Authentication getAuthentication() {
            return this.authentication;
        }

        @Override
        public void setAuthentication(Authentication authentication) {
            this.authentication = authentication;
        }
    }

    @Test
    public void signedIn() throws Exception {

        UsernamePasswordAuthenticationToken principal = 
                this.getPrincipal("test1");

        MockHttpSession session = new MockHttpSession();
        session.setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 
                new MockSecurityContext(principal));


        super.mockMvc
            .perform(
                    get("/api/v1/resource/test")
                    .session(session))
            .andExpect(status().isOk());
    }
}

OpenJDK availability for Windows OS

For Java 12 onwards, official General-Availability (GA) and Early-Access (EA) Windows 64-bit builds of the OpenJDK (GPL2 + Classpath Exception) from Oracle are available as tar.gz/zip from the JDK website.

If you prefer an installer, there are several distributions. There is a public Google Doc and Blog post by the Java Champions community which lists the best-supported OpenJDK distributions. Currently, these are:

How to equalize the scales of x-axis and y-axis in Python matplotlib?

See the documentation on plt.axis(). This:

plt.axis('equal')

doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:

plt.axis('square')

This creates a square plot with equal axes.

Change the background color of a row in a JTable

Resumee of Richard Fearn's answer , to make each second line gray:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

What is the relative performance difference of if/else versus switch statement in Java?

That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.

Alternatively, you can also grab Polymorphism. First create some interface:

public interface Action { 
    void execute(String input);
}

And get hold of all implementations in some Map. You can do this either statically or dynamically:

Map<String, Action> actions = new HashMap<String, Action>();

Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):

actions.get(name).execute(input);

It might be microslower than if/else or switch, but the code is at least far better maintainable.

As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:

If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

REST API Best practice: How to accept list of parameter values as input

First case:

A normal product lookup would look like this

http://our.api.com/product/1

So Im thinking that best practice would be for you to do this

http://our.api.com/Product/101404,7267261

Second Case

Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using [].

PS This can be subjective, so do what you feel comfortable with.

The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.

EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Session 'app': Error Launching activity

I spent a whole lot of hours on this exact issue. The "instant run" fix was a total fail. And I wasn't missing the android.intent.category.LAUNCHER I removed all applicable Android Studio and SDK code and re-installed. Still a no go.

Ultimately I think my issue was marginal hardware. I'm running on a laptop with a AMD A6-4400M processor. There is no hardware acceleration / virtualization tools available. I was just running the standard Android Studio / Google emulator. It was painfully slow, and although I was eventually able to see the emulator and interact with it, I was never able to connect the emulator to Android Studio to upload APK's.

But I did discover an awesome fix.

  • Remove all Android Virtual Devices and install the GenyMotion Emulator (with VirtualBox).
  • I've tried GenyMotion emulators before (with a Linux) and it didn't make much difference in load up speed.
  • On this Windows 10 machine it works exceptionally well. Its pretty quick, easily connects to Android Studio and works well deploying my apps.
  • GenyMotion offers one personal use device at no cost. Kudos to the GenyMotion team!

Answer provided here in case anybody else gets stuck with this error, possibly with this root cause.

Windows 7 - Add Path

The path is a list of directories where the command prompt will look for executable files, if it can't find it in the current directory. The OP seems to be trying to add the actual executable, when it just needs to specify the path where the executable is.

How do I open multiple instances of Visual Studio Code?

I like opening Visual Studio Code from the run prompt/dialog instead, with a sweet and simple cmd /c code -n. Since the run dialog also maintains your command history on a per user basis, it is very convenient. One click and go -

Enter image description here

"Cannot start compilation: the output path is not specified for module..."

You just have to go to your Module settings > Project and specify a "Project compiler output" and make your modules inherit from project. (For that go to Modules > Paths > Inherit project.

This did the trick for me.

Import python package from local directory into interpreter

I used pathlib to add my module directory to my system path as I wanted to avoid installing the module as a package and @maninthecomputer response didn't work for me

import sys
from pathlib import Path

cwd = str(Path(__file__).parent)
sys.path.insert(0, cwd)
from my_module import my_function

How to calculate the median of an array?

public int[] data={31, 29, 47, 48, 23, 30, 21
        , 40, 23, 39, 47, 47, 42, 44, 23, 26, 44, 32, 20, 40};

public double median()
    {
        Arrays.sort(this.data);
        double result=0;
        int size=this.data.length;


        if(size%2==1)
        {
            result=data[((size-1)/2)+1];
            System.out.println(" uneven size : "+result);
        }
        else
        { 
            int middle_pair_first_index =(size-1)/2;
            result=(data[middle_pair_first_index+1]+data[middle_pair_first_index])/2;
            System.out.println(" Even size : "+result);
        }

        return result;
    }

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

Another Repeated column in mapping for entity error

Hope this will help!

@OneToOne(optional = false)
    @JoinColumn(name = "department_id", insertable = false, updatable = false)
    @JsonManagedReference
    private Department department;

@JsonIgnore
    public Department getDepartment() {
        return department;
    }

@OneToOne(mappedBy = "department")
private Designation designation;

@JsonIgnore
    public Designation getDesignation() {
        return designation;
    }

How can I rename a single column in a table at select?

select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2 
ON t1.Key = t2.Key 

like this ?

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

Read MS Exchange email in C#

I got a solution working in the end using Redemption, have a look at these questions...

jQuery - Create hidden form element on the fly

if you want to add more attributes just do like:

$('<input>').attr('type','hidden').attr('name','foo[]').attr('value','bar').appendTo('form');

Or

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'foo[]',
    value: 'bar'
}).appendTo('form');

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Android canvas draw rectangle

paint.setStrokeWidth(3);

paint.setColor(BLACK);

and either one of your drawRect should work.

How to import a bak file into SQL Server Express

There is a step by step explanation (with pictures) available @ Restore DataBase

  1. Click Start, select All Programs, click Microsoft SQL Server 2008 and select SQL Server Management Studio.
    This will bring up the Connect to Server dialog box.
    Ensure that the Server name YourServerName and that Authentication is set to Windows Authentication.
    Click Connect.

  2. On the right, right-click Databases and select Restore Database.
    This will bring up the Restore Database window.

  3. On the Restore Database screen, select the From Device radio button and click the "..." box.
    This will bring up the Specify Backup screen.

  4. On the Specify Backup screen, click Add.
    This will bring up the Locate Backup File.

  5. Select the DBBackup folder and chose your BackUp File(s).

  6. On the Restore Database screen, under Select the backup sets to restore: place a check in the Restore box, next to your data and in the drop-down next to To database: select DbName.

  7. You're done.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

Simple CSS: Text won't center in a button

make sure:

box-sizing : content-box;

Hibernate error - QuerySyntaxException: users is not mapped [from users]

Just to share my finding. I still got the same error even if the query was targeting the correct class name. Later on I realised that I was importing the Entity class from the wrong package.

The problem was solved after I change the import line from:

import org.hibernate.annotations.Entity;

to

import javax.persistence.Entity;

Refresh Page C# ASP.NET

Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.

Response.Redirect(Request.RawUrl);

How to check if PHP array is associative or sequential?

Improvement from Mark Amery

function isAssoc($arr)
{
    // Is it set, is an array, not empty and keys are not sequentialy numeric from 0
    return isset($arr) && is_array($arr) && count($arr)!=0 && array_keys($arr) !== range(0, count($arr) - 1);
}

This tests if variable exists, if it is an array, if it is not an empty array and if the keys are not sequential from 0.

To see if the array is associative

if (isAssoc($array)) ...

To see if it numeric

if (!isAssoc($array)) ...

Installing Python packages from local file system folder to virtualenv with pip

Assuming you have virtualenv and a requirements.txt file, then you can define inside this file where to get the packages:

# Published pypi packages 
PyJWT==1.6.4
email_validator==1.0.3
# Remote GIT repo package, this will install as django-bootstrap-themes
git+https://github.com/marquicus/django-bootstrap-themes#egg=django-bootstrap-themes
# Local GIT repo package, this will install as django-knowledge
git+file:///soft/SANDBOX/python/django/forks/django-knowledge#egg=django-knowledge

HTML img tag: title attribute vs. alt attribute?

No, I think alt is better because the purpose of that attribute is to provide "alternate" text in the event that the image cannot be view (whether it be that the image is missing or that the browser itself is incapable of displaying it).

How to download PDF automatically using js?

/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
    save.download = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
            document.location = save.href; 
// window event not working here
        }else{
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }   
}

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window = window.open(fileURL, '_blank');
    _window.document.close();
    _window.document.execCommand('SaveAs', true, fileName || fileURL)
    _window.close();
}
}

How to use?

download_file(fileURL, fileName); //call function

Source: convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/

How can I get the current PowerShell executing file?

Try the following

$path =  $MyInvocation.MyCommand.Definition 

This may not give you the actual path typed in but it will give you a valid path to the file.

PHP exec() vs system() vs passthru()

If you're running your PHP script from the command-line, passthru() has one large benefit. It will let you execute scripts/programs such as vim, dialog, etc, letting those programs handle control and returning to your script only when they are done.

If you use system() or exec() to execute those scripts/programs, it simply won't work.

Gotcha: For some reason, you can't execute less with passthru() in PHP.

Where does Visual Studio look for C++ header files?

If the project came with a Visual Studio project file, then that should already be configured to find the headers for you. If not, you'll have to add the include file directory to the project settings by right-clicking the project and selecting Properties, clicking on "C/C++", and adding the directory containing the include files to the "Additional Include Directories" edit box.

Presenting modal in iOS 13 fullscreen

This worked for me:

yourViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen

Transpose a range in VBA

This gets you X and X' as variant arrays you can pass to another function.

Dim X() As Variant
Dim XT() As Variant
X = ActiveSheet.Range("InRng").Value2
XT = Application.Transpose(X)

To have the transposed values as a range, you have to pass it via a worksheet as in this answer. Without seeing how your covariance function works it's hard to see what you need.

Is there a simple, elegant way to define singletons?

Creating a singleton decorator (aka an annotation) is an elegant way if you want to decorate (annotate) classes going forward. Then you just put @singleton before your class definition.

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

Calculating number of full months between two dates in SQL

What's your definition of a month? Technically a month can be 28,29,30 or 31 days depending on the month and leap years.

It seems you're considering a month to be 30 days since in your example you disregarded that May has 31 days, so why not just do the following?

SELECT DATEDIFF(DAY, '2009-04-16', '2009-05-15')/30
    , DATEDIFF(DAY, '2009-04-16', '2009-05-16')/30
    , DATEDIFF(DAY, '2009-04-16', '2009-06-16')/30

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

How to iterate over the file in python

You should learn about EAFP vs LBYL.

from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
    if isinstance(infile, basestring):
        infile=open(infile,'r')
    if isinstance(outfile, basestring):
        outfile=open(outfile,'w')
    for lineno, line in enumerate(infile, 1):
        line = line.strip()
         try:
             print >>outfile, int(line,16)
         except ValueError:
             return "Bad value at line %i: %r" % (lineno, line)

if __name__ == "__main__":
    from sys import argv, exit
    exit(main(*argv[1:]))

In jQuery, how do I select an element by its name attribute?

can also use a CSS class to define the range of radio buttons and then use the following to determine the value

$('.radio_check:checked').val()

How to use XPath contains() here?

//ul[@class="featureList" and li//text()[contains(., "Model")]]

PRINT statement in T-SQL

So, if you have a statement something like the following, you're saying that you get no 'print' result?

select * from sysobjects
PRINT 'Just selected * from sysobjects'

If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like

raiserror ('My Print Statement', 10,1) with nowait

This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.