Programs & Examples On #Window.opener

The opener property returns a reference to the window that created the window.

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

javascript close current window

Works only in Google Chrome with self.close();. Tested in v48.

window.close() won't do what you want as the documentation for it clearly states that scripts may close only the windows that were opened by it.

Close popup window

For such a seemingly simple thing this can be a royal pain in the butt! I found a solution that works beautifully (class="video-close" is obviously particular to this button and optional)

 <a href="javascript:window.open('','_self').close();" class="video-close">Close this window</a>

When to use window.opener / window.parent / window.top

top, parent, opener (as well as window, self, and iframe) are all window objects.

  1. window.opener -> returns the window that opens or launches the current popup window.
  2. window.top -> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.
  3. window.parent -> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or self

javascript - pass selected value from popup window to parent window input box

From your code

<input type=button value="Select" onClick="sendValue(this.form.details);"

Im not sure that your this.form.details valid or not.

IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;

I can't found an input's id contain details I'm just found only id=sku1 (recommend you to add " like id="sku1").

And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.

First page.

<html>
<head>
<script>
    function callFromDialog(id,data){ //for callback from the dialog
        document.getElementById(id).value = data;
        // do some thing other if you want
    }

    function choose(id){
        var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
        window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
    }
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>

Look in function choose I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#)

Popup Page

<html>
<head>
<script>
    function goSelect(data){
        var idFromCallPage = getUrlVars()["id"];
        window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
        window.close();
    }


    function getUrlVars(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>

I have add function getUrlVars for get URL param that the parent has pass to child.

Okay, when select data in the popup, for this case it's will call function goSelect

In that function will get URL param to sent back.

And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog

By fully is window.opener.callFromDialog(idFromCallPage,data);

Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data; It's ok too.

JavaScript error: "is not a function"

I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:

const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function

The fix was:

const car = await carFactory.getCar();
car.drive()

Posting this incase it helps anyone else facing this error.

Window.open as modal popup?

That solution will open up a new browser window without the normal features such as address bar and similar.

To implement a modal popup, I suggest you to take a look at jQuery and SimpleModal, which is really slick.

(Here are some simple demos using SimpleModal: http://www.ericmmartin.com/projects/simplemodal-demos/)

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.

Connect to SQL Server through PDO using SQL Server Driver

Figured this out. Pretty simple:

 new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]",  "[username]", "[password]");

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

Chang your application level build.gradle file's:

implementation 'com.android.support:appcompat-v7:23.1.0'

to

 implementation 'com.android.support:appcompat-v7:23.0.1'

Insert, on duplicate update in PostgreSQL?

Personally, I've set up a "rule" attached to the insert statement. Say you had a "dns" table that recorded dns hits per customer on a per-time basis:

CREATE TABLE dns (
    "time" timestamp without time zone NOT NULL,
    customer_id integer NOT NULL,
    hits integer
);

You wanted to be able to re-insert rows with updated values, or create them if they didn't exist already. Keyed on the customer_id and the time. Something like this:

CREATE RULE replace_dns AS 
    ON INSERT TO dns 
    WHERE (EXISTS (SELECT 1 FROM dns WHERE ((dns."time" = new."time") 
            AND (dns.customer_id = new.customer_id)))) 
    DO INSTEAD UPDATE dns 
        SET hits = new.hits 
        WHERE ((dns."time" = new."time") AND (dns.customer_id = new.customer_id));

Update: This has the potential to fail if simultaneous inserts are happening, as it will generate unique_violation exceptions. However, the non-terminated transaction will continue and succeed, and you just need to repeat the terminated transaction.

However, if there are tons of inserts happening all the time, you will want to put a table lock around the insert statements: SHARE ROW EXCLUSIVE locking will prevent any operations that could insert, delete or update rows in your target table. However, updates that do not update the unique key are safe, so if you no operation will do this, use advisory locks instead.

Also, the COPY command does not use RULES, so if you're inserting with COPY, you'll need to use triggers instead.

How to check string length with JavaScript

<html>
<head></head>
<title></title>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<body>
Type here:<input type="text" id="inputbox" value="type here"/>
<br>
Length:<input type="text" id="length"/>
<script type='text/javascript'>
    $(window).keydown(function (e) {
    //use e.which
    var length = 0;
    if($('#inputbox').val().toString().trim().length > 0)
    {
        length = $('#inputbox').val().toString().trim().length;
    }

    $('#length').val(length.toString());
  })
</script>
</body>
</html>

Ruby: What is the easiest way to remove the first element from an array?

This is pretty neat:

head, *tail = [1, 2, 3, 4, 5]
#==> head = 1, tail = [2, 3, 4, 5]

As written in the comments, there's an advantage of not mutating the original list.

How to convert DateTime to a number with a precision greater than days in T-SQL?

You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.

DECLARE @Date DATETIME = Getdate()
DECLARE @DateInt INT = CONVERT(VARCHAR(30), @Date, 112)
DECLARE @TimeInt INT = REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
DECLARE @DateTimeInt BIGINT = CONVERT(VARCHAR(30), @Date, 112) + REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
SELECT @Date as Date, @DateInt DateInt, @TimeInt TimeInt, @DateTimeInt DateTimeInt

Date                    DateInt     TimeInt     DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107    150821      20130107150821

How to show particular image as thumbnail while implementing share on Facebook?

I see that all the answers provided are correct. However, one important detail was overlooked: The size of the image MUST be at least 200 X 200 px, otherwise Facebook will substitute the thumbnail with the first available image that meets the criteria on the page. Another fact is that the minimum required is to include the 3 metas that Facebook requires for the og:image to take effect:

<meta property="og:title" content="Title of the page" />
<!-- NEXT LINE Even if page is dynamically generated and URL contains query parameters -->
<meta property="og:url" content="http://yoursite.com" />
<meta property="og:image" content="http://convertaholics.com/convertaholics-og.png" />

Debug your page with Facebook debugger and fix all the warnings and it should work like a charm! https://developers.facebook.com/tools/debug

Find element in List<> that contains a value

hi body very late but i am writing

if(mylist.contains(value)){}

Jquery - How to make $.post() use contentType=application/json?

I know this is a late answer, I actually have a shortcut method that I use for posting/reading to/from MS based services.. it works with MVC as well as ASMX etc...

Use:

$.msajax(
  '/services/someservice.asmx/SomeMethod'
  ,{}  /*empty object for nothing, or object to send as Application/JSON */
  ,function(data,jqXHR) {
    //use the data from the response.
  }
  ,function(err,jqXHR) {
    //additional error handling.
  }
);
//sends a json request to an ASMX or WCF service configured to reply to JSON requests.
(function ($) {
  var tries = 0; //IE9 seems to error out the first ajax call sometimes... will retry up to 5 times

  $.msajax = function (url, data, onSuccess, onError) {
    return $.ajax({
      'type': "POST"
      , 'url': url
      , 'contentType': "application/json"
      , 'dataType': "json"
      , 'data': typeof data == "string" ? data : JSON.stringify(data || {})
      ,beforeSend: function(jqXHR) {
        jqXHR.setRequestHeader("X-MicrosoftAjax","Delta=true");
      }
      , 'complete': function(jqXHR, textStatus) {
        handleResponse(jqXHR, textStatus, onSuccess, onError, function(){
          setTimeout(function(){
            $.msajax(url, data, onSuccess, onError);
          }, 100 * tries); //try again
        });
      }
    });
  }

  $.msajax.defaultErrorMessage = "Error retreiving data.";


  function logError(err, errorHandler, jqXHR) {
    tries = 0; //reset counter - handling error response

    //normalize error message
    if (typeof err == "string") err = { 'Message': err };

    if (console && console.debug && console.dir) {
      console.debug("ERROR processing jQuery.msajax request.");
      console.dir({ 'details': { 'error': err, 'jqXHR':jqXHR } });
    }

    try {
      errorHandler(err, jqXHR);
    } catch (e) {}
    return;
  }


  function handleResponse(jqXHR, textStatus, onSuccess, onError, onRetry) {
    var ret = null;
    var reterr = null;
    try {
      //error from jqXHR
      if (textStatus == "error") {
        var errmsg = $.msajax.defaultErrorMessage || "Error retreiving data.";

        //check for error response from the server
        if (jqXHR.status >= 300 && jqXHR.status < 600) {
          return logError( jqXHR.statusText || msg, onError, jqXHR);
        }

        if (tries++ < 5) return onRetry();

        return logError( msg, onError, jqXHR);
      }

      //not an error response, reset try counter
      tries = 0;

      //check for a redirect from server (usually authentication token expiration).
      if (jqXHR.responseText.indexOf("|pageRedirect||") > 0) {
        location.href = decodeURIComponent(jqXHR.responseText.split("|pageRedirect||")[1].split("|")[0]).split('?')[0];
        return;
      }

      //parse response using ajax enabled parser (if available)
      ret = ((JSON && JSON.parseAjax) || $.parseJSON)(jqXHR.responseText);

      //invalid response
      if (!ret) throw jqXHR.responseText;  

      // d property wrap as of .Net 3.5
      if (ret.d) ret = ret.d;

      //has an error
      reterr = (ret && (ret.error || ret.Error)) || null; //specifically returned an "error"

      if (ret && ret.ExceptionType) { //Microsoft Webservice Exception Response
        reterr = ret
      }

    } catch (err) {
      reterr = {
        'Message': $.msajax.defaultErrorMessage || "Error retreiving data."
        ,'debug': err
      }
    }

    //perform final logic outside try/catch, was catching error in onSuccess/onError callbacks
    if (reterr) {
      logError(reterr, onError, jqXHR);
      return;
    }

    onSuccess(ret, jqXHR);
  }

} (jQuery));

NOTE: I also have a JSON.parseAjax method that is modified from json.org's JS file, that adds handling for the MS "/Date(...)/" dates...

The modified json2.js file isn't included, it uses the script based parser in the case of IE8, as there are instances where the native parser breaks when you extend the prototype of array and/or object, etc.

I've been considering revamping this code to implement the promises interfaces, but it's worked really well for me.

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

Get value of a string after last slash in JavaScript

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }

oracle diff: how to compare two tables?

For this kind of question I think you have to be very specific about what you are looking for, as there are many ways of interpreting it and many different approaches. Some approaches are going to be too big a hammer if your question does not warrant it.

At the simplest level, there is "Is the table data exactly the same or not?", which you might attempt to answer with a simple count comparison before moving on to anything more complex.

At the other end of the scale there is "show me the rows from each table for which there is not an equivalent row in the other table" or "show me where rows have the same identifying key but different data values".

If you actually want to sync Table A with Table B then that might be relatively straightforward, using a MERGE command.

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

JOptionPane Yes or No window

You are writing if(true) so it will always show "Hello " message.

You should take decision on the basis of value of n returned.

Sum all the elements java arraylist

Using Java 8 streams:

double sum = m.stream()
    .mapToDouble(a -> a)
    .sum();

System.out.println(sum); 

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Copy text from nano editor to shell

For whoever still looking for a copy + paste solution in nano editor

To select text

  • ctrl+6
  • Use arrow to move the cursor to where you want the mark to end

Note: If you want to copy the whole line, no need to mark just move the cursor to the line

To copy:

  • Press alt + 6

To paste:

  • Press ctrl + U

Reference

Cannot install packages inside docker Ubuntu image

Add following command in Dockerfile:

RUN apt-get update

PowerShell: Create Local User Account

Another alternative is the old school NET USER commands:

NET USER username "password" /ADD

OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.

NET LOCALGROUP "group" "user" /add to set group membership.

MongoDB: How to update multiple documents with a single command?

Starting in v3.3 You can use updateMany

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

In v2.2, the update function takes the following form:

 db.collection.update(
   <query>,
   <update>,
   { upsert: <boolean>, multi: <boolean> }
)

https://docs.mongodb.com/manual/reference/method/db.collection.update/

jQuery Multiple ID selectors

You can use multiple id's the way you wrote:

$('#upload_link, #upload_link2, #upload_link3')

However, that doesn't mean that those ids exist within the DOM when you've executed your code. It also doesn't mean that upload is a legitimate function. It also doesn't mean that upload has been built in a way that allows for multiple elements in a selection.

upload is a custom jQuery plugin, so you'll have to show what's going on with upload for us to be able to help you.

React Native android build failed. SDK location not found

I don't think it's recommended to update the local.properties file to get to add the missing environment vars.

Update your environment variables:

How to open the AVD manager on OSX from iTerm2?

android-28 / android-30

sdk can be installed on /Library/Android/sdk or /usr/local/ to be sure check it by

which sdkmanager

Export ANDROID_HOME

export ANDROID_HOME=$HOME/Library/Android/sdk

or

export ANDROID_HOME="/usr/local/share/android-sdk"

Then add it to the $PATH

export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/build-tools/28.0.1:$PATH

android-23

export ANT_HOME=/usr/local/opt/ant
export MAVEN_HOME=/usr/local/opt/maven
export GRADLE_HOME=/usr/local/opt/gradle
export ANDROID_HOME=/usr/local/share/android-sdk
export ANDROID_SDK_ROOT=/usr/local/share/android-sdk
export ANDROID_NDK_HOME=/usr/local/share/android-ndk
export INTEL_HAXM_HOME=/usr/local/Caskroom/intel-haxm

I used brew cask to install Android SDK following these instructions.

More info see https://developer.android.com/studio/intro/update#sdk-manager

Replacing instances of a character in a string

If you are replacing by an index value specified in variable 'n', then try the below:

def missing_char(str, n):
 str=str.replace(str[n],":")
 return str

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Genymotion "Lollipop Preview - Nexus 5" virtual device

More GApps here

Note that Google+ shows lot of errors before updated.

Python/Json:Expecting property name enclosed in double quotes

For anyone who wants a quick-fix, this simply replaces all single quotes with double quotes:

import json 

predictions = []

def get_top_k_predictions(predictions_path):
    '''load the predictions'''
    
    with open (predictions_path) as json_lines_file:
        for line in json_lines_file:
            predictions.append(json.loads(line.replace("'", "\"")))
            
    
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")

Convert HTML to NSAttributedString in iOS

Here is the Swift 5 version of Mobile Dan's answer:

public extension NSAttributedString {
    convenience init?(_ html: String) {
        guard let data = html.data(using: .unicode) else {
                return nil
        }

        try? self.init(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
    }
}

SQL: How to properly check if a record exists

I would prefer not use Count function at all:

IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
     <do smth>

For example if you want to check if user exists before inserting it into the database the query can look like this:

IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END

Static Block in Java

A static block executes once in the life cycle of any program, another property of static block is that it executes before the main method.

How can I read user input from the console?

string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console

Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.

Console.ReadLine() reads a string (so then you need to change the string to a double)

Add SUM of values of two LISTS into new LIST

From docs

import operator
list(map(operator.add, first,second))

Go build: "Cannot find package" (even though GOPATH is set)

In the recent go versions from 1.14 onwards, we have to do go mod vendor before building or running, since by default go appends -mod=vendor to the go commands. So after doing go mod vendor, if we try to build, we won't face this issue.

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

How to remove RVM (Ruby Version Manager) from my system

Per RVM's troubleshooting documentation "How do I completely clean out all traces of RVM from my system, including for system wide installs?":

Here is a custom script which we name as 'cleanout-rvm'. While you can definitely use rvm implode as a regular user or rvmsudo rvm implode for a system wide install, this script is useful as it steps completely outside of RVM and cleans out RVM without using RVM itself, leaving no traces.

#!/bin/bash
/usr/bin/sudo rm -rf $HOME/.rvm $HOME/.rvmrc /etc/rvmrc /etc/profile.d/rvm.sh /usr/local/rvm /usr/local/bin/rvm
/usr/bin/sudo /usr/sbin/groupdel rvm
/bin/echo "RVM is removed. Please check all .bashrc|.bash_profile|.profile|.zshrc for RVM source lines and delete or comment out if this was a Per-User installation."

Check if a variable is null in plsql

Always remember to be careful with nulls in pl/sql conditional clauses as null is never greater, smaller, equal or unequal to anything. Best way to avoid them is to use nvl.

For example

declare
  i integer;
begin
  if i <> 1 then
    i:=1;
    foobar();
  end if;
end;
/

Never goes inside the if clause.

These would work.

if 1<>nvl(i,1) then
if i<> 1 or i is null then

Abstract class in Java

It's a class that cannot be instantiated, and forces implementing classes to, possibly, implement abstract methods that it outlines.

CSS class for pointer cursor

UPDATE for Bootstrap 4 stable

The cursor: pointer; rule has been restored, so buttons will now by default have the cursor on hover:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">_x000D_
<button type="button" class="btn btn-success">Sample Button</button>
_x000D_
_x000D_
_x000D_


No, there isn't. You need to make some custom CSS for this.

If you just need a link that looks like a button (with pointer), use this:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">_x000D_
<a class="btn btn-success" href="#" role="button">Sample Button</a>
_x000D_
_x000D_
_x000D_

Inject service in app.config

I don't think you're supposed to be able to do this, but I have successfully injected a service into a config block. (AngularJS v1.0.7)

angular.module('dogmaService', [])
    .factory('dogmaCacheBuster', [
        function() {
            return function(path) {
                return path + '?_=' + Date.now();
            };
        }
    ]);

angular.module('touch', [
        'dogmaForm',
        'dogmaValidate',
        'dogmaPresentation',
        'dogmaController',
        'dogmaService',
    ])
    .config([
        '$routeProvider',
        'dogmaCacheBusterProvider',
        function($routeProvider, cacheBuster) {
            var bust = cacheBuster.$get[0]();

            $routeProvider
                .when('/', {
                    templateUrl: bust('touch/customer'),
                    controller: 'CustomerCtrl'
                })
                .when('/screen2', {
                    templateUrl: bust('touch/screen2'),
                    controller: 'Screen2Ctrl'
                })
                .otherwise({
                    redirectTo: bust('/')
                });
        }
    ]);

angular.module('dogmaController', [])
    .controller('CustomerCtrl', [
        '$scope',
        '$http',
        '$location',
        'dogmaCacheBuster',
        function($scope, $http, $location, cacheBuster) {

            $scope.submit = function() {
                $.ajax({
                    url: cacheBuster('/customers'),  //server script to process data
                    type: 'POST',
                    //Ajax events
                    // Form data
                    data: formData,
                    //Options to tell JQuery not to process data or worry about content-type
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function() {
                        $location
                            .path('/screen2');

                        $scope.$$phase || $scope.$apply();
                    }
                });
            };
        }
    ]);

SQL Server function to return minimum date (January 1, 1753)

Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

Increasing the timeout value in a WCF service

Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.

From there you can change the binding options for both the client and the services, one of these options will be for time-outs.

Are (non-void) self-closing tags valid in HTML5?

Self-closing tags are valid in HTML5, but not required.

<br> and <br /> are both fine.

How to check if a column exists in a datatable

DataColumnCollection col = datatable.Columns;        
if (!columns.Contains("ColumnName1"))
{
   //Column1 Not Exists
}

if (columns.Contains("ColumnName2"))
{
   //Column2 Exists
}

pip3: command not found but python3-pip is already installed

On Windows 10 install Python from Python.org Once installed add these two paths to PATH env variable C:\Users<your user>\AppData\Local\Programs\Python\Python38 C:\Users<your user>\AppData\Local\Programs\Python\Python38\Scripts

Open command prompt and following command should be working python --version pip --version

Error: Jump to case label

C++11 standard on jumping over some initializations

JohannesD gave an explanation, now for the standards.

The C++11 N3337 standard draft 6.7 "Declaration statement" says:

3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

[ Example:

void f() {
   // ...
  goto lx;    // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;    // OK, jump implies destructor
              // call for a followed by construction
              // again immediately following label ly
}

— end example ]

As of GCC 5.2, the error message now says:

crosses initialization of

C

C allows it: c99 goto past initialization

The C99 N1256 standard draft Annex I "Common warnings" says:

2 A block with initialization of an object that has automatic storage duration is jumped into

Mocking member variables of a class using Mockito

I had the same issue where a private value was not set because Mockito does not call super constructors. Here is how I augment mocking with reflection.

First, I created a TestUtils class that contains many helpful utils including these reflection methods. Reflection access is a bit wonky to implement each time. I created these methods to test code on projects that, for one reason or another, had no mocking package and I was not invited to include it.

public class TestUtils {
    // get a static class value
    public static Object reflectValue(Class<?> classToReflect, String fieldNameValueToFetch) {
        try {
            Field reflectField  = reflectField(classToReflect, fieldNameValueToFetch);
            reflectField.setAccessible(true);
            Object reflectValue = reflectField.get(classToReflect);
            return reflectValue;
        } catch (Exception e) {
            fail("Failed to reflect "+fieldNameValueToFetch);
        }
        return null;
    }
    // get an instance value
    public static Object reflectValue(Object objToReflect, String fieldNameValueToFetch) {
        try {
            Field reflectField  = reflectField(objToReflect.getClass(), fieldNameValueToFetch);
            Object reflectValue = reflectField.get(objToReflect);
            return reflectValue;
        } catch (Exception e) {
            fail("Failed to reflect "+fieldNameValueToFetch);
        }
        return null;
    }
    // find a field in the class tree
    public static Field reflectField(Class<?> classToReflect, String fieldNameValueToFetch) {
        try {
            Field reflectField = null;
            Class<?> classForReflect = classToReflect;
            do {
                try {
                    reflectField = classForReflect.getDeclaredField(fieldNameValueToFetch);
                } catch (NoSuchFieldException e) {
                    classForReflect = classForReflect.getSuperclass();
                }
            } while (reflectField==null || classForReflect==null);
            reflectField.setAccessible(true);
            return reflectField;
        } catch (Exception e) {
            fail("Failed to reflect "+fieldNameValueToFetch +" from "+ classToReflect);
        }
        return null;
    }
    // set a value with no setter
    public static void refectSetValue(Object objToReflect, String fieldNameToSet, Object valueToSet) {
        try {
            Field reflectField  = reflectField(objToReflect.getClass(), fieldNameToSet);
            reflectField.set(objToReflect, valueToSet);
        } catch (Exception e) {
            fail("Failed to reflectively set "+ fieldNameToSet +"="+ valueToSet);
        }
    }

}

Then I can test the class with a private variable like this. This is useful for mocking deep in class trees that you have no control as well.

@Test
public void testWithRectiveMock() throws Exception {
    // mock the base class using Mockito
    ClassToMock mock = Mockito.mock(ClassToMock.class);
    TestUtils.refectSetValue(mock, "privateVariable", "newValue");
    // and this does not prevent normal mocking
    Mockito.when(mock.somthingElse()).thenReturn("anotherThing");
    // ... then do your asserts
}

I modified my code from my actual project here, in page. There could be a compile issue or two. I think you get the general idea. Feel free to grab the code and use it if you find it useful.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I had the similar issue for my Spring Boot - Gradle application running on Eclipse Luna. I could resolve it by manually adding an entry in my project's .classpath

<classpathentry sourcepath="C:/Users/<username>/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-simple/1.7.7/3150039466ad03e6ef1c7ec1c2cbb0d96710cf64/slf4j-simple-1.7.7-sources.jar" kind="lib" path="C:/Users/<username>/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-simple/1.7.7/8095d0b9f7e0a9cd79a663c740e0f8fb31d0e2c8/slf4j-simple-1.7.7.jar"/>

Idea is to follow this solution. But how to implement is dependent on case to case. One way of fixing is the one that I used above.

Hope this helps.

CSS width of a <span> tag

spans default to inline style, which you can't specify the width of.

display: inline-block;

would be a good way, except IE doesn't support it

you can, however, hack a multiple browser solution

Git resolve conflict using --ours/--theirs for all files

In case anyone else is looking to simply overwrite everything from one branch (say master) with the contents of another, there's an easier way:

git merge origin/master --strategy=ours

Thanks to https://stackoverflow.com/a/1295232/560114

Or for the other way around, see Is there a "theirs" version of "git merge -s ours"?

Search and replace a line in a file in Python

This should work: (inplace editing)

import fileinput

# Does a list of files, and
# redirects STDOUT to the file in question
for line in fileinput.input(files, inplace = 1): 
      print line.replace("foo", "bar"),

What range of values can integer types store in C++

The minimum ranges you can rely on are:

  • short int and int: -32,767 to 32,767
  • unsigned short int and unsigned int: 0 to 65,535
  • long int: -2,147,483,647 to 2,147,483,647
  • unsigned long int: 0 to 4,294,967,295

This means that no, long int cannot be relied upon to store any 10 digit number. However, a larger type long long int was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is:

  • long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807
  • unsigned long long int: 0 to 18,446,744,073,709,551,615

So that type will be big enough (again, if you have it available).


A note for those who believe I've made a mistake with these lower bounds - I haven't. The C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int is not required to be able to represent the value -32,768.

Get the current language in device

The others have given good answers for the device language,

if you wish the app language the easiest way to do it is by adding an app_lang key to your strings.xml file, and specify the lang for each of the langs as well.

That way, if your app's default language is different from the device language, you can chose to send that as parameter for your services.

How to read file from res/raw by name

Here is example of taking XML file from raw folder:

 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

Then you can:

 String sxml = readTextFile(XmlFileInputStream);

when:

 public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }

How does DateTime.Now.Ticks exactly work?

You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

CSS / HTML Navigation and Logo on same line

Firstly, let's use some semantic HTML.

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Get in Touch</a></li>
    </ul>
</nav>

In fact, you can even get away with the more minimalist:

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <a href="#">Home</a>
    <a href="#">Projects</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Get in Touch</a>
</nav>

Then add some CSS:

.navigation-bar {
    width: 100%;  /* i'm assuming full width */
    height: 80px; /* change it to desired width */
    background-color: red; /* change to desired color */
}
.logo {
    display: inline-block;
    vertical-align: top;
    width: 50px;
    height: 50px;
    margin-right: 20px;
    margin-top: 15px;    /* if you want it vertically middle of the navbar. */
}
.navigation-bar > a {
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    height: 80px;        /* if you want it to take the full height of the bar */
    line-height: 80px;    /* if you want it vertically middle of the navbar */
}

Obviously, the actual margins, heights and line-heights etc. depend on your design.

Other options are to use tables or floats for layout, but these are generally frowned upon.

Last but not least, I hope you get cured of div-itis.

How to add an object to an ArrayList in Java

You need to use the new operator when creating the object

Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step

or else

Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list

and your constructor shouldn't contain void. Else it becomes a method in your class.

public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such

How to analyze disk usage of a Docker container

Keep in mind that docker ps --size may be an expensive command, taking more than a few minutes to complete. The same applies to container list API requests with size=1. It's better not to run it too often.

Take a look at alternatives we compiled, including the du -hs option for the docker persistent volume directory.

Increment counter with loop

Try the following:

<c:set var="count" value="0" scope="page" />

//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>

How to resize a custom view programmatically?

if you are overriding onMeasure, don't forget to update the new sizes

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(newWidth, newHeight);
}

How to decode HTML entities using jQuery?

Without any jQuery:

_x000D_
_x000D_
function decodeEntities(encodedString) {_x000D_
  var textArea = document.createElement('textarea');_x000D_
  textArea.innerHTML = encodedString;_x000D_
  return textArea.value;_x000D_
}_x000D_
_x000D_
console.log(decodeEntities('1 &amp; 2')); // '1 & 2'
_x000D_
_x000D_
_x000D_

This works similarly to the accepted answer, but is safe to use with untrusted user input.


Security issues in similar approaches

As noted by Mike Samuel, doing this with a <div> instead of a <textarea> with untrusted user input is an XSS vulnerability, even if the <div> is never added to the DOM:

_x000D_
_x000D_
function decodeEntities(encodedString) {_x000D_
  var div = document.createElement('div');_x000D_
  div.innerHTML = encodedString;_x000D_
  return div.textContent;_x000D_
}_x000D_
_x000D_
// Shows an alert_x000D_
decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">')
_x000D_
_x000D_
_x000D_

However, this attack is not possible against a <textarea> because there are no HTML elements that are permitted content of a <textarea>. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.

_x000D_
_x000D_
function decodeEntities(encodedString) {_x000D_
    var textArea = document.createElement('textarea');_x000D_
    textArea.innerHTML = encodedString;_x000D_
    return textArea.value;_x000D_
}_x000D_
_x000D_
// Safe, and returns the correct answer_x000D_
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))
_x000D_
_x000D_
_x000D_

Warning: Doing this using jQuery's .html() and .val() methods instead of using .innerHTML and .value is also insecure* for some versions of jQuery, even when using a textarea. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to .html(). Hence code like this shows an alert in jQuery 1.8:

_x000D_
_x000D_
//<!-- CDATA_x000D_
// Shows alert_x000D_
$("<textarea>")_x000D_
.html("<script>alert(1337);</script>")_x000D_
.text();_x000D_
_x000D_
//-->
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

* Thanks to Eru Penkman for catching this vulnerability.

Android EditText for password with android:hint

Here is your answer:

There are different category for inputType so I used for pssword is textPaswword

<EditText
    android:inputType="textPassword"
    android:id="@+id/passwor"
    android:textColorHint="#ffffff"
    android:layout_marginRight="15dp"
    android:layout_marginLeft="15dp"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:hint="********"
    />

How can I save multiple documents concurrently in Mongoose/Node.js?

Here is another way without using additional libraries (no error checking included)

function saveAll( callback ){
  var count = 0;
  docs.forEach(function(doc){
      doc.save(function(err){
          count++;
          if( count == docs.length ){
             callback();
          }
      });
  });
}

How can I trigger a JavaScript event click

Fair warning:

element.onclick() does not behave as expected. It only runs the code within onclick="" attribute, but does not trigger default behavior.

I had similar issue with radio button not setting to checked, even though onclick custom function was running fine. Had to add radio.checked = "true"; to set it. Probably the same goes and for other elements (after a.onclick() there should be also window.location.href = "url";)

How to make custom dialog with rounded corners in android

For anyone who like do things in XML, specially in case where you are using Navigation architecture component actions in order to navigate to dialogs

You can use:

<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">

    <!-- dialog_background is drawable shape with corner radius -->
    <item name="android:background">@drawable/dialog_background</item>

    <item name="android:windowBackground">@android:color/transparent</item>
</style>

In Perl, how do I create a hash whose keys come from a given array?

You can place the code into a subroutine, if you don't want pollute your namespace.

my $hash_ref =
  sub{
    my %hash;
    @hash{ @{[ qw'one two three' ]} } = undef;
    return \%hash;
  }->();

Or even better:

sub keylist(@){
  my %hash;
  @hash{@_} = undef;
  return \%hash;
}

my $hash_ref = keylist qw'one two three';

# or

my @key_list = qw'one two three';
my $hash_ref = keylist @key_list;

If you really wanted to pass an array reference:

sub keylist(\@){
  my %hash;
  @hash{ @{$_[0]} } = undef if @_;
  return \%hash;
}

my @key_list = qw'one two three';
my $hash_ref = keylist @key_list;

How to convert a plain object into an ES6 Map?

ES6

convert object to map:

const objToMap = (o) => new Map(Object.entries(o));

convert map to object:

const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

Note: the mapToObj function assumes map keys are strings (will fail otherwise)

Updating to latest version of CocoaPods?

Open the Terminal -> copy below command

sudo gem install cocoapods

It will install the latest stable version of cocoapods.

after that, you need to update pod using below command

pod setup

You can check pod version using below command

pod --version

How do I get the first element from an IEnumerable<T> in .net?

FirstOrDefault ?

Elem e = enumerable.FirstOrDefault();
//do something with e

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Building on Oded's answer, you could also set the default option but not make it a selectable option if it's just dummy text. For example you could do:

<option selected="selected" disabled="disabled">Select a language</option>

This would show "Select a language" before the user clicks the select box but the user wouldn't be able to select it because of the disabled attribute.

How to draw a custom UIView that is just a circle - iPhone app

Swift 3 - Xcode 8.1

@IBOutlet weak var myView: UIView!

override func viewDidLoad() {
    super.viewDidLoad() 

    let size:CGFloat = 35.0
    myView.bounds = CGRect(x: 0, y: 0, width: size, height: size)
    myView.layer.cornerRadius = size / 2
    myView.layer.borderWidth = 1
    myView.layer.borderColor = UIColor.Gray.cgColor        
}

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Vbscript list all PDF files in folder and subfolders

Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\NOLA BOOTHE\My Documents\operating system"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
    Wscript.Echo objFile.Name
Next

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

With num_rows() you first perform the query, and then you can check how many rows you got. count_all_results() on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.

// num rows example
$this->db->select('*');
$this->db->where('whatever');
$query = $this->db->get('table');
$num = $query->num_rows();
// here you can do something with $query

// count all example
$this->db->where('whatever');
$num = $this->db->count_all_results('table');
// here you only have $num, no $query

How do I read from parameters.yml in a controller in symfony2?

You can use:

public function indexAction()
{
   dump( $this->getParameter('api_user'));
}

For more information I recommend you read the doc :

http://symfony.com/doc/2.8/service_container/parameters.html

Use CSS to automatically add 'required field' asterisk to form inputs

It is 2019 and previous answers to this problem are not using

  1. CSS grid
  2. CSS variables
  3. HTML5 form elements
  4. SVG in CSS

CSS grid is the way to do forms in 2019 as you can have your labels preceding your inputs without having extra divs, spans, spans with asterisks in and other relics.

Here is where we are going with minimal CSS:

Example screenshot

The HTML for the above:

<form action="https://www.example.com/register/" method="post" id="form-validate" enctype="multipart/form-data">
    <p class="form-instructions">Please enter the following information to create your account.</p>
    <label for="firstname">First name</label>
    <input type="text" id="firstname" name="firstname" value="" title="First name" maxlength="255" required="">
    <label for="lastname">Last name</label>
    <input type="text" id="lastname" name="lastname" value="" title="Last name" maxlength="255" required="">
    <label for="email_address">Email address</label>
    <input type="email" autocapitalize="off" autocorrect="off" spellcheck="false" name="email" id="email_address" value="" title="Email address" size="30" required="">
    <label for="password">Password</label>
    <input type="password" name="password" id="password" title="Password" required="">
    <label for="confirmation">Confirm password</label>
    <input type="password" name="confirmation" title="Confirm password" id="confirmation" required="">
    <input type="checkbox" name="is_subscribed" title="Subscribe to our newsletter" value="1" id="is_subscribed" class="checkbox">
    <label for="is_subscribed">Subscribe to the newsletter</label>
    <input type="checkbox" name="persistent_remember_me" id="remember_meGCJiRe0GbJ" checked="checked" title="Remember me">
    <label for="remember_meGCJiRe0GbJ">Remember me</label>
    <p class="required">* Required</p>
    <button type="submit" title="Register">Register</button>
</form>

Placeholder text can be added too and is highly recommended. (I am just answering this mid-form).

Now for the CSS variables:

--icon-required: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="-10 -6 16 16"> \
  <line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(15)"></line> \
  <line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(75)"></line> \
  <line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(-45)"></line> \
</svg>');

--icon-tick: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="-2 -2 16 16"> \
            <path fill="green" stroke-linejoin="round" d="M2 6L1 7l3 4 7-10h-1L4 8z"/> \
</svg>');

The CSS for the form elements:

input[type=text][required],
input[type=email][required],
input[type=password][required],
input[type=tel][required] {
    background-image: var(--icon-required);
    background-position-x: right;
    background-repeat: no-repeat;
    background-size: contain;
}

input:valid {
    --icon-required: var(--icon-tick);
}

The form itself should be in CSS grid:

form {
    align-items: center;
    display: grid;
    grid-gap: var(--form-grid-gap);
    grid-template-columns: var(--form-grid-template-columns);
    margin: auto;
}

The values for the columns can be set to 1fr auto or 1fr with anything such as <p> tags in the form set to span 1/-1. You change the variables in your media queries so that you have the input boxes going full width on mobile and as per above on desktop. You can also change your grid gap on mobile if you wish by using the CSS variables approach.

When the boxes are valid then you should get a green tick instead of the asterisk.

The SVG in CSS is a way of saving the browser from having to do a round trip to the server to get an image of the asterisk. In this way you can fine tune the asterisks, the examples here are at an unusual angle, you can edit this out as the SVG icon above is entirely readable. The viewbox can also be amended to place the asterisk above or below the centre.

Tracking CPU and Memory usage per process

Perfmon.exe is built into windows.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Python csv string to array

As others have already pointed out, Python includes a module to read and write CSV files. It works pretty well as long as the input characters stay within ASCII limits. In case you want to process other encodings, more work is needed.

The Python documentation for the csv module implements an extension of csv.reader, which uses the same interface but can handle other encodings and returns unicode strings. Just copy and paste the code from the documentation. After that, you can process a CSV file like this:

with open("some.csv", "rb") as csvFile: 
    for row in UnicodeReader(csvFile, encoding="iso-8859-15"):
        print row

Regex for quoted string with escaping quotes

/(["\']).*?(?<!\\)(\\\\)*\1/is

should work with any quoted string

Interview Question: Merge two sorted singly linked lists without creating new nodes

Here is the code on how to merge two sorted linked lists headA and headB:

Node* MergeLists1(Node *headA, Node* headB)
{
    Node *p = headA;
    Node *q = headB;
    Node *result = NULL; 
    Node *pp = NULL;
    Node *qq = NULL;
    Node *head = NULL;
    int value1 = 0;
    int value2 = 0;
    if((headA == NULL) && (headB == NULL))
    {
        return NULL;
    }
    if(headA==NULL)
    {
        return headB;
    }
    else if(headB==NULL)
    {
        return headA;
    }
    else
    {
        while((p != NULL) || (q != NULL))
        {
            if((p != NULL) && (q != NULL))
            {
                int value1 = p->data;
                int value2 = q->data;
                if(value1 <= value2)
                {
                    pp = p->next;
                    p->next = NULL;
                    if(result == NULL)
                    {
                        head = result = p;
                    }
                    else
                    {
                        result->next = p;
                        result = p;
                    }
                    p = pp;
                }
                else
                {
                    qq = q->next;
                    q->next = NULL;
                    if(result == NULL)
                    {
                        head = result = q;
                    }
                    else
                    {
                        result->next = q;
                        result = q;
                    }
                    q = qq;
                }
            }
            else
            {
                if(p != NULL)
                {
                    pp = p->next;
                    p->next = NULL;
                    result->next = p;
                    result = p;
                    p = pp;
                }
                if(q != NULL)
                {
                    qq = q->next;
                    q->next = NULL;
                    result->next = q;
                    result = q;
                    q = qq;
                }
            }
        }
    }
    return head;
}

How to select current date in Hive SQL

According to the LanguageManual, you can use unix_timestamp() to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp()).

Hope that helps.

Prevent PDF file from downloading and printing

if you want to provide a solution, well, there just isn't one. You would have to be able stop the user running a program that can access the buffers in the GPU to prevent them grabbing a screen shot. Anything displayed on the screen can be captured.

If you decide to send a file where the contents are not accessible online, then you need to rely on the security that the end product/application uses. This will also be completely breakable for an extremely determined pserson.

The last option is to send printed documents in the post. The old fashioned way using a good courier service. Costs go up, time delays are inevitble - but you get exactly what you are after. A solution is not without its costs.

Always happy to point out the obvious :)

Converting BitmapImage to Bitmap and vice versa

If you just need to go from BitmapImage to Bitmap it's quite easy,

private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
    {
        return new Bitmap(bitmapImage.StreamSource);
    }

How to calculate time difference in java?

class TimeCalculator { String updateTime;

     public TimeCalculator(String time)
      {
        // time should be in 24 hours format like 15/06/2016 17:39:20  
        this.updateTime = time;
      }

     public String getTimeDifference()
     {
        String td=null;
       // get Current Time
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        Date currentDate = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(currentDate);

        int c_year = calendar.get(Calendar.YEAR);
        int c_month = calendar.get(Calendar.MONTH) + 1;
        int c_day = calendar.get(Calendar.DAY_OF_MONTH);

        // get Editing Time

        Date edit_date = sdf.parse(updateTime);
        Calendar edit_calendar = new GregorianCalendar();
        edit_calendar.setTime(edit_date);

        int e_year = edit_calendar.get(Calendar.YEAR);
        int e_month = edit_calendar.get(Calendar.MONTH) + 1;
        int e_day = edit_calendar.get(Calendar.DAY_OF_MONTH);


        if(e_year==c_year&&e_month==c_month&&e_day==c_day)
            {

             int c_hours = calendar.get(Calendar.HOUR_OF_DAY);
             int c_minutes = calendar.get(Calendar.MINUTE);
             int c_seconds = calendar.get(Calendar.SECOND);

             int e_hours = edit_calendar.get(Calendar.HOUR_OF_DAY);
             int e_minutes = edit_calendar.get(Calendar.MINUTE);
             int e_seconds = edit_calendar.get(Calendar.SECOND);

      if(c_hours==e_hours&&c_minutes==e_minutes&&c_seconds==e_seconds)
         {
           td = "just now";
           return td;
          }
      else if(c_hours==e_hours&&c_minutes==e_minutes)
       {
         int d_seconds = c_seconds-e_seconds;
         td = String.valueOf(d_seconds);
         td = td+" seconds ago";
         return td;
       }
      else if(c_hours==e_hours&&c_minutes!=e_minutes)
       {
         int d_minutes = c_minutes-e_minutes;
         int d_seconds;
         if(c_seconds>e_seconds)
           {
             d_seconds = c_seconds-e_seconds;
           }else{
             d_seconds = e_seconds-c_seconds;
       }
          td = "00:"+String.valueOf(d_minutes)+":"+String.valueOf(d_seconds)+" ago";
        return td;
  }
    else
       {
        int d_minutes,d_seconds,d_hours;
        d_hours=c_hours-e_hours;
        if(c_minutes>e_minutes)
       {
         d_minutes = c_minutes-e_minutes;
       }else{
         d_minutes = e_minutes-c_minutes;
       }
        if(c_seconds>e_seconds)
          {
            d_seconds = c_seconds-e_seconds;
          }else{
            d_seconds = e_seconds-c_seconds;
          }

      td = String.valueOf(d_hours)+":"+String.valueOf(d_minutes)+":"+String.valueOf(d_seconds)+" ago";
     return td;
  }
}
 else if(e_year==c_year&&e_month==c_month&&c_day==e_day+1){
   td = "yesterday";
   return td;
 }
 else{
    td = updateTime;
    return td;
     }
}}

Copy files from one directory into an existing directory

Depending on some details you might need to do something like this:

r=$(pwd)
case "$TARG" in
    /*) p=$r;;
    *) p="";;
    esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"

... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.

The extra fussing is to handle relative or absolute targets.

(This doesn't rely on subtle semantics of the cp command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp and I don't know if they'll continue to be so in the future).

Adding subscribers to a list using Mailchimp's API v3

These are good answers but detached from a full answer as to how you would get a form to send data and handle that response. This will demonstrate how to add a member to a list with v3.0 of the API from an HTML page via jquery .ajax().

In Mailchimp:

  1. Acquire your API Key and List ID
  2. Make sure you setup your list and what custom fields you want to use with it. In this case, I've set up zipcode as a custom field in the list BEFORE I did the API call.
  3. Check out the API docs on adding members to lists. We are using the create method which requires the use of HTTP POST requests. There are other options in here that require PUT if you want to be able to modify/delete subs.

HTML:

<form id="pfb-signup-submission" method="post">
  <div class="sign-up-group">
    <input type="text" name="pfb-signup" id="pfb-signup-box-fname" class="pfb-signup-box" placeholder="First Name">
    <input type="text" name="pfb-signup" id="pfb-signup-box-lname" class="pfb-signup-box" placeholder="Last Name">
    <input type="email" name="pfb-signup" id="pfb-signup-box-email" class="pfb-signup-box" placeholder="[email protected]">
    <input type="text" name="pfb-signup" id="pfb-signup-box-zip" class="pfb-signup-box" placeholder="Zip Code">
  </div>
  <input type="submit" class="submit-button" value="Sign-up" id="pfb-signup-button"></a>
  <div id="pfb-signup-result"></div>
</form>

Key things:

  1. Give your <form> a unique ID and don't forget the method="post" attribute so the form works.
  2. Note the last line #signup-result is where you will deposit the feedback from the PHP script.

PHP:

<?php
  /*
   * Add a 'member' to a 'list' via mailchimp API v3.x
   * @ http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   *
   * ================
   * BACKGROUND
   * Typical use case is that this code would get run by an .ajax() jQuery call or possibly a form action
   * The live data you need will get transferred via the global $_POST variable
   * That data must be put into an array with keys that match the mailchimp endpoints, check the above link for those
   * You also need to include your API key and list ID for this to work.
   * You'll just have to go get those and type them in here, see README.md
   * ================
   */

  // Set API Key and list ID to add a subscriber
  $api_key = 'your-api-key-here';
  $list_id = 'your-list-id-here';

  /* ================
   * DESTINATION URL
   * Note: your API URL has a location subdomain at the front of the URL string
   * It can vary depending on where you are in the world
   * To determine yours, check the last 3 digits of your API key
   * ================
   */
  $url = 'https://us5.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';

  /* ================
   * DATA SETUP
   * Encode data into a format that the add subscriber mailchimp end point is looking for
   * Must include 'email_address' and 'status'
   * Statuses: pending = they get an email; subscribed = they don't get an email
   * Custom fields go into the 'merge_fields' as another array
   * More here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   * ================
   */
  $pfb_data = array(
    'email_address' => $_POST['emailname'],
    'status'        => 'pending',
    'merge_fields'  => array(
      'FNAME'       => $_POST['firstname'],
      'LNAME'       => $_POST['lastname'],
      'ZIPCODE'     => $_POST['zipcode']
    ),
  );

  // Encode the data
  $encoded_pfb_data = json_encode($pfb_data);

  // Setup cURL sequence
  $ch = curl_init();

  /* ================
   * cURL OPTIONS
   * The tricky one here is the _USERPWD - this is how you transfer the API key over
   * _RETURNTRANSFER allows us to get the response into a variable which is nice
   * This example just POSTs, we don't edit/modify - just a simple add to a list
   * _POSTFIELDS does the heavy lifting
   * _SSL_VERIFYPEER should probably be set but I didn't do it here
   * ================
   */
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_pfb_data);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  $results = curl_exec($ch); // store response
  $response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get HTTP CODE
  $errors = curl_error($ch); // store errors

  curl_close($ch);

  // Returns info back to jQuery .ajax or just outputs onto the page

  $results = array(
    'results' => $result_info,
    'response' => $response,
    'errors' => $errors
  );

  // Sends data back to the page OR the ajax() in your JS
  echo json_encode($results);
?>

Key things:

  1. CURLOPT_USERPWD handles the API key and Mailchimp doesn't really show you how to do this.
  2. CURLOPT_RETURNTRANSFER gives us the response in such a way that we can send it back into the HTML page with the .ajax() success handler.
  3. Use json_encodeon the data you received.

JS:

// Signup form submission
$('#pfb-signup-submission').submit(function(event) {
  event.preventDefault();

  // Get data from form and store it
  var pfbSignupFNAME = $('#pfb-signup-box-fname').val();
  var pfbSignupLNAME = $('#pfb-signup-box-lname').val();
  var pfbSignupEMAIL = $('#pfb-signup-box-email').val();
  var pfbSignupZIP = $('#pfb-signup-box-zip').val();

  // Create JSON variable of retreived data
  var pfbSignupData = {
    'firstname': pfbSignupFNAME,
    'lastname': pfbSignupLNAME,
    'email': pfbSignupEMAIL,
    'zipcode': pfbSignupZIP
  };

  // Send data to PHP script via .ajax() of jQuery
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'mailchimp-signup.php',
    data: pfbSignupData,
    success: function (results) {
      $('#pfb-signup-box-fname').hide();
      $('#pfb-signup-box-lname').hide();
      $('#pfb-signup-box-email').hide();
      $('#pfb-signup-box-zip').hide();
      $('#pfb-signup-result').text('Thanks for adding yourself to the email list. We will be in touch.');
      console.log(results);
    },
    error: function (results) {
      $('#pfb-signup-result').html('<p>Sorry but we were unable to add you into the email list.</p>');
      console.log(results);
    }
  });
});

Key things:

  1. JSON data is VERY touchy on transfer. Here, I am putting it into an array and it looks easy. If you are having problems, it is likely because of how your JSON data is structured. Check this out!
  2. The keys for your JSON data will become what you reference in the PHP _POST global variable. In this case it will be _POST['email'], _POST['firstname'], etc. But you could name them whatever you want - just remember what you name the keys of the data part of your JSON transfer is how you access them in PHP.
  3. This obviously requires jQuery ;)

How do I get a list of files in a directory in C++?

Solving this will require a platform specific solution. Look for opendir() on unix/linux or FindFirstFile() on Windows. Or, there are many libraries that will handle the platform specific part for you.

How to uncommit my last commit in Git

If you haven't pushed your changes yet use git reset --soft [Hash for one commit] to rollback to a specific commit. --soft tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard tells git to delete the changes being rolled back.

What is secret key for JWT based authentication and how to generate it?

You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.

In Java, you could do something like this.

String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

JPanel setBackground(Color.BLACK) does nothing

You have to call the super.paintComponent(); as well, to allow the Java API draw the original background. The super refers to the original JPanel code.

public void paintComponent(Graphics g){
    super.paintComponent(g);

    g.setColor(Color.red);
    g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}

AWK to print field $2 first, then field $1

Maybe your file contains CRLF terminator. Every lines followed by \r\n.

awk recognizes the $2 actually $2\r. The \r means goto the start of the line.

{print $2\r$1} will print $2 first, then return to the head, then print $1. So the field 2 is overlaid by the field 1.

How to display a confirmation dialog when clicking an <a> link?

I'd suggest avoiding in-line JavaScript:

var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].onclick = function() {
        var check = confirm("Are you sure you want to leave?");
        if (check == true) {
            return true;
        }
        else {
            return false;
        }
    };
}?

JS Fiddle demo.

The above updated to reduce space, though maintaining clarity/function:

var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].onclick = function() {
        return confirm("Are you sure you want to leave?");
    };
}

JS Fiddle demo.

A somewhat belated update, to use addEventListener() (as suggested, by bažmegakapa, in the comments below):

function reallySure (event) {
    var message = 'Are you sure about that?';
    action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].addEventListener('click', reallySure);
}

JS Fiddle demo.

The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:

function reallySure (event) {
    var message = 'Are you sure about that?';
    action = confirm(message) ? true : event.preventDefault();
}

function actionToFunction (event) {
    switch (event.target.tagName.toLowerCase()) {
        case 'a' :
            reallySure(event);
            break;
        default:
            break;
    }
}

document.body.addEventListener('click', actionToFunction);

JS Fiddle demo.

Because the event-handling is attached to the body element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName of a, the click-handling is passed to the reallySure() function.

References:

How to find the serial port number on Mac OS X?

I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!

Worth the 99c :) http://itunes.apple.com/us/app/tcp2serial/id506186902?mt=12

Passing on command line arguments to runnable JAR

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Installation of SQL Server Business Intelligence Development Studio

If you have installed SQL 2005 express edition and want to install BIDS (Business Intelligence Development Studio) then go to here Microsoft SQL Server 2005 Express Edition Toolkit

This has an option to install BIDS on my machine, and is the only way l could get hold of BIDS for SQL Server 2005 express edition.

Also this package l think has also allowed me to install both BIDS 2005 & 2008 express edition on the same machine.

Is it possible to style a select box?

As for CSS, Mozilla seems to be the most friendly, especially from FF 3.5+. Webkit browsers mostly just do their own thing, and ignore any style. IE is very limited, though IE8 lets you at least style border color/width.

The following actually looks fairly nice in FF 3.5+ (picking your color preference, of course):

select {
    -moz-border-radius: 4px;
    -moz-box-shadow: 1px 1px 5px #cfcfcf inset;
    border: 1px solid #cfcfcf;
    vertical-align: middle;
    background-color: transparent;
}
option {
    background-color: #fef5e6;
    border-bottom: 1px solid #ebdac0;
    border-right: 1px solid #d6bb86;
    border-left: 1px solid #d6bb86;
}
option:hover {
    cursor: pointer;
}

But when it comes to IE, you have to disable the background color on the option if you don't want it to display when the option menu isn't pulled down. And, as I said, webkit does its own thing.

Why am I getting error CS0246: The type or namespace name could not be found?

i also faced same problem,

Reason: why i faced this error is, rather then creating new partial view, i have created class and then renamed its extension from ".cs" to ".cshtml".

Solution: Just delete that rename view and re-create proper partial/full view. it will work fine after that.

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

How to make a transparent HTML button?

To get rid of the outline when clicking, add outline:none

jsFiddle example

button {
    background-color: Transparent;
    background-repeat:no-repeat;
    border: none;
    cursor:pointer;
    overflow: hidden;
    outline:none;
}

_x000D_
_x000D_
button {_x000D_
    background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}
_x000D_
<button>button</button>
_x000D_
_x000D_
_x000D_

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

I think it may be a bug in chrome. There was a similar issue long back: See this.

Try in a different browser. I think it should work fine.

Is there a RegExp.escape function in JavaScript?

This is a shorter version.

RegExp.escape = function(s) {
    return s.replace(/[$-\/?[-^{|}]/g, '\\$&');
}

This includes the non-meta characters of %, &, ', and ,, but the JavaScript RegExp specification allows this.

Authentication failed to bitbucket

This problem occurs because the password of your git account and your PC might be different. So include your user name as shown in the below example:

https://[email protected]/...

https: //[email protected]/...

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

This works for me:

#include <iostream>

using namespace std;

#define CONCAT2(a,b)     string(a)+string(b)
#define CONCAT3(a,b,c)   string(a)+string(b)+string(c)
#define CONCAT4(a,b,c,d) string(a)+string(b)+string(c)+string(d)

#define HOMEDIR "c:\\example"

int main()
{

    const char* filename = "myfile";

    string path = CONCAT4(HOMEDIR,"\\",filename,".txt");

    cout << path;
    return 0;
}

Output:

c:\example\myfile.txt

Virtualenv Command Not Found

this works in ubuntu 18 and above (not tested in previous versions):

sudo apt install python3-virtualenv

Extract code country from phone number [libphonenumber]

Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.

I don't need to set the country in parameter if my phone number begins with "+". Here is an example :

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    // phone must begin with '+'
    PhoneNumber numberProto = phoneUtil.parse(phone, "");
    int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

Regular expression for matching latitude/longitude coordinates?

^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$

Regex breakdown:

^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$

-? # accept negative values

^ # Start of string

[0-9]{1,3} # Match 1-3 digits (i. e. 0-999)

(?: # Try to match...

\. # a decimal point

[0-9]{1,10} # followed by one to 10 digits (i. e. 0-9999999999)

)? # ...optionally

$ # End of string

IntelliJ show JavaDocs tooltip on mouse over

The answer is CTRL + P (NOT CTRL + Q)

Someone else posted this answer on JetBrains forum: The idea is a different IDE. Try to discover its features and try to make the best of it, rather than trying to emulate whatever you used before. For the most part, Idea has very high usability (much better than Eclipse IMHO) and is streamlined for supporting code editing as best as possible (rather than relying on wizards too much for example).

  • Javadoc: Ctrl-Q
  • A quick view of the implementation: Ctrl-Shift-I
  • Show context: Alt-Q
  • Show parameters (in a method call): Ctrl-P
  • Show error description. Ctrl-F1

... plus many more shortcuts to navigate in code and different idea views.

I think it rather nice that you can see just the specific bit of information you are interested in with a simple keystroke. Have a look at the menus which will also show the possibly modified shortcuts for your keymap.

0 Avatar Jens Voß Created June 12, 2008, 09:26 And, elsandros, in addition to what Stephen writes: Since you seem to be interested in IDEA's keyboard shortcuts, I highly recommend the "Key Promoter" plugin which helps you memorize the relevant shortcuts quickly.

Also very useful is the "Goto Action" feature, invoked by Ctrl-Shift-A. In the popup, you can enter a keyword (e.g. "Javadoc"), and the IDE tells you the available actions matching your search, along with keyboard shortcuts and the containing action groups (which often also give you a clue about how to navigate to the action using the menu).

JavaScript: How to find out if the user browser is Chrome?

_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
  isAndroid: /Android/.test(navigator.userAgent),_x000D_
  isCordova: !!window.cordova,_x000D_
  isEdge: /Edge/.test(navigator.userAgent),_x000D_
  isFirefox: /Firefox/.test(navigator.userAgent),_x000D_
  isChrome: /Google Inc/.test(navigator.vendor),_x000D_
  isChromeIOS: /CriOS/.test(navigator.userAgent),_x000D_
  isChromiumBased: !!window.chrome && !/Edge/.test(navigator.userAgent),_x000D_
  isIE: /Trident/.test(navigator.userAgent),_x000D_
  isIOS: /(iPhone|iPad|iPod)/.test(navigator.platform),_x000D_
  isOpera: /OPR/.test(navigator.userAgent),_x000D_
  isSafari: /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent),_x000D_
  isTouchScreen: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,_x000D_
  isWebComponentsSupported: 'registerElement' in document && 'import' in document.createElement('link') && 'content' in document.createElement('template')_x000D_
}, null, '  '));
_x000D_
_x000D_
_x000D_

How can I find my php.ini on wordpress?

I just came across this thread while searching for an answer to why the php.ini file would be within the /wp-admin/ folder for WordPress that I have just seen in an odd setup - because it really really shouldn't be there.

WordPress by default doesn't include a php.ini file within the /wp-admin/ folder, so you should not have one there yourself. The php.ini file is designed to override the main server PHP configuration settings so that your account on the server is treated differently, within limits. As such, if you do need to use this file, please, for your own sanity (and that of others who happen to work with your systems in the future...), place the php.ini file in the root of your account, not hidden away in the /wp-admin/ folder, or any other folder for that matter.

I'm surprised to see so many others commenting that it should be in the /wp-admin/ folder to be honest. I'd love to see some official documentation from WordPress stating that this is best practice, as this is certainly something that I would completely avoid.

How do I determine if a port is open on a Windows server?

On Windows Server you can use

netstat -an | where{$_.Contains("Yourport")}

Convert a double to a QString

Instead of QString::number() i would use QLocale::toString(), so i can get locale aware group seperatores like german "1.234.567,89".

Powershell script to check if service is started, if not then start it

I think you may have over-complicated your code: If you are just checking to see if a service is running and, if not, run it and then stop re-evaluating, the following should suffice:

Good point on the refresh.

$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

while ($arrService.Status -ne 'Running')
{

    Start-Service $ServiceName
    write-host $arrService.status
    write-host 'Service starting'
    Start-Sleep -seconds 60
    $arrService.Refresh()
    if ($arrService.Status -eq 'Running')
    {
        Write-Host 'Service is now Running'
    }

}

POST request with a simple string in body with Alamofire

let parameters = ["foo": "bar"]
              
    // All three of these calls are equivalent
    AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
    AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
    AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
    
    

How can I scale an entire web page with CSS?

CSS will not be able to zoom on demand, but if you couple CSS with JS, you could change some values to make a page look bigger. However, as it has been said, this feature is standard nowadays in modern browsers: no need to replicate it. As a matter of fact, replicating it will slow down your website (more things to load, more JS or CSS to parse or execute and apply, etc.)

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

Iterate over each line in a string in PHP

It's overly-complicated and ugly but in my opinion this is the way to go:

$fp = fopen("php://memory", 'r+');
fputs($fp, $data);
rewind($fp);
while($line = fgets($fp)){
  // deal with $line
}
fclose($fp);

Why isn't .ico file defined when setting window's icon?

Make sure the .ico file isn't corrupted as well. I got the same error which went away when I tried a different .ico file.

What is JavaScript's highest integer value that a number can go to without losing precision?

ECMAScript 6:

Number.MAX_SAFE_INTEGER = Math.pow(2, 53)-1;
Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;

In Perl, how can I read an entire file into a string?

You could simply create a sub-routine:

#Get File Contents
sub gfc
{
    open FC, @_[0];
    join '', <FC>;
}

Select mysql query between date?

Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:

This WILL include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'

This WON'T include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'

How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details .. http://unixpapa.com/js/key.html

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

How can I get a side-by-side diff when I do "git diff"?

Try git difftool

Use git difftool instead of git diff. You'll never go back.

UPDATE to add an example usage:

Here is a link to another stackoverflow that talks about git difftool: How do I view 'git diff' output with my preferred diff tool/ viewer?

For newer versions of git, the difftool command supports many external diff tools out-of-the-box. For example vimdiff is auto supported and can be opened from the command line by:

cd /path/to/git/repo
git difftool --tool=vimdiff

Other supported external diff tools are listed via git difftool --tool-help here is an example output:

'git difftool --tool=<tool>' may be set to one of the following:
        araxis
        kompare
        vimdiff
        vimdiff2

The following tools are valid, but not currently available:
        bc3
        codecompare
        deltawalker
        diffuse
        ecmerge
        emerge
        gvimdiff
        gvimdiff2
        kdiff3
        meld
        opendiff
        tkdiff
        xxdiff

How to embed matplotlib in pyqt - for Dummies

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

How do I remove the "extended attributes" on a file in Mac OS X?


Answer (Individual Files)


1. Showcase keys to use in selection.

xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

2. Pick a Key to delete.

xattr -d com.apple.lastuseddate#PS ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -d kMDItemIsScreenCapture ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

3. Showcase keys again to see they have been removed.

xattr -l ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

4. Lastly, REMOVE ALL keys for a particular file

xattr -c ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

Answer (All Files In A Directory)


1. Showcase keys to use in selection.

xattr -r ~/Desktop

2. Remove a Specific Key for EVERY FILE in a directory

xattr -rd com.apple.FinderInfo ~/Desktop

3. Remove ALL keys on EVERY FILE in a directory

xattr -rc ~/Desktop

WARN: Once you delete these you DON'T get them back!
FAULT ERROR: There is NO UNDO.


Errors


I wanted to address the error's people are getting. Because the errors drove me nuts too... On a mac if you install xattr in python, then your environment may have an issue.

There are two different paths on my mac for xattr

type -a xattr

    # xattr is /usr/local/bin/xattr    # PYTHON Installed Version
    # xattr is /usr/bin/xattr          # Mac OSX Installed Version

So in one of the example's where -c will not work in xargs is because in bash you default to the non-python version.

Works with -c

/usr/bin/xattr -c

Does NOT Work with -c

/usr/local/bin/xattr -c
    # option -c not recognized

My Shell/Terminal defaults to /usr/local/bin/xattr because my $PATH /usr/local/bin: is before /usr/bin: which I believe is the default.

I can prove this because, if you try to uninstall the python xattr you will see:

pip3 uninstall xattr
Uninstalling xattr-0.9.6:
  Would remove:
    /usr/local/bin/xattr
    /usr/local/lib/python3.7/site-packages/xattr-0.9.6.dist-info/*
    /usr/local/lib/python3.7/site-packages/xattr/*
Proceed (y/n)?

Workarounds


To Fix option -c not recognized Errors.

  1. Uninstall any Python xattr you may have: pip3 uninstall xattr
  2. Close all Terminal windows & quit Terminal
  3. Reopen a new Terminal window.
  4. ReRun xattr command and it should now work.

OR

If you want to keep the Python xattr then use

/usr/bin/xattr

for any Shell commands in Terminal


Example:


Python's version of xattr doesn't handle images at all:

Good-Mac:~ JayRizzo$ xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # Traceback (most recent call last):
    #   File "/usr/local/bin/xattr", line 8, in <module>
    #     sys.exit(main())
    #   File "/usr/local/lib/python3.7/site-packages/xattr/tool.py", line 196, in main
    #     attr_value = attr_value.decode('utf-8')
    # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2: invalid start byte

Good-Mac:~ JayRizzo$ /usr/bin/xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

Man Pages

MAN PAGE for OSX xattr

MAN PAGE for Python xattr VERSION 0.6.4

NOTE: I could not find the python help page for current VERSION 0.9.6

Thanks for Reading!

How can I override inline styles with external CSS?

inline-styles in a document have the highest priority, so for example say if you want to change the color of a div element to blue, but you've an inline style with a color property set to red

<div style="font-size: 18px; color: red;">
   Hello World, How Can I Change The Color To Blue?
</div>
div {
   color: blue; 
   /* This Won't Work, As Inline Styles Have Color Red And As 
      Inline Styles Have Highest Priority, We Cannot Over Ride 
      The Color Using An Element Selector */
}

So, Should I Use jQuery/Javascript? - Answer Is NO

We can use element-attr CSS Selector with !important, note, !important is important here, else it won't over ride the inline styles..

<div style="font-size: 30px; color: red;">
    This is a test to see whether the inline styles can be over ridden with CSS?
</div>
div[style] {
   font-size: 12px !important;
   color: blue !important;
}

Demo

Note: Using !important ONLY will work here, but I've used div[style] selector to specifically select div having style attribute

Select element based on multiple classes

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB {
/*style here*/
}

Class & Id

.classA#idB {
/*style here*/
}

Id & Id

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector {
/*style here*/
}

or

.left.ui-class-selector {
/*style here*/
}

ClientScript.RegisterClientScriptBlock?

The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.

Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )

Guessing the problem

If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.

Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.

How to force div to appear below not next to another?

#map {
  float: right;
  width: 700px;
  height: 500px;
}
#list {
  float:left;
  width:200px;
  background: #eee;
  list-style: none;
  padding: 0;
}
#similar {
  float: left;
  clear: left;
  width: 200px;
  background: #000;
}

Checking if a double (or float) is NaN in C++

There is also a header-only library present in Boost that have neat tools to deal with floating point datatypes

#include <boost/math/special_functions/fpclassify.hpp>

You get the following functions:

template <class T> bool isfinite(T z);
template <class T> bool isinf(T t);
template <class T> bool isnan(T t);
template <class T> bool isnormal(T t);

If you have time then have a look at whole Math toolkit from Boost, it has many useful tools and is growing quickly.

Also when dealing with floating and non-floating points it might be a good idea to look at the Numeric Conversions.

Adding image inside table cell in HTML

Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.

File Not Found when running PHP with Nginx

in case it helps someone, my issue seems to be just because I was using a subfolder under my home directory, even though permissions seem correct and I don't have SELinux or anything like that. changing it to be under /var/www/something/something made it work.

(if I ever found the real cause, and remember this answer, I'll update it)

How to include JavaScript file or library in Chrome console?

I use this to load ko knockout object in console

document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");

or host locally

document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");

How can I increment a date by one day in Java?

Java 8 added a new API for working with dates and times.

With Java 8 you can use the following lines of code:

// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");

// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);

AngularJs .$setPristine to reset form

$setPristine() was introduced in the 1.1.x branch of angularjs. You need to use that version rather than 1.0.7 in order for it to work.

See http://plnkr.co/edit/815Bml?p=preview

How to recompile with -fPIC

I had this problem when building FFMPEG static libraries (e.g. libavcodec.a) for Android x86_64 target platform (using Android NDK clang). When statically linking with my library the problem occured although all FFMPEG C -> object files (*.o) were compiled with -fPIC compile option:

x86_64/libavcodec.a(h264_qpel_10bit.o): 
requires dynamic R_X86_64_PC32 reloc against 'ff_pw_1023' 
which may overflow at runtime; recompile with -fPIC

The problem occured only for libavcodec.a and libswscale.a.

Source of this problem is that FFMPEG has assembler optimizations for x86* platforms e.g. the reported problem cause is in libavcodec/h264_qpel_10bit.asm -> h264_qpel_10bit.o.

When producing X86-64 bit static library (e.g. libavcodec.a) it looks like assembler files (e.g. libavcodec/h264_qpel_10bit.asm) uses some x86 (32bit) assembler commands which are incompatible when statically linking with x86-64 bit target library since they don't support required relocation type.

Possible solutions:

  1. compile all ffmpeg files with no assembler optimizations (for ffmpeg this is configure option: --disable-asm)
  2. produce dynamic libraries (e.g. libavcodec.so) and link them in your final library dynamically

I chose 1) and it solved the problem.

Reference: https://tecnocode.co.uk/2014/10/01/dynamic-relocs-runtime-overflows-and-fpic/

How to get JSON from webpage into Python script

you can use json.dumps:

import json

# Hier comes you received data

data = json.dumps(response)

print(data)

for loading json and write it on file the following code is useful:

data = json.loads(json.dumps(Response, sort_keys=False, indent=4))
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=False, indent=4)

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Mock HttpContext.Current in Test Init Method

If your application third party redirect internally, so it is better to mock HttpContext in below way :

HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };

Change windows hostname from command line

The previously mentioned wmic command is the way to go, as it is installed by default in recent versions of Windows.

Here is my small improvement to generalize it, by retrieving the current name from the environment:

wmic computersystem where name="%COMPUTERNAME%" 
     call rename name="NEW-NAME"

NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.

How can I generate an apk that can run without server with react-native?

Generate debug APK without dev-server

If you really want to generate a debug APK (for testing purpose) that can run without the development server, Here is the link to my answer to another similar post which may help you.
https://stackoverflow.com/a/65762142/7755579

All you've to do is:

  1. edit android/app/build.gradle
project.ext.react = [
    ...
    bundleInDebug: true, // add this line
]
  1. run this command at the root directory of your project
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
  1. Then, run gradlew assembleDebug inside /android folder
    If build failed, I suggest you to build from Android studio

sql how to cast a select query

If you're using SQL (which you didn't say):

select cast(column as varchar(200)) from table 

You can use it in any statement, for example:

select value where othervalue in( select cast(column as varchar(200)) from table)
from othertable

If you want to do a join query, the answer is here already in another post :)

did you register the component correctly? For recursive components, make sure to provide the "name" option

I had this error and discovered the issue was because the name of the component was identical to the name of a prop.

import Control from '@/Control.vue';
export default {
    name: 'Question',
    components: {
        Control
    },
    props: ['Control', 'source'],

I was using file components. I changed the Control.vue to InputControl.vue and this warning disappeared.

Cannot enqueue Handshake after invoking quit

SOLUTION: to prevent this error(for AWS LAMBDA):

In order to exit of "Nodejs event Loop" you must end the connection, and then reconnect. Add the next code to invoke the callback:

connection.end( function(err) {
        if (err) {console.log("Error ending the connection:",err);}

       //  reconnect in order to prevent the"Cannot enqueue Handshake after invoking quit"

         connection = mysql.createConnection({
                host     : 'rds.host',
                port     :  3306,
                user     : 'user',
               password : 'password',
               database : 'target database'

               });
        callback(null, {
            statusCode: 200,
            body: response,

        });
    });

exception in thread 'main' java.lang.NoClassDefFoundError:

Here is what finally worked.

`@echo off
set path=%path%;C:\Program Files\Java\jdk1.7.0_71\bin;
set classpath=C:\Program Files\Java\jdk1.7.0_71\lib;
cd <packageDirectoryName>
javac .\trainingPackage\HelloWorld.java
cd ..
java trainingPackage.HelloWorld 
REM (Make sure you are on the parent directory of the PackageName and not inside the    Packagedirectory when executing java).`

sql try/catch rollback/commit - preventing erroneous commit after rollback

Transaction counter

--@@TRANCOUNT = 0
begin try
--@@TRANCOUNT = 0
BEGIN TRANSACTION tran1
 --@@TRANCOUNT = 1

        --your code
        -- if failed  @@TRANCOUNT = 1
        -- if success @@TRANCOUNT = 0

COMMIT TRANSACTION tran1

end try

begin catch
    print 'FAILED'
end catch

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

I think this one will answer your question :P

$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=??desc&limit=1&grab_content&content_limit=1";

Using cURL

//  Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

Using file_get_contents

$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));

Accessing

$array["threads"][13/* thread id */]["title"/* thread key */]

And

$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

Using routes in Express-js

You could also organise them into modules. So it would be something like.

./
controllers
    index.js
    indexController.js
app.js

and then in the indexController.js of the controllers export your controllers.

//indexController.js
module.exports = function(){
//do some set up

var self = {
     indexAction : function (req,res){
       //do your thing
}
return self;
};

then in index.js of controllers dir

exports.indexController = require("./indexController");

and finally in app.js

var controllers = require("./controllers");

app.get("/",controllers.indexController().indexAction);

I think this approach allows for clearer seperation and also you can configure your controllers by passing perhaps a db connection in.

How to change Angular CLI favicon

Since you have replaced the favicon.ico file physically, there must be a caching issue somewhere. There is a cache in your browser. Force it to get flushed by pressing Ctrl+F5.

If the default icon is still displayed, try another browser with a clean cache (i.e. you haven't visited the page with that browser yet).

Clear Cache Shortcuts: (Source)

Windows
IE:Ctrl+R; Firefox:Ctrl+Shift+R; Chrome:Ctrl+R, or Ctrl+F5, or Shift+F5.

Mac
Safari:?+R; Firefox/Chrome:?+Shift+R.

C subscripted value is neither array nor pointer nor vector when assigning an array element value

You are not passing your 2D array correctly. This should work for you

int rotateArr(int *arr[])

or

int rotateArr(int **arr) 

or

int rotateArr(int arr[][N]) 

Rather than returning the array pass the target array as argument. See John Bode's answer.

C++ int float casting

You need to use cast. I see the other answers, and they will really work, but as the tag is C++ I'd suggest you to use static_cast:

float m = static_cast< float >( a.y - b.y ) / static_cast< float >( a.x - b.x );

Assigning default value while creating migration file

Default migration generator does not handle default values (column modifiers are supported but do not include default or null), but you could create your own generator.

You can also manually update the migration file prior to running rake db:migrate by adding the options to add_column:

add_column :tweet, :retweets_count, :integer, :null => false, :default => 0

... and read Rails API

Are list-comprehensions and functional functions faster than "for loops"?

Adding a twist to Alphii answer, actually the for loop would be second best and about 6 times slower than map

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        a += i**2
    return a

def square_sum3(numbers):
    a = 0
    map(lambda x: a+x**2, numbers)
    return a

def square_sum4(numbers):
    a = 0
    return [a+i**2 for i in numbers]

time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])

Main changes have been to eliminate the slow sum calls, as well as the probably unnecessary int() in the last case. Putting the for loop and map in the same terms makes it quite fact, actually. Remember that lambdas are functional concepts and theoretically shouldn't have side effects, but, well, they can have side effects like adding to a. Results in this case with Python 3.6.1, Ubuntu 14.04, Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz

0:00:00.257703 #Reduce
0:00:00.184898 #For loop
0:00:00.031718 #Map
0:00:00.212699 #List comprehension

Understanding `scale` in R

It provides nothing else but a standardization of the data. The values it creates are known under several different names, one of them being z-scores ("Z" because the normal distribution is also known as the "Z distribution").

More can be found here:

http://en.wikipedia.org/wiki/Standard_score

Changing background color of selected item in recyclerview

What I did to achieve this was actually taking a static variable to store the last clicked position of the item in the RecyclerView and then notify the adapter to update the layout at the position on the last clicked position i.e. notifyItemChanged(lastClickedPosition) whenever a new position is clicked. Calling notifyDataSetChanged() on the whole layout is very costly and unfeasible so doing this for only one position is much better.

Here's the code for this:

public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {

private String android_versionnames[];
private Context mContext;
private static lastClickedPosition = -1; // Variable to store the last clicked item position


    public RecyclerDataAdapter(Context context,String android_versionnames[]){
        this.android_versionnames = android_versionnames;
        this.mContext = context;
        }
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.row_layout,
                parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.tv1.setText(android_versionnames[position]);    
        holder.itemView.setBackgroundColor(mContext.getResources().
        getColor(R.color.cardview_light_background));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                    
            v.setBackgroundColor(mContext.getResources().
            getColor(R.color.dark_background));
                if (lastClickedPosition != -1)
                    notifyItemChanged(lastClickedPosition);
                lastClickedPosition = position;
            }
        });
    }


    @Override
    public int getItemCount() {
        return android_versionnames.length;
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tv1;

        public ViewHolder(final View itemView) {
            super(itemView);
            tv1=(TextView)itemView.findViewById(R.id.txtView1);
        }
    }
}

So we will be actually updating only the intended item and not re-running unnecessary updates to the items which have not even been changed.

How to identify numpy types in python?

Use the builtin type function to get the type, then you can use the __module__ property to find out where it was defined:

>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

try {
    Class<?> c = Class.forName("java.lang.Daemons");
    Field maxField = c.getDeclaredField("MAX_FINALIZE_NANOS");
    maxField.setAccessible(true);
    maxField.set(null, Long.MAX_VALUE);
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

OpenCV Python rotate image by X degrees around specific point

Quick tweak to @alex-rodrigues answer... deals with shape including the number of channels.

import cv2
import numpy as np

def rotateImage(image, angle):
    center=tuple(np.array(image.shape[0:2])/2)
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
    return cv2.warpAffine(image, rot_mat, image.shape[0:2],flags=cv2.INTER_LINEAR)

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

import swineflu

x = swineflu.fibo()   # create an object `x` of class `fibo`, an instance of the class
x.f()                 # call the method `f()`, bound to `x`. 

Here is a good tutorial to get started with classes in Python.

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next

This will delete all rows that had been selected.

Normalize columns of pandas data frame

Based on this post: https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range

You can do the following:

def normalize(df):
    result = df.copy()
    for feature_name in df.columns:
        max_value = df[feature_name].max()
        min_value = df[feature_name].min()
        result[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
    return result

You don't need to stay worrying about whether your values are negative or positive. And the values should be nicely spread out between 0 and 1.

Remove Top Line of Text File with PowerShell

Using variable notation, you can do it without a temporary file:

${C:\file.txt} = ${C:\file.txt} | select -skip 1

function Remove-Topline ( [string[]]$path, [int]$skip=1 ) {
  if ( -not (Test-Path $path -PathType Leaf) ) {
    throw "invalid filename"
  }

  ls $path |
    % { iex "`${$($_.fullname)} = `${$($_.fullname)} | select -skip $skip" }
}

Copy all values in a column to a new column in a pandas dataframe

Following up on these solutions, here is some helpful code illustrating :

#
# Copying columns in pandas without slice warning
#
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))

#
# copies column B into new column D
df.loc[:,'D'] = df['B']
print df

#
# creates new column 'E' with values -99
# 
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df

#
# creates new column 'F' with values -99
# 
# Copy command only overwrites values which meet criteria 'B'>0
df['F']=-99
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df

Error: fix the version conflict (google-services plugin)

With

com.android.tools.build:gradle:3.2.0

You have to use:

classpath 'com.google.gms:google-services:4.1.0'

This fixed my problem

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

This particular commands worked for me. sudo apt-get remove --purge nginx nginx-full nginx-common

and sudo apt-get install nginx

credit to this answer on stackexchnage

How can I create tests in Android Studio?

I would suggest to use gradle.build file.

  1. Add a src/androidTest/java directory for the tests (Like Chris starts to explain)

  2. Open gradle.build file and specify there:

    android {
    
        compileSdkVersion rootProject.compileSdkVersion
        buildToolsVersion rootProject.buildToolsVersion
    
        sourceSets {
    
            androidTest {
                java.srcDirs = ['androidTest/java']
            }
        }
    }
    
  3. Press "Sync Project with Gradle file" (at the top panel). You should see now a folder "java" (inside "androidTest") is a green color.

  4. Now You are able to create there any test files and execute they.

How to get absolute path to file in /resources folder of your project

To return a file or filepath

URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath();  // return file path

dereferencing pointer to incomplete type

Outside of possible scenarios involving whole-program optimization, the code code generated for something like:

struct foo *bar;
struct foo *test(struct foo *whatever, int blah)
{
  return blah ? whatever: bar;
}

will be totally unaffected by what members struct foo might contain. Because make utilities will generally recompile any compilation unit in which the complete definition of a structure appears, even when such changes couldn't actually affect the code generated for them, it's common to omit complete structure definitions from compilation units that don't actually need them, and such omission is generally not worthy of a warning.

A compiler needs to have a complete structure or union definition to know how to handle declarations objects of the type with automatic or static duration, declarations of aggregates containing members of the type, or code which accesses members of the structure or union. If the compiler doesn't have the information needed to perform one of the above operations, it will have no choice but to squawk about it.

Incidentally, there's one more situation where the Standard would allow a compiler to require a complete union definition to be visible but would not require a diagnostic: if two structures start with a Common Initial Sequence, and a union type containing both is visible when the compiler is processing code that uses a pointer of one of the structure types to inspects a member of that Common Initial Sequence, the compiler is required to recognize that such code might be accessing the corresponding member of a structure of the other type. I don't know what compilers if any comply with the Standard when the complete union type is visible but not when it isn't [gcc is prone to generate non-conforming code in either case unless the -fno-strict-aliasing flag is used, in which case it will generate conforming code in both cases] but if one wants to write code that uses the CIS rule in such a fashion as to guarantee correct behavior on conforming compilers, one may need to ensure that complete union type definition is visible; failure to do so may result in a compiler silently generating bogus code.

jquery how to get the page's current screen top position?

Use this to get the page scroll position.

var screenTop = $(document).scrollTop();

$('#content').css('top', screenTop);

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

SQL Inner join more than two tables

try this method given below, modify to suit your need.

SELECT
  employment_status.staff_type,
  COUNT(monthly_pay_register.age),
  monthly_pay_register.BASIC_SALARY,
  monthly_pay_register.TOTAL_MONTHLY_ALLOWANCES,
  monthly_pay_register.MONTHLY_GROSS,
  monthly_pay_register.TOTAL_MONTHLY_DEDUCTIONS,
  monthly_pay_register.MONTHLY_PAY
FROM 
  (monthly_pay_register INNER JOIN deduction_logs 
ON
  monthly_pay_register.employee_info_employee_no = deduction_logs.employee_no)
INNER JOIN
  employment_status ON deduction_logs.employee_no = employment_status.employee_no
WHERE
  monthly_pay_register.`YEAR`=2017
and 
  monthly_pay_register.`MONTH`='may'

How do I sort an observable collection?

My current answer already has the most votes, but I found a better, and more modern, way of doing this.

class MyObject 
{
      public int id { get; set; }
      public string title { get; set; }
}

ObservableCollection<MyObject> myCollection = new ObservableCollection<MyObject>();

//add stuff to collection
// .
// .
// .

myCollection = new ObservableCollection<MyObject>(
    myCollection.OrderBy(n => n.title, Comparer<string>.Create(
    (x, y) => (Utils.Utils.LogicalStringCompare(x, y)))));

How to implement a queue using two stacks?

A solution in c#

public class Queue<T> where T : class
{
    private Stack<T> input = new Stack<T>();
    private Stack<T> output = new Stack<T>();
    public void Enqueue(T t)
    {
        input.Push(t);
    }

    public T Dequeue()
    {
        if (output.Count == 0)
        {
            while (input.Count != 0)
            {
                output.Push(input.Pop());
            }
        }

        return output.Pop();
    }
}

Is this how you define a function in jQuery?

You can extend jQuery prototype and use your function as a jQuery method.

(function($)
{
    $.fn.MyBlah = function(blah)
    {
        $(this).addClass(blah);
        console.log('blah class added');
    };
})(jQuery);

jQuery(document).ready(function($)
{
    $('#blahElementId').MyBlah('newClass');
});

More info on extending jQuery prototype here: http://api.jquery.com/jquery.fn.extend/

Angular 4.3 - HttpClient set params

Since HTTP Params class is immutable therefore you need to chain the set method:

const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");

Kubernetes service external ip pending

Delete existing service and create a same new service solved my problems. My problems is that the loading balancing IP I defines is used so that external endpoint is pending. When I changed a new load balancing IP it still couldn't work.

Finally, delete existing service and create a new one solved my problem.

Can not get a simple bootstrap modal to work

Also,

If you're running your page from Visual Studio and have installed the bootstrap package you need to make sure of two things

  1. That you've also gotten the Bootsrap Modal Dialog package (very important)
  2. You've added it to bundle.config if you're using bundling.

What is %0|%0 and how does it work?

It's a logic bomb, it keeps recreating itself and takes up all your CPU resources. It overloads your computer with too many processes and it forces it to shut down. If you make a batch file with this in it and start it you can end it using taskmgr. You have to do this pretty quickly or your computer will be too slow to do anything.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

there an easy way to fix this error

just replace the files on the folder : C:\xampp\mysql\data\mysql

with the files on : C:\xampp\mysql\backup\mysql

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

On Linux Machine, save the bash script and execute it. If you want to free port 8080, Input 8080 when prompted

echo "Enter port number to be closed :: "
read port
sudo kill $(sudo lsof -t -i:$port)

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

_x000D_
_x000D_
span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

How to add a browser tab icon (favicon) for a website?

I'd recommend you to try http://faviconer.com to convert your .PNG or .GIF to a .ICO file.

You can create both 16x16 and 32x32 (for new retina display) in one .ICO file.

No issues with IE and Firefox

StringBuilder vs String concatenation in toString() in Java

Performance wise String concatenation using '+' is costlier because it has to make a whole new copy of String since Strings are immutable in java. This plays particular role if concatenation is very frequent, eg: inside a loop. Following is what my IDEA suggests when I attempt to do such a thing:

enter image description here

General Rules:

  • Within a single string assignment, using String concatenation is fine.
  • If you're looping to build up a large block of character data, go for StringBuffer.
  • Using += on a String is always going to be less efficient than using a StringBuffer, so it should ring warning bells - but in certain cases the optimisation gained will be negligible compared with the readability issues, so use your common sense.

Here is a nice Jon Skeet blog around this topic.

Apply CSS style attribute dynamically in Angular JS

I would say that you should put styles that won't change into a regular style attribute, and conditional/scope styles into an ng-style attribute. Also, string keys are not necessary. For hyphen-delimited CSS keys, use camelcase.

<div ng-style="{backgroundColor: data.backgroundCol}" style="width:20px; height:20px; margin-top:10px; border:solid 1px black;"></div>

How do I install Python libraries in wheel format?

Once you have a library downloaded you can execute this from the MS-DOS command box:

python setup.py install

The setup.py is located inside every library main folder.

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

invalid use of non-static data member

In C++, nested classes are not connected to any instance of the outer class. If you want bar to access non-static members of foo, then bar needs to have access to an instance of foo. Maybe something like:

class bar {
  public:
    int getA(foo & f ) {return foo.a;}
};

Or maybe

class bar {
  private:
    foo & f;

  public:
    bar(foo & g)
    : f(g)
    {
    }

    int getA() { return f.a; }
};

In any case, you need to explicitly make sure you have access to an instance of foo.

How to upload and parse a CSV file in php

untested but should give you the idea. the view:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>

upload.php controller:


$csv = array();

// check there are no errors
if($_FILES['csv']['error'] == 0){
    $name = $_FILES['csv']['name'];
    $ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
    $type = $_FILES['csv']['type'];
    $tmpName = $_FILES['csv']['tmp_name'];

    // check the file is a csv
    if($ext === 'csv'){
        if(($handle = fopen($tmpName, 'r')) !== FALSE) {
            // necessary if a large csv file
            set_time_limit(0);

            $row = 0;

            while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // number of fields in the csv
                $col_count = count($data);

                // get the values from the csv
                $csv[$row]['col1'] = $data[0];
                $csv[$row]['col2'] = $data[1];

                // inc the row
                $row++;
            }
            fclose($handle);
        }
    }
}

How to check date of last change in stored procedure or function in SQL server

SELECT *
FROM sys.objects
WHERE type IN ('FN', 'IF', 'TF') 
AND name = 'dgdsgds'

Capture close event on Bootstrap Modal

I was having this same problem in a web app using Microsoft Visual Studio 2019, Asp.Net 3.1 and Bootstrap 4.5. I had a modal form open to add a new staff person (only a few input fields) and the Add Staff button would invoke an ajax call to create the staff records in the database. Upon successful return the code would refresh the partial razor page of staff (so the new staff person would appear in the list).

Just before the refresh I would close the Add Staff modal and display a Please Wait modal which only had a bootstrap spinner button on it. What happened is that the Please Wait modal would stay displayed and not close after the staff refresh and the modal('hide') function on this modal was called. Some times the modal would disappear but the modal backdrop would remain effectively locking the Staff List form.

Since Bootstrap has issues with multiple modals open at once, I thought maybe the Add Staff modal was still open when the Please Wait modal was displayed and this was causing problems. I made a function to display the Please Wait modal and do the refresh, and called it using the Javascript function setTimeout() to wait 1/2 second after closing/hiding the Add Staff modal:

//hide the modal form
$("#addNewStaffModal").modal('hide');
setTimeout(RefreshStaffListAfterAddingStaff, 500); //wait for 1/2 second

Here is the code for the refresh function:

function RefreshStaffListAfterAddingStaff() {
    // refresh the staff list in our partial view

    //show the please wait message
    $('#PleaseWaitModal').modal('show');

    //refresh the partial view
    $('#StaffAccountsPartialView').load('StaffAccounts?handler=StaffAccountsPartial',
        function (data, status, jqXGR) {

            //hide the wait modal
            $('#PleaseWaitModal').modal('hide');
            // enable all the fields on our form
            $("#StaffAccountsForm :input").prop("disabled", false);

            //scroll to the top of the staff list window
            window.scroll({
                top: 0,
                left: 0,
                behavior: 'smooth'
            });

        });
}

This seems to have totally solved my problem!

Android Device not recognized by adb

I also faced the same problem and tried almost everything possible from manually installing drivers to editing the winusb.inf file. But nothing worked for me.

Actually, the solution is quite simple. Its always there but we tend to miss it.

Prerequisites

Download the latest Android SDK and the latest drivers from here. Enable USB debugging and open Device Manager and keep it opened.

Steps

1) Connect your device and see if it is detected under "Android Devices" section. If it does, then its OK, otherwise, check the "Other devices" section and install the driver manually.

2) Be sure to check "Android Composite ADB Interface". This is the interface Android needs for ADB to work.

3) Go to "[SDK]/platform-tools", Shift-click there and open Command Prompt and type "adb devices" and see if your device is listed there with an unique ID.

4) If yes, then ADB have been successfully detected at this point. Next, write "adb reboot bootloader" to open the bootloader. At this point check Device Manager under "Android Devices", you will find "Android Bootlaoder Interface". Its not much important to us actually.

5) Next, using the volume down keys, move to "Recovery Mode".

6) THIS IS IMPORTANT - At this point, check the Device Manger under "Android Devices". If you do not see anything under this section or this section at all, then we need to manually install it.

7) Check the "Other devices" section and find your device listed there. Right click -> Update drivers -"Browse my computer..." -> "Let me pick from a list..." and select "ADB Composite Interface".

8) Now you can see your device listed under "Android Devices" even inside the Recovery.

9) Write "adb devices" at this point and you will see your device listed with the same ID.

10) Now, just write "adb sideload [update].zip" and your are done.

Hope this helps.

Flexbox: center horizontally and vertically

I think you want something like the following.

_x000D_
_x000D_
html, body {_x000D_
    height: 100%;_x000D_
}_x000D_
body {_x000D_
    margin: 0;_x000D_
}_x000D_
.flex-container {_x000D_
    height: 100%;_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
    display: -webkit-box;_x000D_
    display: -moz-box;_x000D_
    display: -ms-flexbox;_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.row {_x000D_
    width: auto;_x000D_
    border: 1px solid blue;_x000D_
}_x000D_
.flex-item {_x000D_
    background-color: tomato;_x000D_
    padding: 5px;_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    margin: 10px;_x000D_
    line-height: 20px;_x000D_
    color: white;_x000D_
    font-weight: bold;_x000D_
    font-size: 2em;_x000D_
    text-align: center;_x000D_
}
_x000D_
<div class="flex-container">_x000D_
    <div class="row"> _x000D_
        <div class="flex-item">1</div>_x000D_
        <div class="flex-item">2</div>_x000D_
        <div class="flex-item">3</div>_x000D_
        <div class="flex-item">4</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See demo at: http://jsfiddle.net/audetwebdesign/tFscL/

Your .flex-item elements should be block level (div instead of span) if you want the height and top/bottom padding to work properly.

Also, on .row, set the width to auto instead of 100%.

Your .flex-container properties are fine.

If you want the .row to be centered vertically in the view port, assign 100% height to html and body, and also zero out the body margins.

Note that .flex-container needs a height to see the vertical alignment effect, otherwise, the container computes the minimum height needed to enclose the content, which is less than the view port height in this example.

Footnote:
The flex-flow, flex-direction, flex-wrap properties could have made this design easier to implement. I think that the .row container is not needed unless you want to add some styling around the elements (background image, borders and so on).

A useful resource is: http://demo.agektmr.com/flexbox/

Integer ASCII value to character in BASH using printf

For your second question, it seems the leading-quote syntax (\'A) is specific to printf:

If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote.

From https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.