Programs & Examples On #Inbound

How to access first element of JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

So either correct your source to:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };

and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

If you're curious which protocols .NET supports, you can try HttpClient out on https://www.howsmyssl.com/

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

As Eddie explains above, you can enable better protocols manually:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; 

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

If the other answers don't work you can check if something else is using the port with netstat:

netstat -ano | findstr <your port number>

If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

SQL- Ignore case while searching for a string

See this similar question and answer to searching with case insensitivity - SQL server ignore case in a where expression

Try using something like:

SELECT DISTINCT COL_NAME 
FROM myTable 
WHERE COL_NAME COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%priceorder%'

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true) is set.

This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do

index.html

Set the <base> element properly

<base href="@(Request.ApplicationPath + "/")">

web.config

First redirect 404 to a custom page, for example "Home/Error"

<system.web>
    <customErrors mode="On">
        <error statusCode="404" redirect="~/Home/Error" />
    </customErrors>
</system.web>

Home controller

Implement a simple ActionResult to "translate" input in a clientside route.

public ActionResult Error(string aspxerrorpath) {
    return this.Redirect("~/#/" + aspxerrorpath);
}

This is the simplest way.


It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes

.when("/", {
    templateUrl: "Base/Home",
    controller: "controllerHome"
})
.when("/New", {
    templateUrl: "Base/New",
    controller: "controllerNew"
})
.when("/Show/:title", {
    templateUrl: "Base/Show",
    controller: "controllerShow"
})

It makes sense to redirect URL to client only when it start with "/New" or "/Show/"

public ActionResult Error(string aspxerrorpath) {
    // get clientside route path
    string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);

    // create a set of valid clientside path
    string[] validPaths = { "/New", "/Show/" };

    // check if clientPath is valid and redirect properly
    foreach (string validPath in validPaths) {
        if (clientPath.StartsWith(validPath)) {
            return this.Redirect("~/#/" + clientPath);
        }
    }

    return new HttpNotFoundResult();
}

This is just an example of improved logic, of course every web application has different needs

How to use KeyListener

The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

  1. Make one Key listener class as

    class MyListener implements KeyListener{
    
       // override all the methods of KeyListener interface.
    }
    
  2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

  3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

    JFrame f=new JFrame();
    f.addKeyListener(new MyKeyListener);
    

How is TeamViewer so fast?

My random guess is: TV uses x264 codec which has a commercial license (otherwise TeamViewer would have to release their source code). At some point (more than 5 years ago), I recall main developer of x264 wrote an article about improvements he made for low delay encoding (if you delay by a few frames encoders can compress better), plus he mentioned some other improvements that were relevant for TeamViewer-like use. In that post he mentioned playing quake over video stream with no noticeable issues. Back then I was kind of sure who was the sponsor of these improvements, as TeamViewer was pretty much the only option at that time. x264 is an open source implementation of H264 video codec, and it's insanely good implementation, it's the best one. At the same time it's extremely well optimized. Most likely due to extremely good implementation of x264 you get much better results with TV at lower CPU load. AnyDesk and Chrome Remote Desk use libvpx, which isn't as good as x264 (optimization and video quality wise).

However, I don't think TeamView can beat microsoft's RDP. To me it's the best, however it works between windows PCs or from Mac to Windows only. TV works even from mobiles.

Update: article was written in January 2010, so that work was done roughly 10 years ago. Also, I made a mistake: he played call of duty, not quake. When you posted your question, if my guess is correct, TeamViewer had been using that work for 3 years. Read that blog post from web archive: x264: the best low-latency video streaming platform in the world. When I read the article back in 2010, I was sure that the "startup–which has requested not to be named" that the author mentions was TeamViewer.

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

I had a similar problem which was solved by going to the "SQL Server Configuration Manager" and making sure that the "SQL Server Browser" was configured to start automatically and was started.

I came across this solution in the answer of this forum post: http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/8cdc71eb-6929-4ae8-a5a8-c1f461bd61b4/

I hope this helps somebody out there.

How to change Visual Studio 2012,2013 or 2015 License Key?

For those who will need to remove product key from Visual Studio 2015:

  1. remove registry key HKCR\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F
  2. repair Visual Studio installation

That's it, now you can change the product key if necessary.

Soft keyboard open and close listener in an activity in Android

You can try it:

private void initKeyBoardListener() {
    // ??????????? ???????? ??????????. 
    // Threshold for minimal keyboard height.
    final int MIN_KEYBOARD_HEIGHT_PX = 150;
    // ???? ???????? ?????? view. 
    // Top-level window decor view.
    final View decorView = getWindow().getDecorView();
    // ???????????? ?????????? ?????????. Register global layout listener.
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        // ??????? ????????????? ?????? ????. 
        // Retrieve visible rectangle inside window.
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
            decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
            final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();

            if (lastVisibleDecorViewHeight != 0) {
                if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) {
                    Log.d("Pasha", "SHOW");
                } else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) {
                    Log.d("Pasha", "HIDE");
                }
            }
            // ????????? ??????? ?????? view ?? ?????????? ??????.
            // Save current decor view height for the next call.
            lastVisibleDecorViewHeight = visibleDecorViewHeight;
        }
    });
}

android studio 0.4.2: Gradle project sync failed error

Load Project:>Build, execution, Deployment:>(Check on)compiler Independent modules in parllel.

Show loading image while $.ajax is performed

something like this:

$('#image').show();
$.ajax({
    url: uri,
    cache: false,
    success: function(html){
       $('.info').append(html);
       $('#image').hide();
    }
});

How do you automatically set the focus to a textbox when a web page loads?

It is possible to set autofocus on input elements

<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">

Lightbox to show videos from Youtube and Vimeo?

Check out this list of lightbox plugins, depending on your exact requirements you can find the plugin of your choice from there easier than asking here. If you need a specific lightbox which can do just about anything and everything, try NyroModal.

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

Why doesn't wireshark detect my interface?

On Fedora 29 with Wireshark 3.0.0 only adding a user to the wireshark group is required:

sudo usermod -a -G wireshark $USER

Then log out and log back in (or reboot), and Wireshark should work correctly.

PHP Echo text Color

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

(change) vs (ngModelChange) in angular

(change) event bound to classical input change event.

https://developer.mozilla.org/en-US/docs/Web/Events/change

You can use (change) event even if you don't have a model at your input as

<input (change)="somethingChanged()">

(ngModelChange) is the @Output of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.

https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124

As you discover more in the source code, (ngModelChange) emits the new value.

https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169

So it means you have ability of such usage:

<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
    // do something with new value
}

Basically, it seems like there is no big difference between two, but ngModel events gains the power when you use [ngValue].

  <select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
      <option *ngFor="let currentData of allData" [ngValue]="currentData">
          {{data.name}}
      </option>
  </select>
dataChanged(newObj) {
    // here comes the object as parameter
}

assume you try the same thing without "ngModel things"

<select (change)="changed($event)">
    <option *ngFor="let currentData of allData" [value]="currentData.id">
        {{data.name}}
    </option>
</select>
changed(e){
    // event comes as parameter, you'll have to find selectedData manually
    // by using e.target.data
}

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

Build error, This project references NuGet

In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.

I just edited the Project Name in csproj file of the Project & it Worked...!

What is the difference between 'java', 'javaw', and 'javaws'?

From http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/index.jsp?topic=%2Fcom.ibm.java.doc.user.aix32.60%2Fuser%2Fjava.html:

The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.

And javaws is for Java web start applications, applets, or something like that, I would suspect.

What does '?' do in C++?

The question mark is the conditional operator. The code means that if f==r then 1 is returned, otherwise, return 0. The code could be rewritten as

int qempty()
{
  if(f==r)
    return 1;
  else
    return 0;
}

which is probably not the cleanest way to do it, but hopefully helps your understanding.

How to split a string into an array of characters in Python?

Unpack them:

word = "Paralelepipedo"
print([*word])

C# Error "The type initializer for ... threw an exception

This problem can occur if a class tries to get value of a non-existent key in web.config.

For example, the class has a static variable ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.config doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Had the same problem yesterday. Now, after signing to the developer portal, for every invalid provisioning profile have a button "Renew". After renewing and downloading updated provisioning profile all seems to work as expected, so problem is definitely solved :)

Update: you may have to contact Apple to get a "Renew"-button, or they removed it -- and the solution is to just download it and add it to the keychain, no need to renew.

Reload content in modal (twitter bootstrap)

Here is a coffeescript version that worked for me.

$(document).on 'hidden.bs.modal', (e) ->
  target = $(e.target)
  target.removeData('bs.modal').find(".modal-content").html('')

Facebook share button and custom text

use this function derived from link provided by IJas

function openFbPopUp() {
    var fburl = '';
    var fbimgurl = 'http://';
    var fbtitle = 'Your title';
    var fbsummary = "your description";
    var sharerURL = "http://www.facebook.com/sharer/sharer.php?s=100&p[url]=" + encodeURI(fburl) + "&p[images][0]=" + encodeURI(fbimgurl) + "&p[title]=" + encodeURI(fbtitle) + "&p[summary]=" + encodeURI(fbsummary);
    window.open(
      sharerURL,
      'facebook-share-dialog', 
      'width=626,height=436'); 
    return  false;
}

Or you can also use the latest FB.ui Function if using FB JavaScript SDK for more controlled callback function.

refer: FB.ui

    function openFbPopUp() {
        FB.ui(
          {
            method: 'feed',
            name: 'Facebook Dialogs',
            link: 'https://developers.facebook.com/docs/dialogs/',
            picture: 'http://fbrell.com/f8.jpg',
            caption: 'Reference Documentation',
            description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
          },
          function(response) {
            if (response && response.post_id) {
              alert('Post was published.');
            } else {
              alert('Post was not published.');
            }
          }
        );
    }

TypeError: unsupported operand type(s) for -: 'list' and 'list'

You can't subtract a list from a list.

>>> [3, 7] - [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

Simple way to do it is using numpy:

>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])

You can also use list comprehension, but it will require changing code in the function:

>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]

>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
...     n = len(Array)
...     for column in xrange(n-1):
...         for row in xrange(column+1, n):
...             xmult = Array[row][column] / Array[column][column]
...             Array[row][column] = xmult
...             #print Array[row][col]
...             for col in xrange(0, n):
...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
...             b[row] = b[row]-xmult*b[column]
...     print Array
...     print b
...     return Array, b  # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
...                   np.array([[6],[7]]))
[[ 2  3]
 [-2 -1]]
[[ 6]
 [-5]]
(array([[ 2,  3],
       [-2, -1]]), array([[ 6],
       [-5]]))

Apache: Restrict access to specific source IP inside virtual host

The mod_authz_host directives need to be inside a <Location> or <Directory> block but I've used the former within <VirtualHost> like so for Apache 2.2:

<VirtualHost *:8080>
    <Location />
    Order deny,allow
    Deny from all
    Allow from 127.0.0.1
    </Location>

    ...
</VirtualHost>

Reference: https://askubuntu.com/questions/262981/how-to-install-mod-authz-host-in-apache

How to quietly remove a directory with content in PowerShell

rm -Force -Recurse -Confirm:$false $directory2Delete didn't work in the PowerShell ISE, but it worked through the regular PowerShell CLI.

I hope this helps. It was driving me bannanas.

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

can not find module "@angular/material"

That's what solved this problem for me.

I used:

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations

but INSIDE THE APPLICATION'S FOLDER.

Source: https://medium.com/@ismapro/first-steps-with-angular-cli-and-angular-material-5a90406e9a4

AngularJS sorting rows by table header

I think this working CodePen example that I created will show you exactly how to do what you want.

The template:

<section ng-app="app" ng-controller="MainCtrl">
  <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>
          <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
          First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
            Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
          Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
        <td>{{emp.firstName}}</td>
        <td>{{emp.lastName}}</td>
        <td>{{emp.age}}</td>
      </tr>
    </tbody>
  </table>
</section>

The JavaScript code:

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

app.controller('MainCtrl', function($scope) {
  $scope.orderByField = 'firstName';
  $scope.reverseSort = false;

  $scope.data = {
    employees: [{
      firstName: 'John',
      lastName: 'Doe',
      age: 30
    },{
      firstName: 'Frank',
      lastName: 'Burns',
      age: 54
    },{
      firstName: 'Sue',
      lastName: 'Banter',
      age: 21
    }]
  };
});

How do I extract value from Json

If you don't mind adding a dependency, you can use JsonPath.

import com.jayway.jsonpath.JsonPath;

String firstName = JsonPath.read(rawJsonString, "$.detail.first_name");

"$" specifies the root of the raw json string and then you just specify the path to the field you want. This will always return a string. You'll have to do any casting yourself.

Be aware that it'll throw a PathNotFoundException at runtime if the path you specify doesn't exist.

What's the difference between a method and a function?

Function is the concept mainly belonging to Procedure oriented programming where a function is an an entity which can process data and returns you value

Method is the concept of Object Oriented programming where a method is a member of a class which mostly does processing on the class members.

What is a NullReferenceException, and how do I fix it?

NullReference Exception — Visual Basic

The NullReference Exception for Visual Basic is no different from the one in C#. After all, they are both reporting the same exception defined in the .NET Framework which they both use. Causes unique to Visual Basic are rare (perhaps only one).

This answer will use Visual Basic terms, syntax, and context. The examples used come from a large number of past Stack  Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example similar to yours is very likely listed here.

Note:

  1. This is concept-based: there is no code for you to paste into your project. It is intended to help you understand what causes a NullReferenceException (NRE), how to find it, how to fix it, and how to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.
  2. The examples (from Stack  Overflow posts) do not always show the best way to do something in the first place.
  3. Typically, the simplest remedy is used.

Basic Meaning

The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these:

  • Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)
  • Something which your code assumed would initialize an object, did not
  • Possibly, other code prematurely invalidated an object still in use

Finding The Cause

Since the problem is an object reference which is Nothing, the answer is to examine them to find out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values - the culprit will be Nothing.

IDE debug display

You should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause your code to crash when it tries to use an object which is Nothing. This is what you want because it will identify the exact location of the problem, and allow you to identify the object causing it.

A MsgBox in the Catch which displays Error while... will be of little help. This method also leads to very bad Stack  Overflow questions, because you can't describe the actual exception, the object involved or even the line of code where it happens.

You can also use the Locals Window (Debug -> Windows -> Locals) to examine your objects.

Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting a new question.

See also:

Examples and Remedies

Class Objects / Creating an Instance

Dim reg As CashRegister
...
TextBox1.Text = reg.Amount         ' NRE

The problem is that Dim does not create a CashRegister object; it only declares a variable named reg of that Type. Declaring an object variable and creating an instance are two different things.

Remedy

The New operator can often be used to create the instance when you declare it:

Dim reg As New CashRegister        ' [New] creates instance, invokes the constructor

' Longer, more explicit form:
Dim reg As CashRegister = New CashRegister

When it is only appropriate to create the instance later:

Private reg As CashRegister         ' Declare
  ...
reg = New CashRegister()            ' Create instance

Note: Do not use Dim again in a procedure, including the constructor (Sub New):

Private reg As CashRegister
'...

Public Sub New()
   '...
   Dim reg As New CashRegister
End Sub

This will create a local variable, reg, which exists only in that context (sub). The reg variable with module level Scope which you will use everywhere else remains Nothing.

Missing the New operator is the #1 cause of NullReference Exceptions seen in the Stack  Overflow questions reviewed.

Visual Basic tries to make the process clear repeatedly using New: Using the New Operator creates a new object and calls Sub New -- the constructor -- where your object can perform any other initialization.

To be clear, Dim (or Private) only declares a variable and its Type. The Scope of the variable - whether it exists for the entire module/class or is local to a procedure - is determined by where it is declared. Private | Friend | Public defines the access level, not Scope.

For more information, see:


Arrays

Arrays must also be instantiated:

Private arr as String()

This array has only been declared, not created. There are several ways to initialize an array:

Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}

' For a local array (in a procedure) and using 'Option Infer':
Dim arr = New String(10) {}

Note: Beginning with VS 2010, when initializing a local array using a literal and Option Infer, the As <Type> and New elements are optional:

Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}

The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require As <Type> with Option Strict:

Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14}

Example: Array of class objects

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count - 1
   arrFoo(i).Bar = i * 10       ' Exception
Next

The array has been created, but the Foo objects in it have not.

Remedy

For i As Integer = 0 To arrFoo.Count - 1
    arrFoo(i) = New Foo()         ' Create Foo instance
    arrFoo(i).Bar = i * 10
Next

Using a List(Of T) will make it quite difficult to have an element without a valid object:

Dim FooList As New List(Of Foo)     ' List created, but it is empty
Dim f As Foo                        ' Temporary variable for the loop

For i As Integer = 0 To 5
    f = New Foo()                    ' Foo instance created
    f.Bar =  i * 10
    FooList.Add(f)                   ' Foo object added to list
Next

For more information, see:


Lists and Collections

.NET collections (of which there are many varieties - Lists, Dictionary, etc.) must also be instantiated or created.

Private myList As List(Of String)
..
myList.Add("ziggy")           ' NullReference

You get the same exception for the same reason - myList was only declared, but no instance created. The remedy is the same:

myList = New List(Of String)

' Or create an instance when declared:
Private myList As New List(Of String)

A common oversight is a class which uses a collection Type:

Public Class Foo
    Private barList As List(Of Bar)

    Friend Function BarCount As Integer
        Return barList.Count
    End Function

    Friend Sub AddItem(newBar As Bar)
        If barList.Contains(newBar) = False Then
            barList.Add(newBar)
        End If
    End Function

Either procedure will result in an NRE, because barList is only declared, not instantiated. Creating an instance of Foo will not also create an instance of the internal barList. It may have been the intent to do this in the constructor:

Public Sub New         ' Constructor
    ' Stuff to do when a new Foo is created...
    barList = New List(Of Bar)
End Sub

As before, this is incorrect:

Public Sub New()
    ' Creates another barList local to this procedure
     Dim barList As New List(Of Bar)
End Sub

For more information, see List(Of T) Class.


Data Provider Objects

Working with databases presents many opportunities for a NullReference because there can be many objects (Command, Connection, Transaction, Dataset, DataTable, DataRows....) in use at once. Note: It does not matter which data provider you are using -- MySQL, SQL Server, OleDB, etc. -- the concepts are the same.

Example 1

Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim MaxRows As Integer

con.Open()
Dim sql = "SELECT * FROM tblfoobar_List"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "foobar")
con.Close()

MaxRows = ds.Tables("foobar").Rows.Count      ' Error

As before, the ds Dataset object was declared, but an instance was never created. The DataAdapter will fill an existing DataSet, not create one. In this case, since ds is a local variable, the IDE warns you that this might happen:

img

When declared as a module/class level variable, as appears to be the case with con, the compiler can't know if the object was created by an upstream procedure. Do not ignore warnings.

Remedy

Dim ds As New DataSet

Example 2

ds = New DataSet
da = New OleDBDataAdapter(sql, con)
da.Fill(ds, "Employees")

txtID.Text = ds.Tables("Employee").Rows(0).Item(1)
txtID.Name = ds.Tables("Employee").Rows(0).Item(2)

A typo is a problem here: Employees vs Employee. There was no DataTable named "Employee" created, so a NullReferenceException results trying to access it. Another potential problem is assuming there will be Items which may not be so when the SQL includes a WHERE clause.

Remedy

Since this uses one table, using Tables(0) will avoid spelling errors. Examining Rows.Count can also help:

If ds.Tables(0).Rows.Count > 0 Then
    txtID.Text = ds.Tables(0).Rows(0).Item(1)
    txtID.Name = ds.Tables(0).Rows(0).Item(2)
End If

Fill is a function returning the number of Rows affected which can also be tested:

If da.Fill(ds, "Employees") > 0 Then...

Example 3

Dim da As New OleDb.OleDbDataAdapter("SELECT TICKET.TICKET_NO,
        TICKET.CUSTOMER_ID, ... FROM TICKET_RESERVATION AS TICKET INNER JOIN
        FLIGHT_DETAILS AS FLIGHT ... WHERE [TICKET.TICKET_NO]= ...", con)
Dim ds As New DataSet
da.Fill(ds)

If ds.Tables("TICKET_RESERVATION").Rows.Count > 0 Then

The DataAdapter will provide TableNames as shown in the previous example, but it does not parse names from the SQL or database table. As a result, ds.Tables("TICKET_RESERVATION") references a non-existent table.

The Remedy is the same, reference the table by index:

If ds.Tables(0).Rows.Count > 0 Then

See also DataTable Class.


Object Paths / Nested

If myFoo.Bar.Items IsNot Nothing Then
   ...

The code is only testing Items while both myFoo and Bar may also be Nothing. The remedy is to test the entire chain or path of objects one at a time:

If (myFoo IsNot Nothing) AndAlso
    (myFoo.Bar IsNot Nothing) AndAlso
    (myFoo.Bar.Items IsNot Nothing) Then
    ....

AndAlso is important. Subsequent tests will not be performed once the first False condition is encountered. This allows the code to safely 'drill' into the object(s) one 'level' at a time, evaluating myFoo.Bar only after (and if) myFoo is determined to be valid. Object chains or paths can get quite long when coding complex objects:

myBase.myNodes(3).Layer.SubLayer.Foo.Files.Add("somefilename")

It is not possible to reference anything 'downstream' of a null object. This also applies to controls:

myWebBrowser.Document.GetElementById("formfld1").InnerText = "some value"

Here, myWebBrowser or Document could be Nothing or the formfld1 element may not exist.


UI Controls

Dim cmd5 As New SqlCommand("select Cartons, Pieces, Foobar " _
     & "FROM Invoice where invoice_no = '" & _
     Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & _
     Me.ListBox1.SelectedItem.ToString.Trim & "' And item_name = '" & _
     Me.ComboBox2.SelectedValue.ToString.Trim & "' And expiry_date = '" & _
     Me.expiry.Text & "'", con)

Among other things, this code does not anticipate that the user may not have selected something in one or more UI controls. ListBox1.SelectedItem may well be Nothing, so ListBox1.SelectedItem.ToString will result in an NRE.

Remedy

Validate data before using it (also use Option Strict and SQL parameters):

Dim expiry As DateTime         ' for text date validation
If (ComboBox5.SelectedItems.Count > 0) AndAlso
    (ListBox1.SelectedItems.Count > 0) AndAlso
    (ComboBox2.SelectedItems.Count > 0) AndAlso
    (DateTime.TryParse(expiry.Text, expiry) Then

    '... do stuff
Else
    MessageBox.Show(...error message...)
End If

Alternatively, you can use (ComboBox5.SelectedItem IsNot Nothing) AndAlso...


Visual Basic Forms

Public Class Form1

    Private NameBoxes = New TextBox(5) {Controls("TextBox1"), _
                   Controls("TextBox2"), Controls("TextBox3"), _
                   Controls("TextBox4"), Controls("TextBox5"), _
                   Controls("TextBox6")}

    ' same thing in a different format:
    Private boxList As New List(Of TextBox) From {TextBox1, TextBox2, TextBox3 ...}

    ' Immediate NRE:
    Private somevar As String = Me.Controls("TextBox1").Text

This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will report that Controls does not exist in the current context, or "cannot reference non-static member". So, to some extent, this is a VB-only situation. It is also complex because it can result in a failure cascade.

The arrays and collections cannot be initialized this way. This initialization code will run before the constructor creates the Form or the Controls. As a result:

  • Lists and Collection will simply be empty
  • The Array will contain five elements of Nothing
  • The somevar assignment will result in an immediate NRE because Nothing doesn't have a .Text property

Referencing array elements later will result in an NRE. If you do this in Form_Load, due to an odd bug, the IDE may not report the exception when it happens. The exception will pop up later when your code tries to use the array. This "silent exception" is detailed in this post. For our purposes, the key is that when something catastrophic happens while creating a form (Sub New or Form Load event), exceptions may go unreported, the code exits the procedure and just displays the form.

Since no other code in your Sub New or Form Load event will run after the NRE, a great many other things can be left uninitialized.

Sub Form_Load(..._
   '...
   Dim name As String = NameBoxes(2).Text        ' NRE
   ' ...
   ' More code (which will likely not be executed)
   ' ...
End Sub

Note this applies to any and all control and component references making these illegal where they are:

Public Class Form1

    Private myFiles() As String = Me.OpenFileDialog1.FileName & ...
    Private dbcon As String = OpenFileDialog1.FileName & ";Jet Oledb..."
    Private studentName As String = TextBox13.Text

Partial Remedy

It is curious that VB does not provide a warning, but the remedy is to declare the containers at the form level, but initialize them in form load event handler when the controls do exist. This can be done in Sub New as long as your code is after the InitializeComponent call:

' Module level declaration
Private NameBoxes as TextBox()
Private studentName As String

' Form Load, Form Shown or Sub New:
'
' Using the OP's approach (illegal using OPTION STRICT)
NameBoxes = New TextBox() {Me.Controls("TextBox1"), Me.Controls("TestBox2"), ...)
studentName = TextBox32.Text           ' For simple control references

The array code may not be out of the woods yet. Any controls which are in a container control (like a GroupBox or Panel) will not be found in Me.Controls; they will be in the Controls collection of that Panel or GroupBox. Nor will a control be returned when the control name is misspelled ("TeStBox2"). In such cases, Nothing will again be stored in those array elements and an NRE will result when you attempt to reference it.

These should be easy to find now that you know what you are looking for: VS shows you the error of your ways

"Button2" resides on a Panel

Remedy

Rather than indirect references by name using the form's Controls collection, use the control reference:

' Declaration
Private NameBoxes As TextBox()

' Initialization -  simple and easy to read, hard to botch:
NameBoxes = New TextBox() {TextBox1, TextBox2, ...)

' Initialize a List
NamesList = New List(Of TextBox)({TextBox1, TextBox2, TextBox3...})
' or
NamesList = New List(Of TextBox)
NamesList.AddRange({TextBox1, TextBox2, TextBox3...})

Function Returning Nothing

Private bars As New List(Of Bars)        ' Declared and created

Public Function BarList() As List(Of Bars)
    bars.Clear
    If someCondition Then
        For n As Integer = 0 to someValue
            bars.Add(GetBar(n))
        Next n
    Else
        Exit Function
    End If

    Return bars
End Function

This is a case where the IDE will warn you that 'not all paths return a value and a NullReferenceException may result'. You can suppress the warning, by replacing Exit Function with Return Nothing, but that does not solve the problem. Anything which tries to use the return when someCondition = False will result in an NRE:

bList = myFoo.BarList()
For Each b As Bar in bList      ' EXCEPTION
      ...

Remedy

Replace Exit Function in the function with Return bList. Returning an empty List is not the same as returning Nothing. If there is a chance that a returned object can be Nothing, test before using it:

 bList = myFoo.BarList()
 If bList IsNot Nothing Then...

Poorly Implemented Try/Catch

A badly implemented Try/Catch can hide where the problem is and result in new ones:

Dim dr As SqlDataReader
Try
    Dim lnk As LinkButton = TryCast(sender, LinkButton)
    Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow)
    Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString()
    ViewState("username") = eid
    sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle,
             Pager, mailaddress, from employees1 where username='" & eid & "'"
    If connection.State <> ConnectionState.Open Then
        connection.Open()
    End If
    command = New SqlCommand(sqlQry, connection)

    'More code fooing and barring

    dr = command.ExecuteReader()
    If dr.Read() Then
        lblFirstName.Text = Convert.ToString(dr("FirstName"))
        ...
    End If
    mpe.Show()
Catch

Finally
    command.Dispose()
    dr.Close()             ' <-- NRE
    connection.Close()
End Try

This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty Catch.

There is an extra comma in the SQL (after 'mailaddress') which results in an exception at .ExecuteReader. After the Catch does nothing, Finally tries to perform clean up, but since you cannot Close a null DataReader object, a brand new NullReferenceException results.

An empty Catch block is the devil's playground. This OP was baffled why he was getting an NRE in the Finally block. In other situations, an empty Catch may result in something else much further downstream going haywire and cause you to spend time looking at the wrong things in the wrong place for the problem. (The "silent exception" described above provides the same entertainment value.)

Remedy

Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person uniquely qualified to fix them - the developer.


DBNull is not the same as Nothing

For Each row As DataGridViewRow In dgvPlanning.Rows
    If Not IsDBNull(row.Cells(0).Value) Then
        ...

The IsDBNull function is used to test if a value equals System.DBNull: From MSDN:

The System.DBNull value indicates that the Object represents missing or non-existent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized.

Remedy

If row.Cells(0) IsNot Nothing Then ...

As before, you can test for Nothing, then for a specific value:

If (row.Cells(0) IsNot Nothing) AndAlso (IsDBNull(row.Cells(0).Value) = False) Then

Example 2

Dim getFoo = (From f In dbContext.FooBars
               Where f.something = something
               Select f).FirstOrDefault

If Not IsDBNull(getFoo) Then
    If IsDBNull(getFoo.user_id) Then
        txtFirst.Text = getFoo.first_name
    Else
       ...

FirstOrDefault returns the first item or the default value, which is Nothing for reference types and never DBNull:

If getFoo IsNot Nothing Then...

Controls

Dim chk As CheckBox

chk = CType(Me.Controls(chkName), CheckBox)
If chk.Checked Then
    Return chk
End If

If a CheckBox with chkName can't be found (or exists in a GroupBox), then chk will be Nothing and be attempting to reference any property will result in an exception.

Remedy

If (chk IsNot Nothing) AndAlso (chk.Checked) Then ...

The DataGridView

The DGV has a few quirks seen periodically:

dgvBooks.DataSource = loan.Books
dgvBooks.Columns("ISBN").Visible = True       ' NullReferenceException
dgvBooks.Columns("Title").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Author").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Price").DefaultCellStyle.Format = "C"

If dgvBooks has AutoGenerateColumns = True, it will create the columns, but it does not name them, so the above code fails when it references them by name.

Remedy

Name the columns manually, or reference by index:

dgvBooks.Columns(0).Visible = True

Example 2 — Beware of the NewRow

xlWorkSheet = xlWorkBook.Sheets("sheet1")

For i = 0 To myDGV.RowCount - 1
    For j = 0 To myDGV.ColumnCount - 1
        For k As Integer = 1 To myDGV.Columns.Count
            xlWorkSheet.Cells(1, k) = myDGV.Columns(k - 1).HeaderText
            xlWorkSheet.Cells(i + 2, j + 1) = myDGV(j, i).Value.ToString()
        Next
    Next
Next

When your DataGridView has AllowUserToAddRows as True (the default), the Cells in the blank/new row at the bottom will all contain Nothing. Most attempts to use the contents (for example, ToString) will result in an NRE.

Remedy

Use a For/Each loop and test the IsNewRow property to determine if it is that last row. This works whether AllowUserToAddRows is true or not:

For Each r As DataGridViewRow in myDGV.Rows
    If r.IsNewRow = False Then
         ' ok to use this row

If you do use a For n loop, modify the row count or use Exit For when IsNewRow is true.


My.Settings (StringCollection)

Under certain circumstances, trying to use an item from My.Settings which is a StringCollection can result in a NullReference the first time you use it. The solution is the same, but not as obvious. Consider:

My.Settings.FooBars.Add("ziggy")         ' foobars is a string collection

Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains Nothing when there are no items in the Settings editor to add.

Remedy

Initialize the settings collection in the form's Load event handler, if/when needed:

If My.Settings.FooBars Is Nothing Then
    My.Settings.FooBars = New System.Collections.Specialized.StringCollection
End If

Typically, the Settings collection will only need to be initialized the first time the application runs. An alternate remedy is to add an initial value to your collection in Project -> Settings | FooBars, save the project, then remove the fake value.


Key Points

You probably forgot the New operator.

or

Something yo

How to sum up an array of integers in C#

For extremely large arrays it may pay off to perform the calculation using more than one processors/cores of the machine.

long sum = 0;
var options = new ParallelOptions()
    { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(Partitioner.Create(0, arr.Length), options, range =>
{
    long localSum = 0;
    for (int i = range.Item1; i < range.Item2; i++)
    {
        localSum += arr[i];
    }
    Interlocked.Add(ref sum, localSum);
});

Razor View throwing "The name 'model' does not exist in the current context"

For me, the issue was a conflicting .NET version in one of the libraries that I recently imported. The library I imported was compiled for 4.5.2 and the ASP.NET MVC site I imported it into targeted 4.5. After recompiling said lib for 4.5 the website would comppile.

Also, there were no compilation errors, but the issue was being reported as a "warning". So be sure to read all warnings if there are any.

Java and SQLite

There is a new project SQLJet that is a pure Java implementation of SQLite. It doesn't support all of the SQLite features yet, but may be a very good option for some of the Java projects that work with SQLite databases.

Add new value to an existing array in JavaScript

You can use the .push() method (which is standard JavaScript)

e.g.

var primates = new Array();
primates.push('monkey');
primates.push('chimp');

What is the pythonic way to unpack tuples?

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Java - Convert String to valid URI object

Android has always had the Uri class as part of the SDK: http://developer.android.com/reference/android/net/Uri.html

You can simply do something like:

String requestURL = String.format("http://www.example.com/?a=%s&b=%s", Uri.encode("foo bar"), Uri.encode("100% fubar'd"));

How do I check if a column is empty or null in MySQL?

As defined by the SQL-92 Standard, when comparing two strings of differing widths, the narrower value is right-padded with spaces to make it is same width as the wider value. Therefore, all string values that consist entirely of spaces (including zero spaces) will be deemed to be equal e.g.

'' = ' ' IS TRUE
'' = '  ' IS TRUE
' ' = '  ' IS TRUE
'  ' = '      ' IS TRUE
etc

Therefore, this should work regardless of how many spaces make up the some_col value:

SELECT * 
  FROM T
 WHERE some_col IS NULL 
       OR some_col = ' ';

or more succinctly:

SELECT * 
  FROM T
 WHERE NULLIF(some_col, ' ') IS NULL;

JVM heap parameters

To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed.

You can see this by using Process Explorer by Sysinternals instead of task manager on windows.

So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.

onchange file input change img src and change image color

Below solution tested and its working, hope it will support in your project.
HTML code:
    <input type="file" name="asgnmnt_file" id="asgnmnt_file" class="span8" 
    style="display:none;" onchange="fileSelected(this)">
    <br><br>
    <img id="asgnmnt_file_img" src="uploads/assignments/abc.jpg" width="150" height="150" 
    onclick="passFileUrl()" style="cursor:pointer;">

JavaScript code:
    function passFileUrl(){
    document.getElementById('asgnmnt_file').click();
    }

    function fileSelected(inputData){
    document.getElementById('asgnmnt_file_img').src = window.URL.createObjectURL(inputData.files[0])
    }

Comparing strings in Java

did the same here needed to show "success" twice response is data from PHP

 String res=response.toString().trim;

                            Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
    if ( res.compareTo("success")==0){
    Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
    }

How to model type-safe enum types?

A slightly less verbose way of declaring named enumerations:

object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
  type WeekDay = Value
  val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}

WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString   // returns Fri

Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.

Datetime in where clause

Assuming we're talking SQL Server DateTime

Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:

errorDate BETWEEN '12/20/2008' AND '12/21/2008'

My preferred method for a time range like that is:

'20081220' <= errorDate AND errordate < '20081221'

Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)

Populating a ListView using an ArrayList?

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}

Python, compute list difference

Use set if you don't care about items order or repetition. Use list comprehensions if you do:

>>> def diff(first, second):
        second = set(second)
        return [item for item in first if item not in second]

>>> diff(A, B)
[1, 3, 4]
>>> diff(B, A)
[5]
>>> 

Get nth character of a string in Swift programming language

Swift 4.2

This answer is ideal because it extends String and all of its Subsequences (Substring) in one extension

public extension StringProtocol {
    
    public subscript (i: Int) -> Element {
        return self[index(startIndex, offsetBy: i)]
    }

    public subscript (bounds: CountableClosedRange<Int>) -> SubSequence {
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return self[start...end]
    }
    
    public subscript (bounds: CountableRange<Int>) -> SubSequence {
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return self[start..<end]
    }
    
    public subscript (bounds: PartialRangeUpTo<Int>) -> SubSequence {
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return self[startIndex..<end]
    }
    
    public subscript (bounds: PartialRangeThrough<Int>) -> SubSequence {
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return self[startIndex...end]
    }
    
    public subscript (bounds: CountablePartialRangeFrom<Int>) -> SubSequence {
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        return self[start..<endIndex]
    }
}

Usage

var str = "Hello, playground"

print(str[5...][...5][0])
// Prints ","

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

Less than or equal to

In batch, the > is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /? help):

where compare-op may be one of:

    EQU - equal
    NEQ - not equal
    LSS - less than
    LEQ - less than or equal
    GTR - greater than
    GEQ - greater than or equal

That should explain what you want. The only other compare-op is == which can be switched with the if not parameter. Other then that rely on these three letter ones.

How to change the color of an svg element?

Target the path within the svg:

<svg>
   <path>....
</svg>

You can do inline, like:

<path fill="#ccc">

Or

svg{
   path{
        fill: #ccc

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

How can I sort a std::map first by value, then by key?

As explained in Nawaz's answer, you cannot sort your map by itself as you need it, because std::map sorts its elements based on the keys only. So, you need a different container, but if you have to stick to your map, then you can still copy its content (temporarily) into another data structure.

I think, the best solution is to use a std::set storing flipped key-value pairs as presented in ks1322's answer. The std::set is sorted by default and the order of the pairs is exactly as you need it:

3) If lhs.first<rhs.first, returns true. Otherwise, if rhs.first<lhs.first, returns false. Otherwise, if lhs.second<rhs.second, returns true. Otherwise, returns false.

This way you don't need an additional sorting step and the resulting code is quite short:

std::map<std::string, int> m;  // Your original map.
m["realistically"] = 1;
m["really"]        = 8;
m["reason"]        = 4;
m["reasonable"]    = 3;
m["reasonably"]    = 1;
m["reassemble"]    = 1;
m["reassembled"]   = 1;
m["recognize"]     = 2;
m["record"]        = 92;
m["records"]       = 48;
m["recs"]          = 7;

std::set<std::pair<int, std::string>> s;  // The new (temporary) container.

for (auto const &kv : m)
    s.emplace(kv.second, kv.first);  // Flip the pairs.

for (auto const &vk : s)
    std::cout << std::setw(3) << vk.first << std::setw(15) << vk.second << std::endl;

Output:

  1  realistically
  1     reasonably
  1     reassemble
  1    reassembled
  2      recognize
  3     reasonable
  4         reason
  7           recs
  8         really
 48        records
 92         record

Code on Ideone

Note: Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. As a result, the code for copying your map becomes even shorter and more readable:

for (auto const &[k, v] : m)
    s.emplace(v, k);  // Flip the pairs.

The calling thread cannot access this object because a different thread owns it

There are definitely different ways to do this depending on your needs.

One way I use a UI-updating thread (that's not the main UI thread) is to have the thread start a loop where the entire logical processing loop is invoked onto the UI thread.

Example:

public SomeFunction()
{
    bool working = true;
    Thread t = new Thread(() =>
    {
        // Don't put the working bool in here, otherwise it will 
        // belong to the new thread and not the main UI thread.
        while (working)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                // Put your entire logic code in here.
                // All of this code will process on the main UI thread because
                //  of the Invoke.
                // By doing it this way, you don't have to worry about Invoking individual
                //  elements as they are needed.
            });
        }
    });
}

With this, code executes entirely on main UI thread. This can be a pro for amateur programmers that have difficulty wrapping their heads around cross-threaded operations. However, it can easily become a con with more complex UIs (especially if performing animations). Really, this is only to fake a system of updating the UI and then returning to handle any events that have fired in lieu of efficient cross-threading operations.

Is "delete this" allowed in C++?

You can do so. However, you can't assign to this. Thus the reason you state for doing this, "I want to change the view," seems very questionable. The better method, in my opinion, would be for the object that holds the view to replace that view.

Of course, you're using RAII objects and so you don't actually need to call delete at all...right?

Replace string within file contents

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)

Extracting date from a string in Python

If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date:

import re
from datetime import datetime

match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

Otherwise, if the date is given in an arbitrary form, you can't extract it easily.

How to save and extract session data in codeigniter

initialize the Session class in the constructor of controller using

$this->load->library('session');

for example :

 function __construct()
   {
    parent::__construct();
    $this->load->model('user','',TRUE);
    $this->load->model('user_activity','',TRUE);
    $this->load->library('session');
   }

Can a constructor in Java be private?

I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:

  • to prevent instantiation outside of the object, in the following cases:

    • singleton
    • factory method
    • static-methods-only (utility) class
    • constants-only class
      .
  • to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a synonym for final

  • overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

Oracle "(+)" Operator

That's Oracle specific notation for an OUTER JOIN, because the ANSI-89 format (using a comma in the FROM clause to separate table references) didn't standardize OUTER joins.

The query would be re-written in ANSI-92 syntax as:

   SELECT ...
     FROM a
LEFT JOIN b ON b.id = a.id

This link is pretty good at explaining the difference between JOINs.


It should also be noted that even though the (+) works, Oracle recommends not using it:

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the FROM clause OUTER JOIN syntax:

What is the difference between JavaScript and ECMAScript?

JavaScript is one branch of languages formed around the ECMAScript standard. I believe ECMA is the European Computer Manufacturers Association, not that this is really relevant or anything.

Don't forget another popular language formed around the ECMA Script standard is ActionScript, used in Adobe Flash/Flex.

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

For me it was server responding with something other than 200 and the response was not json formatted. I ended up doing this before the json parse:

# this is the https request for data in json format
response_json = requests.get() 

# only proceed if I have a 200 response which is saved in status_code
if (response_json.status_code == 200):  
     response = response_json.json() #converting from json to dictionary using json library

How I can get and use the header file <graphics.h> in my C++ program?

There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.

I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).

When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

Auto-redirect to another HTML page

I'm Maybe kind of late but here is a way to have a redirect for your website and another link if it does not do in auto redirect for them,

<meta charset="UTF-8" />
<meta http-equiv="refresh" content="5; url=YOUR_URL_HERE" />
<script type="text/javascript">
  window.location.href = "site";
</script>
<title>Page Redirection</title>

<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
If you are not redirected automatically, follow this <a href="/site">Link</a>

Div with margin-left and width:100% overflowing on the right side

Add some css either in the head or in a external document. asp:TextBox are rendered as input :

input {
     width:100%;
}

Your html should look like : http://jsfiddle.net/c5WXA/

Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.

.divClass input {
     width:100%;
}

Doctrine - How to print out the real sql, not just the prepared statement?

A working example:

$qb = $this->createQueryBuilder('a');
$query=$qb->getQuery();
// SHOW SQL: 
echo $query->getSQL(); 
// Show Parameters: 
echo $query->getParameters();

Datatables on-the-fly resizing

I got this to work as follows:

First ensure that in your dataTable definition your aoColumns array includes sWidth data expressed as a % not fixed pixels or ems. Then ensure you have set the bAutoWidth property to false Then add this little but of JS:

update_table_size = function(a_datatable) {
  if (a_datatable == null) return;
  var dtb;
  if (typeof a_datatable === 'string') dtb = $(a_datatable)
  else dtb = a_datatable;
  if (dtb == null) return;

  dtb.css('width', dtb.parent().width());
  dtb.fnAdjustColumSizing();
}

$(window).resize(function() {
  setTimeout(function(){update_table_size(some_table_selector_or_table_ref)}, 250);
});

Works a treat and my table cells handle the white-space: wrap; CSS (which wasn't working without setting the sWidth, and was what led me to this question.)

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"

Proper way to make HTML nested list?

Option 2 is correct: The nested <ul> is a child of the <li> it belongs in.

If you validate, option 1 comes up as an error in html 5 -- credit: user3272456


Correct: <ul> as child of <li>

The proper way to make HTML nested list is with the nested <ul> as a child of the <li> to which it belongs. The nested list should be inside of the <li> element of the list in which it is nested.

<ul>
    <li>Parent/Item
        <ul>
            <li>Child/Subitem
            </li>
        </ul>
    </li>
</ul>

W3C Standard for Nesting Lists

A list item can contain another entire list — this is known as "nesting" a list. It is useful for things like tables of contents, such as the one at the start of this article:

  1. Chapter One
    1. Section One
    2. Section Two
    3. Section Three
  2. Chapter Two
  3. Chapter Three

The key to nesting lists is to remember that the nested list should relate to one specific list item. To reflect that in the code, the nested list is contained inside that list item. The code for the list above looks something like this:

<ol>
  <li>Chapter One
    <ol>
      <li>Section One</li>
      <li>Section Two </li>
      <li>Section Three </li>
    </ol>
  </li>
  <li>Chapter Two</li>
  <li>Chapter Three  </li>
</ol>

Note how the nested list starts after the <li> and the text of the containing list item (“Chapter One”); then ends before the </li> of the containing list item. Nested lists often form the basis for website navigation menus, as they are a good way to define the hierarchical structure of the website.

Theoretically you can nest as many lists as you like, although in practice it can become confusing to nest lists too deeply. For very large lists, you may be better off splitting the content up into several lists with headings instead, or even splitting it up into separate pages.

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

How to add a new column to a CSV file?

This should give you an idea of what to do:

>>> v = open('C:/test/test.csv')
>>> r = csv.reader(v)
>>> row0 = r.next()
>>> row0.append('berry')
>>> print row0
['Name', 'Code', 'berry']
>>> for item in r:
...     item.append(item[0])
...     print item
...     
['blackberry', '1', 'blackberry']
['wineberry', '2', 'wineberry']
['rasberry', '1', 'rasberry']
['blueberry', '1', 'blueberry']
['mulberry', '2', 'mulberry']
>>> 

Edit, note in py3k you must use next(r)

Thanks for accepting the answer. Here you have a bonus (your working script):

import csv

with open('C:/test/test.csv','r') as csvinput:
    with open('C:/test/output.csv', 'w') as csvoutput:
        writer = csv.writer(csvoutput, lineterminator='\n')
        reader = csv.reader(csvinput)

        all = []
        row = next(reader)
        row.append('Berry')
        all.append(row)

        for row in reader:
            row.append(row[0])
            all.append(row)

        writer.writerows(all)

Please note

  1. the lineterminator parameter in csv.writer. By default it is set to '\r\n' and this is why you have double spacing.
  2. the use of a list to append all the lines and to write them in one shot with writerows. If your file is very, very big this probably is not a good idea (RAM) but for normal files I think it is faster because there is less I/O.
  3. As indicated in the comments to this post, note that instead of nesting the two with statements, you can do it in the same line:

    with open('C:/test/test.csv','r') as csvinput, open('C:/test/output.csv', 'w') as csvoutput:

SQL: Return "true" if list of records exists?

I know this is old but I think this will help anyone else who comes looking...

SELECT CAST(COUNT(ProductID) AS bit) AS [EXISTS] FROM Products WHERE(ProductID = @ProductID)

This will ALWAYS return TRUE if exists and FALSE if it doesn't (as opposed to no row).

JavaScript URL Decode function

_x000D_
_x000D_
var uri = "my test.asp?name=ståle&car=saab";_x000D_
console.log(encodeURI(uri));
_x000D_
_x000D_
_x000D_

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Count the occurrences of DISTINCT values

I have resolved the same problem using the below code:

String query = "SELECT violationDate, COUNT(*) as date " +
            "FROM challan " +
            "WHERE challanType = '" + type + "' GROUP BY violationDate";
    

Here violationDate and date are two columns of the result table. date column will return occurrence.

cr.getInt(1)

How do I change Bootstrap 3 column order on mobile layout?

The answers here work for just 2 cells, but as soon as those columns have more in them it can lead to a bit more complexity. I think I've found a generalized solution for any number of cells in multiple columns.

#Goals Get a vertical sequence of tags on mobile to arrange themselves in whatever order the design calls for on tablet/desktop. In this concrete example, one tag must enter flow earlier than it normally would, and another later than it normally would.

##Mobile

[1 headline]
[2 image]
[3 qty]
[4 caption]
[5 desc]

##Tablet+

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][5 desc    ]
[4 caption][          ]
[         ][          ]

So headline needs to shuffle right on tablet+, and technically, so does desc - it sits above the caption tag that precedes it on mobile. You'll see in a moment 4 caption is in trouble too.

Let's assume every cell could vary in height, and needs to be flush top-to-bottom with its next cell (ruling out weak tricks like a table).

As with all Bootstrap Grid problems step 1 is to realize the HTML has to be in mobile-order, 1 2 3 4 5, on the page. Then, determine how to get tablet/desktop to reorder itself in this way - ideally without Javascript.

The solution to get 1 headline and 3 qty to sit to the right not the left is to simply set them both pull-right. This applies CSS float: right, meaning they find the first open space they'll fit to the right. You can think of the browser's CSS processor working in the following order: 1 fits in to the right top corner. 2 is next and is regular (float: left), so it goes to top-left corner. Then 3, which is float: right so it leaps over underneath 1.

But this solution wasn't enough for 4 caption; because the right 2 cells are so short 2 image on the left tends to be longer than the both of them combined. Bootstrap Grid is a glorified float hack, meaning 4 caption is float: left. With 2 image occupying so much room on the left, 4 caption attempts to fit in the next available space - often the right column, not the left where we wanted it.

The solution here (and more generally for any issue like this) was to add a hack tag, hidden on mobile, that exists on tablet+ to push caption out, that then gets covered up by a negative margin - like this:

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][4 hack    ]
[5 caption][6 desc ^^^]
[         ][          ]

http://jsfiddle.net/b9chris/52VtD/16633/

HTML:

<div id=headline class="col-xs-12 col-sm-6 pull-right">Product Headline</div>
<div id=image class="col-xs-12 col-sm-6">Product Image</div>
<div id=qty class="col-xs-12 col-sm-6 pull-right">Qty, Add to cart</div>
<div id=hack class="hidden-xs col-sm-6">Hack</div>
<div id=caption class="col-xs-12 col-sm-6">Product image caption</div>
<div id=desc class="col-xs-12 col-sm-6 pull-right">Product description</div>

CSS:

#hack { height: 50px; }

@media (min-width: @screen-sm) {
    #desc { margin-top: -50px; }
}

So, the generalized solution here is to add hack tags that can disappear on mobile. On tablet+ the hack tags allow displayed tags to appear earlier or later in the flow, then get pulled up or down to cover up those hack tags.

Note: I've used fixed heights for the sake of the simple example in the linked jsfiddle, but the actual site content I was working on varies in height in all 5 tags. It renders properly with relatively large variance in tag heights, especially image and desc.

Note 2: Depending on your layout, you may have a consistent enough column order on tablet+ (or larger resolutions), that you can avoid use of hack tags, using margin-bottom instead, like so:

Note 3: This uses Bootstrap 3. Bootstrap 4 uses a different grid set, and won't work with these examples.

http://jsfiddle.net/b9chris/52VtD/16632/

Equivalent of Oracle's RowID in SQL Server

If you want to uniquely identify a row within the table rather than your result set, then you need to look at using something like an IDENTITY column. See "IDENTITY property" in the SQL Server help. SQL Server does not auto-generate an ID for each row in the table as Oracle does, so you have to go to the trouble of creating your own ID column and explicitly fetch it in your query.

EDIT: for dynamic numbering of result set rows see below, but that would probably an equivalent for Oracle's ROWNUM and I assume from all the comments on the page that you want the stuff above. For SQL Server 2005 and later you can use the new Ranking Functions function to achieve dynamic numbering of rows.

For example I do this on a query of mine:

select row_number() over (order by rn_execution_date asc) as 'Row Number', rn_execution_date as 'Execution Date', count(*) as 'Count'
from td.run
where rn_execution_date >= '2009-05-19'
group by rn_execution_date
order by rn_execution_date asc

Will give you:

Row Number  Execution Date           Count
----------  -----------------        -----
1          2009-05-19 00:00:00.000  280
2          2009-05-20 00:00:00.000  269
3          2009-05-21 00:00:00.000  279

There's also an article on support.microsoft.com on dynamically numbering rows.

Get the previous month's first and last day dates in c#

An approach using extension methods:

class Program
{
    static void Main(string[] args)
    {
        DateTime t = DateTime.Now;

        DateTime p = t.PreviousMonthFirstDay();
        Console.WriteLine( p.ToShortDateString() );

        p = t.PreviousMonthLastDay();
        Console.WriteLine( p.ToShortDateString() );


        Console.ReadKey();
    }
}


public static class Helpers
{
    public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
    {
        DateTime d = currentDate.PreviousMonthLastDay();

        return new DateTime( d.Year, d.Month, 1 );
    }

    public static DateTime PreviousMonthLastDay( this DateTime currentDate )
    {
        return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
    }
}

See this link http://www.codeplex.com/fluentdatetime for some inspired DateTime extensions.

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

Navigation drawer: How do I set the selected item at startup?

You have to call 2 functions for this:

First: for excuting the commands you have implemented in onNavigationItemSelected listener:

onNavigationItemSelected(navigationView.getMenu().getItem(R.id.nav_camera));

Second: for changing the state of the navigation drawer menu item to selected (or checked):

navigationView.setCheckedItem(R.id.nav_camera);

I called both functions and it worked for me.

What does "TypeError 'xxx' object is not callable" means?

The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:

>>> a = 5
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Class instances can also be called if they define a method __call__

One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?

The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

Cache an HTTP 'Get' service response in AngularJS?

I think there's an even easier way now. This enables basic caching for all $http requests (which $resource inherits):

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;
      }])

Selecting Folder Destination in Java?

Along with JFileChooser is possible use this:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

for have a Look and Feel like Windows.

for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available

syntax error: unexpected token <

This happened to me with a page loaded in via an iframe. The iframe src page had a 404 script reference. Obviously I couldn't find the script reference in the parent page, so it took me a while to find the culprit.

Sticky Header after scrolling down

I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.

    $('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
    if (e.currentTarget.scrollTop >= 130) {
        $('.results-label').addClass('fixedSimilarLabel');
    }
    else {      
        $('.results-label').removeClass('fixedSimilarLabel');
    }
});

http://codepen.io/franklynroth/pen/pjEzeK

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

Java Serializable Object to Byte Array

Another interesting method is from com.fasterxml.jackson.databind.ObjectMapper

byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)

Maven Dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

How to modify existing, unpushed commit messages?

  1. If you only want to modify your last commit message, then do:

    git commit --amend
    

That will drop you into your text editor and let you change the last commit message.

  1. If you want to change the last three commit messages, or any of the commit messages up to that point, supply HEAD~3 to the git rebase -i command:

    git rebase -i HEAD~3
    

Google Maps Android API v2 Authorization failure

You need to use the library project located at: ANDROID-SDK-DIRECTORY/extras/google/google_play_services/libproject

This will fix your first issue.

I'm not sure about your second, but it may be a side effect of the first. I am still trying to get the map working in my own app :)

How can I convert a string to upper- or lower-case with XSLT?

XSLT 2.0 has upper-case() and lower-case() functions. In case of XSLT 1.0, you can use translate():

<xsl:value-of select="translate("xslt", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")" />

Sort list in C# with LINQ

Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.

Get size of all tables in database

After some searching, I could not find an easy way to get information on all of the tables. There is a handy stored procedure named sp_spaceused that will return all of the space used by the database. If provided with a table name, it returns the space used by that table. However, the results returned by the stored procedure are not sortable, since the columns are character values.

The following script will generate the information I'm looking for.

create table #TableSize (
    Name varchar(255),
    [rows] int,
    reserved varchar(255),
    data varchar(255),
    index_size varchar(255),
    unused varchar(255))
create table #ConvertedSizes (
    Name varchar(255),
    [rows] int,
    reservedKb int,
    dataKb int,
    reservedIndexSize int,
    reservedUnused int)

EXEC sp_MSforeachtable @command1="insert into #TableSize
EXEC sp_spaceused '?'"
insert into #ConvertedSizes (Name, [rows], reservedKb, dataKb, reservedIndexSize, reservedUnused)
select name, [rows], 
SUBSTRING(reserved, 0, LEN(reserved)-2), 
SUBSTRING(data, 0, LEN(data)-2), 
SUBSTRING(index_size, 0, LEN(index_size)-2), 
SUBSTRING(unused, 0, LEN(unused)-2)
from #TableSize

select * from #ConvertedSizes
order by reservedKb desc

drop table #TableSize
drop table #ConvertedSizes

Adding a favicon to a static HTML page

Most browsers will pick up favicon.ico from the root directory of the site without needing to be told; but they don't always update it with a new one right away.

However, I usually go for the second of your examples:

<link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' />

How to set root password to null

On ubuntu 19.10, mysql 8, this is what worked for me:

$ sudo mysqld --skip-grant-tables &
$ mysql
> use mysql
> alter user set authentication_string='', plugin='mysql_native_password' where user = 'root';
> quit
$ sudo mysqladmin shutdown
$ sudo systemctl start mysql

If you get errors trying to run mysqld_safe, in particular: /var/run/mysqld for UNIX socket file don't exists, you can try creating the dir and running mysqld_safe again.

$ sudo mkdir /var/run/mysqld
$ sudo chown mysql /var/run/mysqld
$ sudo chgrp mysql /var/run/mysqld

Spring Boot Remove Whitelabel Error Page

With Spring Boot > 1.4.x you could do this:

@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
public class MyApi {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}

but then in case of exception the servlet container will display its own error page.

How to lowercase a pandas dataframe string column if it has missing values?

Use apply function,

Xlower = df['x'].apply(lambda x: x.upper()).head(10) 

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

Calculate the display width of a string in Java

Use the getWidth method in the following class:

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;

class StringMetrics {

  Font font;
  FontRenderContext context;

  public StringMetrics(Graphics2D g2) {

    font = g2.getFont();
    context = g2.getFontRenderContext();
  }

  Rectangle2D getBounds(String message) {

    return font.getStringBounds(message, context);
  }

  double getWidth(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getWidth();
  }

  double getHeight(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getHeight();
  }

}

Python glob multiple filetypes

By the results I've obtained from empirical tests, it turned out that glob.glob isn't the better way to filter out files by their extensions. Some of the reason are:

  • The globbing "language" does not allows perfect specification of multiple extension.
  • The former point results in obtaining incorrect results depending on file extensions.
  • The globbing method is empirically proven to be slower than most other methods.
  • Even if it's strange even other filesystems objects can have "extensions", folders too.

I've tested (for correcteness and efficiency in time) the following 4 different methods to filter out files by extensions and puts them in a list:

from glob import glob, iglob
from re import compile, findall
from os import walk


def glob_with_storage(args):

    elements = ''.join([f'[{i}]' for i in args.extensions])
    globs = f'{args.target}/**/*{elements}'
    results = glob(globs, recursive=True)

    return results


def glob_with_iteration(args):

    elements = ''.join([f'[{i}]' for i in args.extensions])
    globs = f'{args.target}/**/*{elements}'
    results = [i for i in iglob(globs, recursive=True)]

    return results


def walk_with_suffixes(args):

    results = []
    for r, d, f in walk(args.target):
        for ff in f:
            for e in args.extensions:
                if ff.endswith(e):
                    results.append(path_join(r,ff))
                    break
    return results


def walk_with_regs(args):

    reg = compile('|'.join([f'{i}$' for i in args.extensions]))

    results = []
    for r, d, f in walk(args.target):
        for ff in f:
            if len(findall(reg,ff)):
                results.append(path_join(r, ff))

    return results

By running the code above on my laptop I obtained the following auto-explicative results.

Elapsed time for '7 times glob_with_storage()':  0.365023 seconds.
mean   : 0.05214614
median : 0.051861
stdev  : 0.001492152
min    : 0.050864
max    : 0.054853

Elapsed time for '7 times glob_with_iteration()':  0.360037 seconds.
mean   : 0.05143386
median : 0.050864
stdev  : 0.0007847381
min    : 0.050864
max    : 0.052859

Elapsed time for '7 times walk_with_suffixes()':  0.26529 seconds.
mean   : 0.03789857
median : 0.037899
stdev  : 0.0005759071
min    : 0.036901
max    : 0.038896

Elapsed time for '7 times walk_with_regs()':  0.290223 seconds.
mean   : 0.04146043
median : 0.040891
stdev  : 0.0007846776
min    : 0.04089
max    : 0.042885

Results sizes:
0 2451
1 2451
2 2446
3 2446

Differences between glob() and walk():
0 E:\x\y\z\venv\lib\python3.7\site-packages\Cython\Includes\numpy
1 E:\x\y\z\venv\lib\python3.7\site-packages\Cython\Utility\CppSupport.cpp
2 E:\x\y\z\venv\lib\python3.7\site-packages\future\moves\xmlrpc
3 E:\x\y\z\venv\lib\python3.7\site-packages\Cython\Includes\libcpp
4 E:\x\y\z\venv\lib\python3.7\site-packages\future\backports\xmlrpc

Elapsed time for 'main':  1.317424 seconds.

The fastest way to filter out files by extensions, happens even to be the ugliest one. Which is, nested for loops and string comparison using the endswith() method.

Moreover, as you can see, the globbing algorithms (with the pattern E:\x\y\z\**/*[py][pyc]) even with only 2 extension given (py and pyc) returns also incorrect results.

How to set a hidden value in Razor

There is a Hidden helper alongside HiddenFor which lets you set the value.

@Html.Hidden("RequiredProperty", "default")

EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.

This code:

<ul>
@{
        var stacks = new System.Diagnostics.StackTrace().GetFrames();
        foreach (var frame in stacks)
        {
            <li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
        }
}
</ul>

Will give output like this:

Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml

So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.

The model backing the 'ApplicationDbContext' context has changed since the database was created

Just Delete the migration History in _MigrationHistory in your DataBase. It worked for me

How to empty ("truncate") a file on linux that already exists and is protected in someway?

You have the noclobber option set. The error looks like it's from csh, so you would do:

cat /dev/null >! file

If I'm wrong and you are using bash, you should do:

cat /dev/null >| file

in bash, you can also shorten that to:

>| file

Why do I get access denied to data folder when using adb?

before we start, do you have a rooted phone? if not, I strongly suggest that it's time you make the jump. 99% of the tutorials that help you to do this require that you have a rooted phone (I know b/c I spent about an hour searching for a way to do it without having a rooted phone.. couldn't find any..) also if you think about it, your iPhone also has to be rooted to do this same task. So it's totally reasonable. More about rooting at end of answer.

from your command line type:

adb shell

this takes you to your android shell comand line (you should see something like this: shell@android:/ $ now type:

shell@android:/ $run-as com.domain.yourapp

this should take you directly to the data directory of com.domain.yourapp:

shell@android:/data/data/com.domain.yourapp $ 

if it doesn't (ie if you get an error) then you probably don't have a rooted phone, or you haven't used your root user privileges. To use your root user privileges, type su on the adb command line and see what happens, if you get an error, then you're phone is not rooted. If it's not, root it first then continue these instructions.

from there you can type ls and you'll see all the directories including the dbs:

shell@android:/data/data/com.domain.yourapp $ ls

cache
databases
lib
shared_prefs   

after that you can use sqlite3 to browse the dbase.. if you don't have it installed (you can find it out by typing sqlite3, if you get command not found then you'll have to install it. To install sqlite, follow instructions here.

about rooting: if you've never rooted your phone before, and you're worried about it screwing your phone, I can tell you with full confidence that there is nothing to worry about. there are tonnes of quick and easy phone rooting tutorials for pretty much all the new and old models out there, and you can root your phone even if you have a mac (I rooted my s3 with my mac).

Add floating point value to android resources/values

Add a float to dimens.xml:

<item format="float" name="my_dimen" type="dimen">1.2</item>

To reference from XML:

<EditText 
    android:lineSpacingMultiplier="@dimen/my_dimen"
    ...

To read this value programmatically you can use ResourcesCompat.getFloat from androidx.core

Gradle dependency:

implementation("androidx.core:core:${version}")

Usage:

import androidx.core.content.res.ResourcesCompat;

...

float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);

How to change the background color of a UIButton while it's highlighted?

In Swift you can override the accessor of the highlighted (or selected) property rather than overriding the setHighlighted method

override var highlighted: Bool {
        get {
            return super.highlighted
        }
        set {
            if newValue {
                backgroundColor = UIColor.blackColor()
            }
            else {
                backgroundColor = UIColor.whiteColor()
            }
            super.highlighted = newValue
        }
    }

What is the closest thing Windows has to fork()?

The closest you say... Let me think... This must be fork() I guess :)

For details see Does Interix implement fork()?

Get exit code of a background process

#/bin/bash

#pgm to monitor
tail -f /var/log/messages >> /tmp/log&
# background cmd pid
pid=$!
# loop to monitor running background cmd
while :
do
    ps ax | grep $pid | grep -v grep
    ret=$?
    if test "$ret" != "0"
    then
        echo "Monitored pid ended"
        break
    fi
    sleep 5

done

wait $pid
echo $?

How to properly URL encode a string in PHP?

The cunningly-named urlencode() and urldecode().

However, you shouldn't need to use urldecode() on variables that appear in $_POST and $_GET.

How to get last items of a list in Python?

a negative index will count from the end of the list, so:

num_list[-9:]

How to center the content inside a linear layout?

I tried solutions mentioned here but It didn't help me. I mind the solution is layout_width have to use wrap_content as value.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_weight="1" >

Python: No acceptable C compiler found in $PATH when installing python

The gcc compiler is not in your $PATH. It means either you dont have gcc installed or it's not in your $PATH variable.

To install gcc use this: (run as root)

  • Redhat base:

    yum groupinstall "Development Tools"
    
  • Debian base:

    apt-get install build-essential
    

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url, [ success(data, textStatus) ] )
  • url - A string containing the URL to which the request is sent.

  • success(data, textStatus) - A callback function that is executed if the request succeeds.

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

Get response from PHP file using AJAX

<script type="text/javascript">
        function returnwasset(){
            alert('return sent');
            $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                dataType:'text'; //or HTML, JSON, etc.
                success: function(response){
                    alert(response);
                    //echo what the server sent back...
                }
            });
        }
    </script>

Force git stash to overwrite added files

Use git checkout instead of git stash apply:

$ git checkout stash -- .
$ git commit

This will restore all the files in the current directory to their stashed version.


If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:

$ git merge --squash --strategy-option=theirs stash

If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using

$ git checkout stash -- <paths...>

or interactively with

$ git checkout -p stash

How to add label in chart.js for pie chart

Use ChartNew.js instead of Chart.js

...

So, I have re-worked Chart.js. Most of the changes, are associated to requests in "GitHub" issues of Chart.js.

And here is a sample http://jsbin.com/lakiyu/2/edit

var newopts = {
    inGraphDataShow: true,
    inGraphDataRadiusPosition: 2,
    inGraphDataFontColor: 'white'
}
var pieData = [
    {
        value: 30,
        color: "#F38630",
    },
    {
       value: 30,
       color: "#F34353",
    },
    {
        value: 30,
        color: "#F34353",
    }
]
var pieCtx = document.getElementById('pieChart').getContext('2d');
new Chart(pieCtx).Pie(pieData, newopts);

It even provides a GUI editor http://charts.livegap.com/

So sweet.

How to convert string to float?

Use atof() or strtof()* instead:

printf("float value : %4.8f\n" ,atof(s)); 
printf("float value : %4.8f\n" ,strtof(s, NULL)); 

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/

  • atoll() is meant for integers.
  • atof()/strtof() is for floats.

The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

*Note that strtof() requires C99 or C++11.

Image comparison - fast algorithm

I have an idea, which can work and it most likely to be very fast. You can sub-sample an image to say 80x60 resolution or comparable, and convert it to grey scale (after subsampling it will be faster). Process both images you want to compare. Then run normalised sum of squared differences between two images (the query image and each from the db), or even better Normalised Cross Correlation, which gives response closer to 1, if both images are similar. Then if images are similar you can proceed to more sophisticated techniques to verify that it is the same images. Obviously this algorithm is linear in terms of number of images in your database so even though it is going to be very fast up to 10000 images per second on the modern hardware. If you need invariance to rotation, then a dominant gradient can be computed for this small image, and then the whole coordinate system can be rotated to canonical orientation, this though, will be slower. And no, there is no invariance to scale here.

If you want something more general or using big databases (million of images), then you need to look into image retrieval theory (loads of papers appeared in the last 5 years). There are some pointers in other answers. But It might be overkill, and the suggest histogram approach will do the job. Though I would think combination of many different fast approaches will be even better.

Can you do greater than comparison on a date in a Rails 3 search?

You can try to use:

where(date: p[:date]..Float::INFINITY)

equivalent in sql

WHERE (`date` >= p[:date])

The result is:

Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)

And I have changed too

order('date ASC, created_at ASC')

For

order(:fecha, :created_at)

Django: Get list of model fields?

I find adding this to django models quite helpful:

def __iter__(self):
    for field_name in self._meta.get_all_field_names():
        value = getattr(self, field_name, None)
        yield (field_name, value)

This lets you do:

for field, val in object:
    print field, val

Java, List only subdirectories from a directory, not files

You can use the JAVA 7 Files api

Path myDirectoryPath = Paths.get("path to my directory");
List<Path> subDirectories = Files.find(
                    myDirectoryPath ,
                    Integer.MAX_VALUE,
                    (filePath, fileAttr) -> fileAttr.isDirectory() && !filePath.equals(myDirectoryPath )
            ).collect(Collectors.toList());

If you want a specific value you can call map with the value you want before collecting the data.

for each inside a for each - Java

If I understand correctly, what you want to do, in pseudo-code is the following:

for (Tweet tweet : tweets) {
    if (!db.containsTweet(tweet.getId())) {
        db.insertTweet(tweet.getText(), tweet.getId());
    }
}

I assume your db class actually uses an sqlite database as a backend? What you could do is implement containsTweet directly and just query the database each time, but that seems less than perfect. The easiest solution if we go by your base code is to just keep a Set around that indexes the tweets. Since I can't be sure what the equals() method of Tweet looks like, I'll just store the identifiers in there. Then you get:

Set<Integer> tweetIds = new HashSet<Integer>(); // or long, whatever
for (Tweet tweet : tweets) {
    if (!tweetIds.contains(tweet.getId())) {
        db.insertTweet(tweet.getText(), tweet.getId());
        tweetIds.add(tweet.getId());
    }
}

It would probably be better to save a tiny bit of this work, by sorting the list of tweets to begin with and then just filtering out duplicate tweets. You could use:

// if tweets is a List
Collections.sort(tweets, new Comparator() {
    public int compare (Object t1, Object t2) {
        // might be the wrong way around
        return ((Tweet)t1).getId() - ((Tweet)t2).getId();
    }
}

Then process it

Integer oldId;
for (Tweet tweet : tweets) {
    if (oldId == null || oldId != tweet.getId()) {
        db.insertTweet(tweet.getText(), tweet.getId());
    }
    oldId = tweet.getId();
}

Yes, you could do this using a second for-loop, but you'll run into performance problems much more quickly than with this approach (although what we're doing here is trading time for memory performance, of course).

good example of Javadoc

Download the sources of Lucene and see how they do it. They have good JavaDocs.

What does the red exclamation point icon in Eclipse mean?

I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.

In my case I was using mvn eclipse:eclipse on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.

I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/

How to connect to local instance of SQL Server 2008 Express

I used (LocalDB)\MSSQLLocalDB as the server name, I was then able to see all the local databases.

How to make child process die after parent exits?

I think a quick and dirty way is to create a pipe between child and parent. When parent exits, children will receive a SIGPIPE.

How to mount a host directory in a Docker container

There are a couple ways you can do this. The simplest way to do so is to use the dockerfile ADD command like so:

ADD . /path/inside/docker/container

However, any changes made to this directory on the host after building the dockerfile will not show up in the container. This is because when building a container, docker compresses the directory into a .tar and uploads that context into the container permanently.

The second way to do this is the way you attempted, which is to mount a volume. Due to trying to be as portable as possible you cannot map a host directory to a docker container directory within a dockerfile, because the host directory can change depending on which machine you are running on. To map a host directory to a docker container directory you need to use the -v flag when using docker run, e.g.,:

# Run a container using the `alpine` image, mount the `/tmp`
# directory from your host into the `/container/directory`
# directory in your container, and run the `ls` command to
# show the contents of that directory.
docker run \
    -v /tmp:/container/directory \
    alpine \
    ls /container/directory

How to set Meld as git mergetool

This worked for me on Windows 8.1 and Windows 10.

git config --global mergetool.meld.path "/c/Program Files (x86)/meld/meld.exe"

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

Finding a branch point with Git?

I've used git rev-list for this sort of thing. For example, (note the 3 dots)

$ git rev-list --boundary branch-a...master | grep "^-" | cut -c2-

will spit out the branch point. Now, it's not perfect; since you've merged master into branch A a couple of times, that'll split out a couple possible branch points (basically, the original branch point and then each point at which you merged master into branch A). However, it should at least narrow down the possibilities.

I've added that command to my aliases in ~/.gitconfig as:

[alias]
    diverges = !sh -c 'git rev-list --boundary $1...$2 | grep "^-" | cut -c2-'

so I can call it as:

$ git diverges branch-a master

ajax jquery simple get request

It seems to me, this is a cross-domain issue since you're not allowed to make a request to a different domain.

You have to find solutions to this problem: - Use a proxy script, running on your server that will forward your request and will handle the response sending it to the browser Or - The service you're making the request should have JSONP support. This is a cross-domain technique. You might want to read this http://en.wikipedia.org/wiki/JSONP

HTML table sort

Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. :)

https://github.com/paulopmx/Flexigrid - Flexgrid
http://datatables.net/index - Data tables.
https://github.com/tonytomov/jqGrid

If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.

How to reload a page using JavaScript

You can perform this task using window.location.reload();. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation

JavaScript window.location object can be used

  • to get current page address (URL)
  • to redirect the browser to another page
  • to reload the same page

window: in JavaScript represents an open window in a browser.

location: in JavaScript holds information about current URL.

The location object is like a fragment of the window object and is called up through the window.location property.

location object has three methods:

  1. assign(): used to load a new document
  2. reload(): used to reload current document
  3. replace(): used to replace current document with a new one

So here we need to use reload(), because it can help us in reloading the same document.

So use it like window.location.reload();.

Online demo on jsfiddle

To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload(). This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.

How to print Boolean flag in NSLog?

%d, 0 is FALSE, 1 is TRUE.

BOOL b; 
NSLog(@"Bool value: %d",b);

or

NSLog(@"bool %s", b ? "true" : "false");

On the bases of data type %@ changes as follows

For Strings you use %@
For int  you use %i
For float and double you use %f

How to install SQL Server Management Studio 2012 (SSMS) Express?

Good evening,

The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out. When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2. Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.

Cheers.

Font is not available to the JVM with Jasper Reports

Actually I fixed this issue in a very simple way

  1. go to your home path, like /root
  2. create a folder named .fonts
  3. copy your all your font files to .fonts, you can copy the font from C:\windows\fonts if you use windows.
  4. sudo apt-get install fontconfig
  5. fc-cache –fv to rebuid fonts caches.

How to start MySQL with --skip-grant-tables?

If you use mysql 5.6 server and have problems with C:\Program Files\MySQL\MySQL Server 5.6\my.ini:

You should go to C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

You should add skip-grant-tables and then you do not need a password.

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
# server_type=3
[mysqld]
skip-grant-tables

Note: after you are done with your work on skip-grant-tables, you should restore your file of C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

"Could not find acceptable representation" using spring-boot-starter-web

You have no public getters for your UpdateResult, for example :

public static class UploadResult {
    private String value;
    public UploadResult(final String value)
    {
        this.value = value;
    }

    public String getValue() {
       return this.value;
    }
}

I believe by default auto discovery is on and will try to discover your getters. You can disable it with @JsonAutoDetect(getterVisibility=Visibility.NONE), and in your example will result in [].

C# Clear all items in ListView

Probably your code works but it is rebound somewhere after you clear it. Make sure that this it not the case. It will be more helpful if you provide some code. Where are you setting your data source? Where are you data binding? Where are you clearing the list?

Setting HTTP headers

Never mind, I figured it out - I used the Set() method on Header() (doh!)

My handler looks like this now:

func saveHandler(w http.ResponseWriter, r *http.Request) {
    // allow cross domain AJAX requests
    w.Header().Set("Access-Control-Allow-Origin", "*")
}

Maybe this will help someone as caffeine deprived as myself sometime :)

Angular 5 - Copy to clipboard

As of Angular Material v9, it now has a clipboard CDK

Clipboard | Angular Material

It can be used as simply as

<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>

Command failed due to signal: Segmentation fault: 11

I just had this issue and found that it was because I had accidentally left an override on a function that I'd moved from the class to a protocol (therefore the subclass was no longer overriding a function of the parent).

PHP Get Highest Value from Array

You could use max() for getting the largest value, but it will return just a value without an according index of array. Then, you could use array_search() to find the according key.

$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxValue = max($array);
$maxIndex = array_search(max($array), $array);
var_dump($maxValue, $maxIndex);

Output:

int 5
string 'd' (length=1)

If there are multiple elements with the same value, you'll have to loop through array to get all the keys.

It's difficult to suggest something good without knowing the problem. Why do you need it? What is the input, what is the desired output?

When should I really use noexcept?

  1. There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

noexcept is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.

If you have a function that cannot throw, ask yourself whether it will like stay noexcept or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept.

On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept. However, keep in mind that the compiler will not be able to detect violations of noexcept if your implementation changes.

  1. For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?

There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:

  1. move operations (move assignment operator and move constructors)
  2. swap operations
  3. memory deallocators (operator delete, operator delete[])
  4. destructors (though these are implicitly noexcept(true) unless you make them noexcept(false))

These functions should generally be noexcept, and it is most likely that library implementations can make use of the noexcept property. For example, std::vector can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).

This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.

  1. When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

The advantage of noexcept against no exception specification or throw() is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw() case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).

In the noexcept case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.

The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.

I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.

How do I close an open port from the terminal on the Mac?

I use lsof combined with kill, as mentioned above; but wrote a quick little bash script to automate this process.

With this script, you can simply type killport 3000 from anywhere, and it will kill all processes running on port 3000.

https://github.com/xtrasimplicity/killport

javascript get child by id

In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

function test(el){
  el.querySelector("#child").style.display = "none";
}

For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

Why is Java's SimpleDateFormat not thread-safe?

ThreadLocal + SimpleDateFormat = SimpleDateFormatThreadSafe

package com.foocoders.text;

import java.text.AttributedCharacterIterator;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class SimpleDateFormatThreadSafe extends SimpleDateFormat {

    private static final long serialVersionUID = 5448371898056188202L;
    ThreadLocal<SimpleDateFormat> localSimpleDateFormat;

    public SimpleDateFormatThreadSafe() {
        super();
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat();
            }
        };
    }

    public SimpleDateFormatThreadSafe(final String pattern) {
        super(pattern);
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(pattern);
            }
        };
    }

    public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) {
        super(pattern, formatSymbols);
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(pattern, formatSymbols);
            }
        };
    }

    public SimpleDateFormatThreadSafe(final String pattern, final Locale locale) {
        super(pattern, locale);
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(pattern, locale);
            }
        };
    }

    public Object parseObject(String source) throws ParseException {
        return localSimpleDateFormat.get().parseObject(source);
    }

    public String toString() {
        return localSimpleDateFormat.get().toString();
    }

    public Date parse(String source) throws ParseException {
        return localSimpleDateFormat.get().parse(source);
    }

    public Object parseObject(String source, ParsePosition pos) {
        return localSimpleDateFormat.get().parseObject(source, pos);
    }

    public void setCalendar(Calendar newCalendar) {
        localSimpleDateFormat.get().setCalendar(newCalendar);
    }

    public Calendar getCalendar() {
        return localSimpleDateFormat.get().getCalendar();
    }

    public void setNumberFormat(NumberFormat newNumberFormat) {
        localSimpleDateFormat.get().setNumberFormat(newNumberFormat);
    }

    public NumberFormat getNumberFormat() {
        return localSimpleDateFormat.get().getNumberFormat();
    }

    public void setTimeZone(TimeZone zone) {
        localSimpleDateFormat.get().setTimeZone(zone);
    }

    public TimeZone getTimeZone() {
        return localSimpleDateFormat.get().getTimeZone();
    }

    public void setLenient(boolean lenient) {
        localSimpleDateFormat.get().setLenient(lenient);
    }

    public boolean isLenient() {
        return localSimpleDateFormat.get().isLenient();
    }

    public void set2DigitYearStart(Date startDate) {
        localSimpleDateFormat.get().set2DigitYearStart(startDate);
    }

    public Date get2DigitYearStart() {
        return localSimpleDateFormat.get().get2DigitYearStart();
    }

    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
        return localSimpleDateFormat.get().format(date, toAppendTo, pos);
    }

    public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
        return localSimpleDateFormat.get().formatToCharacterIterator(obj);
    }

    public Date parse(String text, ParsePosition pos) {
        return localSimpleDateFormat.get().parse(text, pos);
    }

    public String toPattern() {
        return localSimpleDateFormat.get().toPattern();
    }

    public String toLocalizedPattern() {
        return localSimpleDateFormat.get().toLocalizedPattern();
    }

    public void applyPattern(String pattern) {
        localSimpleDateFormat.get().applyPattern(pattern);
    }

    public void applyLocalizedPattern(String pattern) {
        localSimpleDateFormat.get().applyLocalizedPattern(pattern);
    }

    public DateFormatSymbols getDateFormatSymbols() {
        return localSimpleDateFormat.get().getDateFormatSymbols();
    }

    public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) {
        localSimpleDateFormat.get().setDateFormatSymbols(newFormatSymbols);
    }

    public Object clone() {
        return localSimpleDateFormat.get().clone();
    }

    public int hashCode() {
        return localSimpleDateFormat.get().hashCode();
    }

    public boolean equals(Object obj) {
        return localSimpleDateFormat.get().equals(obj);
    }

}

https://gist.github.com/pablomoretti/9748230

Can VS Code run on Android?

There is a 3rd party debugger in the works, it's currently in preview, but you can install the debugger Android extension in VSCode right now and get more information on it here:

https://github.com/adelphes/android-dev-ext

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      stack()
      {element=new int[10];
      top=-1;
      }
      void push(int item)
      {top++;
      if(top==9)
          System.out.println("Overflow");
      else
              {
               top++;
      element[top]=item;

      }

      void pop()
      {if(top==-1)
          System.out.println("Underflow");
      else  
      top--;
      }
      void display()
      {
          System.out.println("\nTop="+top+"\nElement="+element[top]);
      }

      public static void main(String args[])
      {
        stack s1=new stack();
        s1.push(10);
        s1.display();
        s1.push(20);
        s1.display();
        s1.push(30);
        s1.display();
        s1.pop();
        s1.display();
      }

  }

Output

Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

jQuery: Uncheck other checkbox on one checked

Try this

$("[id*='type']").click(
function () {
var isCheckboxChecked = this.checked;
$("[id*='type']").attr('checked', false);
this.checked = isCheckboxChecked;
});

To make it even more generic you can also find checkboxes by the common class implemented on them.

Modified...

Git - deleted some files locally, how do I get them from a remote repository

You need to check out a previous version from before you deleted the files. Try git checkout HEAD^ to checkout the last revision.

"PKIX path building failed" and "unable to find valid certification path to requested target"

Problem is, your eclipse is not able to connect the site which actually it is trying to. I have faced similar issue and below given solution worked for me.

  1. Turn off any third party internet security application e.g. Zscaler
  2. Sometimes also need to disconnect VPN if you are connected.

Thanks

Yes/No message box using QMessageBox

QMessageBox includes static methods to quickly ask such questions:

#include <QApplication>
#include <QMessageBox>

int main(int argc, char **argv)
{
    QApplication app{argc, argv};
    while (QMessageBox::question(nullptr,
                                 qApp->translate("my_app", "Test"),
                                 qApp->translate("my_app", "Are you sure you want to quit?"),
                                 QMessageBox::Yes|QMessageBox::No)
           != QMessageBox::Yes)
        // ask again
        ;
}

If your needs are more complex than provided for by the static methods, you should construct a new QMessageBox object, and call its exec() method to show it in its own event loop and obtain the pressed button identifier. For example, we might want to make "No" be the default answer:

#include <QApplication>
#include <QMessageBox>

int main(int argc, char **argv)
{
    QApplication app{argc, argv};
    auto question = new QMessageBox(QMessageBox::Question,
                                    qApp->translate("my_app", "Test"),
                                    qApp->translate("my_app", "Are you sure you want to quit?"),
                                    QMessageBox::Yes|QMessageBox::No,
                                    nullptr);
    question->setDefaultButton(QMessageBox::No);

    while (question->exec() != QMessageBox::Yes)
        // ask again
        ;
}

How to change default text file encoding in Eclipse?

What worked for me in Eclipse Mars was to go to Window > Preferences > Web > HTML Files, and in the right panel in Encoding select ISO 10646/Unicode(UTF-8), Apply and OK, then and only then my .html files were created with .

Modifying a subset of rows in a pandas dataframe

Use .loc for label based indexing:

df.loc[df.A==0, 'B'] = np.nan

The df.A==0 expression creates a boolean series that indexes the rows, 'B' selects the column. You can also use this to transform a subset of a column, e.g.:

df.loc[df.A==0, 'B'] = df.loc[df.A==0, 'B'] / 2

I don't know enough about pandas internals to know exactly why that works, but the basic issue is that sometimes indexing into a DataFrame returns a copy of the result, and sometimes it returns a view on the original object. According to documentation here, this behavior depends on the underlying numpy behavior. I've found that accessing everything in one operation (rather than [one][two]) is more likely to work for setting.

How to make an empty div take space

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key here is the Box-Sizing and Padding.

How do you declare string constants in C?

One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:

#define HELLO "hello"
#define WORLD "world"

puts( HELLO WORLD );

Not sure that's really an advantage, but it is a technique that cannot be used with const char *'s.

java.lang.IllegalArgumentException: View not attached to window manager

i agree a opinion of 'Damjan'.
if you use many dialogs, should close all dialog in onDestroy() or onStop().
then you may be able to reduce the frequency 'java.lang.IllegalArgumentException: View not attached to window manager' exception occurs.

@Override
protected void onDestroy() {
    Log.d(TAG, "called onDestroy");
    mDialog.dismiss();
    super.onDestroy();
}



but little exceed...
to make it more clear, you prevent to show any dialog after onDestroy called.
i don't use as below. but it's clear.

private boolean mIsDestroyed = false;

private void showDialog() {
    closeDialog();

    if (mIsDestroyed) {
        Log.d(TAG, "called onDestroy() already.");
        return;
    }

    mDialog = new AlertDialog(this)
        .setTitle("title")
        .setMessage("This is DialogTest")
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
        .create();
    mDialog.show();
}

private void closeDialog() {
    if (mDialog != null) {
        mDialog.dismiss();
    }
}

@Override
protected void onDestroy() {
    Log.d(TAG, "called onDestroy");
    mIsDestroyed = true;
    closeDialog();
    super.onDestroy();
}


good luck!

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

FFMPEG mp4 from http live streaming m3u8 file?

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

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

How do I find the difference between two values without knowing which is larger?

abs function is definitely not what you need as it is not calculating the distance. Try abs (-25+15) to see that it's not working. A distance between the numbers is 40 but the output will be 10. Because it's doing the math and then removing "minus" in front. I am using this custom function:


def distance(a, b):
    if (a < 0) and (b < 0) or (a > 0) and (b > 0):
        return abs( abs(a) - abs(b) )
    if (a < 0) and (b > 0) or (a > 0) and (b < 0):
        return abs( abs(a) + abs(b) )

print distance(-25, -15) print distance(25, -15) print distance(-25, 15) print distance(25, 15)

How to enable directory listing in apache web server

See if you are able to access/list the '/icons/' directory. This is useful to test the behavior of Directory in Apache.

for eg : You might be having below config by default in your httpd.conf file.So hit the url : IP:Port/icons/ and see if it list the icons or not.You can also try by putting the 'directory/folder' inside the 'var/www/icons'.

Alias /icons/ "/var/www/icons/"

<Directory "/var/www/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
</Directory>

If it does works then you can crosscheck or modify your custom directory configuration with '' configuration.

Java: convert seconds to minutes, hours and days

my quick answer with basic java arithmetic calculation is this:

First consider the following values:

1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
  1. First divide the input by 86400, if you you can get a number greater than 0 , this is the number of days. 2.Again divide the remained number you get from the first calculation by 3600, this will give you the number of hours
  2. Then divide the remainder of your second calculation by 60 which is the number of Minutes
  3. Finally the remained number from your third calculation is the number of seconds

the code snippet is as follows:

int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;

numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60 
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60  ;

I hope to be helpful to you.

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

Stop form refreshing page on submit

function ajax_form(selector, obj)
{

    var form = document.querySelectorAll(selector);

    if(obj)
    {

        var before = obj.before ? obj.before : function(){return true;};

        var $success = obj.success ? obj.success: function(){return true;};

        for (var i = 0; i < form.length; i++)
        {

            var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;

            var $form = form[i];

            form[i].submit = function()
            {

                var xhttp = new XMLHttpRequest();

                xhttp.open("POST", url, true);

                var FD = new FormData($form);

                /** prevent submiting twice */
                if($form.disable === true)

                    return this;

                $form.disable = true;

                if(before() === false)

                    return;

                xhttp.addEventListener('load', function()
                {

                    $form.disable = false;

                    return $success(JSON.parse(this.response));

                });

                xhttp.send(FD);

            }
        }
    }

    return form;
}

Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm

use it like:

ajax_form('form',
{
    before: function()
    {
        alert('submiting form');
        // if return false form shouldn't be submitted
    },
    success:function(data)
    {
        console.log(data)
    }
}
)[0].submit();

it return nodes so you can do something like submit i above example

so far from perfection but it suppose to work, you should add error handling or remove disable condition

How to check for an undefined or null variable in JavaScript?

If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:

if (window.some_variable != null) {
    // Do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.

How to use HTML to print header and footer on every printed page of a document?

I have been searching for years for a solution and found this post on how to print a footer that works on multiple pages without overlapping page content.

My requirement was IE8, so far I have found that this does not work in Chrome. [update]As of 1 March 2018, it works in Chrome as well

This example uses tables and the tfoot element by setting the css style:

tfoot {display: table-footer-group;}

Discard all and get clean copy of latest revision?

Those steps should be able to be shortened down to:

hg pull
hg update -r MY_BRANCH -C

The -C flag tells the update command to discard all local changes before updating.

However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge extension for that:

hg pull
hg update -r MY_BRANCH -C
hg purge

In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.

PHP absolute path to root

In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:

 $_SERVER['DOCUMENT_ROOT']

The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.

Can an html element have multiple ids?

No you cannot have multiple ids for a single tag, but I have seen a tag with a name attribute and an id attribute which are treated the same by some applications.

Resize an Array while keeping current elements in Java?

You can't resize an array, but you can redefine it keeping old values or use a java.util.List

Here follows two solutions but catch the performance differences running the code below

Java Lists are 450 times faster but 20 times heavier in memory!

testAddByteToArray1 nanoAvg:970355051   memAvg:100000
testAddByteToList1  nanoAvg:1923106     memAvg:2026856
testAddByteToArray1 nanoAvg:919582271   memAvg:100000
testAddByteToList1  nanoAvg:1922660     memAvg:2026856
testAddByteToArray1 nanoAvg:917727475   memAvg:100000
testAddByteToList1  nanoAvg:1904896     memAvg:2026856
testAddByteToArray1 nanoAvg:918483397   memAvg:100000
testAddByteToList1  nanoAvg:1907243     memAvg:2026856
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static byte[] byteArray = new byte[0];
    public static List<Byte> byteList = new ArrayList<>();
    public static List<Double> nanoAvg = new ArrayList<>();
    public static List<Double> memAvg = new ArrayList<>();

    public static void addByteToArray1() {
        // >>> SOLUTION ONE <<<
        byte[] a = new byte[byteArray.length + 1];
        System.arraycopy(byteArray, 0, a, 0, byteArray.length);
        byteArray = a;
        //byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
    }

    public static void addByteToList1() {
        // >>> SOLUTION TWO <<<
        byteList.add(new Byte((byte) 0));
    }

    public static void testAddByteToList1() throws InterruptedException {
        System.gc();
        long m1 = getMemory();
        long n1 = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            addByteToList1();
        }
        long n2 = System.nanoTime();
        System.gc();
        long m2 = getMemory();
        byteList = new ArrayList<>();
        nanoAvg.add(new Double(n2 - n1));
        memAvg.add(new Double(m2 - m1));
    }

    public static void testAddByteToArray1() throws InterruptedException {
        System.gc();
        long m1 = getMemory();
        long n1 = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            addByteToArray1();
        }
        long n2 = System.nanoTime();
        System.gc();
        long m2 = getMemory();
        byteArray = new byte[0];
        nanoAvg.add(new Double(n2 - n1));
        memAvg.add(new Double(m2 - m1));
    }

    public static void resetMem() {
        nanoAvg = new ArrayList<>();
        memAvg = new ArrayList<>();
    }

    public static Double getAvg(List<Double> dl) {
        double max = Collections.max(dl);
        double min = Collections.min(dl);
        double avg = 0;
        boolean found = false;
        for (Double aDouble : dl) {
            if (aDouble < max && aDouble > min) {
                if (avg == 0) {
                    avg = aDouble;
                } else {
                    avg = (avg + aDouble) / 2d;
                }
                found = true;
            }
        }
        if (!found) {
            return getPopularElement(dl);
        }
        return avg;
    }

    public static double getPopularElement(List<Double> a) {
        int count = 1, tempCount;
        double popular = a.get(0);
        double temp = 0;
        for (int i = 0; i < (a.size() - 1); i++) {
            temp = a.get(i);
            tempCount = 0;
            for (int j = 1; j < a.size(); j++) {
                if (temp == a.get(j))
                    tempCount++;
            }
            if (tempCount > count) {
                popular = temp;
                count = tempCount;
            }
        }
        return popular;
    }

    public static void testCompare() throws InterruptedException {
        for (int j = 0; j < 4; j++) {
            for (int i = 0; i < 20; i++) {
                testAddByteToArray1();
            }
            System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
            resetMem();
            for (int i = 0; i < 20; i++) {
                testAddByteToList1();
            }
            System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
            resetMem();
        }
    }

    private static long getMemory() {
        Runtime runtime = Runtime.getRuntime();
        return runtime.totalMemory() - runtime.freeMemory();
    }

    public static void main(String[] args) throws InterruptedException {
        testCompare();
    }
}

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

get list of packages installed in Anaconda

For script creation at Windows cmd or powershell prompt:

C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list

How to kill a child process after a given timeout in Bash?

(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")

If you don't mind downloading something, use timeout (sudo apt-get install timeout) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils)

timeout 10 ping www.goooooogle.com

If you don't want to download something, do what timeout does internally:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )

In case that you want to do a timeout for longer bash code, use the second option as such:

( cmdpid=$BASHPID; 
    (sleep 10; kill $cmdpid) \
   & while ! ping -w 1 www.goooooogle.com 
     do 
         echo crap; 
     done )

What is the difference between re.search and re.match?

re.match attempts to match a pattern at the beginning of the string. re.search attempts to match the pattern throughout the string until it finds a match.

What does 'git remote add upstream' help achieve?

I think it could be used for "retroactively forking"

If you have a Git repo, and have now decided that it should have forked another repo. Retroactively you would like it to become a fork, without disrupting the team that uses the repo by needing them to target a new repo.

But I could be wrong.

ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

yum install -y procps

Running this command on Dockerfile:

RUN yum install -y procps

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

How do I disable text selection with CSS or JavaScript?

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).


All of the correct CSS variations are:

_x000D_
_x000D_
.noselect {_x000D_
  -webkit-touch-callout: none; /* iOS Safari */_x000D_
    -webkit-user-select: none; /* Safari */_x000D_
     -khtml-user-select: none; /* Konqueror HTML */_x000D_
       -moz-user-select: none; /* Firefox */_x000D_
        -ms-user-select: none; /* Internet Explorer/Edge */_x000D_
            user-select: none; /* Non-prefixed version, currently_x000D_
                                  supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
  Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
  Unselectable text._x000D_
</p>
_x000D_
_x000D_
_x000D_


Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.


More information can be found in Mozilla Developer Network documentation.

"SMTP Error: Could not authenticate" in PHPMailer

I had the same issue and did all the tips with no luck. Finally when I changed password to something different, for some reason it worked! (the initial password or the new one did not have any special characters)

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

You can follow this.

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

How to access the content of an iframe with jQuery?

If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):

<?php
    $contents = file_get_contents($external_url);
    $res = file_put_contents($filename, $contents);
?>

then, get the new file content (string) and parse it to html, for example (in jquery):

$.get(file_url, function(string){
    var html = $.parseHTML(string);
    var contents = $(html).contents();
},'html');

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

Convert an object to an XML string

 public static class XMLHelper
    {
        /// <summary>
        /// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
        /// </summary>
        /// <typeparam name="T">Ki?u d? li?u</typeparam>
        /// <param name="value">giá tr?</param>
        /// <param name="omitXmlDeclaration">b? qua declare</param>
        /// <param name="removeEncodingDeclaration">xóa encode declare</param>
        /// <returns>xml string</returns>
        public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
        {
            if (value == null)
            {
                return string.Empty;
            }
            try
            {
                var xmlWriterSettings = new XmlWriterSettings
                {
                    Indent = true,
                    OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
                    Encoding = Encoding.UTF8,
                    NewLineChars = "", // remove \r\n
                };

                var xmlserializer = new XmlSerializer(typeof(T));

                using (var memoryStream = new MemoryStream())
                {
                    using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        xmlserializer.Serialize(xmlWriter, value);
                        //return stringWriter.ToString();
                    }

                    memoryStream.Position = 0;
                    using (var sr = new StreamReader(memoryStream))
                    {
                        var pureResult = sr.ReadToEnd();
                        var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
                        if (omitEncodingDeclaration)
                            return resultAfterOmitEncoding;
                        return pureResult;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XMLSerialize error: ", ex);
            }
        }

        private static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);

            if (pos < 0)
            {
                return text;
            }

            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }

PHP Date Format to Month Name and Year

if you want same string output then try below else use without double quotes for proper output

$str = '20130814';
  echo date('"F Y"', strtotime($str));

//output  : "August 2013" 

How do I run a docker instance from a DockerFile?

You cannot start a container from a Dockerfile.

The process goes like this:

Dockerfile =[docker build]=> Docker image =[docker run]=> Docker container

To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].

[1]: you can also docker import an image from a tarball or again docker load.

Why can't I use Docker CMD multiple times to run multiple services?

The official docker answer to Run multiple services in a container.

It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./my_wrapper_script.sh) or a supervisor like supervisord.

The && workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.

Remove the string on the beginning of an URL

Depends on what you need, you have a couple of choices, you can do:

// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");

// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);

// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");

Create a new workspace in Eclipse

I use File -> Switch Workspace -> Other... and type in my new workspace name.

New workspace composite screenshot (EDIT: Added the composite screen shot.)

Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.

MySQL how to join tables on two fields

JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)

How can I order a List<string>?

ListaServizi = ListaServizi.OrderBy(q => q).ToList();

from unix timestamp to datetime

If using react:

import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';

then:

<td><Moment unix>{1370001284}</Moment></td>