Programs & Examples On #Turing machines

A Turing machine is an idealized model of computation consisting of a finite-state control, an infinite tape holding information, and a read head positioned somewhere over the tape. Turing machines are used in computability theory to reason about the limits of computation, to provide a formal definition for an algorithm, and to provide formal models for nondeterminism.

What is Turing Complete?

In the simplest terms, a Turing-complete system can solve any possible computational problem.

One of the key requirements is the scratchpad size be unbounded and that is possible to rewind to access prior writes to the scratchpad.

Thus in practice no system is Turing-complete.

Rather some systems approximate Turing-completeness by modeling unbounded memory and performing any possible computation that can fit within the system's memory.

Search All Fields In All Tables For A Specific Value (Oracle)

SELECT * from all_objects WHERE object_name like '%your_string%';

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Load HTML File Contents to Div [without the use of iframes]

    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';

Using Jquery AJAX function with datatype HTML

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

});//FIN  AJAX

auto run a bat script in windows 7 at login

Just enable parsing of the autoexec.bat in the registry, using these instructions.

:: works only on windows vista and earlier 
Run REGEDT32.EXE.
Modify the following value within HKEY_CURRENT_USER: 

Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ParseAutoexec 

1 = autoexec.bat is parsed
0 = autoexec.bat is not parsed

react-router (v4) how to go back?

Try:

this.props.router.goBack()

Select SQL results grouped by weeks

the provided solutions seem a little complex? this might help:

https://msdn.microsoft.com/en-us/library/ms174420.aspx

select
   mystuff,
   DATEPART ( year, MyDateColumn ) as yearnr,
   DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc

Connect to external server by using phpMyAdmin

In the config file, change the "host" variable to point to the external server. The config file is called config.inc.php and it will be in the main phpMyAdmin folder. There should be a line like this:

$cfg['Servers'][$i]['host'] = 'localhost';

Just change localhost to your server's IP address.

Note: you may have to configure the external server to allow remote connections, but I've done this several times on shared hosting so it should be fine.

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Framework and .NET Core are both frameworks.

.NET Standard is a standard (in other words, a specification).

You can make an executable project (like a console application, or ASP.NET application) with .NET Framework and .NET Core, but not with .NET Standard.

With .NET Standard you can make only a class library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.

Get value of div content using jquery

your div looks like this:

<div class="readonly_label" id="field-function_purpose">Other</div>

With jquery you can easily get inner content:

Use .html() : HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

var text = $('#field-function_purpose').html(); 

Read more about jquery .html()

or

Use .text() : Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

var text = $('#field-function_purpose').text();

Read more about jquery .text()

IDEA: javac: source release 1.7 requires target release 1.7

check .idea/misc.xml sometimes you need to change languageLevel="JDK_1_X" attribute manually

How to call a C# function from JavaScript?

You can use a Web Method and Ajax:

<script type="text/javascript">             //Default.aspx
   function DeleteKartItems() {     
         $.ajax({
         type: "POST",
         url: 'Default.aspx/DeleteItem',
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $("#divResult").html("success");
         },
         error: function (e) {
             $("#divResult").html("Something Wrong.");
         }
     });
   }
</script>

[WebMethod]                                 //Default.aspx.cs
public static void DeleteItem()
{
    //Your Logic
}

Resolve host name to an ip address

You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here

Custom method names in ASP.NET Web API

I am days into the MVC4 world.

For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:

http://localhost:9000/api/SitesAPI/Disposition/0

With different values for the last parameter to get record with different dispositions.

What Finally worked for me was:

The method in the SitesAPIController:

// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
    Site site = db.Sites.Where(s => s.Disposition == disposition).First();
    return site;
}

And this in the WebApiConfig.cs

// this was already there
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

// this i added
config.Routes.MapHttpRoute(
    name: "Action",
    routeTemplate: "api/{controller}/{action}/{disposition}"
 );

For as long as I was naming the {disposition} as {id} i was encountering:

{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}

When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.

Feel free to edit this answer to make it more accurate/explanatory.

Angular 2: How to call a function after get a response from subscribe http.post

get_categories(number){
 return this.http.post( url, body, {headers: headers, withCredentials:true})
      .map(t=>  {
          this.total = t.json();
          return total;
      }).share();
  );     
}

then

this.get_category(1).subscribe(t=> {
      this.callfunc();
});

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

How to get current location in Android

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.

How to show math equations in general github's markdown(not github's blog)

But github show nothing for the math symbols! please help me, thanks!

GitHub markdown parsing is performed by the SunDown (ex libUpSkirt) library.

The motto of the library is "Standards compliant, fast, secure markdown processing library in C". The important word being "secure" there, considering your question :).

Indeed, allowing javascript to be executed would be a bit off of the MarkDown standard text-to-HTML contract.

Moreover, everything that looks like a HTML tag is either escaped or stripped out.

Tell me how to show math symbols in general github markdown.

Your best bet would be to find a website similar to yuml.me which can generate on-the-fly images from by parsing the provided URL querystring.

Update

I've found some sites providing users with such service: codedogs.com (no longer seems to support embedding) or iTex2Img. You may want to try them out. Of course, others may exist and some Google-fu will help you find them.

given the following markdown syntax

![equation](http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)

it will display the following image

equation http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

Note: In order for the image to be properly displayed, you'll have to ensure the querystring part of the url is percent encoded. You can easily find online tools to help you with that task, such as www.url-encode-decode.com

Request Monitoring in Chrome

The most up-to-date answer to this is: they are listed under the 'Network' button in the developer tools, no longer under 'Resources' like it used to be.

AngularJS - Any way for $http.post to send request parameters instead of JSON?

From AngularJS documentation:

params – {Object.} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.

So, provide string as parameters. If you don't want that, then use transformations. Again, from the documentation:

To override these transformation locally, specify transform functions as transformRequest and/or transformResponse properties of the config object. To globally override the default transforms, override the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties of the $httpProvider.

Refer to documentation for more details.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I do not have a USB serial device, but there must be a way to find the real ports using the HAL libraries directly:

====================================================================
#! /usr/bin/env bash
#
# Uses HAL to find existing serial hardware
#

for sport in $(hal-find-by-capability --capability serial) ; do
  hal-get-property --udi "${sport}" --key serial.device
done

====================================================================

The posted python-dbus code nor this sh script lists the bluetooth /dev/rfcomm* devices, so it is not the best solution.

Note that on other unix platforms, the serial ports are not named ttyS? and even in linux, some serial cards allow you to name the devices. Assuming a pattern in the serial devices names is wrong.

Adjust UILabel height to text

Here is how to calculate the text height in Swift. You can then get the height from the rect and set the constraint height of the label or textView, etc.

let font = UIFont(name: "HelveticaNeue", size: 25)!
let text = "This is some really long text just to test how it works for calculating heights in swift of string sizes. What if I add a couple lines of text?"

let textString = text as NSString

let textAttributes = [NSFontAttributeName: font]

let textRect = textString.boundingRectWithSize(CGSizeMake(320, 2000), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)

SSH to AWS Instance without key pairs

su - root

Goto /etc/ssh/sshd_config

vi sshd_config

Authentication:

PermitRootLogin yes

To enable empty passwords, change to yes (NOT RECOMMENDED)

PermitEmptyPasswords no

Change to no to disable tunnelled clear text passwords

PasswordAuthentication yes

:x!

Then restart ssh service

root@cloudera2:/etc/ssh# service ssh restart
ssh stop/waiting
ssh start/running, process 10978

Now goto sudoers files (/etc/sudoers).

User privilege specification

root  ALL=(ALL)NOPASSWD:ALL
yourinstanceuser  ALL=(ALL)NOPASSWD:ALL    / This is the user by which you are launching instance.

How to make the corners of a button round?

Create file myButton.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorButton"/>
    <corners android:radius="10dp"/>
</shape>

add to your button

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/myButton"/>

target="_blank" vs. target="_new"

it's my understanding that target = whatever will look for a frame/window with that name. If not found, it will open up a new window with that name. If whatever == "_new", it will appear just as if you used _blank except.....

Using one of the reserved target names will bypass the "looking" phase. So, target = "_blank" on a dozen links will open up a dozen blank windows, but target = whatever on a dozen links will only open up one window. target = "_new" on a dozen links may give inconstant behavior. I haven't tried it on several browsers, but should only open up one window.

At least this is how I interpret the rules.

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange.

UsedRange is highly unreliable as shown HERE

To find the last column which has data, use .Find and then subtract from it.

With Sheets("Sheet1")
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastCol = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Column
    Else
        lastCol = 1
    End If
End With

If lastCol > 8 Then
    'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8

    'The above becomes

    Debug.Print lastCol - 8
End If

How to "fadeOut" & "remove" a div in jQuery?

you really should try to use jQuery in a separate file, not inline. Here is what you need:

<a class="notificationClose "><img src="close.png"/></a>

And then this at the bottom of your page in <script> tags at the very least or in a external JavaScript file.

$(".notificationClose").click(function() {
    $("#notification").fadeOut("normal", function() {
        $(this).remove();
    });
});

Calculating average of an array list?

Why use a clumsy for loop with an index when you have the enhanced for loop?

private double calculateAverage(List <Integer> marks) {
  Integer sum = 0;
  if(!marks.isEmpty()) {
    for (Integer mark : marks) {
        sum += mark;
    }
    return sum.doubleValue() / marks.size();
  }
  return sum;
}

Better way to check variable for null or empty string?

empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

How to efficiently use try...catch blocks in PHP

It's more readable a single try catch block. If its important identify a kind of error I recommend customize your Exceptions.

try {
  $tableAresults = $dbHandler->doSomethingWithTableA();
  $tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (TableAException $e){
  throw $e;
} catch (Exception $e) {
  throw $e;
}

how to display a javascript var in html body

Use document.write().

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    var number = 123;_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <h1>_x000D_
      the value for number is:_x000D_
      <script type="text/javascript">_x000D_
        document.write(number)_x000D_
      </script>_x000D_
    </h1>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I slice an ArrayList out of an ArrayList in Java?

In Java, it is good practice to use interface types rather than concrete classes in APIs.

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);

Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

  1. It would be a lot of work to design, implement and test.
  2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
  3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

Error message: "'chromedriver' executable needs to be available in the path"

You can test if it actually is in the PATH, if you open a cmd and type in chromedriver (assuming your chromedriver executable is still named like this) and hit Enter. If Starting ChromeDriver 2.15.322448 is appearing, the PATH is set appropriately and there is something else going wrong.

Alternatively you can use a direct path to the chromedriver like this:

 driver = webdriver.Chrome('/path/to/chromedriver') 

So in your specific case:

 driver = webdriver.Chrome("C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

plot.new has not been called yet

I had the same problem... my problem was that I was closing my quartz window after plot(x,y). Once I kept it open, the lines that previously resulted in errors just added things to my plot (like they were supposed to). Hopefully this might help some people who arrive at this page.

how to get 2 digits after decimal point in tsql?

Assume that you have dynamic currency precision

  • value => 1.002431

  • currency precision => 3

  • `result => 1.002

CAST(Floor(your_float_value) AS VARCHAR) + '.' + REPLACE(STR(FLOOR((your_float_value FLOOR(your_float_value)) * power(10,cu_precision)), cu_precision), SPACE(1), '0')

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

Set UITableView content inset permanently

In Swift:

override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      self.tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
}

Add shadow to custom shape on Android

This is my version of a drop shadow. I was going for a hazy shadow all around the shape and used this answer by Joakim Lundborg as my starting point. What I changed is to add corners to all the shadow items and to increase the radius of the corner for each subsequent shadow item. So here is the xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#02000000" />
            <corners android:radius="8dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#05000000" />
            <corners android:radius="7dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10000000" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#15000000" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20000000" />
            <corners android:radius="4dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#25000000" />
            <corners android:radius="3dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30000000" />
            <corners android:radius="3dp" />
        </shape>
    </item>

    <!-- Background -->
    <item>
    <shape>
            <solid android:color="#0099CC" />
        <corners android:radius="3dp" />
    </shape>
   </item>
</layer-list>

How do I get the unix timestamp in C as an int?

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}

Smooth GPS data

Mapped to CoffeeScript if anyones interested. **edit -> sorry using backbone too, but you get the idea.

Modified slightly to accept a beacon with attribs

{latitude: item.lat,longitude: item.lng,date: new Date(item.effective_at),accuracy: item.gps_accuracy}

MIN_ACCURACY = 1

# mapped from http://stackoverflow.com/questions/1134579/smooth-gps-data

class v.Map.BeaconFilter

  constructor: ->
    _.extend(this, Backbone.Events)

  process: (decay,beacon) ->

    accuracy     = Math.max beacon.accuracy, MIN_ACCURACY

    unless @variance?
      # if variance nil, inititalise some values
      @variance     = accuracy * accuracy
      @timestamp_ms = beacon.date.getTime();
      @lat          = beacon.latitude
      @lng          = beacon.longitude

    else

      @timestamp_ms = beacon.date.getTime() - @timestamp_ms

      if @timestamp_ms > 0
        # time has moved on, so the uncertainty in the current position increases
        @variance += @timestamp_ms * decay * decay / 1000;
        @timestamp_ms = beacon.date.getTime();

      # Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
      # NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
      _k  = @variance / (@variance + accuracy * accuracy)
      @lat = _k * (beacon.latitude  - @lat)
      @lng = _k * (beacon.longitude - @lng)

      @variance = (1 - _k) * @variance

    [@lat,@lng]

CSS - Expand float child DIV height to parent's height

I found a lot of answers, but probably the best solution for me is

.parent { 
  overflow: hidden; 
}
.parent .floatLeft {
  # your other styles
  float: left;
  margin-bottom: -99999px;
  padding-bottom: 99999px;
}

You can check other solutions here http://css-tricks.com/fluid-width-equal-height-columns/

Pair/tuple data type in Go

You could do something like this if you wanted

package main

import "fmt"

type Pair struct {
    a, b interface{}
}

func main() {
    p1 := Pair{"finished", 42}
    p2 := Pair{6.1, "hello"}
    fmt.Println("p1=", p1, "p2=", p2)
    fmt.Println("p1.b", p1.b)
    // But to use the values you'll need a type assertion
    s := p1.a.(string) + " now"
    fmt.Println("p1.a", s)
}

However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.

Java method to sum any number of ints

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

setTimeout in React Native

Classic javascript mistake.

setTimeout(function(){this.setState({timePassed: true})}, 1000)

When setTimeout runs this.setState, this is no longer CowtanApp, but window. If you define the function with the => notation, es6 will auto-bind this.

setTimeout(() => {this.setState({timePassed: true})}, 1000)

Alternatively, you could use a let that = this; at the top of your render, then switch your references to use the local variable.

render() {
  let that = this;
  setTimeout(function(){that.setState({timePassed: true})}, 1000);

If not working, use bind.

setTimeout(
  function() {
      this.setState({timePassed: true});
  }
  .bind(this),
  1000
);

Python conversion from binary string to hexadecimal

Use python's binascii module

import binascii

binFile = open('somebinaryfile.exe','rb')
binaryData = binFile.read(8)

print binascii.hexlify(binaryData)

jQuery: find element by text

In jQuery documentation it says:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination

Therefore it is not enough that you use :contains() selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}

GetType used in PowerShell, difference between variables

Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.

Instead, do:

Get-Date | Select-Object -ExpandProperty DayOfWeek

That will get you the same result as:

(Get-Date).DayOfWeek

The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem), for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath works as expected and returns an array of just the full paths.

retrieve links from web page using python and BeautifulSoup

To find all the links, we will in this example use the urllib2 module together with the re.module *One of the most powerful function in the re module is "re.findall()". While re.search() is used to find the first match for a pattern, re.findall() finds all the matches and returns them as a list of strings, with each string representing one match*

import urllib2

import re
#connect to a URL
website = urllib2.urlopen(url)

#read html code
html = website.read()

#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)

print links

Sort a list of tuples by 2nd item (integer value)

The fact that the sort values in the OP are integers isn't relevant to the question per se. In other words, the accepted answer would work if the sort value was text. I bring this up to also point out that the sort can be modified during the sort (for example, to account for upper and lower case).

>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: x[1])
[(148, 'ABC'), (221, 'DEF'), (121, 'abc'), (231, 'def')]
>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: str.lower(x[1]))
[(121, 'abc'), (148, 'ABC'), (231, 'def'), (221, 'DEF')]

How can I list ALL grants a user received?

Sorry guys, but selecting from all_tab_privs_recd where grantee = 'your user' will not give any output except public grants and current user grants if you run the select from a different (let us say, SYS) user. As documentation says,

ALL_TAB_PRIVS_RECD describes the following types of grants:

Object grants for which the current user is the grantee
Object grants for which an enabled role or PUBLIC is the grantee

So, if you're a DBA and want to list all object grants for a particular (not SYS itself) user, you can't use that system view.

In this case, you must perform a more complex query. Here is one taken (traced) from TOAD to select all object grants for a particular user:

select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                       4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                       7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                       11, 'PACKAGE BODY', 12, 'TRIGGER',
                       13, 'TYPE', 14, 'TYPE BODY',
                       19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',
                       22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',
                       28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',
                       32, 'INDEXTYPE', 33, 'OPERATOR',
                       34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',
                       40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',
                       42, 'MATERIALIZED VIEW',
                       43, 'DIMENSION',
                       44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',
                       66, 'JOB', 67, 'PROGRAM', 74, 'SCHEDULE',
                       48, 'CONSUMER GROUP',
                       51, 'SUBSCRIPTION', 52, 'LOCATION',
                       55, 'XML SCHEMA', 56, 'JAVA DATA',
                       57, 'EDITION', 59, 'RULE',
                       62, 'EVALUATION CONTEXT',
                       'UNDEFINED') object_type,
       o.name object_name,
       '' column_name
        from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
             table_privilege_map tpm
        where oa.obj# = o.obj#
          and oa.grantor# = ur.user#
          and oa.grantee# = ue.user#
          and oa.col# is null
          and oa.privilege# = tpm.privilege
          and u.user# = o.owner#
          and o.TYPE# in (2, 4, 6, 9, 7, 8, 42, 23, 22, 13, 33, 32, 66, 67, 74, 57)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0
union all -- column level grants
select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 2, 'TABLE', 4, 'VIEW', 42, 'MATERIALIZED VIEW') object_type,
       o.name object_name,
       c.name column_name
from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
     sys.col$ c, table_privilege_map tpm
where oa.obj# = o.obj#
  and oa.grantor# = ur.user#
  and oa.grantee# = ue.user#
  and oa.obj# = c.obj#
  and oa.col# = c.col#
  and bitand(c.property, 32) = 0 /* not hidden column */
  and oa.col# is not null
  and oa.privilege# = tpm.privilege
  and u.user# = o.owner#
  and o.TYPE# in (2, 4, 42)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0;

This will list all object grants (including column grants) for your (specified) user. If you don't want column level grants then delete all part of the select beginning with 'union' clause.

UPD: Studying the documentation I found another view that lists all grants in much simpler way:

select * from DBA_TAB_PRIVS where grantee = 'your user';

Bear in mind that there's no DBA_TAB_PRIVS_RECD view in Oracle.

Is there way to use two PHP versions in XAMPP?

Unless it has to be absolutely and definitely XAMPP, you can try to get what you want with WAMP. WAMP is pretty much the same thing in different package.

Once you have it installed, you can just switch between php versions here:

enter image description here

You can install as many versions of PHP as you need.

Here's how it is done in detail.

Just go here: WAMP download

Then select your base server, e.g. latest with php7.

Then, when WAMP 3 is installed, go to folder: addons and select php version (or versions) you are after. They offer php flavors starting from php 5.3.29, which should work with mysql_connect.

To install addon, during installation (double click exe file) just point to folder where you have your WAMP 3 installed.

Then you can use content of other folders, like: applications etc. to add more functionality

Everything's interfaced, so you can concentrate on coding and not hacking your environment.

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

What is the difference between a port and a socket?

The port was the easiest part, it is just a unique identifier for a socket. A socket is something processes can use to establish connections and to communicate with each other. Tall Jeff had a great telephone analogy which was not perfect, so I decided to fix it:

  • ip and port ~ phone number
  • socket ~ phone device
  • connection ~ phone call
  • establishing connection ~ calling a number
  • processes, remote applications ~ people
  • messages ~ speech

Can't check signature: public key not found

I got the same message but my files are decrypted as expected. Please check in your destination path if you could see the output file file.

How can I remove a button or make it invisible in Android?

To remove button in java code:

Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(View.GONE);

To transparent Button in java code:

Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(View.INVISIBLE);

To remove button in Xml file:

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>

To transparent button in Xml file:

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>

bootstrap 4 file input doesn't show the file name

If you want you can use the recommended Bootstrap plugin to dynamize your custom file input: https://www.npmjs.com/package/bs-custom-file-input

This plugin can be use with or without jQuery and works with React an Angular

How do you send a Firebase Notification to all devices via CURL?

The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity

FirebaseMessaging.getInstance().subscribeToTopic("all");

Now send the request as

{
   "to":"/topics/all",
   "data":
   {
      "title":"Your title",
      "message":"Your message"
      "image-url":"your_image_url"
   }
}

This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.

You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM


To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

Read more about conditions and topics here on FCM documentation

How to style components using makeStyles and still have lifecycle methods in Material UI?

What we ended up doing is stopped using the class components and created Functional Components, using useEffect() from the Hooks API for lifecycle methods. This allows you to still use makeStyles() with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.

Example:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

How to use a WSDL

I would fire up Visual Studio, create a web project (or console app - doesn't matter).

For .Net Standard:

  1. I would right-click on the project and pick "Add Service Reference" from the Add context menu.
  2. I would click on Advanced, then click on Add Service Reference.
  3. I would get the complete file path of the wsdl and paste into the address bar. Then fire the Arrow (go button).
  4. If there is an error trying to load the file, then there must be a broken and unresolved url the file needs to resolve as shown below: enter image description here Refer to this answer for information on how to fix: Stackoverflow answer to: Unable to create service reference for wsdl file

If there is no error, you should simply set the NameSpace you want to use to access the service and it'll be generated for you.

For .Net Core

  1. I would right click on the project and pick Connected Service from the Add context menu.
  2. I would select Microsoft WCF Web Service Reference Provider from the list.
  3. I would press browse and select the wsdl file straight away, Set the namespace and I am good to go. Refer to the error fix url above if you encounter any error.

Any of the methods above will generate a simple, very basic WCF client for you to use. You should find a "YourservicenameClient" class in the generated code.

For reference purpose, the generated cs file can be found in your Obj/debug(or release)/XsdGeneratedCode and you can still find the dlls in the TempPE folder.

The created Service(s) should have methods for each of the defined methods on the WSDL contract.

Instantiate the client and call the methods you want to call - that's all there is!

YourServiceClient client = new YourServiceClient();
client.SayHello("World!");

If you need to specify the remote URL (not using the one created by default), you can easily do this in the constructor of the proxy client:

YourServiceClient client = new YourServiceClient("configName", "remoteURL");

where configName is the name of the endpoint to use (you will use all the settings except the URL), and the remoteURL is a string representing the URL to connect to (instead of the one contained in the config).

Delete sql rows where IDs do not have a match from another table

Using LEFT JOIN/IS NULL:

DELETE b FROM BLOB b 
  LEFT JOIN FILES f ON f.id = b.fileid 
      WHERE f.id IS NULL

Using NOT EXISTS:

DELETE FROM BLOB 
 WHERE NOT EXISTS(SELECT NULL
                    FROM FILES f
                   WHERE f.id = fileid)

Using NOT IN:

DELETE FROM BLOB
 WHERE fileid NOT IN (SELECT f.id 
                        FROM FILES f)

Warning

Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.

How to extract URL parameters from a URL with Ruby or Rails?

For a pure Ruby solution combine URI.parse with CGI.parse (this can be used even if Rails/Rack etc. are not required):

CGI.parse(URI.parse(url).query) 
# =>  {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }

Print multiple arguments in Python

Keeping it simple, I personally like string concatenation:

print("Total score for " + name + " is " + score)

It works with both Python 2.7 an 3.X.

NOTE: If score is an int, then, you should convert it to str:

print("Total score for " + name + " is " + str(score))

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Sound effects in JavaScript / HTML5

_x000D_
_x000D_
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;_x000D_
var audioContext = new AudioContextFunc();_x000D_
var player=new WebAudioFontPlayer();_x000D_
var instrumVox,instrumApplause;_x000D_
var drumClap,drumLowTom,drumHighTom,drumSnare,drumKick,drumCrash;_x000D_
loadDrum(21,function(s){drumClap=s;});_x000D_
loadDrum(30,function(s){drumLowTom=s;});_x000D_
loadDrum(50,function(s){drumHighTom=s;});_x000D_
loadDrum(15,function(s){drumSnare=s;});_x000D_
loadDrum(5,function(s){drumKick=s;});_x000D_
loadDrum(70,function(s){drumCrash=s;});_x000D_
loadInstrument(594,function(s){instrumVox=s;});_x000D_
loadInstrument(1367,function(s){instrumApplause=s;});_x000D_
function loadDrum(n,callback){_x000D_
  var info=player.loader.drumInfo(n);_x000D_
  player.loader.startLoad(audioContext, info.url, info.variable);_x000D_
  player.loader.waitLoad(function () {callback(window[info.variable])});_x000D_
}_x000D_
function loadInstrument(n,callback){_x000D_
  var info=player.loader.instrumentInfo(n);_x000D_
  player.loader.startLoad(audioContext, info.url, info.variable);_x000D_
  player.loader.waitLoad(function () {callback(window[info.variable])});_x000D_
}_x000D_
function uhoh(){_x000D_
  var when=audioContext.currentTime;_x000D_
  var b=0.1;_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, instrumVox, when+b*0, 60, b*1);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, instrumVox, when+b*3, 56, b*4);_x000D_
}_x000D_
function applause(){_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, instrumApplause, audioContext.currentTime, 54, 3);_x000D_
}_x000D_
function badumtss(){_x000D_
  var when=audioContext.currentTime;_x000D_
  var b=0.11;_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*0, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumLowTom, when+b*0, drumLowTom.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*1, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumHighTom, when+b*1, drumHighTom.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*3, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumKick, when+b*3, drumKick.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumCrash, when+b*3, drumCrash.zones[0].keyRangeLow, 3.5);_x000D_
}
_x000D_
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>_x000D_
<button onclick='badumtss();'>badumtss</button>_x000D_
<button onclick='uhoh();'>uhoh</button>_x000D_
<button onclick='applause();'>applause</button>_x000D_
<br/><a href='https://github.com/surikov/webaudiofont'>More sounds</a>
_x000D_
_x000D_
_x000D_

html 5 audio tag width

You can use html and be a boss with simple things :

<embed src="music.mp3" width="3000" height="200" controls>

How do I create an average from a Ruby array?

You can choose one of the below solutions as you wish.

Bruteforce

[0,4,8,2,5,0,2,6].sum.to_f / [0,4,8,2,5,0,2,6].size.to_f

=> 3.375

Method

def avg(array)
  array.sum.to_f / array.size.to_f
end  

avg([0,4,8,2,5,0,2,6])
=> 3.375

Monkey Patching

class Array
  def avg
    sum.to_f / size.to_f
  end
end

[0,4,8,2,5,0,2,6].avg
=> 3.375

But I don't recommend to monkey patch the Array class, this practice is dangerous and can potentially lead to undesirable effects on your system.

For our good, ruby language provides a nice feature to overcome this problem, the Refinements, which is a safe way for monkey patching on ruby.

To simplify, with the Refinements you can monkey patch the Array class and the changes will only be available inside the scope of the class that is using the refinement! :)

You can use the refinement inside the class you are working on and you are ready to go.

Refinements

module ArrayRefinements
  refine Array do
    def avg
      sum.to_f / size.to_f
    end
  end
end

class MyClass
  using ArrayRefinements

  def test(array)
    array.avg
  end
end

MyClass.new.test([0,4,8,2,5,0,2,6])
=> 3.375

Difference between scaling horizontally and vertically for databases

Let's start with the need for scaling that is increasing resources so that your system can now handle more requests than it earlier could.

When you realise your system is getting slow and is unable to handle the current number of requests, you need to scale the system.

This provides you with two options. Either you increase the resources in the server which you are using currently, i.e, increase the amount of RAM, CPU, GPU and other resources. This is known as vertical scaling.

Vertical scaling is typically costly. It does not make the system fault tolerant, i.e if you are scaling application running with single server, if that server goes down, your system will go down. Also the amount of threads remains the same in vertical scaling. Vertical scaling may require your system to go down for a moment when process takes place. Increasing resources on a server requires a restart and put your system down.

Another solution to this problem is increasing the amount of servers present in the system. This solution is highly used in the tech industry. This will eventually decrease the request per second rate in each server. If you need to scale the system, just add another server, and you are done. You would not be required to restart the system. Number of threads in each system decreases leading to high throughput. To segregate the requests, equally to each of the application server, you need to add load balancer which would act as reverse proxy to the web servers. This whole system can be called as a single cluster. Your system may contain a large number of requests which would require more amount of clusters like this.

Hope you get the whole concept of introducing scaling to the system.

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

Eclipse shows errors but I can't find them

I just removed all the private libraries in JavaBuildPath and added the jars again.. It worked

Get type name without full namespace

Try this to get type parameters for generic types:

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

Maybe not the best solution (due to the recursion), but it works. Outputs look like:

Dictionary<String, Object>

How to print an exception in Python 3?

Although if you want a code that is compatible with both python2 and python3 you can use this:

import logging
try:
    1/0
except Exception as e:
    if hasattr(e, 'message'):
        logging.warning('python2')
        logging.error(e.message)
    else:
        logging.warning('python3')
        logging.error(e)

Shared folder between MacOSX and Windows on Virtual Box

I had the exact same issue, after rightly have configured in Mac OSX host a SharedFolder with Auto-Mount enabled. On the Guest OS, it is also required to install VirtualBox Guest Additions. For the case of Windows, it is:

VBoxWindowsAdditions.exe

Right after this installation, i could perfectly view the shared folder content under This PC and Network ("\VBOXSVR\Installers").

VB.NET - How to move to next item a For Each Loop?

I'd use the Continue statement instead:

For Each I As Item In Items

    If I = x Then
        Continue For
    End If

    ' Do something

Next

Note that this is slightly different to moving the iterator itself on - anything before the If will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator() and then MoveNext()/Current explicitly rather than using a For Each loop.

Why use $_SERVER['PHP_SELF'] instead of ""

I know that the question is two years old, but it was the first result of what I am looking for. I found a good answers and I hope I can help other users.

Look at this

I will make this brief:

  • use the $_SERVER["PHP_SELF"] Variable with htmlspecialchars():

    `htmlspecialchars($_SERVER["PHP_SELF"]);`
    
  • PHP_SELF returns the filename of the currently executing script.

  • The htmlspecialchars() function converts special characters to HTML entities. --> NO XSS

Return anonymous type results?

Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type?

Use use object to return a list of Anonymous types without creating a custom type. This will work without the compiler error (in .net 4.0). I returned the list to the client and then parsed it on JavaScript:

public object GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result;
}

How can I force browsers to print background images in CSS?

Use psuedo-elements. While many browsers will ignore background images, psuedo-elements with their content set to an image are technically NOT background images. You can then position the background image roughly where the image should have gone (though it's not as easy or precise as the original image).

One drawback is that for this to work in Chrome, you need to specify this behavior outside of your print media query, and then make it visible in the print media query block. So, something like this...

.image:before{
        visibility:hidden;
        position:absolute;
        content: url("your/image/path");
    }   

@media print {
.image{
   position:relative;
    }
    .image:before{
       visibility:visible;
       top:etc...
    }       
}

The drawback is that the image will often be downloaded on normal page loads, adding unnecessary bulk. You can avoid that by just using the same image/path you'd already used for the original, visible image.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.

This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.

If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:

s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T

On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE

attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY 

Eclipse Workspaces: What for and why?

Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.

Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.

Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).

So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.

How to call servlet through a JSP page

You can use RequestDispatcher as you usually use it in Servlet:

<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
     RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);
%>

Always be aware that don't commit any response before you use forward, as it will lead to IllegalStateException.

How can I read large text files in Python, line by line, without loading it into memory?

Heres the code for loading text files of any size without causing memory issues. It support gigabytes sized files

https://gist.github.com/iyvinjose/e6c1cb2821abd5f01fd1b9065cbc759d

download the file data_loading_utils.py and import it into your code

usage

import data_loading_utils.py.py
file_name = 'file_name.ext'
CHUNK_SIZE = 1000000


def process_lines(data, eof, file_name):

    # check if end of file reached
    if not eof:
         # process data, data is one single line of the file

    else:
         # end of file reached

data_loading_utils.read_lines_from_file_as_data_chunks(file_name, chunk_size=CHUNK_SIZE, callback=self.process_lines)

process_lines method is the callback function. It will be called for all the lines, with parameter data representing one single line of the file at a time.

You can configure the variable CHUNK_SIZE depending on your machine hardware configurations.

Opacity CSS not working in IE8

Setting these (exactly like I have written) has served me when I needed it:

-moz-opacity: 0.70;
opacity:.70;
filter: alpha(opacity=70);

When should one use a spinlock instead of mutex?

Mecki's answer pretty well nails it. However, on a single processor, using a spinlock might make sense when the task is waiting on the lock to be given by an Interrupt Service Routine. The interrupt would transfer control to the ISR, which would ready the resource for use by the waiting task. It would end by releasing the lock before giving control back to the interrupted task. The spinning task would find the spinlock available and proceed.

How do I evenly add space between a label and the input field regardless of length of text?

2019 answer:

Some time has passed and I changed my approach now when building forms. I've done thousands of them till today and got really tired of typing id for every label/input pair, so this was flushed down the toilet. When you dive input right into the label, things work the same way, no ids necessary. I also took advantage of flexbox being, well, very flexible.

HTML:

<label>
  Short label <input type="text" name="dummy1" />
</label>

<label>
  Somehow longer label <input type="text" name="dummy2" />
</label>

<label>
  Very long label for testing purposes <input type="text" name="dummy3" />
</label>

CSS:

label {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  text-align: right;
  width: 400px;
  line-height: 26px;
  margin-bottom: 10px;
}

input {
  height: 20px;
  flex: 0 0 200px;
  margin-left: 10px;
}

Fiddle DEMO


Original answer:

Use label instead of span. It's meant to be paired with inputs and preserves some additional functionality (clicking label focuses the input).

This might be exactly what you want:

HTML:

<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">

<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">

<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">

CSS:

label {
    width:180px;
    clear:left;
    text-align:right;
    padding-right:10px;
}

input, label {
    float:left;
}

jsfiddle DEMO here.

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.

See also these very similar questions:

Here's an example, as demonstrated in this jsFiddle:

<html><head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
    <a class="checked" href="http://www.google.com">Click here</a>
    <script type="text/javascript">

        $(function() {
            $('.checked').click(function(e) {
                e.preventDefault();
                var dialog = $('<p>Are you sure?</p>').dialog({
                    buttons: {
                        "Yes": function() {alert('you chose yes');},
                        "No":  function() {alert('you chose no');},
                        "Cancel":  function() {
                            alert('you chose cancel');
                            dialog.dialog('close');
                        }
                    }
                });
            });
        });

    </script>
</body><html>

invalid new-expression of abstract class type

invalid new-expression of abstract class type 'box'

There is nothing unclear about the error message. Your class box has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.

If this is a bug, fix your box class by implementing the missing member(s).

If it's by design, derive from box, implement the missing member(s) and use the derived class.

Before and After Suite execution hook in jUnit 4.x

As for "Note: we're using maven 2 for our build. I've tried using maven's pre- & post-integration-test phases, but, if a test fails, maven stops and doesn't run post-integration-test, which is no help."

you can try the failsafe-plugin instead, I think it has the facility to ensure cleanup occurs regardless of setup or intermediate stage status

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

Make Font Awesome icons in a circle?

UPDATE:

Upon learning flex recently, there is a cleaner way (no tables and less css). Set the wrapper as display: flex; and to center it's children give it the properties align-items: center; for (vertical) and justify-content: center; (horizontal) centering.

See this updated JS Fiddle


Strange that nobody suggested this before.. I always use tables to do this.
Simply make a wrapper have display: table and center stuff inside it with text-align: center for horizontal and vertical-align: middle for vertical alignment.

<div class='wrapper'>
  <i class='icon fa fa-bars'></i>
</div>

and some sass like this

.wrapper{
  display: table; 

  i{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }

}

or see this JS Fiddle

Why is AJAX returning HTTP status code 0?

For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.

Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.

How to format DateTime in Flutter , How to get current time in flutter?

With this approach, there is no need to import any library.

DateTime now = DateTime.now();

String convertedDateTime = "${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString()}-${now.minute.toString()}";

Output

2020-12-05 14:57

Pass Javascript Array -> PHP

You can transfer array from javascript to PHP...

Javascript... ArraySender.html

<script language="javascript">

//its your javascript, your array can be multidimensional or associative

plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info'; 
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3'; 
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4'; 
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5'; 

function convertJsArr2Php(JsArr){
    var Php = '';
    if (Array.isArray(JsArr)){  
        Php += 'array(';
        for (var i in JsArr){
            Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
            if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
                Php += ', ';
            }
        }
        Php += ')';
        return Php;
    }
    else{
        return '\'' + JsArr + '\'';
    }
}


function ajaxPost(str, plArrayC){
    var xmlhttp;
    if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
    else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    xmlhttp.open("POST",str,true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send('Array=' + plArrayC);
}

ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>

and PHP Code... ArrayReader.php

<?php 

eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);

?>

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

Switch statement for greater-than/less-than

Untested and unsure if this will work, but why not do a few if statements before, to set variables for the switch statement.

var small, big;

if(scrollLeft < 1000){
    //add some token to the page
    //call it small
}


switch (//reference token/) {
  case (small):
   //do stuff
   break;
  case (big):
   //do stuff;
   break;
}

The controller for path was not found or does not implement IController

Also, for those who the solution above didn't work, here's is what worked for me:

I have a solution with multiple projects. All projects were in MVC3. I installed Visual Studio 2012 in my machine and it seems that some projects were automatically upgraded to MVC4.

I got this problem

The controller for path '/etc/etc' was not found or does not implement IController

because the project that handled that route was pointing to MVC4.

I had to manually update their references to use MVC3. You can also do that by opening the .csproj file with a text editor. Find the reference to MVC3 and remove this line:

<SpecificVersion>False</SpecificVersion>

How to find out if a file exists in C# / .NET?

I use WinForms and my way to use File.Exists(string path) is the next one:

public bool FileExists(string fileName)
{
    var workingDirectory = Environment.CurrentDirectory;
    var file = $"{workingDirectory}\{fileName}";
    return File.Exists(file);
}

fileName must include the extension like myfile.txt

Android - default value in editText

First you need to load the user details somehow

Then you need to find your EditText if you don't have it-

EditText et = (EditText)findViewById(R.id.youredittext);

after you've found your EditText, call

et.setText(theUserName);

Read and overwrite a file in Python

Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.

How to upgrade Git on Windows to the latest version?

Just run:

$ git update-git-for-windows

How to add the text "ON" and "OFF" to toggle button

    .switch
    {
            width: 50px;
            height: 30px;
            position: relative;
            display:inline-block;
    }

    .switch input
    {
            display: none;
    }

    .slider
    {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
            cursor: pointer;
            background-color: gray;
            border-radius: 30px;

    }
    .slider:before
    {

        position: absolute;
        background-color: #fff;
        height: 20px;
        width: 20px;
        content: "";
        left: 5px;
        bottom: 5px;
        border-radius: 50%;
        transition: ease-in-out .5s;
    }

    .slider:after
    {
        content: "Off";

        color: white;
        display: block;
        position: absolute;
        transform: translate(-50%,-50%);
        top: 50%;
        left: 70%;
        transition: all .5s;
        font-size: 10px;
        font-family: Verdana,sans-serif;
    }

    input:checked + .slider:after
    {
        transition: all .5s;
        left: 30%;
        content: "On"

    }
    input:checked + .slider
    {
        background-color: blue;

    }

    input:checked + .slider:before
    {
        transform: translateX(20px);
    }



    **The HTML CODE**

    <label class="switch">

                <input type="checkbox"/>

                 <div class="slider">

                </div>
        </label>


If You want to add long text like activate or Deactivate

just make few changes 

.switch
{
        width:90px
}
.slider:after
{
     left: 60%; //as you want in percenatge
}
input:checked + .slider:after
{
       left:40%; //exactly opposite of .slider:after 
}

and last

input:checked + .slider:before
{
    transform: translateX(60px); //as per your choice but 60px is perfect
}

content as per your choice where you have witten "On" and "Off"

What is the proper way to re-attach detached objects in Hibernate?

Property hibernate.allow_refresh_detached_entity did the trick for me. But it is a general rule, so it is not very suitable if you want to do it only in some cases. I hope it helps.

Tested on Hibernate 5.4.9

SessionFactoryOptionsBuilder

Source file not compiled Dev C++

This error occurred because your settings are not correct.

For example I receive

cannot open output file Project1.exe: Permission denied
collect2.exe: error: ld returned 1 exit status

mingw32-make.exe: *** [Project1.exe] Error 1

Because I have no permission to write on my exe file.

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

When do I have to use interfaces instead of abstract classes?

Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .

Interface : It define just protocol which all subclass need to follow.

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

Homebrew: Could not symlink, /usr/local/bin is not writable

My problem was

Error: Could not symlink share/man/man7/ABORT.7
/usr/local/share/man/man7 is not writable.

chown didn't help, but i followed running brew doctor advices and this warning helped me:

Warning: Broken symlinks were found. Remove them with `brew prune`:
/usr/local/share/man/man3/* 

After brew prune all worked fine!

Java Multiple Inheritance

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

class A {  
    void msg() {
        System.out.println("From A");
    }  
}

class B {  
    void msg() {
        System.out.println("From B");
    }  
}

class C extends A,B { // suppose if this was possible
    public static void main(String[] args) {  
        C obj = new C();  
        obj.msg(); // which msg() method would be invoked?  
    }
} 

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

How to convert Set<String> to String[]?

Set<String> stringSet= new HashSet<>();
String[] s = (String[])stringSet.toArray();

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

Javascript form validation with password confirming

 if ($("#Password").val() != $("#ConfirmPassword").val()) {
          alert("Passwords do not match.");
      }

A JQuery approach that will eliminate needless code.

Tools for creating Class Diagrams

I've used Enterprise Architect in the past - not free, but not too expensive, and it produces nice diagrams.

Counting the Number of keywords in a dictionary in python

If the question is about counting the number of keywords then would recommend something like

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

in the main function have something that loops through the data and pass the values to countoccurrences function

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

The code outputs

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

Can't push to remote branch, cannot be resolved to branch

I ran into the same issue and noticed that I had mixed up the casing while checking out the branch. I checked out branchName instead of BranchName and when I tried to push to remote, I got the same error.

The fix:

git push --set-upstream origin BranchName

By setting upstream to the correct name, the correct branch was updated on github and I was then able to checkout the correct branch name with

git checkout BranchName 

And it should be up to date with your last push.

Passing data to a jQuery UI Dialog

Ok the first issue with the div tag was easy enough: I just added a style="display:none;" to it and then before showing the dialog I added this in my dialog script:

$("#dialog").css("display", "inherit");

But for the post version I'm still out of luck.

CSS customized scroll bar in div

Custom scroll bars aren't possible with CSS, you'll need some JavaScript magic.

Some browsers support non-spec CSS rules, such as ::-webkit-scrollbar in Webkit but is not ideal since it'll only work in Webkit. IE had something like that too, but I don't think they support it anymore.

Get the ID of a drawable in ImageView

I answered something like this in another question already, but will change it just a little for this one.

Unfortunately, there is no getImageResource() or getDrawableId(). But, I created a simple workaround by using the ImageView tags.

In onCreate():

imageView0 = (ImageView) findViewById(R.id.imageView0);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);

imageView0.setTag(R.drawable.apple);
imageView1.setTag(R.drawable.banana);
imageView2.setTag(R.drawable.cereal);

Then, if you like, you can create a simple function to get the drawable id:

private int getDrawableId(ImageView iv) {
    return (Integer) iv.getTag();
}

Too easy.

Search of table names

I'm using this and works fine

SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '%%'

Writing sqlplus output to a file

just to save my own deductions from all this is (for saving DBMS_OUTPUT output on the client, using sqlplus):

  • no matter if i use Toad/with polling or sqlplus, for a long running script with occasional dbms_output.put_line commands, i will get the output in the end of the script execution
  • set serveroutput on; and dbms_output.enable(); should be present in the script
  • to save the output SPOOL command was not enough to get the DBMS_OUTPUT lines printed to a file - had to use the usual > windows CMD redirection. the passwords etc. can be given to the empty prompt, after invoking sqlplus. also the "/" directives and the "exit;" command should be put either inside the script, or given interactively as the password above (unless it is specified during the invocation of sqlplus)

Objective-C and Swift URL encoding

This is how I am doing this in swift.

extension String {
    func encodeURIComponent() -> String {
        return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    }

    func decodeURIComponent() -> String {
        return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
    }
}

How do I remove/delete a folder that is not empty?

To delete a folder even if it might not exist (avoiding the race condition in Charles Chow's answer) but still have errors when other things go wrong (e.g. permission problems, disk read error, the file isn't a directory)

For Python 3.x:

import shutil

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, FileNotFoundError):
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

The Python 2.7 code is almost the same:

import shutil
import errno

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, OSError) and \
        except_instance.errno == errno.ENOENT:
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

SQL Server procedure declare a list

Alternative to @Peter Monks.

If the number in the 'in' statement is small and fixed.

DECLARE @var1 varchar(30), @var2 varchar(30), @var3  varchar(30);

SET @var1 = 'james';
SET @var2 = 'same';
SET @var3 = 'dogcat';

Select * FROM Database Where x in (@var1,@var2,@var3);

Modifying a query string without reloading the page

I've used the following JavaScript library with great success:

https://github.com/balupton/jquery-history

It supports the HTML5 history API as well as a fallback method (using #) for older browsers.

This library is essentially a polyfill around `history.pushState'.

How do you do block comments in YAML?

For Visual Studio Code (VSCode) users, the shortcut to comment out multiple lines is to highlight the lines you want to comment and then press:

ctrl + /

Pressing ctrl + / again can also be used to toggle comments off for one or more selected lines.

converting list to json format - quick and easy way

If you are using WebApi, HttpResponseMessage is a more elegant way to do it

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

irb(main):005:0> {}.class
=> Hash
irb(main):006:0> [].class
=> Array

Checking if element exists with Python Selenium

driver.find_element_by_id("some_id").size() is class method.

What we need is :

driver.find_element_by_id("some_id").size which is dictionary so :

if driver.find_element_by_id("some_id").size['width'] != 0 : print 'button exist'

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

How to trap on UIViewAlertForUnsatisfiableConstraints?

Followed Stephen's advice and tried to debug the code and whoa! it worked. The answer lies in the debug message itself.

Will attempt to recover by breaking constraint NSLayoutConstraint:0x191f0920 H:[MPKnockoutButton:0x17a876b0]-(34)-[MPDetailSlider:0x17a8bc50](LTR)>

The line above tells you that the runtime worked by removing this constraint. May be you don't need Horizontal Spacing on your button (MPKnockoutButton). Once you clear this constraint, it won't complain at runtime & you would get the desired behaviour.

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

Round to 5 (or other number) in Python

round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...

def round5(x):
    return int(round(x*2, -1)) / 2

Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shifting

def round5(x):
    return int(round(x << 1, -1)) >> 1

error: pathspec 'test-branch' did not match any file(s) known to git

You can also get this error with any version of git if the remote branch was created after your last clone/fetch and your local repo doesn't know about it yet. I solved it by doing a git fetch first which "tells" your local repo about all the remote branches.

git fetch
git checkout test-branch

How do I print an IFrame from javascript in Safari/Chrome

Put a print function in the iframe and call it from the parent.

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()

Sys is undefined

I was using telerik and had exactly same problem.

adding this to web.config resolved my issue :)

<location path="Telerik.Web.UI.WebResource.axd">   
   <system.web>  
     <authorization>  
       <allow users="*"/>  
     </authorization>  
   </system.web>  
</location>

maybe it will help you too. it was Authentication problem.

Source

Undo git pull, how to bring repos to old state

Suppose $COMMIT was the last commit id before you performed git pull. What you need to undo the last pull is

git reset --hard $COMMIT

.

Bonus:

In speaking of pull, I would like to share an interesting trick,

git pull --rebase

This above command is the most useful command in my git life which saved a lots of time.

Before pushing your newly commit to server, try this command and it will automatically sync latest server changes (with a fetch + merge) and will place your commit at the top in git log. No need to worry about manual pull/merge.

Find details at: http://gitolite.com/git-pull--rebase

How do I set a VB.Net ComboBox default value

Another good method for setting a DropDownList style combobox:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You should only need to unbind the service in onDestroy(). Then, The warning will go.

See here.

As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().

Can Mysql Split a column?

It seems to work:

substring_index ( substring_index ( context,',',1 ), ',', -1) 
substring_index ( substring_index ( context,',',2 ), ',', -1)
substring_index ( substring_index ( context,',',3 ), ',', -1)
substring_index ( substring_index ( context,',',4 ), ',', -1)

it means 1st value, 2nd, 3rd, etc.

Explanation:

The inner substring_index returns the first n values that are comma separated. So if your original string is "34,7,23,89", substring_index( context,',', 3) returns "34,7,23".
The outer substring_index takes the value returned by the inner substring_index and the -1 allows you to take the last value. So you get "23" from the "34,7,23".
Instead of -1 if you specify -2, you'll get "7,23", because it took the last two values.

Example:

select * from MyTable where substring_index(substring_index(prices,',',1),',',-1)=3382;

Here, prices is the name of a column in MyTable.

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

Where can I download Eclipse Android bundle?

Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from

ADT for Eclipse

How to check for a JSON response using RSpec?

Simple and easy to way to do this.

# set some variable on success like :success => true in your controller
controller.rb
render :json => {:success => true, :data => data} # on success

spec_controller.rb
parse_json = JSON(response.body)
parse_json["success"].should == true

How can I access Oracle from Python?

import cx_Oracle
   dsn_tns = cx_Oracle.makedsn('host', 'port', service_name='give service name') 
   conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns) 
   c = conn.cursor()
   c.execute('select count(*) from schema.table_name')
for row in c:
   print row
conn.close()

Note :

  1. In (dsn_tns) if needed, place an 'r' before any parameter in order to address any special character such as '\'.

  2. In (conn) if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name' or password=r'password'

  3. use triple quotes if you want to spread your query across multiple lines.

call javascript function onchange event of dropdown list

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

SQL Server: Filter output of sp_who2

I am writing here for future use of my own. It uses sp_who2 and insert into table variable instead of temp table because Temp table cannot be used twice if you do not drop it. And shows blocked and blocker at the same line.

--blocked: waiting becaused blocked by blocker
--blocker: caused blocking
declare @sp_who2 table(
    SPID int,
    Status varchar(max),
    Login varchar(max),
    HostName varchar(max),
    BlkBy varchar(max),
    DBName varchar(max),
    Command varchar(max),
    CPUTime int,
    DiskIO int,
    LastBatch varchar(max),
    ProgramName varchar(max),
    SPID_2 int,
    REQUESTID int
)
insert into @sp_who2 exec sp_who2
select  w.SPID blocked_spid, w.BlkBy blocker_spid, tblocked.text blocked_text, tblocker.text blocker_text
from    @sp_who2 w
        inner join sys.sysprocesses pblocked on w.SPID = pblocked.spid
        cross apply sys.dm_exec_sql_text(pblocked.sql_handle) tblocked
        inner join sys.sysprocesses pblocker on case when w.BlkBy = '  .' then 0 else cast(w.BlkBy as int) end = pblocker.spid
        cross apply sys.dm_exec_sql_text(pblocker.sql_handle) tblocker
where   pblocked.Status = 'SUSPENDED'

JPA Query.getResultList() - use in a generic way

The above query returns the list of Object[]. So if you want to get the u.name and s.something from the list then you need to iterate and cast that values for the corresponding classes.

How to start MySQL server on windows xp

mysql -u root -p

After entering this command in terminal, it will ask for password Enter the password and you are ready to go!

Insert HTML from CSS

No. The only you can do is to add content (and not an element) using :before or :after pseudo-element.

More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content

Is there a vr (vertical rule) in html?

As pointed out by others, the concept of a vertical rule does not fit in with the original ideas behind the structure and presentation of HTML documents. However, these days (especially with the proliferation of web-apps) there are is a small number of scenarios where this would indeed be useful.

For example, consider a horizontal navigation menu fixed at the top of the screen, similar to the menu-bar in most windowed GUI applications. You have several top-level menu items arranged from left-to-right which when clicked open up drop-down menus. Years ago, it was common practice to create this with a single-row table, but this is bad HTML and it is widely recognised that the correct way to go would be a list with heavily customised CSS.

Now, say you want to group similar items, but add a vertical separator in between groups, to achieve something like this:

[Item 1a] [Item 1b] | [Item 2a] [Item 2b]

Using <hr style="width: 1px; height: 100%; ..." /> works, but may be considered semantically incorrect as you are changing what that element is actually for. Furthermore, you can't use this within certain elements where the HTML DTD allows only inline-level elements (e.g. within a <span> element).

A better option would be <span style="display: inline-block; width:1px; height:100%; background:#000; margin: 0 2px;"></span>, however not all browsers support the display: inline-block; CSS property, so the only real inline-level option is to use an image like so:

<img src="pixel.gif" alt="|" style="width:1px; height:100%; background:#000; margin: 0 2px;" />

This has the added advantage of being compatible with text-only browsers (like lynx) as the pipe character is displayed instead of the image. (It still annoys me that M$IE incorrectly uses alt text as a tooltip; that's what the title attribute is for!)

A method to reverse effect of java String.split()?

Google also provides a joiner class in their Google Collections library:

Joiner API

Google Collections

sort csv by column

The reader acts like a generator. On a file with some fake data:

>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Using operator.itemgetter as Ignacio suggests:

>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]

VBA Go to last empty row

try this:

Sub test()

With Application.WorksheetFunction
    Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With

End Sub

Hope this works for you.

Calling a function when ng-repeat has finished

If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:

const dereg = scope.$watch('$$childTail.$last', last => {
    if (last) {
        dereg();
        // do yr stuff -- you may still need a $timeout here
    }
});

This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.

Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file

$("#register-form").submit(function (event) {

    var entrance = $(this).find('input[name="IsValid"]').val();
    var password = $(this).find('input[name="objPassword"]').val();
    var namesurname = $(this).find('input[name="objNameSurname"]').val();
    var email = $(this).find('input[name="objEmail"]').val();
    var gsm = $(this).find('input[name="objGsm"]').val();
    var adres = $(this).find('input[name="objAddress"]').val();
    var termsOk = $(this).find('input[name="objAcceptTerms"]').val();

    var formURL = $(this).attr("action");


    if (request) {
        request.abort(); // cancel if any process on pending
    }

    var postData = {
        "objAskGrant": entrance,
        "objPass": password,
        "objNameSurname": namesurname,
        "objEmail": email,
        "objGsm": parseInt(gsm),
        "objAdres": adres,
        "objTerms": termsOk
    };

    $.post(formURL,postData,function(data,status){
        console.log("Data: " + data + "\nStatus: " + status);
    });

    event.preventDefault();
});

PHP Edit:

 if (isset($_POST)) {

    $fValid = clear($_POST['objAskGrant']);
    $fTerms = clear($_POST['objTerms']);

    if ($fValid) {
        $fPass = clear($_POST['objPass']);
        $fNameSurname = clear($_POST['objNameSurname']);
        $fMail = clear($_POST['objEmail']);
        $fGsm = clear(int($_POST['objGsm']));
        $fAddress = clear($_POST['objAdres']);
        $UserIpAddress = "hidden";
        $UserCityLocation = "hidden";
        $UserCountry = "hidden";

        $DateTime = new DateTime();
        $result = $date->format('d-m-Y-H:i:s');
        $krr = explode('-', $result);
        $resultDateTime = implode("", $krr);

        $data = array('error' => 'Yükleme Sirasinda Hata Olustu');

        $kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
        $retval = mysql_query( $kayit, $conn ); // Update with you connection details
            if ($retval) {
                $data = array('success' => 'Register Completed', 'postData' => $_POST);
            }

        } // valid ends
    }echo json_encode($data);

Start / Stop a Windows Service from a non-Administrator user account

It's significantly easier to grant management permissions to a service using one of these tools:

  • Group Policy
  • Security Template
  • subinacl.exe command-line tool.

Here's the MSKB article with instructions for Windows Server 2008 / Windows 7, but the instructions are the same for 2000 and 2003.

Proper indentation for Python multiline strings

The textwrap.dedent function allows one to start with correct indentation in the source, and then strip it from the text before use.

The trade-off, as noted by some others, is that this is an extra function call on the literal; take this into account when deciding where to place these literals in your code.

import textwrap

def frobnicate(param):
    """ Frobnicate the scrognate param.

        The Weebly-Ruckford algorithm is employed to frobnicate
        the scrognate to within an inch of its life.

        """
    prepare_the_comfy_chair(param)
    log_message = textwrap.dedent("""\
            Prepare to frobnicate:
            Here it comes...
                Any moment now.
            And: Frobnicate!""")
    weebly(param, log_message)
    ruckford(param)

The trailing \ in the log message literal is to ensure that line break isn't in the literal; that way, the literal doesn't start with a blank line, and instead starts with the next full line.

The return value from textwrap.dedent is the input string with all common leading whitespace indentation removed on each line of the string. So the above log_message value will be:

Prepare to frobnicate:
Here it comes...
    Any moment now.
And: Frobnicate!

How do I kill this tomcat process in Terminal?

this works very well (find tomcat processes and kill them forcibly)

ps -ef | grep tomcat | awk '{print $2}' | xargs kill -9

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

How to ping an IP address

This should work:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Pinger {

private static String keyWordTolookFor = "average";

public Pinger() {
    // TODO Auto-generated constructor stub
}


 public static void main(String[] args) {
 //Test the ping method on Windows.
 System.out.println(ping("192.168.0.1")); }


public String ping(String IP) {
    try {
        String line;
        Process p = Runtime.getRuntime().exec("ping -n 1 " + IP);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (((line = input.readLine()) != null)) {

            if (line.toLowerCase().indexOf(keyWordTolookFor.toLowerCase()) != -1) {

                String delims = "[ ]+";
                String[] tokens = line.split(delims);
                return tokens[tokens.length - 1];
            } 
        }

        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
    return "Offline";
}

}

Automatic prune with Git fetch or pull

git config --global fetch.prune true

To always --prune for git fetch and git pull in all your Git repositories:

git config --global fetch.prune true

This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

[fetch]
    prune = true

git config remote.origin.prune true

To always --prune but from one single repository:

git config remote.origin.prune true
                 #^^^^^^
                 #replace with your repo name

This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

[remote "origin"]
    url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    fetch = +refs/heads/*:refs/remotes/origin/*
    prune = true

You can also use --global within the second command or use instead --local within the first command.


git config --global gui.pruneDuringFetch true

If you use git gui you may also be interested by:

git config --global gui.pruneDuringFetch true

that appends:

[gui]
    pruneDuringFetch = true

References

The corresponding documentations from git help config:

--global

  For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

 

--local

  For writing options: write to the repository .git/config file. This is the default behavior.

 

fetch.prune

  If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

 

gui.pruneDuringFetch

  "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

 

remote.<name>.prune

  When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

In my case, my xml had multiple namespaces and attributes. So I used this site to generate the objects - https://xmltocsharp.azurewebsites.net/

And used the below code to deserialize

 XmlDocument doc =  new XmlDocument();
        doc.Load("PathTo.xml");
        User obj;
        using (TextReader textReader = new StringReader(doc.OuterXml))
        {
            using (XmlTextReader reader = new XmlTextReader(textReader))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(User));
                obj = (User)serializer.Deserialize(reader);
            }
        }

How to show the Project Explorer window in Eclipse

Using the latest Luna upgrade. The only solution that worked was Window >> New Window. It's very easy to lose that critical bar.

Printing leading 0's in C

If you need to store the ZIP Code in a character array, zipcode[], you can use this:

snprintf(zipcode, 6, "%05.5d", atoi(zipcode));

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Embed a PowerPoint presentation into HTML

DocStoc.com and Scribd.com both work well with Internet Explorer 6 and Internet Explorer 7. They'll show a variety of document types, including PowerPoint files (.ppt). I use these services for my intranet here at work. Of course, just remember to mark your documents as 'private' after you upload them.

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

Is there 'byte' data type in C++?

if you are using windows, in WinDef.h you have:

typedef unsigned char BYTE;

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

Method to Add new or update existing item in Dictionary

Functionally, they are equivalent.

Performance-wise map[key] = value would be quicker, as you are only making single lookup instead of two.

Style-wise, the shorter the better :)

The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.

What does the term "canonical form" or "canonical representation" in Java mean?

canonical representation means view the character in different style for example if I write a letter A means another person may write the letter A in different style:)

This is according to OPTICAL CHARACTER RECOGNITION FIELD

Specified cast is not valid.. how to resolve this

If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

Count number of rows by group using dplyr

Another option, not necesarily more elegant, but does not require to refer to a specific column:

mtcars %>% 
  group_by(cyl, gear) %>%
  do(data.frame(nrow=nrow(.)))

Converting Varchar Value to Integer/Decimal Value in SQL Server

The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2), it should work

 SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table

OR

 SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table

How to Export-CSV of Active Directory Objects?

the first command is correct but change from convert to export to csv, as below,

Get-ADUser -Filter * -Properties * `
    | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
    | Sort-Object -Property Name `
    | Export-Csv -path  C:\Users\*\Desktop\file1.csv

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

The Best solution that works in most cases is

Here is an example:

<ImageView android:id="@+id/avatar"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:scaleType="fitXY"/>

Make hibernate ignore class variables that are not mapped

JPA will use all properties of the class, unless you specifically mark them with @Transient:

@Transient
private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

In docker image of PHP-FPM, i've see such approach:

# cat /usr/local/etc/php-fpm.d/docker.conf
[global]
error_log = /proc/self/fd/2

[www]
; if we send this to /proc/self/fd/1, it never appears
access.log = /proc/self/fd/2

Node.js: for each … in not working

Unfortunately node does not support for each ... in, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.

You'll have to settle for array.forEach(function(item) { /* etc etc */ }).

EDIT: From Google's official V8 website:

V8 implements ECMAScript as specified in ECMA-262.

On the same MDN website where it says that for each ...in is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.

How to compare character ignoring case in primitive types

Generic methods to compare a char at a position between 2 strings with ignore case.

public static boolean isEqualIngoreCase(char one, char two){
    return Character.toLowerCase(one)==Character .toLowerCase(two);
}

public static boolean isEqualStringCharIgnoreCase(String one, String two, int position){
    char oneChar = one.charAt(position);
    char twoChar = two.charAt(position);
    return isEqualIngoreCase(oneChar, twoChar);
}

Function call

boolean isFirstCharEqual = isEqualStringCharIgnoreCase("abc", "ABC", 0)

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

How to clean project cache in Intellij idea like Eclipse's clean?

Maybe not THE answer, but it's definitely AN answer.

If nothing else is working for you, go the nuclear option: Close IDEA and delete the ".../.IntelliJIdea/system" directory using your local file system tools.

The .IntelliJIdea directory is usually found in your home directory. Your IDE configuration is in the ".../.IntelliJIdea/config" directory, so it should be fine.

Obviously, this is not the "IDEA" way to do it and would be completely unsupported by JetBrains. Also - I don't use Android Studio so I dunno if this will cause problems, but there you go.

It's worked for me before when I've had problems getting IDEA to start and nothing else works to get me going. Maybe back up your entire .IntelliJIdea directory if you have a morbid fear of losing all your work >.<

EntityType has no key defined error

All is right but in my case i have two class like this

namespace WebAPI.Model
{
   public class ProductsModel
{ 
        [Table("products")]
        public class Products
        {
            [Key]
            public int slno { get; set; }

            public int productId { get; set; }
            public string ProductName { get; set; }

            public int Price { get; set; }
}
        }
    }

After deleting the upper class it works fine for me.

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

How to detect control+click in Javascript from an onclick div attribute?

Try this:

var control = false;
$(document).on('keyup keydown', function(e) {
  control = e.ctrlKey;
});

$('div#1').on('click', function() {
  if (control) {
    // control-click
  } else {
    // single-click
  }
});

And the right-click triggers a contextmenu event, so:

$('div#1').on('contextmenu', function() {
  // right-click handler
})

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

How can I change the color of pagination dots of UIPageControl?

Adding to existing answers, it can be done like,

enter image description here

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

For me, the problem was a typo on my ~/.ssh/config file. I had:

Host host1:
  HostName 10.10.1.1
  User jlyonsmith

The problem was the : after the host1 - it should not be there. ssh gives no warnings for typos in the ~/.ssh/config file. When it can't find host1 it looks for the machine locally, can't find it and prints the cryptic error message.

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.