Programs & Examples On #Winhttprequest

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Another option is to ask IDEA to behave like eclipse with eclipse shortcut keys. You can use all eclipse shortcuts by enabling this.

Here are the steps:

1- With IDEA open, press Control + `. Following options will be popped up.

enter image description here

2- Select Keymap. You will see another pop-up. Select Eclipse there.

enter image description here

3- Now press Ctrl + Shift + O. You are done!

Proper way to get page content

get page content by page name:

<?php
$page = get_page_by_title( 'page-name' );
$content = apply_filters('the_content', $page->post_content); 
echo $content;
?>

Visual Studio SignTool.exe Not Found

1.Just Disable signing from the properties of your project it will solve issue :)
2.The other method is to purchase the certificate for your product from Digicert or Comodo or any other you want. You can get some free certificates for One pc use.

Set value of hidden input with jquery

$('input[name="testing"]').val(theValue);

Android: Test Push Notification online (Google Cloud Messaging)

Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool

ArrayAdapter in android to create simple listview

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

Here, resource means the 'id' of the Layout you are using while instantiating the view.

Now, this layout has many child views with their own ids. So, textViewResourceId tells which child view we need to populate with the data.

How to create a backup of a single table in a postgres database?

If you prefer a graphical user interface, you can use pgAdmin III (Linux/Windows/OS X). Simply right click on the table of your choice, then "backup". It will create a pg_dump command for you.

enter image description here

enter image description here

enter image description here

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

if you don't care about performances for errors this is the smallest you can do

Object.setPrototypeOf(MyError.prototype, Error.prototype)
function MyError(message) {
    const error = new Error(message)
    Object.setPrototypeOf(error, MyError.prototype);
    return error
}

you can use it without new just MyError(message)

By changing the prototype after the constructor Error is called we don't have to set the callstack and message

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Try the following:

if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
    update PageImage
    set VisitCount=1
    where PID=@pid and PageNumber=@pageno
end 
else
begin
    update PageImage 
    set VisitCount=VisitCount+1
    where PID=@pid and PageNumber=@pageno
end

What is the difference between React Native and React?

React vs React Native

ReactJS

  • React is used for creating websites, web apps, SPAs etc.

  • React is a Javascript library used for creating UI hierarchy.

  • It is responsible for rendering of UI components, It is considered as V part Of MVC framework.

  • React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time.

  • React uses components as basic unit of UI which can be reused this saves coding time. Simple and easy to learn.

    React Native

  • React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios.

  • React native have all the benefits of ReactJS

  • React native allows developers to create native apps in web-style approach.

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

In my case, I was passsing all models 'Users' to column and it wasn't mapped correctly, so I just passed 'Users.Name' and it fixed it.

var data = db.ApplicationTranceLogs 
             .Include(q=>q.Users)
             .Include(q => q.LookupItems) 
             .Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users,*** ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data }) 
             .ToList();

var data = db.ApplicationTranceLogs 
             .Include(q=>q.Users).Include(q => q.LookupItems) 
             .Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users.Name***, ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data }) 
             .ToList();

Run a controller function whenever a view is opened/shown

If you have assigned a certain controller to your view, then your controller will be invoked every time your view loads. In that case, you can execute some code in your controller as soon as it is invoked, for example this way:

<ion-nav-view ng-controller="indexController" name="other" ng-init="doSomething()"></ion-nav-view>

And in your controller:

app.controller('indexController', function($scope) {
    /*
        Write some code directly over here without any function,
        and it will be executed every time your view loads.
        Something like this:
    */
    $scope.xyz = 1;
});

Edit: You might try to track state changes and then execute some code when the route is changed and a certain route is visited, for example:

$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ ... })

You can find more details here: State Change Events.

jQuery.each - Getting li elements inside an ul

$(function() {
    $('.phrase .items').each(function(i, items_list){
        var myText = "";

        $(items_list).find('li').each(function(j, li){
            alert(li.text());
        })

        alert(myText);

    });
};

How to style the <option> with only CSS?

EDIT 2015 May

Disclaimer: I've taken the snippet from the answer linked below:

Important Update!

In addition to WebKit, as of Firefox 35 we'll be able to use the appearance property:

Using -moz-appearance with the none value on a combobox now remove the dropdown button

So now in order to hide the default styling, it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

For IE 11 support, you can use [::-ms-expand][15].

select::-ms-expand { /* for IE 11 */
    display: none;
}

Old Answer

Unfortunately what you ask is not possible by using pure CSS. However, here is something similar that you can choose as a work around. Check the live code below.

_x000D_
_x000D_
div { _x000D_
  margin: 10px;_x000D_
  padding: 10px; _x000D_
  border: 2px solid purple; _x000D_
  width: 200px;_x000D_
  -webkit-border-radius: 5px;_x000D_
  -moz-border-radius: 5px;_x000D_
  border-radius: 5px;_x000D_
}_x000D_
div > ul { display: none; }_x000D_
div:hover > ul {display: block; background: #f9f9f9; border-top: 1px solid purple;}_x000D_
div:hover > ul > li { padding: 5px; border-bottom: 1px solid #4f4f4f;}_x000D_
div:hover > ul > li:hover { background: white;}_x000D_
div:hover > ul > li:hover > a { color: red; }
_x000D_
<div>_x000D_
  Select_x000D_
  <ul>_x000D_
    <li><a href="#">Item 1</a></li>_x000D_
    <li><a href="#">Item 2</a></li>_x000D_
    <li><a href="#">Item 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EDIT

Here is the question that you asked some time ago. How to style a <select> dropdown with CSS only without JavaScript? As it tells there, only in Chrome and to some extent in Firefox you can achieve what you want. Otherwise, unfortunately, there is no cross browser pure CSS solution for styling a select.

HTML tag inside JavaScript

<div id="demo"></div>

<input type="submit" name="submit" id="submit" value="Submit" onClick="return empty()">


<script type="text/javascript">
        function empty()
        {
          var x;
          x = document.getElementById("feedbackpost").value;
          if (x == "")
           {
             var demo = document.getElementById("demo");
             demo.innerHTML =document.write='<h1>Hello member</h1>';
              return false;
           };
        }
    </script>

Is it possible to style a mouseover on an image map using CSS?

CSS Only:

Thinking about it on my way to the supermarket, you could of course also skip the entire image map idea, and make use of :hover on the elements on top of the image (changed the divs to a-blocks). Which makes things hell of a lot simpler, no jQuery needed...

Short explanation:

  • Image is in the bottom
  • 2 x a with display:block and absolute positioning + opacity:0
  • Set opacity to 0.2 on hover

Example:

_x000D_
_x000D_
.area {_x000D_
    background:#fff;_x000D_
    display:block;_x000D_
    height:475px;_x000D_
    opacity:0;_x000D_
    position:absolute;_x000D_
    width:320px;_x000D_
}_x000D_
#area2 {_x000D_
    left:320px;_x000D_
}_x000D_
#area1:hover, #area2:hover {_x000D_
    opacity:0.2;_x000D_
}
_x000D_
<a id="area1" class="area" href="#"></a>_x000D_
<a id="area2" class="area" href="#"></a>_x000D_
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/640px-Saimiri_sciureus-1_Luc_Viatour.jpg" width="640" height="475" />
_x000D_
_x000D_
_x000D_

Original Answer using jQuery

I just created something similar with jQuery, I don't think it can be done with CSS only.

Short explanation:

  • Image is in the bottom
  • Divs with rollover (image or color) with absolute positioning + display:none
  • Transparent gif with the actual #map is on top (absolute position) (to prevent call to mouseout when the rollovers appear)
  • jQuery is used to show/hide the divs

_x000D_
_x000D_
    $(document).ready(function() {_x000D_
        if($('#location-map')) {_x000D_
            $('#location-map area').each(function() {_x000D_
                var id = $(this).attr('id');_x000D_
                $(this).mouseover(function() {_x000D_
                    $('#overlay'+id).show();_x000D_
                    _x000D_
                });_x000D_
                _x000D_
                $(this).mouseout(function() {_x000D_
                    var id = $(this).attr('id');_x000D_
                    $('#overlay'+id).hide();_x000D_
                });_x000D_
            _x000D_
            });_x000D_
        }_x000D_
    });
_x000D_
body,html {_x000D_
    margin:0;_x000D_
}_x000D_
#emptygif {_x000D_
    position:absolute;_x000D_
    z-index:200;_x000D_
}_x000D_
#overlayr1 {_x000D_
    position:absolute;_x000D_
    background:#fff;_x000D_
    opacity:0.2;_x000D_
    width:300px;_x000D_
    height:160px;_x000D_
    z-index:100;_x000D_
    display:none;_x000D_
}_x000D_
#overlayr2 {_x000D_
    position:absolute;_x000D_
    background:#fff;_x000D_
    opacity:0.2;_x000D_
    width:300px;_x000D_
    height:160px;_x000D_
    top:160px;_x000D_
    z-index:100;_x000D_
    display:none;_x000D_
}
_x000D_
<img src="http://www.tfo.be/jobs/axa/premiumplus/img/empty.gif" width="300" height="350" border="0" usemap="#location-map" id="emptygif" />_x000D_
<div id="overlayr1">&nbsp;</div>_x000D_
<div id="overlayr2">&nbsp;</div>_x000D_
<img src="http://2.bp.blogspot.com/_nP6ESfPiKIw/SlOGugKqaoI/AAAAAAAAACs/6jnPl85TYDg/s1600-R/monkey300.jpg" width="300" height="350" border="0" />_x000D_
<map name="location-map" id="location-map">_x000D_
  <area shape="rect" coords="0,0,300,160" href="#" id="r1" />_x000D_
  <area shape="rect" coords="0,161,300,350" href="#" id="r2"/>_x000D_
</map>
_x000D_
_x000D_
_x000D_

Hope it helps..

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

How to overload __init__ method based on argument type?

OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

a = [1,2]

b = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

How to get a MemoryStream from a Stream in .NET?

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

What's the purpose of SQL keyword "AS"?

When you aren't sure which syntax to choose, especially when there doesn't seem to be much to separate the choices, consult a book on heuristics. As far as I know, the only heuristics book for SQL is 'Joe Celko's SQL Programming Style':

A correlation name is more often called an alias, but I will be formal. In SQL-92, they can have an optional AS operator, and it should be used to make it clear that something is being given a new name. [p16]

This way, if your team doesn't like the convention, you can blame Celko -- I know I do ;)


UPDATE 1: IIRC for a long time, Oracle did not support the AS (preceding correlation name) keyword, which may explain why some old timers don't use it habitually.


UPDATE 2: the term 'correlation name', although used by the SQL Standard, is inappropriate. The underlying concept is that of a ‘range variable’.


UPDATE 3: I just re-read what Celko wrote and he is wrong: the table is not being renamed! I now think:

A correlation name is more often called an alias, but I will be formal. In Standard SQL they can have an optional AS keyword but it should not be used because it may give the impression that something is being renamed when it is not. In fact, it should be omitted to enforce the point that it is a range variable.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

If you have different pool per user make sure user and group are set correctly in configuration file. You can find nginx user in /etc/nginx/nginx.conf file. nginx group is same as nginx user.

user = [pool-user]
group = [pool-group]
listen.owner = [nginx-user]
listen.group = [nginx-group]

Finding rows that don't contain numeric data in Oracle

In contrast to SGB's answer, I prefer doing the regexp defining the actual format of my data and negating that. This allows me to define values like $DDD,DDD,DDD.DD In the OPs simple scenario, it would look like

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^[0-9]+$');

which finds all non-positive integers. If you wau accept negatiuve integers also, it's an easy change, just add an optional leading minus.

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+$');

accepting floating points...

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+(\.[0-9]+)?$');

Same goes further with any format. Basically, you will generally already have the formats to validate input data, so when you will desire to find data that does not match that format ... it's simpler to negate that format than come up with another one; which in case of SGB's approach would be a bit tricky to do if you want more than just positive integers.

Difference between clean, gradlew clean

  1. ./gradlew clean

    Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

  2. ./gradlew clean assembleDebug

    Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

  3. ./gradlew clean :assembleDebug

    Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

  4. Android Studio --> Build --> Clean

    Is essentially the same as ./gradlew clean. See here.

For more info, I suggest taking the time to read through the Android docs, especially this one.

Autoplay an audio with HTML5 embed tag while the player is invisible

For future reference to people who find this page later you can use:

<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>
</audio>

How to redirect output of systemd service to a file

If you have a newer distro with a newer systemd (systemd version 236 or newer), you can set the values of StandardOutput or StandardError to file:YOUR_ABSPATH_FILENAME.


Long story:

In newer versions of systemd there is a relatively new option (the github request is from 2016 ish and the enhancement is merged/closed 2017 ish) where you can set the values of StandardOutput or StandardError to file:YOUR_ABSPATH_FILENAME. The file:path option is documented in the most recent systemd.exec man page.

This new feature is relatively new and so is not available for older distros like centos-7 (or any centos before that).

How do I add 1 day to an NSDate?

A working Swift 3+ implementation based on highmaintenance's answer and vikingosegundo's comment. This Date extension also has additional options to change year, month and time:

extension Date {

    /// Returns a Date with the specified amount of components added to the one it is called with
    func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
        let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
        return Calendar.current.date(byAdding: components, to: self)
    }

    /// Returns a Date with the specified amount of components subtracted from the one it is called with
    func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
        return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
    }

}

Usage for only adding a day as asked by OP would then be:

let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)

What is output buffering?

I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.

If output buffering is turned off, then echo will send data immediately to the Browser.

enter image description here

If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.

enter image description here

phpinfo

To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.

enter image description here In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.

php.ini

It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.

; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
;   functions.
; Possible Values:
;   On = Enabled and buffer is unlimited. (Use with caution)
;   Off = Disabled
;   Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096

The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php

Example: ob_get_clean()

Below you can see how to capture an echo and manipulate it before sending it to the browser.

// Turn on output buffering  
ob_start();  

echo 'Hello World';  // save to output buffer

$output = ob_get_clean();  // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output  

echo $output;  // send to output stream / Browser

// OUTPUT:  
HELLO WORLD

Examples: Hackingwithphp.com

More info about Output buffer with examples can be found here:

http://www.hackingwithphp.com/13/0/0/output-buffering

REST API - Use the "Accept: application/json" HTTP Header

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}

How to make a boolean variable switch between true and false every time a method is invoked?

Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

This flips the variable.

How to find common elements from multiple vectors?

A good answer already, but there are a couple of other ways to do this:

unique(c[c%in%a[a%in%b]])

or,

tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

Material UI and Grid system

I looked around for an answer to this and the best way I found was to use Flex and inline styling on different components.

For example, to make two paper components divide my full screen in 2 vertical components (in ration of 1:4), the following code works fine.

const styles = {
  div:{
    display: 'flex',
    flexDirection: 'row wrap',
    padding: 20,
    width: '100%'
  },
  paperLeft:{
    flex: 1,
    height: '100%',
    margin: 10,
    textAlign: 'center',
    padding: 10
  },
  paperRight:{
    height: 600,
    flex: 4,
    margin: 10,
    textAlign: 'center',
  }
};

class ExampleComponent extends React.Component {
  render() {
    return (
      <div>
        <div style={styles.div}>
          <Paper zDepth={3} style={styles.paperLeft}>
            <h4>First Vertical component</h4>
          </Paper>
          <Paper zDepth={3} style={styles.paperRight}>
              <h4>Second Vertical component</h4>
          </Paper>
        </div>
      </div>
    )
  }
}

Now, with some more calculations, you can easily divide your components on a page.

Further Reading on flex

TypeError: 'NoneType' object is not iterable in Python

You're calling write_file with arguments like this:

write_file(foo, bar)

But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.

How to replace blank (null ) values with 0 for all records?

The following Query also works and you won't need an update query if that's what you'd prefer:

IIF(Column Is Null,0,Column)

Easy way to build Android UI?

DroidDraw seems to be very useful. It has a clean and easy interface and it is a freeware. Available for Windows, Linux and Mac OS X. I advice a donation.

If you don't like it, you should take a look at this site. There are some other options and other useful tools.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Problem 1

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

Solution 1

To work with version 2 of log4j aka "log4j2"

-Dlog4j.configuration=

should read

-Dlog4j.configurationFile=

Problem 2

log4j:WARN ....

Solution 2

In your project, uninclude the log4j-1.2 jar and instead, include the log4j-1.2-api-2.1.jar. I wasn't sure how exactly to exclude the log4j 1.2. I knew that what dependency of my project was requiring it. So, with some reading, I excluded a bunch of stuff.

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.10</artifactId>
    <version>0.8.2.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>                
        </exclusion>
        <exclusion>
            <groupId>org.apache.log4j</groupId>
            <artifactId>log4j-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </exclusion>          
    </exclusions>
</dependency>

I am not sure which of the exclusions did the trick. Separately, I included a dependency to the 1.2 api which bridges to 2.x.

<!--
    http://logging.apache.org/log4j/2.0/manual/migration.html
    http://logging.apache.org/log4j/2.0/maven-artifacts.html
    Log4j 1.x API Bridge
    If existing components use Log4j 1.x and you want to have this logging
    routed to Log4j 2, then remove any log4j 1.x dependencies and add the
    following.
-->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-1.2-api</artifactId>
    <version>2.2</version>
</dependency>

Now, the 1.2 logs which were only going to the console actually flow to our 2.x appenders.

Javascript: 'window' is not defined

Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

For array type Please try this one.

 List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));

Please See here for details to deserialise Json

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

Loop through all elements in XML using NodeList

Here is another way to loop through XML elements using JDOM.

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }

How to enter newline character in Oracle?

begin   
   dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;

Enum String Name from Value

You can convert the int back to an enumeration member with a simple cast, and then call ToString():

int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();

Remove accents/diacritics in a string in JavaScript

The format for new RegExp is

RegExp(something, 'modifiers');

So you would want

accentsTidy = function(s){
                        var r=s.toLowerCase();
                        r = r.replace(new RegExp("\\s", 'g'),"");
                        r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
                        r = r.replace(new RegExp("æ", 'g'),"ae");
                        r = r.replace(new RegExp("ç", 'g'),"c");
                        r = r.replace(new RegExp("[èéêë]", 'g'),"e");
                        r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
                        r = r.replace(new RegExp("ñ", 'g'),"n");                            
                        r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
                        r = r.replace(new RegExp("œ", 'g'),"oe");
                        r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
                        r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
                        r = r.replace(new RegExp("\\W", 'g'),"");
                        return r;
                };

Avoid browser popup blockers

I didn't want to make the new page unless the callback returned successfully, so I did this to simulate the user click:

function submitAndRedirect {
  apiCall.then(({ redirect }) => {
      const a = document.createElement('a');
      a.href = redirect;
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
  });
}

Possible to access MVC ViewBag object from Javascript file?

Use this code in your .cshtml file.

 @{
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    var val = jss.Serialize(ViewBag.somevalue); 
    }

    <script>
        $(function () {
            var val = '@Html.Raw(val)';
            var obj = $.parseJSON(val);
            console.log(0bj);
    });
    </script>

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

How to iterate over the file in python

You should learn about EAFP vs LBYL.

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

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

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

Git Cherry-pick vs Merge Workflow

Both rebase (and cherry-pick) and merge have their advantages and disadvantages. I argue for merge here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase is preferred.)

merge is preferred over cherry-pick and rebase for a couple of reasons.

  1. Robustness. The SHA1 identifier of a commit identifies it not just in and of itself but also in relation to all other commits that precede it. This offers you a guarantee that the state of the repository at a given SHA1 is identical across all clones. There is (in theory) no chance that someone has done what looks like the same change but is actually corrupting or hijacking your repository. You can cherry-pick in individual changes and they are likely the same, but you have no guarantee. (As a minor secondary issue the new cherry-picked commits will take up extra space if someone else cherry-picks in the same commit again, as they will both be present in the history even if your working copies end up being identical.)
  2. Ease of use. People tend to understand the merge workflow fairly easily. rebase tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.

Even with a merge-heavy workflow rebase and cherry-pick are still useful for particular cases:

  1. One downside to merge is cluttered history. rebase prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase code that you have shared with other repositories. Once a commit is pushed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.
  2. cherry-pick is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.

As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.

How to Count Duplicates in List with LINQ

The other solutions use GroupBy. GroupBy is slow (it holds all the elements in memory) so I wrote my own method CountBy:

public static Dictionary<TKey,int> CountBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
    var countsByKey = new Dictionary<TKey,int>();
    foreach(var x in source)
    {
        var key = keySelector(x);
        if (!countsByKey.ContainsKey(key))
            countsByKey[key] = 0;
        countsByKey[key] += 1;
    }
    return countsByKey;
}

How to determine if binary tree is balanced?

Note 1: The height of any sub-tree is computed only once.

Note 2: If the left sub-tree is unbalanced then the computation of the right sub-tree, potentially containing million elements, is skipped.

// return height of tree rooted at "tn" if, and only if, it is a balanced subtree
// else return -1
int maxHeight( TreeNode const * tn ) {
    if( tn ) {
        int const lh = maxHeight( tn->left );
        if( lh == -1 ) return -1;
        int const rh = maxHeight( tn->right );
        if( rh == -1 ) return -1;
        if( abs( lh - rh ) > 1 ) return -1;
        return 1 + max( lh, rh );
    }
    return 0;
}

bool isBalanced( TreeNode const * root ) {
    // Unless the maxHeight is -1, the subtree under "root" is balanced
    return maxHeight( root ) != -1;
}

How to find all duplicate from a List<string>?

    lblrepeated.Text = ""; 
    string value = txtInput.Text;
    char[] arr = value.ToCharArray();
    char[] crr=new char[1];        
   int count1 = 0;        
    for (int i = 0; i < arr.Length; i++)
    {
        int count = 0;  
        char letter=arr[i];
        for (int j = 0; j < arr.Length; j++)
        {
            char letter3 = arr[j];
                if (letter == letter3)
                {
                    count++;
                }                    
        }
        if (count1 < count)
        {
            Array.Resize<char>(ref crr,0);
            int count2 = 0;
            for(int l = 0;l < crr.Length;l++)
            {
                if (crr[l] == letter)
                    count2++;                    
            }


            if (count2 == 0)
            {
                Array.Resize<char>(ref crr, crr.Length + 1);
                crr[crr.Length-1] = letter;
            }

            count1 = count;               
        }
        else if (count1 == count)
        {
            int count2 = 0;
            for (int l = 0; l < crr.Length; l++)
            {
                if (crr[l] == letter)
                    count2++;
            }


            if (count2 == 0)
            {
                Array.Resize<char>(ref crr, crr.Length + 1);
                crr[crr.Length - 1] = letter;
            }

            count1 = count; 
        }
    }

    for (int k = 0; k < crr.Length; k++)
        lblrepeated.Text = lblrepeated.Text + crr[k] + count1.ToString();

Open popup and refresh parent page on close popup

You can reach main page with parent command (parent is the window) after the step you can make everything...

    function funcx() {
        var result = confirm('bla bla bla.!');
        if(result)
            //parent.location.assign("http://localhost:58250/Ekocc/" + document.getElementById('hdnLink').value + "");
            parent.location.assign("http://blabla.com/" + document.getElementById('hdnLink').value + "");
    } 

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

jQuery DataTable overflow and text-wrapping issues

Using the classes "responsive nowrap" on the table element should do the trick.

specifying goal in pom.xml

I ran into this when trying to run spring boot from the command line...

mvn spring-boot:run

I accidentally mis-typed the command as...

mvn spring-boot run

So it was looking for the commands... run, build etc...

Getting a File's MD5 Checksum in Java

The com.google.common.hash API offers:

  • A unified user-friendly API for all hash functions
  • Seedable 32- and 128-bit implementations of murmur3
  • md5(), sha1(), sha256(), sha512() adapters, change only one line of code to switch between these, and murmur.
  • goodFastHash(int bits), for when you don't care what algorithm you use
  • General utilities for HashCode instances, like combineOrdered / combineUnordered

Read the User Guide (IO Explained, Hashing Explained).

For your use-case Files.hash() computes and returns the digest value for a file.

For example a digest calculation (change SHA-1 to MD5 to get MD5 digest)

HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());
"SHA-1: " + hc.toString();

Note that is much faster than , so use if you do not need a cryptographically secure checksum. Note also that should not be used to store passwords and the like since it is to easy to brute force, for passwords use , or instead.

For long term protection with hashes a Merkle signature scheme adds to the security and The Post Quantum Cryptography Study Group sponsored by the European Commission has recommended use of this cryptography for long term protection against quantum computers (ref).

Note that has a higher collision rate than the others.

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

Stop a gif animation onload, on mouseover start the activation

A more elegant version of Mark Kramer's would be to do the following:

function animateImg(id, gifSrc){
  var $el = $(id),
    staticSrc = $el.attr('src');
  $el.hover(
    function(){
      $(this).attr("src", gifSrc);
    },
    function(){
      $(this).attr("src", staticSrc);
    });
}

$(document).ready(function(){
  animateImg('#id1', 'gif/gif1.gif');
  animateImg('#id2', 'gif/gif2.gif');
});

Or even better would be to use data attributes:

$(document).ready(function(){
  $('.animated-img').each(function(){
    var $el = $(this),
      staticSrc = $el.attr('src'),
      gifSrc = $el.data('gifSrc');
    $el.hover(
      function(){
        $(this).attr("src", gifSrc);
      },
      function(){
        $(this).attr("src", staticSrc);
      });
  });
});

And the img el would look something like:

<img class="animated-img" src=".../img.jpg" data-gif-src=".../gif.gif" />

Note: This code is untested but should work fine.

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

Regarding C++ Include another class

C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.

Example

ClassOne.hpp:

class ClassOne
{
public:
  ClassOne(); // note, no function body        
  int method(); // no body here either
private:
  int member;
};

ClassOne.cpp:

#include "ClassOne.hpp"

// implementation of constructor
ClassOne::ClassOne()
 :member(0)
{}

// implementation of "method"
int ClassOne::method()
{
  return member++;
}

main.cpp:

#include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler

int main(int argc, char* argv[])
{
  ClassOne c1;
  c1.method();

  return 0;
}

Using "&times" word in html changes to ×

&times; stands for × in html. Use &amp;times to get &times

Detecting a long press with Android

GestureDetector is the best solution.

Here is an interesting alternative. In onTouchEvent on every ACTION_DOWN schedule a Runnable to run in 1 second. On every ACTION_UP or ACTION_MOVE, cancel scheduled Runnable. If cancelation happens less than 1s from ACTION_DOWN event, Runnable won't run.

final Handler handler = new Handler(); 
Runnable mLongPressed = new Runnable() { 
    public void run() { 
        Log.i("", "Long press!");
    }   
};

@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView){
    if(event.getAction() == MotionEvent.ACTION_DOWN)
        handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
    if((event.getAction() == MotionEvent.ACTION_MOVE)||(event.getAction() == MotionEvent.ACTION_UP))
        handler.removeCallbacks(mLongPressed);
    return super.onTouchEvent(event, mapView);
}

Making a Sass mixin with optional arguments

A DRY'r Way of Doing It

And, generally, a neat trick to remove the quotes.

@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
  -webkit-box-shadow: $top $left $blur $color #{$inset};
  -moz-box-shadow:    $top $left $blur $color #{$inset};
  box-shadow:         $top $left $blur $color #{$inset};
}

SASS Version 3+, you can use unquote():

@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
  -webkit-box-shadow: $top $left $blur $color unquote($inset);
  -moz-box-shadow:    $top $left $blur $color unquote($inset);
  box-shadow:         $top $left $blur $color unquote($inset);
} 

Picked this up over here: pass a list to a mixin as a single argument with SASS

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

download rpm packages and run the following command:

rpm -Uvh glibc-2.15-60.el6.x86_64.rpm \
glibc-common-2.15-60.el6.x86_64.rpm \
glibc-devel-2.15-60.el6.x86_64.rpm \
glibc-headers-2.15-60.el6.x86_64.rpm

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

angularjs make a simple countdown

Please take a look at this example here. It is a simple example of a count up! Which I think you could easily modify to create a count down.

http://jsfiddle.net/ganarajpr/LQGE2/

JavaScript code:

function AlbumCtrl($scope,$timeout) {
    $scope.counter = 0;
    $scope.onTimeout = function(){
        $scope.counter++;
        mytimeout = $timeout($scope.onTimeout,1000);
    }
    var mytimeout = $timeout($scope.onTimeout,1000);

    $scope.stop = function(){
        $timeout.cancel(mytimeout);
    }
}

HTML markup:

<!doctype html>
<html ng-app>
<head>
    <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
    <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>
<body>
<div ng-controller="AlbumCtrl">
    {{counter}}
    <button ng-click="stop()">Stop</button>    
</div>
</body>
</html>

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How can I show dots ("...") in a span with hidden overflow?

Thanks a lot @sandeep for his answer.

My problem was that I want to show / hide text on span with mouse click. So by default short text with dots is shown and by clicking long text appears. Clicking again hides that long text and shows short one again.

Quite easy thing to do: just add / remove class with text-overflow:ellipsis.

HTML:

<span class="spanShortText cursorPointer"  onclick="fInventoryShippingReceiving.ShowHideTextOnSpan(this);">Some really long description here</span>

CSS (same as @sandeep with .cursorPointer added)

.spanShortText {
  display: inline-block;
  width: 100px;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

.cursorPointer {
  cursor: pointer;
}

JQuery part - basically just removes / adds class cSpanShortText.

  function ShowHideTextOnSpan(element) {
    var cSpanShortText = 'spanShortText';
    var $el = $(element);
    if ($el.hasClass(cSpanShortText)) {
      $el.removeClass(cSpanShortText)
    } else {
      $el.addClass(cSpanShortText);
    }
  }

Using headers with the Python requests library's get method

This answer taught me that you can set headers for an entire session:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

Bonus: Sessions also handle cookies.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Compile to stand alone exe for C# app in Visual Studio 2010

Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...

Get value of multiselect box using jQuery or pure JS

You could do like this too.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

Register DLL file on Windows Server 2008 R2

That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.

What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.

To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.

How to redirect stdout to both file and console with scripting?

To redirect output to a file and a terminal without modifying how your Python script is used outside, you could use pty.spawn(itself):

#!/usr/bin/env python
"""Redirect stdout to a file and a terminal inside a script."""
import os
import pty
import sys

def main():
    print('put your code here')

if __name__=="__main__":
    sentinel_option = '--dont-spawn'
    if sentinel_option not in sys.argv:
        # run itself copying output to the log file
        with open('script.log', 'wb') as log_file:
            def read(fd):
                data = os.read(fd, 1024)
                log_file.write(data)
                return data

            argv = [sys.executable] + sys.argv + [sentinel_option]
            rc = pty.spawn(argv, read)
    else:
        sys.argv.remove(sentinel_option)
        rc = main()
    sys.exit(rc)

If pty module is not available (on Windows) then you could replace it with teed_call() function that is more portable but it provides ordinary pipes instead of a pseudo-terminal -- it may change behaviour of some programs.

The advantage of pty.spawn and subprocess.Popen -based solutions over replacing sys.stdout with a file-like object is that they can capture the output at a file descriptor level e.g., if the script starts other processes that can also produce output on stdout/stderr. See my answer to the related question: Redirect stdout to a file in Python?

Java: Get last element after split

You can use the StringUtils class in Apache Commons:

StringUtils.substringAfterLast(one, "-");

Windows recursive grep command-line

I just searched a text with following command which listed me all the file names containing my specified 'search text'.

C:\Users\ak47\Desktop\trunk>findstr /S /I /M /C:"search text" *.*

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

There are two problems with your attempt.

First, you've used n+1 instead of i+1, so you're going to return something like [5, 5, 5, 5] instead of [1, 2, 3, 4].

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

So:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the range function, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use for with a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range function first, just to use it for naturalNumbers. (It's already pretty close.)


There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of my_list are my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n))

Determine Whether Integer Is Between Two Other Integers?

You want the output to print the given statement if and only if the number falls between 10,000 and 30,000.

Code should be;

if number >= 10000 and number <= 30000:
    print("you have to pay 5% taxes")

How can you undo the last git add?

You cannot undo the latest git add, but you can undo all adds since the last commit. git reset without a commit argument resets the index (unstages staged changes):

git reset

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

T-SQL Cast versus Convert

Convert has a style parameter for date to string conversions.

http://msdn.microsoft.com/en-us/library/ms187928.aspx

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

Specify a Root Path of your HTML directory for script links?

As Alexander Jank mentioned <base href="http://www.example.com/default/"> is great. When using sub-domains e.g. default.example.com base works great, because the JS and CSS loads from the said sub-domain and is accessible to both default.example.com and example.com/default

When using the root path, and your JS and CSS files are located in example.com/css, or example.com/js, then the subdomain has no access and the root of the subdomain is not accessible, except using the base.

How to reset all checkboxes using jQuery or pure JS?

If you mean how to remove the 'checked' state from all checkboxes:

$('input:checkbox').removeAttr('checked');

Mongoose: Find, modify, save

I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified it worked.

User.findOne({username: oldUsername}, function (err, user) {
   user.username = newUser.username;
   user.password = newUser.password;
   user.rights = newUser.rights;

   user.markModified(username)
   user.markModified(password)
   user.markModified(rights)
    user.save(function (err) {
    if(err) {
        console.error('ERROR!');
    }
});
});

tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

Send and receive messages through NSNotificationCenter in Objective-C?

SWIFT 5.1 of selected answer for newbies

class TestClass {
    deinit {
        // If you don't remove yourself as an observer, the Notification Center
        // will continue to try and send notification objects to the deallocated
        // object.
        NotificationCenter.default.removeObserver(self)
    }

    init() {
        super.init()

        // Add this instance of TestClass as an observer of the TestNotification.
        // We tell the notification center to inform us of "TestNotification"
        // notifications using the receiveTestNotification: selector. By
        // specifying object:nil, we tell the notification center that we are not
        // interested in who posted the notification. If you provided an actual
        // object rather than nil, the notification center will only notify you
        // when the notification was posted by that particular object.

        NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
    }

    @objc func receiveTest(_ notification: Notification?) {
        // [notification name] should always be @"TestNotification"
        // unless you use this method for observation of other notifications
        // as well.

        if notification?.name.isEqual(toString: "TestNotification") != nil {
            print("Successfully received the test notification!")
        }
    }
}

... somewhere else in another class ...

 func someMethod(){
        // All instances of TestClass will be notified
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
 }

PNG transparency issue in IE8

Dan Tello fix worked well for me.

One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.

Correcting the width and height CSS or removing them altogether fixed.

Value Change Listener to JTextField

textBoxName.getDocument().addDocumentListener(new DocumentListener() {
   @Override
   public void insertUpdate(DocumentEvent e) {
       onChange();
   }

   @Override
   public void removeUpdate(DocumentEvent e) {
      onChange();
   }

   @Override
   public void changedUpdate(DocumentEvent e) {
      onChange();
   } 
});

But I would not just parse anything the user (maybe on accident) touches on his keyboard into an Integer. You should catch any Exceptions thrown and make sure the JTextField is not empty.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Increase max execution time for php

PHP file (for example, my_lengthy_script.php)

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

.htaccess file

<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>

More configuration options

<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200
</IfModule>

If wordpress, set this in the config.php file,

define('WP_MEMORY_LIMIT', '128M');

If drupal, sites/default/settings.php

ini_set('memory_limit', '128M');

If you are using other frameworks,

ini_set('memory_limit', '128M');

You can increase memory as gigabyte.

ini_set('memory_limit', '3G'); // 3 Gigabytes

259200 means:-

( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days

More details on my blog

Creating SolidColorBrush from hex color value

How to get Color from Hexadecimal color code using .NET?

This I think is what you are after, hope it answers your question.

To get your code to work use Convert.ToByte instead of Convert.ToInt...

string colour = "#ffaacc";

Color.FromRgb(
Convert.ToByte(colour.Substring(1,2),16),
Convert.ToByte(colour.Substring(3,2),16),
Convert.ToByte(colour.Substring(5,2),16));

C/C++ check if one bit is set in, i.e. int variable

Why not use something as simple as this?

uint8_t status = 255;
cout << "binary: ";

for (int i=((sizeof(status)*8)-1); i>-1; i--)
{
  if ((status & (1 << i)))
  {
    cout << "1";
  } 
  else
  {
    cout << "0";
  }
}

OUTPUT: binary: 11111111

How to execute two mysql queries as one in PHP/MYSQL?

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

Is it possible to dynamically compile and execute C# code fragments?

I recently needed to spawn processes for unit testing. This post was useful as I created a simple class to do that with either code as a string or code from my project. To build this class, you'll need the ICSharpCode.Decompiler and Microsoft.CodeAnalysis NuGet packages. Here's the class:

using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public static class CSharpRunner
{
   public static object Run(string snippet, IEnumerable<Assembly> references, string typeName, string methodName, params object[] args) =>
      Invoke(Compile(Parse(snippet), references), typeName, methodName, args);

   public static object Run(MethodInfo methodInfo, params object[] args)
   {
      var refs = methodInfo.DeclaringType.Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n));
      return Invoke(Compile(Decompile(methodInfo), refs), methodInfo.DeclaringType.FullName, methodInfo.Name, args);
   }

   private static Assembly Compile(SyntaxTree syntaxTree, IEnumerable<Assembly> references = null)
   {
      if (references is null) references = new[] { typeof(object).Assembly, typeof(Enumerable).Assembly };
      var mrefs = references.Select(a => MetadataReference.CreateFromFile(a.Location));
      var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, mrefs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

      using (var ms = new MemoryStream())
      {
         var result = compilation.Emit(ms);
         if (result.Success)
         {
            ms.Seek(0, SeekOrigin.Begin);
            return Assembly.Load(ms.ToArray());
         }
         else
         {
            throw new InvalidOperationException(string.Join("\n", result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")));
         }
      }
   }

   private static SyntaxTree Decompile(MethodInfo methodInfo)
   {
      var decompiler = new CSharpDecompiler(methodInfo.DeclaringType.Assembly.Location, new DecompilerSettings());
      var typeInfo = decompiler.TypeSystem.MainModule.Compilation.FindType(methodInfo.DeclaringType).GetDefinition();
      return Parse(decompiler.DecompileTypeAsString(typeInfo.FullTypeName));
   }

   private static object Invoke(Assembly assembly, string typeName, string methodName, object[] args)
   {
      var type = assembly.GetType(typeName);
      var obj = Activator.CreateInstance(type);
      return type.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args);
   }

   private static SyntaxTree Parse(string snippet) => CSharpSyntaxTree.ParseText(snippet);
}

To use it, call the Run methods as below:

void Demo1()
{
   const string code = @"
   public class Runner
   {
      public void Run() { System.IO.File.AppendAllText(@""C:\Temp\NUnitTest.txt"", System.DateTime.Now.ToString(""o"") + ""\n""); }
   }";

   CSharpRunner.Run(code, null, "Runner", "Run");
}

void Demo2()
{
   CSharpRunner.Run(typeof(Runner).GetMethod("Run"));
}

public class Runner
{
   public void Run() { System.IO.File.AppendAllText(@"C:\Temp\NUnitTest.txt", System.DateTime.Now.ToString("o") + "\n"); }
}

Returning value from Thread

What you are looking for is probably the Callable<V> interface in place of Runnable, and retrieving the value with a Future<V> object, which also lets you wait until the value has been computed. You can achieve this with an ExecutorService, which you can get from Executors.newSingleThreadExecutor() .

public void test() {
    int x;
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Integer> result = es.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            // the other thread
            return 2;
        }
    });
    try {
        x = result.get();
    } catch (Exception e) {
        // failed
    }
    es.shutdown();
}

What does 'var that = this;' mean in JavaScript?

The use of that is not really necessary if you make a workaround with the use of call() or apply():

var car = {};
car.starter = {};

car.start = function(){
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to our main object
        this.starter.active = true;
    };

    activateStarter.apply(this);
};

Duplicate / Copy records in the same MySQL table

I have a similar issue, and this is what I'm doing:

insert into Preguntas  (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` )  select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18

Been Preguntas:

CREATE TABLE IF NOT EXISTS `Preguntas` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `EncuestaID` int(11) DEFAULT NULL,
  `Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Seccion` int(11) DEFAULT NULL,
  `RespuestaID` bigint(11) DEFAULT NULL,
  `Texto` text COLLATE utf8_unicode_ci ,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;

So, the ID is automatically incremented and also I'm using a fixed value ('23') for EncuestaID.

What issues should be considered when overriding equals and hashCode in Java?

equals() method is used to determine the equality of two objects.

as int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.

we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.

Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it.

public class Tiger {
  private String color;
  private String stripePattern;
  private int height;

  @Override
  public boolean equals(Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
      result = false;
    } else {
      Tiger tiger = (Tiger) object;
      if (this.color == tiger.getColor()
          && this.stripePattern == tiger.getStripePattern()) {
        result = true;
      }
    }
    return result;
  }

  // just omitted null checks
  @Override
  public int hashCode() {
    int hash = 3;
    hash = 7 * hash + this.color.hashCode();
    hash = 7 * hash + this.stripePattern.hashCode();
    return hash;
  }

  public static void main(String args[]) {
    Tiger bengalTiger1 = new Tiger("Yellow", "Dense", 3);
    Tiger bengalTiger2 = new Tiger("Yellow", "Dense", 2);
    Tiger siberianTiger = new Tiger("White", "Sparse", 4);
    System.out.println("bengalTiger1 and bengalTiger2: "
        + bengalTiger1.equals(bengalTiger2));
    System.out.println("bengalTiger1 and siberianTiger: "
        + bengalTiger1.equals(siberianTiger));

    System.out.println("bengalTiger1 hashCode: " + bengalTiger1.hashCode());
    System.out.println("bengalTiger2 hashCode: " + bengalTiger2.hashCode());
    System.out.println("siberianTiger hashCode: "
        + siberianTiger.hashCode());
  }

  public String getColor() {
    return color;
  }

  public String getStripePattern() {
    return stripePattern;
  }

  public Tiger(String color, String stripePattern, int height) {
    this.color = color;
    this.stripePattern = stripePattern;
    this.height = height;

  }
}

Example Code Output:

bengalTiger1 and bengalTiger2: true 
bengalTiger1 and siberianTiger: false 
bengalTiger1 hashCode: 1398212510 
bengalTiger2 hashCode: 1398212510 
siberianTiger hashCode: –1227465966

jQuery AutoComplete Trigger Change Event

This post is pretty old, but for thoses who got here in 2016. None of the example here worked for me. Using keyup instead of autocompletechange did the job. Using jquery-ui 10.4

$("#CompanyList").on("keyup", function (event, ui) {
    console.log($(this).val());
});

Hope this help!

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

psql: could not connect to server: No such file or directory (Mac OS X)

I just got the same issue as I have put my machine(ubuntu) for update and got below error:

could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

After completing the updating process when I restart my system error gone. And its work like charm as before.. I guess this was happened as pg was updating and another process started.

How can I install a local gem?

Well, it's this my DRY installation:

  1. Look into a computer with already installed gems needed in the cache directory (by default: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache)
  2. Copy all "*.gems files" to a computer without gems in own gem cache place (by default the same patron path of first step: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache)
  3. In the console be located in the gems cache (cd [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache) and fire the gem install anygemwithdependencieshere (by example cucumber-2.99.0)

It's DRY because after install any gem, by default rubygems put the gem file in the cache gem directory and not make sense duplicate thats files, it's more easy if you want both computer has the same versions (or bloqued by paranoic security rules :v)

Edit: In some versions of ruby or rubygems, it don't work and fire alerts or error, you can put gems in other place but not get DRY, other alternative is using launch integrated command gem server and add the localhost url in gem sources, more information in: https://guides.rubygems.org/run-your-own-gem-server/

makefile execute another target

Actually you are right: it runs another instance of make. A possible solution would be:

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : clean clearscr all

clearscr:
    clear

By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

EDIT Aug 4

What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

Hence the makefile becomes

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : | clean clearscr all

clearscr:
    clear

EDIT Dec 5

It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)

install:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  command1  # this line will be a subshell
  command2  # this line will be another subshell
  @command3  # Use `@` to hide the command line
  $(call log_error, "It works, yey!")

uninstall:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  ....
  $(call log_error, "Nuked!")

How to reset the state of a Redux store?

For me to reset the state to its initial state, I wrote the following code:

const appReducers = (state, action) =>
   combineReducers({ reducer1, reducer2, user })(
     action.type === "LOGOUT" ? undefined : state,
     action
);

Write a function that returns the longest palindrome in a given string

This Solution is of O(n^2) complexity. O(1) is the space complexity.

public class longestPalindromeInAString {

        public static void main(String[] args) {
            String a =  "xyMADAMpRACECARwl"; 
            String res = "";
            //String longest = a.substring(0,1);
            //System.out.println("longest => " +longest);
            for (int i = 0; i < a.length(); i++) {
                String temp = helper(a,i,i);//even palindrome
                if(temp.length() > res.length()) {res = temp ;}
                temp = helper(a,i,i+1);// odd length palindrome
                if(temp.length() > res.length()) { res = temp ;}

            }//for
            System.out.println(res);
            System.out.println("length of " + res + " is " + res.length());

        }

        private static String helper(String a, int left, int right) {
            while(left>= 0 && right <= a.length() -1  &&  a.charAt(left) == a.charAt(right)) {
                left-- ;right++ ;
            }
            String curr = a.substring(left + 1 , right);
            System.out.println("curr =>" +curr);
            return curr ;
        }

    }

Setting "checked" for a checkbox with jQuery

Here is code for checked and unchecked with a button:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
        });
        set=unset;
    });
});

Update: Here is the same code block using the newer Jquery 1.6+ prop method, which replaces attr:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
        });
        set=unset;
    });
});

Fast way of finding lines in one file that are not in another?

The comm command (short for "common") may be useful comm - compare two sorted files line by line

#find lines only in file1
comm -23 file1 file2 

#find lines only in file2
comm -13 file1 file2 

#find lines common to both files
comm -12 file1 file2 

The man file is actually quite readable for this.

A terminal command for a rooted Android to remount /System as read/write

You can run the mount command without parameter in order to get partition information before constructing your mount command. Here is an example of the mount command without parameter outputed from my HTC Hero.

$ mount
mount
rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock3 /system yaffs2 rw 0 0
/dev/block/mtdblock5 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock4 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:1 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=
1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,s
hortname=mixed,utf8,errors=remount-ro 0 0

$date + 1 year?

If you are using PHP 5.3, it is because you need to set the default time zone:

date_default_timezone_set()

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

How to get the parents of a Python class?

Use bases if you just want to get the parents, use __mro__ (as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).

Bases (and first getting the class for an existing object):

>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)

For mro in recent Python versions:

>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)

Obviously, when you already have a class definition, you can just call __mro__ on that directly:

>>> class A(): pass
>>> A.__mro__
(__main__.A, object)

How do I save JSON to local text file

It's my solution to save local data to txt file.

_x000D_
_x000D_
function export2txt() {_x000D_
  const originalData = {_x000D_
    members: [{_x000D_
        name: "cliff",_x000D_
        age: "34"_x000D_
      },_x000D_
      {_x000D_
        name: "ted",_x000D_
        age: "42"_x000D_
      },_x000D_
      {_x000D_
        name: "bob",_x000D_
        age: "12"_x000D_
      }_x000D_
    ]_x000D_
  };_x000D_
_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {_x000D_
    type: "text/plain"_x000D_
  }));_x000D_
  a.setAttribute("download", "data.txt");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2txt()">Export data to local txt file</button>
_x000D_
_x000D_
_x000D_

Java: using switch statement with enum under subclass

Wrong:

case AnotherClass.MyEnum.VALUE_A

Right:

case VALUE_A:

Git command to checkout any branch and overwrite local changes

The new git-switch command (starting in GIT 2.23) also has a flag --discard-changes which should help you. git pull might be necessary afterwards.

Warning: it's still considered to be experimental.

insert a NOT NULL column to an existing table

Other SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to NULL. If you don't allow NULL, and don't have a default, what is the value going to be?

Since SQL Server supports ADD CONSTRAINT, I'd recommend Pavel's approach of creating a nullable column, and then adding a NOT NULL constraint after you've filled it with non-NULL values.

Update multiple values in a single statement

Have you tried with a sub-query for every field:

UPDATE
    MasterTbl
SET
    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
    ....

How to include static library in makefile

CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine
LIBS = libmine.a -lpthread 

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

As an additional reference for the other responses, instead of using "UTF-8" you can use:

HTTP.UTF_8

which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.

Programmatically get own phone number in iOS

AppStore will reject it, as it's reaching outside of application container.

Apps should be self-contained in their bundles, and may not read or write data outside the designated container area

Section 2.5.2 : https://developer.apple.com/app-store/review/guidelines/#software-requirements

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Android lollipop change navigation bar color

You can also modify your theme using theme Editor by clicking :

Tools -> Android -> Theme Editor

Then, you don't even need to put some extra content in your .xml or .class files.

Using grep to search for hex strings in a file

If you want search for printable strings, you can use:

strings -ao filename | grep string

strings will output all printable strings from a binary with offsets, and grep will search within.

If you want search for any binary string, here is your friend:

How to use a wildcard in the classpath to add multiple jars?

If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.

I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.

It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.

PHP Get name of current directory

getcwd();

or

dirname(__FILE__);

or (PHP5)

basename(__DIR__) 

http://php.net/manual/en/function.getcwd.php

http://php.net/manual/en/function.dirname.php

You can use basename() to get the trailing part of the path :)

In your case, I'd say you are most likely looking to use getcwd(), dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

Eg:

main.php
libs/common.php
libs/images/editor.php

In your common.php you need to use functions in editor.php, so you use

common.php:

require_once dirname(__FILE__) . '/images/editor.php';

main.php:

require_once libs/common.php

That way when common.php is require'd in main.php, the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.

How to map and remove nil values in Ruby

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

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

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

Get the index of the object inside an array, matching a condition

Georg have already mentioned ES6 have Array.findIndex for this. And some other answers are workaround for ES5 using Array.some method.

One more elegant approach can be

var index;
for(index = yourArray.length; index-- > 0 && yourArray[index].prop2 !== "yutu";);

At the same time I will like to emphasize, Array.some may be implemented with binary or other efficient searching technique. So, it might perform better over for loop in some browser.

Android Studio - No JVM Installation found

My variables pointed to other system variables so JDK_HOME was

%programfiles%\Java\jdk1.8.0_45

and i had to explicitly change it to

C:\Program Files\Java\jdk1.8.0_45

Similar for JAVA_HOME

Parse JSON in JavaScript?

The standard way to parse JSON in JavaScript is JSON.parse()

The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:

_x000D_
_x000D_
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
_x000D_
_x000D_
_x000D_


The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().

When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.

jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around JSON.parse().

Why are elementwise additions much faster in separate loops than in a combined loop?

It's not because of a different code, but because of caching: RAM is slower than the CPU registers and a cache memory is inside the CPU to avoid to write the RAM every time a variable is changing. But the cache is not big as the RAM is, hence, it maps only a fraction of it.

The first code modifies distant memory addresses alternating them at each loop, thus requiring continuously to invalidate the cache.

The second code don't alternate: it just flow on adjacent addresses twice. This makes all the job to be completed in the cache, invalidating it only after the second loop starts.

Console.log(); How to & Debugging javascript

Breakpoints and especially conditional breakpoints are your friends.

Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)

Convert tuple to list and back

You could dramatically speed up your stuff if you used just one list instead of a list of lists. This is possible of course only if all your inner lists are of the same size (which is true in your example, so I just assume this).

WIDTH = 6
level1 = [ 1,1,1,1,1,1,
           1,0,0,0,0,1,
           1,0,0,0,0,1,
           1,0,0,0,0,1,
           1,0,0,0,0,1,
           1,1,1,1,1,1 ]
print level1[x + y*WIDTH]  # print value at (x,y)

And you could be even faster if you used a bitfield instead of a list:

WIDTH = 8  # better align your width to bytes, eases things later
level1 = 0xFC84848484FC  # bit field representation of the level
print "1" if level1 & mask(x, y) else "0"  # print bit at (x, y)
level1 |= mask(x, y)  # set bit at (x, y)
level1 &= ~mask(x, y)  # clear bit at (x, y)

with

def mask(x, y):
  return 1 << (WIDTH-x + y*WIDTH)

But that's working only if your fields just contain 0 or 1 of course. If you need more values, you'd have to combine several bits which would make the issue much more complicated.

How to cast int to enum in C++?

Test castEnum = static_cast<Test>(a-1); will cast a to A. If you don't want to substruct 1, you can redefine the enum:

enum Test
{
    A:1, B
};

In this case Test castEnum = static_cast<Test>(a); could be used to cast a to A.

How to get PID of process I've just started within java program?

Since Java 9 class Process has new method long pid(), so it is as simple as

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "path");
try {
    Process p = pb.start();
    long pid = p.pid();      
} catch (IOException ex) {
    // ...
}

How can I compile and run c# program without using visual studio?

If you have .NET v4 installed (so if you have a newer windows or if you apply the windows updates)

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe somefile.cs

or

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.sln

or

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.csproj

It's highly probable that if you have .NET installed, the %FrameworkDir% variable is set, so:

%FrameworkDir%\v4.0.30319\csc.exe ...

%FrameworkDir%\v4.0.30319\msbuild.exe ...

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Which font is used in Visual Studio Code Editor and how to change fonts?

In the default settings, VS Code uses the following fonts (14 pt) in descending order:

  • Monaco
  • Menlo
  • Consolas
  • "Droid Sans Mono"
  • "Inconsolata"
  • "Courier New"
  • monospace (fallback)

How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.

relevant areas

Adding an onclick function to go to url in JavaScript?

If you would like to open link in a new tab, you can:

$("a#thing_to_click").on('click',function(){
    window.open('https://yoururl.com', '_blank');
});

Android Studio doesn't start, fails saying components not installed

For OSX (Mac)

I tried install as Administrator (sudo) but it's did not work


After that I solve the problem by this,

when setup, select custom setup instead of standard setup

then, it will solve this problem

Oracle DB : java.sql.SQLException: Closed Connection

You have to validate the connection.

If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

pool.setValidateConnectionOnBorrow(true);

But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

if (connection == null || !((ValidConnection) connection).isValid())

See the Oracle documentation for further details.

Replace whitespace with a comma in a text file in Linux

tr ' ' ',' <input >output 

Substitutes each space with a comma, if you need you can make a pass with the -s flag (squeeze repeats), that replaces each input sequence of a repeated character that is listed in SET1 (the blank space) with a single occurrence of that character.

Use of squeeze repeats used to after substitute tabs:

tr -s '\t' <input | tr '\t' ',' >output 

How do I run a class in a WAR from the command line?

To execute SomeClass.main(String [] args) from a deployed war file do:

Step 1: Write class SomeClass.java that has a main method method i.e. (public static void main(String[] args) {...})

Step 2: Deploy your WAR

Step 3: cd /usr/local/yourprojectsname/tomcat/webapps/projectName/WEB-INF

Step 4: java -cp "lib/jar1.jar:lib/jar2.jar: ... :lib/jarn.jar" com.mypackage.SomeClass arg1 arg2 ... arg3

Note1: (to see if the class SomeOtherClass.class is in /usr/tomcat/webapps/projectName/WEB-INF/lib)

run --> cd /usr/tomcat/webapps/projectName/WEB-INF/lib && find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep SomeOtherClass.class; then echo "$jarfile"; fi; done

Note2: Write to standard out so you can see if your main actually works via print statements to the console. This is called a back door.

Note3: The comment above by Bozhidar Bozhanov seems correct

Read a zipped file as a pandas DataFrame

https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial

Please follow this link.

import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
                                 header=1, sep='\t', quotechar='"')

#traffic_station_df['Address'] = 'address'

#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

anaconda - graphviz - can't import after installation

I tried this way and worked for me.

conda install -c anaconda graphviz
pip install graphviz

open link of google play store in mobile version android

Open app page on Google Play:

Intent intent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("market://details?id=" + context.getPackageName()));
startActivity(intent);

jQuery convert line breaks to br (nl2br equivalent)

Put this in your code (preferably in a general js functions library):

String.prototype.nl2br = function()
{
    return this.replace(/\n/g, "<br />");
}

Usage:

var myString = "test\ntest2";

myString.nl2br();

creating a string prototype function allows you to use this on any string.

Difference between [routerLink] and routerLink

Assume that you have

const appRoutes: Routes = [
  {path: 'recipes', component: RecipesComponent }
];

<a routerLink ="recipes">Recipes</a>

It means that clicking Recipes hyperlink will jump to http://localhost:4200/recipes

Assume that the parameter is 1

<a [routerLink] = "['/recipes', parameter]"></a>

It means that passing dynamic parameter, 1 to the link, then you navigate to http://localhost:4200/recipes/1

How to create threads in nodejs

If you're using Rx, it's rather simple to plugin in rxjs-cluster to split work into parallel execution. (disclaimer: I'm the author)

https://www.npmjs.com/package/rxjs-cluster

Django: Calling .update() on a single model instance retrieved by .get()?

As @Nils mentionned, you can use the update_fields keyword argument of the save() method to manually specify the fields to update.

obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2

obj_instance.save(update_fields=['field', 'field2'])

The update_fields value should be a list of the fields to update as strings.

See https://docs.djangoproject.com/en/2.1/ref/models/instances/#specifying-which-fields-to-save

How can I do a BEFORE UPDATED trigger with sql server?

All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.

To do something before an update, check out INSTEAD OF UPDATE Triggers.

How to save username and password with Mercurial?

A simple hack is to add username and password to the push url in your project's .hg/hgrc file:

[paths]
default = http://username:[email protected]/myproject

(Note that in this way you store the password in plain text)

If you're working on several projects under the same domain, you might want to add a rewrite rule in your ~/.hgrc file, to avoid repeating this for all projects:

[rewrite]
http.//mydomain.com = http://username:[email protected]

Again, since the password is stored in plain text, I usually store just my username.

If you're working under Gnome, I explain how to integrate Mercurial and the Gnome Keyring here:

http://aloiroberto.wordpress.com/2009/09/16/mercurial-gnome-keyring-integration/

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

Laravel Request::all() Should Not Be Called Statically

also it happens when you import following library to api.php file. this happens by some IDE's suggestion to import it for not finding the Route Class.

just remove it and everything going to work fine.

use Illuminate\Routing\Route;

update:

seems if you add this library it wont lead to error

use Illuminate\Support\Facades\Route;

How to find out which processes are using swap space in Linux?

I suppose you could get a good guess by running top and looking for active processes using a lot of memory. Doing this programatically is harder---just look at the endless debates about the Linux OOM killer heuristics.

Swapping is a function of having more memory in active use than is installed, so it is usually hard to blame it on a single process. If it is an ongoing problem, the best solution is to install more memory, or make other systemic changes.

Replace HTML page with contents retrieved via AJAX

You could try doing

document.getElementById(id).innerHTML = ajax_response

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

When MySQL's only_full_group_by mode is turned on, it means that strict ANSI SQL rules will apply when using GROUP BY. With regard to your query, this means that if you GROUP BY of the proof_type column, then you can only select two things:

  • the proof_type column, or
  • aggregates of any other column


By "aggregates" of other columns, I mean using an aggregate function such as MIN(), MAX(), or AVG() with another column. So in your case the following query would be valid:

SELECT proof_type,
       MAX(id) AS max_id,
       MAX(some_col),
       MIN(some_other_col)
FROM tbl_customer_pod_uploads
WHERE load_id = '78' AND
      status = 'Active'
GROUP BY proof_type

The vast majority of MySQL GROUP BY questions which I see on SO have strict mode turned off, so the query is running, but with incorrect results. In your case, the query won't run at all, forcing you to think about what you really want to do.

Note: The ANSI SQL extends what is allowed to be selected in GROUP BY by also including columns which are functionally dependent on the column(s) being selected. An example of functional dependency would be grouping by a primary key column in a table. Since the primary key is guaranteed to be unique for every record, therefore the value of any other column would also be determined. MySQL is one of the databases which allows for this (SQL Server and Oracle do not AFAIK).

Common xlabel/ylabel for matplotlib subplots

Since I consider it relevant and elegant enough (no need to specify coordinates to place text), I copy (with a slight adaptation) an answer to another related question.

import matplotlib.pyplot as plt
fig, axes = plt.subplots(5, 2, sharex=True, sharey=True, figsize=(6,15))
# add a big axis, hide frame
fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axis
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.xlabel("common X")
plt.ylabel("common Y")

This results in the following (with matplotlib version 2.2.0):

5 rows and 2 columns subplots with common x and y axis labels

Storing and retrieving datatable from session

this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.

for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.

PS: but like I said, this might be totally unrelated to your query :)

How to generate all permutations of a list?

My Python Solution:

def permutes(input,offset):
    if( len(input) == offset ):
        return [''.join(input)]

    result=[]        
    for i in range( offset, len(input) ):
         input[offset], input[i] = input[i], input[offset]
         result = result + permutes(input,offset+1)
         input[offset], input[i] = input[i], input[offset]
    return result

# input is a "string"
# return value is a list of strings
def permutations(input):
    return permutes( list(input), 0 )

# Main Program
print( permutations("wxyz") )

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

Scrolling to an Anchor using Transition/CSS3

You can find the answer to your question on the following page:

https://stackoverflow.com/a/17633941/2359161

Here is the JSFiddle that was given:

http://jsfiddle.net/YYPKM/3/

Note the scrolling section at the end of the CSS, specifically:

_x000D_
_x000D_
/*_x000D_
 *Styling_x000D_
 */_x000D_
_x000D_
html,body {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: relative; _x000D_
}_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: #fff; _x000D_
position: fixed; _x000D_
left: 0; top: 0; _x000D_
width:100%;_x000D_
height: 3.5rem;_x000D_
z-index: 10; _x000D_
}_x000D_
_x000D_
nav {_x000D_
width: 100%;_x000D_
padding-top: 0.5rem;_x000D_
}_x000D_
_x000D_
nav ul {_x000D_
list-style: none;_x000D_
width: inherit; _x000D_
margin: 0; _x000D_
}_x000D_
_x000D_
_x000D_
ul li:nth-child( 3n + 1), #main .panel:nth-child( 3n + 1) {_x000D_
background: rgb( 0, 180, 255 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 2), #main .panel:nth-child( 3n + 2) {_x000D_
background: rgb( 255, 65, 180 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 3), #main .panel:nth-child( 3n + 3) {_x000D_
background: rgb( 0, 255, 180 );_x000D_
}_x000D_
_x000D_
ul li {_x000D_
display: inline-block; _x000D_
margin: 0 8px;_x000D_
margin: 0 0.5rem;_x000D_
padding: 5px 8px;_x000D_
padding: 0.3rem 0.5rem;_x000D_
border-radius: 2px; _x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #fff;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
width: 100%;_x000D_
height: 500px;_x000D_
z-index:0; _x000D_
-webkit-transform: translateZ( 0 );_x000D_
transform: translateZ( 0 );_x000D_
-webkit-transition: -webkit-transform 0.6s ease-in-out;_x000D_
transition: transform 0.6s ease-in-out;_x000D_
-webkit-backface-visibility: hidden;_x000D_
backface-visibility: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.panel h1 {_x000D_
font-family: sans-serif;_x000D_
font-size: 64px;_x000D_
font-size: 4rem;_x000D_
color: #fff;_x000D_
position:relative;_x000D_
line-height: 200px;_x000D_
top: 33%;_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/*_x000D_
 *Scrolling_x000D_
 */_x000D_
_x000D_
a[ id= "servicios" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( 0px);_x000D_
transform: translateY( 0px );_x000D_
}_x000D_
_x000D_
a[ id= "galeria" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -500px );_x000D_
transform: translateY( -500px );_x000D_
}_x000D_
a[ id= "contacto" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -1000px );_x000D_
transform: translateY( -1000px );_x000D_
}
_x000D_
<a id="servicios"></a>_x000D_
<a id="galeria"></a>_x000D_
<a id="contacto"></a>_x000D_
<header class="nav">_x000D_
<nav>_x000D_
    <ul>_x000D_
        <li><a href="#servicios"> Servicios </a> </li>_x000D_
        <li><a href="#galeria"> Galeria </a> </li>_x000D_
        <li><a href="#contacto">Contacta  nos </a> </li>_x000D_
    </ul>_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<section id="main">_x000D_
<article class="panel" id="servicios">_x000D_
    <h1> Nuestros Servicios</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="galeria">_x000D_
    <h1> Mustra de nuestro trabajos</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="contacto">_x000D_
    <h1> Pongamonos en contacto</h1>_x000D_
</article>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How do I block comment in Jupyter notebook?

I add the same situation and went in a couple of stackoverfow, github and tutorials showing complex solutions. Nothing simple though! Some with "Hold the alt key and move the mouse while the cursor shows a cross" which is not for laptop users (at least for me), some others with configuration files...

I found it after a good sleep night. My environment is laptop, ubuntu and Jupyter/Ipython 5.1.0 :

Just select/highlight one line, a block or something, and then "Ctrl"+"/" and it's magic :)

Count the number of occurrences of a string in a VARCHAR field?

try this:

 select TITLE,
        (length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT 
  FROM <table> 


SQL Fiddle Demo

How to fix error with xml2-config not found when installing PHP from sources?

Ubuntu, Debian:

sudo apt install libxml2-dev

Centos:

sudo yum install libxml2-devel

How to convert webpage into PDF by using Python

If you use selenium and chromium, you do not need to manage cookies by you self, and you can generate pdf page from chromium's print as pdf. You can refer this project to realize it. https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter

modified base > https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter/blob/master/sample/html_to_pdf_converter.py

import sys
import json, base64


def send_devtools(driver, cmd, params={}):
    resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
    url = driver.command_executor._url + resource
    body = json.dumps({'cmd': cmd, 'params': params})
    response = driver.command_executor._request('POST', url, body)
    return response.get('value')


def get_pdf_from_html(driver, url, print_options={}, output_file_path="example.pdf"):
    driver.get(url)

    calculated_print_options = {
        'landscape': False,
        'displayHeaderFooter': False,
        'printBackground': True,
        'preferCSSPageSize': True,
    }
    calculated_print_options.update(print_options)
    result = send_devtools(driver, "Page.printToPDF", calculated_print_options)
    data = base64.b64decode(result['data'])
    with open(output_file_path, "wb") as f:
        f.write(data)



# example
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

url = "https://stackoverflow.com/questions/23359083/how-to-convert-webpage-into-pdf-by-using-python#"
webdriver_options = Options()
webdriver_options.add_argument("--no-sandbox")
webdriver_options.add_argument('--headless')
webdriver_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chromedriver, options=webdriver_options)
get_pdf_from_html(driver, url)
driver.quit()

ListView inside ScrollView is not scrolling on Android

Use this method and your listview become scrollable inside scrollview:-

   ListView lstNewsOffer.setAdapter(new ViewOfferAdapter(
                            ViewNewsDetail.this, viewOfferList));
                    getListViewSize(lstNewsOffer);

void getListViewSize(ListView myListView) {
    ListAdapter myListAdapter = myListView.getAdapter();
    if (myListAdapter == null) {
        // do nothing return null
        return;
    }
    // set listAdapter in loop for getting final size
    int totalHeight = 0;
    for (int size = 0; size < myListAdapter.getCount(); size++) {
        View listItem = myListAdapter.getView(size, null, myListView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }
    // setting listview item in adapter
    ViewGroup.LayoutParams params = myListView.getLayoutParams();
    params.height = totalHeight
            + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
    myListView.setLayoutParams(params);
    // print height of adapter on log
    Log.i("height of listItem:", String.valueOf(totalHeight));
}

Convert JS date time to MySQL datetime

I'm using this long time and it's very helpful for me, use as you like

Date.prototype.date=function() {
    return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}

Date.prototype.time=function() {
    return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}

Date.prototype.dateTime=function() {
    return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}

Date.prototype.addTime=function(time) {
    var time=time.split(":")
    var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
    rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
    return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}

Date.prototype.addDate=function(time) {
    var time=time.split("-")
    var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
    rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
    return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}

Date.prototype.subDate=function(time) {
    var time=time.split("-")
    var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
    rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
    return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}

and then just:

new Date().date()

which returns current date in 'MySQL format'

for add time is

new Date().addTime('0:30:0')

which will add 30 minutes.... and so on

What does it mean when an HTTP request returns status code 0?

If you are testing on local PC, it won't work. To test Ajax example you need to place the HTML files on a web server.

How to close an iframe within iframe itself

function closeWin()   // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}


<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" /> 

How to detect lowercase letters in Python?

To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:
    if c.islower():
         print c

Note that in Python 3 you should use print(c) instead of print c.


Possibly ending up with assigning those letters to a different variable.

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'

Update records using LINQ

You have two options as far as I know:

  1. Perform your query, iterate over it to modify the entities, then call SaveChanges().
  2. Execute a SQL command like you mentioned at the top of your question. To see how to do this, take a look at this page.

If you use option 2, you're losing some of the abstraction that the Entity Framework gives you, but if you need to perform a very large update, this might be the best choice for performance reasons.

How can I play sound in Java?

I'm surprised nobody suggested using Applet. Use Applet. You'll have to supply the beep audio file as a wav file, but it works. I tried this on Ubuntu:

package javaapplication2;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaApplication2 {

    public static void main(String[] args) throws MalformedURLException {
        File file = new File("/path/to/your/sounds/beep3.wav");
        URL url = null;
        if (file.canRead()) {url = file.toURI().toURL();}
        System.out.println(url);
        AudioClip clip = Applet.newAudioClip(url);
        clip.play();
        System.out.println("should've played by now");
    }
}
//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

If you want to pass a pointer-to-int into your function,

Declaration of function (if you need it):

void Fun(int *ptr);

Definition of function:

void Fun(int *ptr) {
    int *other_pointer = ptr;  // other_pointer points to the same thing as ptr
    *other_ptr = 3;            // manipulate the thing they both point to
}

Use of function:

int main() {
    int x = 2;
    printf("%d\n", x);
    Fun(&x);
    printf("%d\n", x);
}

Note as a general rule, that variables called Ptr or Pointer should never have type int, which is what you have then in your code. A pointer-to-int has type int *.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

It means "make bar point to the same thing oof points to".

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

That doesn't mean anything, it's invalid. bar is a pointer *oof is an int. You can't assign one to the other.

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

Nope, that's invalid again. &bar is a pointer to the bar variable, but it is what's called an "rvalue", or "temporary", and it cannot be assigned to. It's like the result of an arithmetic calculation. You can't write x + 1 = 5.

It might help you to think of pointers as addresses. bar = oof means "make bar, which is an address, equal to oof, which is also an address". bar = &foo means "make bar, which is an address, equal to the address of foo". If bar = *oof meant anything, it would mean "make bar, which is an address, equal to *oof, which is an int". You can't.

Then, & is the address-of operator. It means "the address of the operand", so &foo is the address of foo (i.e, a pointer to foo). * is the dereference operator. It means "the thing at the address given by the operand". So having done bar = &foo, *bar is foo.

JavaScript window resize event

jQuery is just wrapping the standard resize DOM event, eg.

window.onresize = function(event) {
    ...
};

jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

Remove array element based on object property

Say you want to remove the second object by it's field property.

With ES6 it's as easy as this.

myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)

How do I find out my python path using python?

Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:

sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
os.environ['PYTHONPATH'].split(os.pathsep)

grep for special characters in Unix

Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)

But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:

Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.  (-F is specified
          by POSIX.)

How to Add Date Picker To VBA UserForm

In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.

JavaScript - Get Portion of URL Path

If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2017 (Developer Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQLServer2017Media\Developer_ENU and click OK

Get month name from number

For arbitaray range of month numbers

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

will yield correct list. Adjust start-parameter from where January begins in the month-integer list.

How to automatically insert a blank row after a group of data

I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:

  1. I sorted my file according to control fields
  2. I added a column to the file
  3. I used the "IF" function to determine when there is a change in the control data .
  4. If there is a change the result will indicate "yes", otherwise "no"
  5. Then I filtered the data to group all "yes" items
  6. I copied mutual fund names, folio number etc (no financial data)
  7. Then I removed the filter and sorted the file again. The result is a row added at the desired place. (It is not entirely a blank row, because if it is fully blank, sorting will not place the row at the desired place.)
  8. After sorting, you can easily delete all values to get a completely blank row.

This method also may be tried by the readers.

Android fastboot waiting for devices

To use the fastboot command you first need to put your device in fastboot mode:

$ adb reboot bootloader

Once the device is in fastboot mode, you can boot it with your own kernel, for example:

$ fastboot boot myboot.img

The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:

$ fastboot flash boot myboot.img

Hope that helps.

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Get epoch for a specific date using Javascript

You can also use Date.now() function.

how to set default main class in java?

If the two jars that you want to create are the mostly the same, and the only difference is the main class that should be started from each, you can put all of the classes in a third jar. Then create two jars with just a manifest in each. In the MANIFEST.MF file, name the entry class using the Main-Class attribute.

Additionally, specify the Class-Path attribute. The value of this should be the name of the jar file that contains all of the shared code. Then deploy all three jar files in the same directory. Of course, if you have third-party libraries, those can be listed in the Class-Path attribute too.

Specifying width and height as percentages without skewing photo proportions in HTML

width="50%" and height="50%" sets the width and height attributes to half of the parent element's width and height if I'm not mistaken. Also setting just width or height should set the width or height to the percentage of the parent element, if you're using percents.

Replace a string in a file with nodejs

This may help someone:

This is a little different than just a global replace

from the terminal we run
node replace.js

replace.js:

function processFile(inputFile, repString = "../") {
var fs = require('fs'),
    readline = require('readline'),
    instream = fs.createReadStream(inputFile),
    outstream = new (require('stream'))(),
    rl = readline.createInterface(instream, outstream);
    formatted = '';   

const regex = /<xsl:include href="([^"]*)" \/>$/gm;

rl.on('line', function (line) {
    let url = '';
    let m;
    while ((m = regex.exec(line)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        url = m[1];
    }

    let re = new RegExp('^.* <xsl:include href="(.*?)" \/>.*$', 'gm');

    formatted += line.replace(re, `\t<xsl:include href="${repString}${url}" />`);
    formatted += "\n";
});

rl.on('close', function (line) {
    fs.writeFile(inputFile, formatted, 'utf8', function (err) {
        if (err) return console.log(err);
    });

});
}


// path is relative to where your running the command from
processFile('build/some.xslt');

This is what this does. We have several file that have xml:includes

However in development we need the path to move down a level.

From this

<xsl:include href="common/some.xslt" />

to this

<xsl:include href="../common/some.xslt" />

So we end up running two regx patterns one to get the href and the other to write there is probably a better way to do this but it work for now.

Thanks

How do I clone a job in Jenkins?

All the answers here are super helpful but miss one very weird bug about Jenkins. After you have edited the new job configurations, sometimes if your zoom level is too high, you may not see the save or apply button option. The button is present on the page and hidden by your zoom level, you have to zoom out until you see the button at the bottom left of your page.

Strange, I know!

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

Disable scrolling in webview?

Adding the margin details to the body will prevent scrolling if your content properly wraps, as so:

<body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0">

Easy enough, and a lot less code + bug overhead :)