Programs & Examples On #Ruby in steel

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

Flutter.io Android License Status Unknown

I was facing issue. The tools folder was also missing from the Android SDK folder. I believe tools folder appears only after installing Android SDL tools(obsolete). This option was not available for me.

Solution: I upgraded the Java from version 8 to version 12 and I was able to install the tools. You may still get the error Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses while giving the command flutter doctor -v. Run the command flutter doctor --android-licenses, the licences will be reviewed when you click yes every time this question appears Accept? (y/N):

Hopefully it will help someone.

How do I call ::CreateProcess in c++ to launch a Windows executable?

Bear in mind that using WaitForSingleObject can get you into trouble in this scenario. The following is snipped from a tip on my website:

The problem arises because your application has a window but isn't pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST), then the SendMessage won't return to the new application until all applications have handled the message - but your app can't handle the message because it isn't pumping messages.... so the new app locks up, so your wait never succeeds.... DEADLOCK.

If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.

The only safe ways round this are:

  1. split off the Wait into a separate thread, or
  2. use a timeout on the Wait and use PeekMessage in your Wait loop to ensure that you pump messages, or
  3. use the MsgWaitForMultipleObjects API.

Set an environment variable in git bash

If you want to set environment variables permanently in Git-Bash, you have two options:

  1. Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.

  2. Set up env variables in .bash_profile file.

.bash_profile is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile. You can change the path to the bash home folder by setting HOME Windows environment variable.

.bash_profile file uses the regular Bash syntax and commands

# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir

# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"

Read more information about Bash configurations files.

Short IF - ELSE statement

The "ternary expression" x ? y : z can only be used for conditional assignment. That is, you could do something like:

String mood = inProfit() ? "happy" : "sad";

because the ternary expression is returning something (of type String in this example).

It's not really meant to be used as a short, in-line if-else. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).

So the proper way to do this would just be with an if-else block:

if (jXPanel6.isVisible()) {
    jXPanel6.setVisible(true);
}
else {
    jXPanel6.setVisible(false);
}

which of course can be shortened to

jXPanel6.setVisible(jXPanel6.isVisible());

Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).

Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.

In Javascript, how to conditionally add a member to an object?

I would do this

var a = someCondition ? { b: 5 } : {};

Edited with one line code version

Change background color of edittext in android

You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem

Using holoeverywhere

just change some of the 9patch resources to customize the edittext look and feel.

Displaying tooltip on mouse hover of a text

Well, take a look, this works, If you have problems please tell me:

using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        ToolTip tip = new ToolTip();
        void richTextBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!timer1.Enabled)
            {
                string link = GetWord(richTextBox1.Text, richTextBox1.GetCharIndexFromPosition(e.Location));
                //Checks whether the current word i a URL, change the regex to whatever you want, I found it on www.regexlib.com.
//you could also check if current word is bold, underlined etc. but I didn't dig into it.
                if (System.Text.RegularExpressions.Regex.IsMatch(link, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$"))
                {
                    tip.ToolTipTitle = link;
                    Point p = richTextBox1.Location;
                    tip.Show(link, this, p.X + e.X,
                        p.Y + e.Y + 32, //You can change it (the 35) to the tooltip's height - controls the tooltips position.
                        1000);
                    timer1.Enabled = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e) //The timer is to control the tooltip, it shouldn't redraw on each mouse move.
        {
            timer1.Enabled = false;
        }

        public static string GetWord(string input, int position) //Extracts the whole word the mouse is currently focused on.
        {
            char s = input[position];
            int sp1 = 0, sp2 = input.Length;
            for (int i = position; i > 0; i--)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp1 = i;
                    break;
                }
            }

            for (int i = position; i < input.Length; i++)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp2 = i;
                    break;
                }
            }

            return input.Substring(sp1, sp2 - sp1).Replace("\n", "");
        }
    }
}

To the power of in C?

For another approach, note that all the standard library functions work with floating point types. You can implement an integer type function like this:

unsigned power(unsigned base, unsigned degree)
{
    unsigned result = 1;
    unsigned term = base;
    while (degree)
    {
        if (degree & 1)
            result *= term;
        term *= term;
        degree = degree >> 1;
    }
    return result;
}

This effectively does repeated multiples, but cuts down on that a bit by using the bit representation. For low integer powers this is quite effective.

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

You can parse the date using the Date constructor, then spit out the individual time components:

_x000D_
_x000D_
function convert(str) {_x000D_
  var date = new Date(str),_x000D_
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
    day = ("0" + date.getDate()).slice(-2);_x000D_
  return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
_x000D_
_x000D_

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

_x000D_
_x000D_
function convert(str) {_x000D_
  var mnths = {_x000D_
      Jan: "01",_x000D_
      Feb: "02",_x000D_
      Mar: "03",_x000D_
      Apr: "04",_x000D_
      May: "05",_x000D_
      Jun: "06",_x000D_
      Jul: "07",_x000D_
      Aug: "08",_x000D_
      Sep: "09",_x000D_
      Oct: "10",_x000D_
      Nov: "11",_x000D_
      Dec: "12"_x000D_
    },_x000D_
    date = str.split(" ");_x000D_
_x000D_
  return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
_x000D_
_x000D_

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

Sometimes it occurs when some installations are not completed correctly, the process is stuck, or a file is still opened. So, when you try to run the installation again and the installation requires deleting, you can see the aforementioned error. In my case, shutting down the python processes and command prompt utilization helped.

Html.HiddenFor value property not getting set

I believe there is a simpler solution. You must use Html.Hidden instead of Html.HiddenFor. Look:

@Html.Hidden("CRN", ViewData["crn"]);

This will create an INPUT tag of type="hidden", with id="CRN" and name="CRN", and the correct value inside the value attribute.

Hope it helps!

How to generate unique id in MySQL?

This generates random ids:

CREATE TABLE Persons (
    ID Integer PRIMARY KEY AUTOINCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

What is the Linux equivalent to DOS pause?

read -n1 is not portable. A portable way to do the same might be:

(   trap "stty $(stty -g;stty -icanon)" EXIT
    LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
)   </dev/tty

Besides using read, for just a press ENTER to continue prompt you could do:

sed -n q </dev/tty

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

Line continue character in C#

You can use verbatim literals:

const string test = @"Test
123
456
";

But the indentation of the 1st line is tricky/ugly.

Conditional Formatting using Excel VBA code

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

How to compile and run C files from within Notepad++ using NppExec plugin?

For perl,

To run perl script use this procedure

Requirement: You need to setup classpath variable.

Go to plugins->NppExec->Execute

In command section, type this

cmd /c cd "$(CURRENT_DIRECTORY)"&&"$(FULL_CURRENT_PATH)"

Save it and give name to it.(I give Perl).

Press OK. If editor wants to restart, do it first.

Now press F6 and you will find your Perl script output on below side.

Note: Not required seperate config for seperate files.

For java,

Requirement: You need to setup JAVA_HOME and classpath variable.

Go to plugins->NppExec->Execute

In command section, type this

cmd /c cd "$(CURRENT_DIRECTORY)"&&"%JAVA_HOME%\bin\javac""$(FULL_CURRENT_PATH)"

your *.class will generate on location of current folder; despite of programming error.

For Python,

Use this Plugin Python Plugin

Go to plugins->NppExec-> Run file in Python intercative

By using this you can run scripts within Notepad++.

For PHP,

No need for different configuration just download this plugin.

PHP Plugin and done.

For C language,

Requirement: You need to setup classpath variable.
I am using MinGW compiler.

Go to plugins->NppExec->Execute

paste this into there

   NPP_SAVE

   CD $(CURRENT_DIRECTORY)

   C:\MinGW32\bin\gcc.exe -g "$(FILE_NAME)" 

   a

(Remember to give above four lines separate lines.)

Now, give name, save and ok.

Restart Npp.

Go to plugins->NppExec->Advanced options.

Menu Item->Item Name (I have C compiler)

Associated Script-> from combo box select the above name of script.

Click on Add/modify and Ok.

Now assign shortcut key as given in first answer.

Press F6 and select script or just press shortcut(I assigned Ctrl+2).

For C++,

Only change g++ instead of gcc and *.cpp instead on *.c

That's it!!

Calculate number of hours between 2 dates in PHP

In addition to @fyrye's very helpful answer this is an okayish workaround for the mentioned bug (this one), that DatePeriod substracts one hour when entering summertime, but doesn't add one hour when leaving summertime (and thus Europe/Berlin's March has its correct 743 hours but October has 744 instead of 745 hours):

Counting the hours of a month (or any timespan), considering DST-transitions in both directions

function getMonthHours(string $year, string $month, \DateTimeZone $timezone): int
{
    // or whatever start and end \DateTimeInterface objects you like
    $start = new \DateTimeImmutable($year . '-' . $month . '-01 00:00:00', $timezone);
    $end = new \DateTimeImmutable((new \DateTimeImmutable($year . '-' . $month . '-01 23:59:59', $timezone))->format('Y-m-t H:i:s'), $timezone);
    
    // count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
    $hours = iterator_count(new \DatePeriod($start, new \DateInterval('PT1H'), $end));
    
    // find transitions and check, if there is one that leads to a positive offset
    // that isn't added by \DatePeriod
    // this is the workaround for https://bugs.php.net/bug.php?id=75685
    $transitions = $timezone->getTransitions((int)$start->format('U'), (int)$end->format('U'));
    if (2 === count($transitions) && $transitions[0]['offset'] - $transitions[1]['offset'] > 0) {
        $hours += (round(($transitions[0]['offset'] - $transitions[1]['offset'])/3600));
    }
    
    return $hours;
}

$myTimezoneWithDST = new \DateTimeZone('Europe/Berlin');
var_dump(getMonthHours('2020', '01', $myTimezoneWithDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithDST)); // 743
var_dump(getMonthHours('2020', '10', $myTimezoneWithDST)); // 745, finally!

$myTimezoneWithoutDST = new \DateTimeZone('UTC');
var_dump(getMonthHours('2020', '01', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '10', $myTimezoneWithoutDST)); // 744

P.S. If you check a (longer) timespan, which leads to more than those two transitions, my workaround won't touch the counted hours to reduce the potential of funny side effects. In such cases, a more complicated solution must be implemented. One could iterate over all found transitions and compare the current with the last and check if it is one with DST true->false.

Laravel Update Query

It is very simple to do. Code are given below :

 DB::table('user')->where('email', $userEmail)->update(array('member_type' => $plan));  

Filter by process/PID in Wireshark

On Windows there is an experimental build that does this, as described on the mailing list, Filter by local process name

Missing artifact com.sun:tools:jar

Ended up using eclipse.ini fix:

openFile
-vm (Your Java Home JDK here)

For example, -vm C:\Java\JDK\1.6.

Had to also change JRE to JDK:

In Eclipse IDE go to:

  1. Window -> Preferences -> Installed JREs
  2. Click on Add (to locate new JRE)
  3. Select standard JVM -> next
  4. Click on Directory to locate JRE home, put JDK_INSTALL_LOCATION and finish.
  5. Go to your java project's Properties -> Java build Path -> Libraries -> select JRE -> Edit -> select Workspace default JRE -> finish
  6. Do a full workspace cleanup with project -> clean.

Creating temporary files in Android

You can use the cache dir using context.getCacheDir().

File temp=File.createTempFile("prefix","suffix",context.getCacheDir());

How to call C++ function from C?

You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.

Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:

 // *.h file
 // ...
 #ifdef __cplusplus
 #define EXTERNC extern "C"
 #else
 #define EXTERNC
 #endif

 typedef void* mylibrary_mytype_t;

 EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
 EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
 EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);

 #undef EXTERNC
 // ...


 // *.cpp file
 mylibrary_mytype_t mylibrary_mytype_init() {
   return new MyType;
 }

 void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
    MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
    delete typed_ptr;
 }

 void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
    MyType* typed_self = static_cast<MyType*>(untyped_self);
    typed_self->doIt(param);
 }

SELECT INTO USING UNION QUERY

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

Import file size limit in PHPMyAdmin

With WAMP, on Windows10, open

c:\wamp64\alias\phpmyadmin.conf

and change 128 by 256 at the end of these lines

  php_admin_value upload_max_filesize 128M
  php_admin_value post_max_size 128M

Restart WAMP

Aborting a shell script if any command returns a non-zero value

To add to the accepted answer:

Bear in mind that set -e sometimes is not enough, specially if you have pipes.

For example, suppose you have this script

#!/bin/bash
set -e 
./configure  > configure.log
make

... which works as expected: an error in configure aborts the execution.

Tomorrow you make a seemingly trivial change:

#!/bin/bash
set -e 
./configure  | tee configure.log
make

... and now it does not work. This is explained here, and a workaround (Bash only) is provided:

#!/bin/bash
set -e 
set -o pipefail

./configure  | tee configure.log
make

How to Maximize a firefox browser window using Selenium WebDriver with node.js

Try this:

self.ff_driver = Firefox()
self.ff_driver.maximize_window()

How do I reset a sequence in Oracle?

There is another way to reset a sequence in Oracle: set the maxvalue and cycle properties. When the nextval of the sequence hits the maxvalue, if the cycle property is set then it will begin again from the minvalue of the sequence.

The advantage of this method compared to setting a negative increment by is the sequence can continue to be used while the reset process runs, reducing the chance you need to take some form of outage to do the reset.

The value for maxvalue has to be greater than the current nextval, so the procedure below includes an optional parameter allowing a buffer in case the sequence is accessed again between selecting the nextval in the procedure and setting the cycle property.

create sequence s start with 1 increment by 1;

select s.nextval from dual
connect by level <= 20;

   NEXTVAL
----------
         1 
...
        20

create or replace procedure reset_sequence ( i_buffer in pls_integer default 0)
as
  maxval pls_integer;
begin

  maxval := s.nextval + greatest(i_buffer, 0); --ensure we don't go backwards!
  execute immediate 'alter sequence s cycle minvalue 0 maxvalue ' || maxval;
  maxval := s.nextval;
  execute immediate 'alter sequence s nocycle maxvalue 99999999999999';

end;
/
show errors

exec reset_sequence;

select s.nextval from dual;

   NEXTVAL
----------
         1 

The procedure as stands still allows the possibility that another session will fetch the value 0, which may or may not be an issue for you. If it is, you could always:

  • Set minvalue 1 in the first alter
  • Exclude the second nextval fetch
  • Move the statement to set the nocycle property into another procedure, to be run at a later date (assuming you want to do this).

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

SELECT using 'CASE' in SQL

which platform ?

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    ELSE FRUIT ='B' THEN 'BANANA' 
   END AS FRUIT     
FROM FRUIT_TABLE;

Is it possible to send a variable number of arguments to a JavaScript function?

You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.

To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):

var otherFunc = function() {
   alert(arguments.length); // Outputs: 10
}

var myFunc = function() {
  alert(arguments.length); // Outputs: 10
  otherFunc.apply(this, arguments);
}
myFunc(1,2,3,4,5,6,7,8,9,10);

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

How can I pass arguments to anonymous functions in JavaScript?

What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).

You could do this however:

<input type="button" value="Click me" id="myButton"/>

<script type="text/javascript">

    var myButton = document.getElementById("myButton");

    var myMessage = "it's working";

    var myDelegate = function(message) {
        alert(message);
    }

    myButton.onclick = function() { 
        myDelegate(myMessage);
    };

</script>

Convert PDF to clean SVG?

This topic is quite old, but here is a handy solution that I found:

http://www.cityinthesky.co.uk/opensource/pdf2svg/

It offers a tool, pdf2png, which once installed does exactly the job in command line. I've tested it with irreproachable results so far, including with bitmaps.

EDIT : My mistake, this tool also converts letters to paths, so it does not address the initial question. However it does a good job anyway, and can be useful to anyone who does not intend to modify the code in the svg file, so I'll leave the post.

How does Facebook Sharer select Images and other metadata when sharing my URL?

As of 2013, if you're using facebook.com/sharer.php (PHP) you can simply make any button/link like:

<a class="btn" target="_blank" href="http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo urlencode(YOUR_TITLE);?>&amp;p[summary]=<?php echo urlencode(YOUR_PAGE_DESCRIPTION) ?>&amp;p[url]=<?php echo urlencode(YOUR_PAGE_URL); ?>&amp;p[images][0]=<?php echo urlencode(YOUR_LINK_THUMBNAIL); ?>">share on facebook</a>

Link query parameters:

p[title] = Define a page title
p[summary] = An URL description, most likely describing the contents of the page
p[url] = The absolute URL for the page you're sharing 
p[images][0] = The URL of the thumbnail image to be used as post thumbnail on facebook

It's plain simple: you do not need any js or other settings. Is just an HTML raw link. Style the A tag in any way you want to.

How to change bower's default components folder?

Try putting the components.json file in the public directory of your application, rather than the root directory, then re-run bower install ...try this in your app home directory:

cp components.json public
cd public
bower install

How do I use $scope.$watch and $scope.$apply in AngularJS?

AngularJS extends this events-loop, creating something called AngularJS context.

$watch()

Every time you bind something in the UI you insert a $watch in a $watch list.

User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />

Here we have $scope.user, which is bound to the first input, and we have $scope.pass, which is bound to the second one. Doing this we add two $watches to the $watch list.

When our template is loaded, AKA in the linking phase, the compiler will look for every directive and creates all the $watches that are needed.

AngularJS provides $watch, $watchcollection and $watch(true). Below is a neat diagram explaining all the three taken from watchers in depth.

Enter image description here

angular.module('MY_APP', []).controller('MyCtrl', MyCtrl)
function MyCtrl($scope,$timeout) {
  $scope.users = [{"name": "vinoth"},{"name":"yusuf"},{"name":"rajini"}];

  $scope.$watch("users", function() {
    console.log("**** reference checkers $watch ****")
  });

  $scope.$watchCollection("users", function() {
    console.log("**** Collection  checkers $watchCollection ****")
  });

  $scope.$watch("users", function() {
    console.log("**** equality checkers with $watch(true) ****")
  }, true);

  $timeout(function(){
     console.log("Triggers All ")
     $scope.users = [];
     $scope.$digest();

     console.log("Triggers $watchCollection and $watch(true)")
     $scope.users.push({ name: 'Thalaivar'});
     $scope.$digest();

     console.log("Triggers $watch(true)")
     $scope.users[0].name = 'Superstar';
     $scope.$digest();
  });
}

http://jsfiddle.net/2Lyn0Lkb/

$digest loop

When the browser receives an event that can be managed by the AngularJS context the $digest loop will be fired. This loop is made from two smaller loops. One processes the $evalAsync queue, and the other one processes the $watch list. The $digest will loop through the list of $watch that we have

app.controller('MainCtrl', function() {
  $scope.name = "vinoth";

  $scope.changeFoo = function() {
      $scope.name = "Thalaivar";
  }
});

{{ name }}
<button ng-click="changeFoo()">Change the name</button>

Here we have only one $watch because ng-click doesn’t create any watches.

We press the button.

  1. The browser receives an event which will enter the AngularJS context
  2. The $digest loop will run and will ask every $watch for changes.
  3. Since the $watch which was watching for changes in $scope.name reports a change, it will force another $digest loop.
  4. The new loop reports nothing.
  5. The browser gets the control back and it will update the DOM reflecting the new value of $scope.name
  6. The important thing here is that EVERY event that enters the AngularJS context will run a $digest loop. That means that every time we write a letter in an input, the loop will run checking every $watch in this page.

$apply()

If you call $apply when an event is fired, it will go through the angular-context, but if you don’t call it, it will run outside it. It is as easy as that. $apply will call the $digest() loop internally and it will iterate over all the watches to ensure the DOM is updated with the newly updated value.

The $apply() method will trigger watchers on the entire $scope chain whereas the $digest() method will only trigger watchers on the current $scope and its children. When none of the higher-up $scope objects need to know about the local changes, you can use $digest().

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

It looks like a bug http://code.google.com/p/android/issues/detail?id=939.

Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          /> 

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp" 
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/> 

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

Font awesome is not showing icon

You needed to close your `<link />` 
As you can see in your <head></head> tag. This will solve your problem

<head>
    <link rel="stylesheet" href="../css/font-awesome.css" />
    <link rel="stylesheet" href="../css/font-awesome.min.css" />
</head>

Change div width live with jQuery

Got better solution:

$('#element').resizable({
    stop: function( event, ui ) {
        $('#element').height(ui.originalSize.height);
    }
});

mySQL :: insert into table, data from another table?

INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)  
SELECT campaign_id, from_number, received_msg, date_received
  FROM `received_txts`
 WHERE `campaign_id` = '8'

Javascript: console.log to html

I come a bit late with a more advanced version of Arun P Johny's answer. His solution doesn't handle multiple console.log() arguments and doesn't give an access to the original function.

Here's my version:

_x000D_
_x000D_
(function (logger) {_x000D_
    console.old = console.log;_x000D_
    console.log = function () {_x000D_
        var output = "", arg, i;_x000D_
_x000D_
        for (i = 0; i < arguments.length; i++) {_x000D_
            arg = arguments[i];_x000D_
            output += "<span class=\"log-" + (typeof arg) + "\">";_x000D_
_x000D_
            if (_x000D_
                typeof arg === "object" &&_x000D_
                typeof JSON === "object" &&_x000D_
                typeof JSON.stringify === "function"_x000D_
            ) {_x000D_
                output += JSON.stringify(arg);   _x000D_
            } else {_x000D_
                output += arg;   _x000D_
            }_x000D_
_x000D_
            output += "</span>&nbsp;";_x000D_
        }_x000D_
_x000D_
        logger.innerHTML += output + "<br>";_x000D_
        console.old.apply(undefined, arguments);_x000D_
    };_x000D_
})(document.getElementById("logger"));_x000D_
_x000D_
// Testing_x000D_
console.log("Hi!", {a:3, b:6}, 42, true);_x000D_
console.log("Multiple", "arguments", "here");_x000D_
console.log(null, undefined);_x000D_
console.old("Eyy, that's the old and boring one.");
_x000D_
body {background: #333;}_x000D_
.log-boolean,_x000D_
.log-undefined {color: magenta;}_x000D_
.log-object,_x000D_
.log-string {color: orange;}_x000D_
.log-number {color: cyan;}
_x000D_
<pre id="logger"></pre>
_x000D_
_x000D_
_x000D_

I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old().

Here's a minified version of the script above to paste inline, just for you:

<script>
    !function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span>&nbsp;";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
    (document.body);
</script>

Replace document.body in the parentheses with whatever element you wish to log into.

How to output numbers with leading zeros in JavaScript?

You could extend the Number object:

Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
}

Examples:

(9).pad();  //returns "09"

(7).pad(3);  //returns "007"

"Conversion to Dalvik format failed with error 1" on external JAR

This can also be caused if you have added Android.jar file to your build path, perhaps by an accidental quick fix in Eclipse. Remove it with right clicking Project -> build path -> configure build path -> android.jar, remove.

What's the @ in front of a string in C#?

It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.

So "C:\\Users\\Rich" is the same as @"C:\Users\Rich"

There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @"""" evaluates to ".

How can I pause setInterval() functions?

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.

Business logic in MVC

It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here

ImportError: No module named 'django.core.urlresolvers'

urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.

pip install django==2.0 --upgrade

Upgrade python in a virtualenv

This approach always works for me:

# First of all, delete all broken links. Replace  my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs

Taken from:

How can I execute a PHP function in a form action?

Is it really a function call on the action attribute? or it should be on the onSUbmit attribute, because by convention action attribute needs a page/URL.

I think you should use AJAX with that,

There are plenty PHP AJAX Frameworks to choose from

http://www.phplivex.com/example/submitting-html-forms-with-ajax

http://www.xajax-project.org/en/docs-tutorials/learn-xajax-in-10-minutes/

ETC.

Or the classic way

http://www.w3schools.com/php/php_ajax_php.asp

I hope these links help

Possible to perform cross-database queries with PostgreSQL?

Just to add a bit more information.

There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.

contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.

PostgreSQL FAQ

operator << must take exactly one argument

I ran into this problem with templated classes. Here's a more general solution I had to use:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // Friend means operator<< can use private variables
    // It needs to be declared as a template, but T is taken
    template <class U>
    friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}

// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
  obj.toString(os);
  return os;
}

Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.

The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(

Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.

This works too:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // For some reason this requires using T, and not U as above
    friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
    {
        obj.toString(os);
        return os;
    }
}

I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.

'xmlParseEntityRef: no name' warnings while loading xml into a php file

Try to clean the HTML first using this function:

$html = htmlspecialchars($html);

Special chars are usually represented differently in HTML and it might be confusing for the compiler. Like & becomes &amp;.

Load a Bootstrap popover content with AJAX. Is this possible?

I like Çagatay's solution, but I the popups were not hiding on mouseout. I added this extra functionality with this:

// hides the popup
$('*[data-poload]').bind('mouseout',function(){
   var e=$(this);
   e.popover('hide'); 
});

Difference between Spring MVC and Struts MVC

Spring MVC is deeply integreated in Spring, Struts MVC is not.

Transparent CSS background color

yes, thats possible. just use the rgba-syntax for your background-color.

.menue{
  background-color: rgba(255, 0, 0, 0.5); //semi-transparent red
}

Get class name using jQuery

Direct way

myid.className

_x000D_
_x000D_
console.log( myid.className )
_x000D_
<div id="myid" class="myclass"></div>
_x000D_
_x000D_
_x000D_

What is the difference between join and merge in Pandas?

I always use join on indices:

import pandas as pd
left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]}).set_index('key')
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]}).set_index('key')
left.join(right, lsuffix='_l', rsuffix='_r')

     val_l  val_r
key            
foo      1      4
bar      2      5

The same functionality can be had by using merge on the columns follows:

left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]})
left.merge(right, on=('key'), suffixes=('_l', '_r'))

   key  val_l  val_r
0  foo      1      4
1  bar      2      5

Why can't I do <img src="C:/localfile.jpg">?

I see two possibilities for what you are trying to do:

  1. You want your webpage, running on a server, to find the file on the computer that you originally designed it?

  2. You want it to fetch it from the pc that is viewing at the page?

Option 1 just doesn't make sense :)

Option 2 would be a security hole, the browser prohibits a web page (served from the web) from loading content on the viewer's machine.

Kyle Hudson told you what you need to do, but that is so basic that I find it hard to believe this is all you want to do.

Java 8 - Difference between Optional.flatMap and Optional.map

Note:- below is the illustration of map and flatmap function, otherwise Optional is primarily designed to be used as a return type only.

As you already may know Optional is a kind of container which may or may not contain a single object, so it can be used wherever you anticipate a null value(You may never see NPE if use Optional properly). For example if you have a method which expects a person object which may be nullable you may want to write the method something like this:

void doSome(Optional<Person> person){
  /*and here you want to retrieve some property phone out of person
    you may write something like this:
  */
  Optional<String> phone = person.map((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}
class Person{
  private String phone;
  //setter, getters
}

Here you have returned a String type which is automatically wrapped in an Optional type.

If person class looked like this, i.e. phone is also Optional

class Person{
  private Optional<String> phone;
  //setter,getter
}

In this case invoking map function will wrap the returned value in Optional and yield something like:

Optional<Optional<String>> 
//And you may want Optional<String> instead, here comes flatMap

void doSome(Optional<Person> person){
  Optional<String> phone = person.flatMap((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}

PS; Never call get method (if you need to) on an Optional without checking it with isPresent() unless you can't live without NullPointerExceptions.

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

Comparing object properties in c#

Do you override .ToString() on all of your objects that are in the properties? Otherwise, that second comparison could come back with null.

Also, in that second comparison, I'm on the fence about the construct of !( A == B) compared to (A != B), in terms of readability six months/two years from now. The line itself is pretty wide, which is ok if you've got a wide monitor, but might not print out very well. (nitpick)

Are all of your objects always using properties such that this code will work? Could there be some internal, non-propertied data that could be different from one object to another, but all exposed data is the same? I'm thinking of some data which could change over time, like two random number generators that happen to hit the same number at one point, but are going to produce two different sequences of information, or just any data that doesn't get exposed through the property interface.

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

Referencing value in a closed Excel workbook using INDIRECT?

OK,

Here's a dinosaur method for you on Office 2010.

Write the full address you want using concatenate (the "&" method of combining text).

Do this for all the addresses you need. It should look like:

="="&"'\FULL NETWORK ADDRESS including [Spreadsheet Name]"&W3&"'!$w4"

The W3 is a dynamic reference to what sheet I am using, the W4 is the cell I want to get from the sheet.

Once you have this, start up a macro recording session. Copy the cell and paste it into another. I pasted it into a merged cell and it gave me the classic "Same size" error. But one thing it did was paste the resulting text from my concatenate (including that extra "=").

Copy over however many you did this for. Then, go into each pasted cell, select he text and just hit enter. It updates it to an active direct reference.

Once you have finished, put the cursor somewhere nice and stop the macro. Assign it to a button and you are done.

It is a bit of a PITA to do this the first time, but once you have done it, you have just made the square peg fit that daamned round hole.

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

Is there a php echo/print equivalent in javascript

this is an another way:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

How can I change the remote/target repository URL on Windows?

The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.

On my machine in a repo I regularly use it looks like this:

KidA% cat .git/config 
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    autocflg = true
[remote "origin"]
    url = ssh://localhost:8888/opt/local/var/git/project.git
    #url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*

The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.

This is the file that is getting manipulated under-the-hood when you run something like git remote rm or git remote add but in this case since its only a typo you made it might make sense to correct it this way.

ReferenceError: variable is not defined

It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var:

$(function(){
    value = "10";
});
value; // "10"

This is equivalent to writing window.value = "10";.

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

Some operations in Excel are limited by available Memory. If you repeat the same process over and over it could produce a memory overflow and excel will not be able to repeat it anymore. This happened to me while trying to create several sheets in the same workbook.

stopPropagation vs. stopImmediatePropagation

stopPropagation will prevent any parent handlers from being executed stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing

Quick example from the jquery documentation:

_x000D_
_x000D_
$("p").click(function(event) {_x000D_
  event.stopImmediatePropagation();_x000D_
});_x000D_
_x000D_
$("p").click(function(event) {_x000D_
  // This function won't be executed_x000D_
  $(this).css("background-color", "#f00");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>example</p>
_x000D_
_x000D_
_x000D_

Note that the order of the event binding is important here!

_x000D_
_x000D_
$("p").click(function(event) {_x000D_
  // This function will now trigger_x000D_
  $(this).css("background-color", "#f00");_x000D_
});_x000D_
_x000D_
$("p").click(function(event) {_x000D_
  event.stopImmediatePropagation();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>example</p>
_x000D_
_x000D_
_x000D_

How to get the Android device's primary e-mail address

Use this method:

 public String getUserEmail() {
    AccountManager manager = AccountManager.get(App.getInstance());
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<>();
    for (Account account : accounts) {
        possibleEmails.add(account.name);
    }
    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        return possibleEmails.get(0);
    }
    return "";
}

Note that this requires the GET_ACCOUNTS permission:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Then:

editTextEmailAddress.setText(getUserEmail());

Oracle: how to UPSERT (update or insert into a table?)

I've been using the first code sample for years. Notice notfound rather than count.

UPDATE tablename SET val1 = in_val1, val2 = in_val2
    WHERE val3 = in_val3;
IF ( sql%notfound ) THEN
    INSERT INTO tablename
        VALUES (in_val1, in_val2, in_val3);
END IF;

The code below is the possibly new and improved code

MERGE INTO tablename USING dual ON ( val3 = in_val3 )
WHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2
WHEN NOT MATCHED THEN INSERT 
    VALUES (in_val1, in_val2, in_val3)

In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could have execute the correct insert or update with a single index lookup.

I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.

Proper way to initialize C++ structs

That seems to me the easiest way. Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.

struct Point 
{ 
   int x, y; 
};  

int main() 
{ 
   // A valid initialization. member x gets value 0 and y 
   // gets value 1.  The order of declaration is followed. 
   struct Point p1 = {0, 1};  
}

There is good information about structs in c++ - https://www.geeksforgeeks.org/structures-in-cpp/

Matplotlib legends in subplot

What you want cannot be done, because plt.legend() places a legend in the current axes, in your case in the last one.

If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this

f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()

enter image description here

Note that you pass to legend not the axes, as in your example code, but the lines as returned by the plot invocation.

PS

Of course you can invoke legend after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.

3D Plotting from X, Y, Z Data, Excel or other Tools

You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

      13    21   29      37    45   
1000  75.2                              
1000       79.21                            
1000             80.02                      
5000             87.9                   
5000                    88.54               
5000                           88.56            
10000            90.11      
10000                   90.79   
10000                          90.87

Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

The best 3D representation that Excel will give you of the above data is pretty confusing:

enter image description here

Representing this limited dataset as 2D data might be a better choice:

enter image description here

As a note for future reference, these types of questions usually do a little better on superuser.com.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

If you are attempting to debug from a different computer than you were originally you will get the dreaded INSTALL_FAILED_UPDATE_INCOMPATIBLE error. However, there is a way to proceed without uninstalling the app and losing your data.

To see how to transfer the debug.keystore that is required so you don't get the message "The device already has an application with the same application but a different signature. In order to proceed you will have to uninstall the existing application." (and lose your data). See Update the app in another machine with same debug.keystore in android

What is the difference between Task.Run() and Task.Factory.StartNew()

According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:

I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.

Here are the actual reasons:

  1. Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
  2. Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);

private static void A() { }

Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!

So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.

In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().

For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html

How to stop a setTimeout loop?

setTimeout returns a timer handle, which you can use to stop the timeout with clearTimeout.

So for instance:

function setBgPosition() {
    var c = 0,
        timer = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
        timer = setTimeout(run, 200);
    }
    timer = setTimeout(run, 200);

    return stop;

    function stop() {
        if (timer) {
            clearTimeout(timer);
            timer = 0;
        }
}

So you'd use that as:

var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();

Note that rather than having setBgPosition call itself again, I've just had it set c back to 0. Otherwise, this wouldn't work. Also note that I've used 0 as a handle value for when the timeout isn't pending; 0 isn't a valid return value from setTimeout so it makes a handy flag.

This is also one of the (few) places I think you'd be better off with setInterval rather than setTimeout. setInterval repeats. So:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
    }
    return setInterval(run, 200);
}

Used like this:

var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);

All of the above notwithstanding, I'd want to find a way to make setBgPosition stop things itself, by detecting that some completion condition has been satisfied.

Using union and order by clause in mysql

(select add_date,col2 from table_name) 
  union 
(select add_date,col2 from table_name) 
  union 
(select add_date,col2 from table_name) 

order by add_date

MySQL: selecting rows where a column is null

There's also a <=> operator:

SELECT pid FROM planets WHERE userid <=> NULL

Would work. The nice thing is that <=> can also be used with non-NULL values:

SELECT NULL <=> NULL yields 1.

SELECT 42 <=> 42 yields 1 as well.

See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

The git diff command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.

If you had a branch named origin, the commit hash at tip of the branch would have been used if you supplied origin to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin.

An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:

git diff origin/<branchname>

git diff <branchname> origin/<branchname>

Or other documented variants.

Edit: Having read further, I realise I'm slightly wrong, git diff origin is shorthand for diffing against the head of the specified remote, so git diff origin = git diff origin/HEAD (compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)

It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.

Running git branch -r will show you if origin/HEAD is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>).

Java List.contains(Object with field value equal to x)

Streams

If you are using Java 8, perhaps you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}

Or alternatively, you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
}

This method will return true if the List<MyObject> contains a MyObject with the name name. If you want to perform an operation on each of the MyObjects that getName().equals(name), then you could try something like this:

public void perform(final List<MyObject> list, final String name){
    list.stream().filter(o -> o.getName().equals(name)).forEach(
            o -> {
                //...
            }
    );
}

Where o represents a MyObject instance.

Alternatively, as the comments suggest (Thanks MK10), you could use the Stream#anyMatch method:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().anyMatch(o -> o.getName().equals(name));
}

Store mysql query output into a shell variable

If you have particular database name and a host on which you want the query to be executed then follow below query:

outputofquery=$(mysql -u"$dbusername" -p"$dbpassword" -h"$dbhostname" -e "SELECT A, B, C FROM table_a;" $dbname)

So to run the mysql queries you need to install mysql client on linux

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

How can I copy network files using Robocopy?

You should be able to use Windows "UNC" paths with robocopy. For example:

robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder

Robocopy has the ability to recover from certain types of network hiccups automatically.

Enterprise app deployment doesn't work on iOS 7.1

I can confirm it works, But You have to put html AND plist on dropbox. It works also for non-enterprise OTA, i.e. You want to share app with your dev. team.

I did:

a) on my site I made a page with this link:

.. href="https://dl.dropboxusercontent.com/u//(your DB id)/ipa.html">MyApp

b) on DropBox I wrote another HTML page:

.. https://dl.dropboxusercontent.com/u/(your DB id)/MyApp.plist"> Tap to Install MyApp

c) moved plist on DropBox but leaving it to POINT to my old server (no https)

What is Linux’s native GUI API?

In Linux the graphical user interface is not a part of the operating system. The graphical user interface found on most Linux desktops is provided by software called the X Window System, which defines a device independent way of dealing with screens, keyboards and pointer devices.

X Window defines a network protocol for communication, and any program that knows how to "speak" this protocol can use it. There is a C library called Xlib that makes it easier to use this protocol, so Xlib is kind of the native GUI API. Xlib is not the only way to access an X Window server; there is also XCB.

Toolkit libraries such as GTK+ (used by GNOME) and Qt (used by KDE), built on top of Xlib, are used because they are easier to program with. For example they give you a consistent look and feel across applications, make it easier to use drag-and-drop, provide components standard to a modern desktop environment, and so on.

How X draws on the screen internally depends on the implementation. X.org has a device independent part and a device dependent part. The former manages screen resources such as windows, while the latter communicates with the graphics card driver, usually a kernel module. The communication may happen over direct memory access or through system calls to the kernel. The driver translates the commands into a form that the hardware on the card understands.

As of 2013, a new window system called Wayland is starting to become usable, and many distributions have said they will at some point migrate to it, though there is still no clear schedule. This system is based on OpenGL/ES API, which means that in the future OpenGL will be the "native GUI API" in Linux. Work is being done to port GTK+ and QT to Wayland, so that current popular applications and desktop systems would need minimal changes. The applications that cannot be ported will be supported through an X11 server, much like OS X supports X11 apps through Xquartz. The GTK+ port is expected to be finished within a year, while Qt 5 already has complete Wayland support.

To further complicate matters, Ubuntu has announced they are developing a new system called Mir because of problems they perceive with Wayland. This window system is also based on the OpenGL/ES API.

Converting between strings and ArrayBuffers

I used this and works for me.

function arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}



function base64ToArrayBuffer(base64) {
    var binary_string =  window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

Updating .class file in jar

A JAR file is just a .zip in disguise. The zipped folder contains .class files.

If you're on macOS:

  1. Rename the file to possess the '.zip' extension. e.g. myJar.jar -> myJar.zip.
  2. Decompress the '.zip' (double click on it). A new folder called 'myJar' will appear
  3. Find and replace the .class file with your new .class file.
  4. Select all the contents of the folder 'myJar' and choose 'Compress x items'. DO NOT ZIP THE FOLDER ITSELF, ONLY ITS CONTENTS

Miscellaneous - Compiling a single .class file, with reference to a original jar, on macOS

  1. Make a file myClass.java, containing your code.
  2. Open terminal from Spotlight.
  3. javac -classpath originalJar.jar myClass.java This will create your compiled class called myClass.class.

From here, follow the steps above. You can also use Eclipse to compile it, simply reference the original jar by right clicking on the project, 'Build Path' -> 'Add External Archives'. From here you should be able to compile it as a jar, and use the zip technique above to retrieve the class from the jar.

Javascript objects: get parent

Try this until a non-no answer appears:

function parent() {
  this.child;
  interestingProperty = "5";
  ...
}

function child() {
  this.parent;
  ...
}

a = new parent();
a.child = new child();
a.child.parent = a; // this gives the child a reference to its parent

alert(a.interestingProperty+" === "+a.child.parent.interestingProperty);

How do I get a YouTube video thumbnail from the YouTube API?

Here's the top answer optimized for manual use. The video ID token without separators enables selecting with a double click.

Each YouTube video has four generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/YOUTUBEVIDEOID/0.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/1.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/2.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/YOUTUBEVIDEOID/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

https://img.youtube.com/vi/YOUTUBEVIDEOID/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/maxresdefault.jpg

All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

PowerShell : retrieve JSON object by field value

I just asked the same question here: https://stackoverflow.com/a/23062370/3532136 It has a good solution. I hope it helps ^^. In resume, you can use this:

The Json file in my case was called jsonfile.json:

{
    "CARD_MODEL_TITLE": "OWNER'S MANUAL",
    "CARD_MODEL_SUBTITLE": "Configure your download",
    "CARD_MODEL_SELECT": "Select Model",
    "CARD_LANG_TITLE": "Select Language",
    "CARD_LANG_DEVICE_LANG": "Your device",
    "CARD_YEAR_TITLE": "Select Model Year",
    "CARD_YEAR_LATEST": "(Latest)",
    "STEPS_MODEL": "Model",
    "STEPS_LANGUAGE": "Language",
    "STEPS_YEAR": "Model Year",
    "BUTTON_BACK": "Back",
    "BUTTON_NEXT": "Next",
    "BUTTON_CLOSE": "Close"
}

Code:

$json = (Get-Content "jsonfile.json" -Raw) | ConvertFrom-Json

$json.psobject.properties.name

Output:

CARD_MODEL_TITLE
CARD_MODEL_SUBTITLE
CARD_MODEL_SELECT
CARD_LANG_TITLE
CARD_LANG_DEVICE_LANG
CARD_YEAR_TITLE
CARD_YEAR_LATEST
STEPS_MODEL
STEPS_LANGUAGE
STEPS_YEAR
BUTTON_BACK
BUTTON_NEXT
BUTTON_CLOSE

Thanks to mjolinor.

Duplicate symbols for architecture x86_64 under Xcode

Update answer for 2021, Xcode 12.X:

pod deintegrate 
pod install

Hope this helps!

How can I get the selected VALUE out of a QCombobox?

I confirm the easiest way is to do this:

uiAnalyseAssets::AnalyseAssets(QWidget *parent)
: QWidget(parent)
{
ui.comboBox->addItem("text1");
ui.comboBox->addItem("text2");

...
}

void mainFunction::yourFunction( int index )
{
 int value = ui.comboBox->currentText();
}

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

string minusvalue = TextBox1.Text.ToString();

if (Convert.ToDouble(minusvalue) < 0)
{ 
    // set color of text in TextBox1 to red color and bold.
    TextBox1.ForeColor = Color.Red;
}

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

I had the same issue

Just make sure that you have the latest versions of all the dependencies. I used the current versions for Firebase core and auth. The newer versions have bug fixes.

You can get the latest versions from here : https://firebase.google.com/support/release-notes/android

Using the latest version at current point of time:

in app/build.gradle :

dependencies {
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.google.firebase:firebase-auth:16.1.0'
}

warning: implicit declaration of function

If you have the correct headers defined & are using a non GlibC library (such as Musl C) gcc will also throw error: implicit declaration of function when GNU extensions such as malloc_trim are encountered.

The solution is to wrap the extension & the header:

#if defined (__GLIBC__)
  malloc_trim(0);
#endif

How to pass an array into a function, and return the results with an array

You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

function foo(&$arr) { # note the &
  $arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6

That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

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

I am using ,Mongo 3.4.0

The $rename operator updates the name of a field and has the following form:

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

for e.g

db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )

The new field name must differ from the existing field name. To specify a in an embedded document, use dot notation.

This operation renames the field nmae to name for all documents in the collection:

db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )

db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);

In the method above false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.

Rename a Field in an Embedded Document

db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )

use link : https://docs.mongodb.com/manual/reference/operator/update/rename/

What is the maximum value for an int32?

In C use INT32_MAX after #include <stdint.h>. In C++ use INT32_MAX after #include <cstdint>.

Or INT_MAX for platform-specific size or UINT32_MAX or UINT_MAX for unsigned int. See http://www.cplusplus.com/reference/cstdint/ and http://www.cplusplus.com/reference/climits/.

Or sizeof(int).

Subtracting 2 lists in Python

import numpy as np
a = [2,2,2]
b = [1,1,1]
np.subtract(a,b)

HTML img onclick Javascript

use this simple cod:

    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}
</style>
</head>
<body>

<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>

<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
}
</script>

</body>
</html>

this code open and close your photo.

Git clone particular version of remote repository

You could "reset" your repository to any commit you want (e.g. 1 month ago).

Use git-reset for that:

git clone [remote_address_here] my_repo
cd my_repo
git reset --hard [ENTER HERE THE COMMIT HASH YOU WANT]

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

Instead of defining the width, you could just put a margin-left on your li, so that the spacing is consistent, and just make sure the margin(s)+li fit within 900px.

nav li {
  line-height: 87px;
  float: left;
  text-align: center;
  margin-left: 35px;
}

Hope this helps.

What's the difference between git clone --mirror and git clone --bare

A clone copies the refs from the remote and stuffs them into a subdirectory named 'these are the refs that the remote has'.

A mirror copies the refs from the remote and puts them into its own top level - it replaces its own refs with those of the remote.

This means that when someone pulls from your mirror and stuffs the mirror's refs into thier subdirectory, they will get the same refs as were on the original. The result of fetching from an up-to-date mirror is the same as fetching directly from the initial repo.

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

how to delete default values in text field using selenium?

clear() didn't work for me. But this did:

input.sendKeys(Keys.CONTROL, Keys.chord("a")); //select all text in textbox
input.sendKeys(Keys.BACK_SPACE); //delete it
input.sendKeys("new text"); //enter new text

HTTP Status 504

Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).

If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.

for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.

POST request with a simple string in body with Alamofire

If you use Alamofire, it is enough to encoding type to "URLEncoding.httpBody"

With that, you can send your data as a string in the httpbody allthough you defined it json in your code.

It worked for me..

UPDATED for

  var url = "http://..."
    let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
    let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]

    let url =  NSURL(string:"url" as String)

    request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
        response in response

        let jsonResponse = response.result.value as! NSDictionary

        if jsonResponse["access_token"] != nil
        {
            access_token = String(describing: jsonResponse["accesstoken"]!)

        }

    })

symbol(s) not found for architecture i386

In a C++ project using a defined templatized class, while receiving the same error, I selected .cpp file with the defined templatized class in the Project Navigator, then Delete > Remove Reference. Also the associated .h file, while still referenced in the project, needs to have a #include statement to the .cpp as follows:

#ifndef __CircularBuffer__CircularBufferT__
#define __CircularBuffer__CircularBufferT__

... snip ...

#include "CircularBufferT.cpp"
#endif /* defined(__CircularBuffer__CircularBufferT__) */

If you want to see, a simple project example is on github:

This is a little bit of indirection trickery and I don't recall the original source of this workaround.

How to include multiple js files using jQuery $.getScript() method

I have improved @adeneo script so it will load all scripts in the specified order. It doesn't do chain loading, so it's very fast, but if you want even faster, change the 50 ms wait time.

$.getMultiScripts = function(arr, path) {

    function executeInOrder(scr, code, resolve) {
        // if its the first script that should be executed
        if (scr == arr[0]) {
            arr.shift();
            eval(code);
            resolve();
            console.log('executed', scr);
        } else {
            // waiting
            setTimeout(function(){
                executeInOrder(scr, code, resolve);
            }, 50);
        }
    }

    var _arr = $.map(arr, function(scr) {

        return new Promise((resolve) => {
            jQuery.ajax({
                type: "GET",
                url: (path || '') + scr,
                dataType: "text",
                success: function(code) {
                    console.log('loaded  ', scr);
                    executeInOrder(scr, code, resolve);
                },
                cache: true
            });
        });

    });
        
    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));
        
    return $.when.apply($, _arr);
}

Usage is the same:

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

How can I save application settings in a Windows Forms application?

"Does this mean that I should use a custom XML file to save configuration settings?" No, not necessarily. We use SharpConfig for such operations.

For instance, if a configuration file is like that

[General]
# a comment
SomeString = Hello World!
SomeInteger = 10 # an inline comment

We can retrieve values like this

var config = Configuration.LoadFromFile("sample.cfg");
var section = config["General"];

string someString = section["SomeString"].StringValue;
int someInteger = section["SomeInteger"].IntValue;

It is compatible with .NET 2.0 and higher. We can create configuration files on the fly and we can save it later.

Source: http://sharpconfig.net/
GitHub: https://github.com/cemdervis/SharpConfig

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

MySQL Event Scheduler on a specific time everyday

This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:

CREATE EVENT event_name
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    # Your awesome query

How can I create a correlation matrix in R?

There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!

edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.

if d is the matrix (or the original data frame) and the column names are what you want, then the following works:

axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)

las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.

edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:

image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')

word-wrap break-word does not work in this example

Use this code (taken from css-tricks) that will work on all browser

overflow-wrap: break-word;
word-wrap: break-word;

-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;

/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;

Get docker container id from container name

Docker image inspect ImageName\ImageId --format={{'.ConatinerConfig.Hostname'}}

Getting the minimum of two values in SQL

The solutions using CASE, IIF, and UDF are adequate, but impractical when extending the problem to the general case using more than 2 comparison values. The generalized solution in SQL Server 2008+ utilizes a strange application of the VALUES clause:

SELECT
PaidForPast=(SELECT MIN(x) FROM (VALUES (PaidThisMonth),(OwedPast)) AS value(x))

Credit due to this website: http://sqlblog.com/blogs/jamie_thomson/archive/2012/01/20/use-values-clause-to-get-the-maximum-value-from-some-columns-sql-server-t-sql.aspx

Remote Connections Mysql Ubuntu

I was facing the same problem when I was trying to connect Mysql to a Remote Server. I had found out that I had to change the bind-address to the current private IP address of the DB server. But when I was trying to add the bind-address =0.0.0.0 line in my.cnf file, it was not understanding the line when I tried to create a DB.

Upon searching, I found out the original place where bind-address was declared.

The actual declaration is in : /etc/mysql/mariadb.conf.d/50-server.cnf

Therefore I changed the bind-address directly there and then all seems working.

If condition inside of map() React

You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:

renderItem = (id) => {
    // just standard if statement
    if (this.props.schema.collectionName.length < 0) {
        return (
            <Expandable>
                <ObjectDisplay
                    key={id}
                    parentDocumentId={id}
                    schema={schema[this.props.schema.collectionName]}
                    value={this.props.collection.documents[id]}
                />
            </Expandable>
        );
    }
    return (
        <h1>hejsan</h1>
    );
}

Then just call it when mapping:

render() {
    return (
        <div>
            <div className="box">
                { 
                    this.props.collection.ids
                        .filter(
                            id =>
                            // note: this is only passed when in top level of document
                            this.props.collection.documents[id][
                                this.props.schema.foreignKey
                            ] === this.props.parentDocumentId
                        )
                        .map(this.renderItem)
                }
            </div>
        </div>
    )
}

Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.

XML Schema (XSD) validation tool?

You can connect your XML schema to Microsoft Visual Studio's Intellisense. This option gives you both real-time validation AND autocomplete, which is just awesome.

I have this exact scenario running on my free copy of Microsoft Visual C++ 2010 Express.

Closing Bootstrap modal onclick

Close the modal box using javascript

$('#product-options').modal('hide');

Open the modal box using javascript

$('#product-options').modal('show');

Toggle the modal box using javascript

$('#myModal').modal('toggle');

Means close the modal if it's open and vice versa.

How do you print in a Go test using the "testing" package?

The *_test.go file is a Go source like the others, you can initialize a new logger every time if you need to dump complex data structure, here an example:

// initZapLog is delegated to initialize a new 'log manager'
func initZapLog() *zap.Logger {
    config := zap.NewDevelopmentConfig()
    config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
    config.EncoderConfig.TimeKey = "timestamp"
    config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    logger, _ := config.Build()
    return logger
}

Then, every time, in every test:

func TestCreateDB(t *testing.T) {
    loggerMgr := initZapLog()
    // Make logger avaible everywhere
    zap.ReplaceGlobals(loggerMgr)
    defer loggerMgr.Sync() // flushes buffer, if any
    logger := loggerMgr.Sugar()
    logger.Debug("START")
    conf := initConf()
    /* Your test here
    if false {
        t.Fail()
    }*/
}

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

insert/delete/update trigger in SQL server

I use that for all status (update, insert and delete)

CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE 
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Activity  NVARCHAR (50)

-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
    SET @Activity = 'UPDATE'
END

-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
    SET @Activity = 'INSERT'
END

-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
    SET @Activity = 'DELETE'
END



-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
                                                 UNION 
                                                 SELECT * FROM deleted
                                                 ) AS A ORDER BY A.Date DESC
                            ) AS T


-- try catch
BEGIN TRY 

    INSERT INTO MyTable  (
           [Code]
          ,[Name]
           .....
          ,[Activity])
    SELECT [Code]
          ,[Name]
          ,@Activity 
    FROM #tmpTbl

END TRY BEGIN CATCH END CATCH


-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

SET NOCOUNT OFF;
END

In Bootstrap open Enlarge image in modal

    <div class="row" style="display:inline-block">

    <div class="col-lg-12">
        <h1 class="page-header">Thumbnail Gallery</h1>

            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="This is my title" data-caption="Some lovely red flowers" data-image="http://onelive.us/wp-content/uploads/2014/08/flower-delivery-online.jpg" data-target="#image-gallery">
                <img class="img-responsive" src="http://onelive.us/wp-content/uploads/2014/08/flower-delivery-online.jpg" alt="Short alt text">
            </a>
        </div>
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="The car i dream about" data-caption="If you sponsor me, I can drive this car" data-image="http://www.picturesnew.com/media/images/car-image.jpg" data-target="#image-gallery">
                <img class="img-responsive" src="http://www.picturesnew.com/media/images/car-image.jpg" alt="A alt text">
            </a>
        </div>
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="Im so nice" data-caption="And if there is money left, my girlfriend will receive this car" data-image="http://upload.wikimedia.org/wikipedia/commons/7/78/1997_Fiat_Panda.JPG" data-target="#image-gallery">
                <img class="img-responsive" src="http://upload.wikimedia.org/wikipedia/commons/7/78/1997_Fiat_Panda.JPG" alt="Another alt text">
            </a>
        </div>
</div>


<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="image-gallery-title"></h4>
            </div>
            <div class="modal-body">
                <img id="image-gallery-image" class="img-responsive" src="">
            </div>
            <div class="modal-footer">

                <div class="col-md-2">
                    <button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>
                </div>

                <div class="col-md-8 text-justify" id="image-gallery-caption">
                    This text will be overwritten by jQuery
                </div>

                <div class="col-md-2">
                    <button type="button" id="show-next-image" class="btn btn-default">Next</button>
                </div>
            </div>
        </div>
    </div>
</div>



<script>
$(document).ready(function(){

    loadGallery(true, 'a.thumbnail');

    //This function disables buttons when needed
    function disableButtons(counter_max, counter_current){
        $('#show-previous-image, #show-next-image').show();
        if(counter_max == counter_current){
            $('#show-next-image').hide();
        } else if (counter_current == 1){
            $('#show-previous-image').hide();
        }
    }

    /**
     *
     * @param setIDs        Sets IDs when DOM is loaded. If using a PHP counter, set to false.
     * @param setClickAttr  Sets the attribute for the click handler.
     */

    function loadGallery(setIDs, setClickAttr){
        var current_image,
            selector,
            counter = 0;

        $('#show-next-image, #show-previous-image').click(function(){
            if($(this).attr('id') == 'show-previous-image'){
                current_image--;
            } else {
                current_image++;
            }

            selector = $('[data-image-id="' + current_image + '"]');
            updateGallery(selector);
        });

        function updateGallery(selector) {
            var $sel = selector;
            current_image = $sel.data('image-id');
            $('#image-gallery-caption').text($sel.data('caption'));
            $('#image-gallery-title').text($sel.data('title'));
            $('#image-gallery-image').attr('src', $sel.data('image'));
            disableButtons(counter, $sel.data('image-id'));
        }

        if(setIDs == true){
            $('[data-image-id]').each(function(){
                counter++;
                $(this).attr('data-image-id',counter);
            });
        }
        $(setClickAttr).on('click',function(){
            updateGallery($(this));
        });
    }
});
</script>

mongodb count num of distinct values per field/key

MongoDB has a distinct command which returns an array of distinct values for a field; you can check the length of the array for a count.

There is a shell db.collection.distinct() helper as well:

> db.countries.distinct('country');
[ "Spain", "England", "France", "Australia" ]

> db.countries.distinct('country').length
4

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

execute shell command from android

A modification of the code by @CarloCannas:

public static void sudo(String...strings) {
    try{
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

(You are welcome to find a better place for outputStream.close())

Usage example:

private static void suMkdirs(String path) {
    if (!new File(path).isDirectory()) {
        sudo("mkdir -p "+path);
    }
}

Update: To get the result (the output to stdout), use:

public static String sudoForResult(String...strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;
    try{
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        Closer.closeSilently(outputStream, response);
    }
    return res;
}
public static String readFully(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString("UTF-8");
}

The utility to silently close a number of Closeables (So?ket may be no Closeable) is:

public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
    // Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                Log.d("closing: "+x);
                if (x instanceof Closeable) {
                    ((Closeable)x).close();
                } else if (x instanceof Socket) {
                    ((Socket)x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket)x).close();
                } else {
                    Log.d("cannot close: "+x);
                    throw new RuntimeException("cannot close "+x);
                }
            } catch (Throwable e) {
                Log.x(e);
            }
        }
    }
}
}

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

How to change color of SVG image using CSS (jQuery SVG image replacement)?

for :hover event animations we can left the styles inside svg file, like a

<svg xmlns="http://www.w3.org/2000/svg">
<defs>
  <style>
  rect {
    fill:rgb(165,225,75);
    stroke:none;
    transition: 550ms ease-in-out;
    transform-origin:125px 125px;
  }
  rect:hover {
    fill:rgb(75,165,225);
    transform:rotate(360deg);
  }
  </style>
</defs>
  <rect x='50' y='50' width='150' height='150'/>
</svg>

check this on svgshare

How to setup Tomcat server in Netbeans?

In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:

  1. Tools -> Plugins -> Available plugins, search for 'tomcat' and install the one named "Java EE Base plugin".
  2. Restart Netbeans
  3. On the project view (default left side of the screen), go to services, right click on Servers and then "Add Server"
  4. Select Apache Tomcat, enter username and password and config the rest and finish

Change variable name in for loop using R

d <- 5
for(i in 1:10) { 
 nam <- paste("A", i, sep = "")
 assign(nam, rnorm(3)+d)
}

More info here or even here!

How do I make a fully statically linked .exe with Visual Studio Express 2005?

My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):

  1. Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".

  2. Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"

Not sure why both were needed. I used this to remove a dependency on glut32.dll.

Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.

How to refresh materialized view in oracle

a bit late to the game, but I found a way to make the original syntax in this question work (I'm on Oracle 11g)

** first switch to schema of your MV **

EXECUTE DBMS_MVIEW.REFRESH(LIST=>'MV_MY_VIEW');

alternatively you can add some options:

EXECUTE DBMS_MVIEW.REFRESH(LIST=>'MV_MY_VIEW',PARALLELISM=>4);

this actually works for me, and adding parallelism option sped my execution about 2.5 times.

More info here: How to Refresh a Materialized View in Parallel

PHP Foreach Arrays and objects

Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}

How could I convert data from string to long in c#

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value

Switch on ranges of integers in JavaScript

This does not require a switch statement. It is clearer, more concise, faster, and optimises better, to use if else statements...

var d = this.dealer;
if (1 <= d && d <= 11) { // making sure in range 1..11
    if (d <= 4) {
        alert("1 to 4");
    } else if (d <= 8) {
        alert("5 to 8");
    } else {
        alert("9 to 11");
    }
} else {
    alert("not in range");
}

Speed test

I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/

  • Chrome: switch was around 70% slower than if else

  • Firefox: switch was around 5% slower than if else

  • IE: switch was around 5% slower than if else

  • Safari: switch was around 95% slower than if else

Notes:

Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.

For numeric ranges, I like to use this kind of construction...

if (1 <= d && d <= 11) {...}

... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".

Clearer

A few people don't think this is clearer. I'd say it is not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense.

My concern, with "switch (true)", is that it can appear to be a meaningless line of code. Many coders, reading that will not know what to make of it.

For my own code, I'm more willing to use obscure structures from time to time, but if anyone else will look at it, I try to use clearer constructs. I think it is better to use the constructs for what they are intended.

Optimisation

In a modern environment, code is often going to be minified for production, so you can write clear concise code, with readable variable names and helpful comments. There's no clear reason to use switch in this way.

I also tried putting both constructs through a minifier. The if/else structure compresses well, becoming a single short expression using nested ternary operators. The switch statement when minified remains a switch, complete with "switch", "case" and "break" tokens, and as a result is considerably longer in code.

How switch(true) works

I think "switch(true) is obscure, but it seems some people just want to use it, so here's an explanation of why it works...

A switch/case statement works by matching the part in the switch with each case, and then executing the code on the first match. In most use cases, we have a variable or non-constant expression in the switch, and then match it.

With "switch(true), we will find the first expression in the case statements that is true. If you read "switch (true)" as "find the first expression that is true", the code feels more readable.

Formatting code snippets for blogging on Blogger

Emacs specific answer : As far as blogger is concerned, it allows inline css. The problem with javascript based highlighters is that you have to live with their color scheme or implement your own. But, like me, if you are a fan of your own emacs color scheme, you have a much better option available. I have hacked up the "htmlize.el" package for emacs to add the following four functions...

  1. blog-htmlize-buffer
  2. blog-htmlize-region
  3. blog-htmlize-buffer-with-linum
  4. blog-htmlize-region-with-linum

These functions will output copy-paste ready html (inline styled) in a new buffer in emacs, which you can directly use in your blog post. The output looks exactly same as you would see the code in emacs (including the color scheme).

Here is a link to my blog, where you can find detailed information of how to use the "blog-htmlize.el" with emacs. This does away with html-encoding the "less than" and "greater than" signs also. And as emacs is doing all the highlighting and styling, you do not have to worry about whether the js library supports the language of your snippets, nor do you have to meddle with your template code in blogger.

You can find the elisp file here (save the file as blog-htmlize.el)

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

how concatenate two variables in batch script?

The way is correct, but can be improved a bit with the extended set-syntax.

set "var=xyz"

Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.

Your code would look like

set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

Use PHP to convert PNG to JPG with compression?

Do this to convert safely a PNG to JPG with the transparency in white.

$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file 
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);

break/exit script

Perhaps you just want to stop executing a long script at some point. ie. like you want to hard code an exit() in C or Python.

print("this is the last message")
stop()
print("you should not see this")

Getting the base url of the website and globally passing it to twig in Symfony 2

Why do you need to get this root url ? Can't you generate directly absolute URL's ?

{{ url('_demo_hello', { 'name': 'Thomas' }) }}

This Twig code will generate the full http:// url to the _demo_hello route.

In fact, getting the base url of the website is only getting the full url of the homepage route :

{{ url('homepage') }}

(homepage, or whatever you call it in your routing file).

Multiple left joins on multiple tables in one query

You can do like this

SELECT something
FROM
    (a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'

How to trim a file extension from a String in JavaScript?

The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.

I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):

var name = "2015-01-01_backup.tar.gz";
name.replace(/(\.[^/.]+)+$/, "");

Proper Linq where clauses

EDIT: LINQ to Objects doesn't behave how I'd expected it to. You may well be interested in the blog post I've just written about this...


They're different in terms of what will be called - the first is equivalent to:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido")
          .Where(x => x.Fat == true)

wheras the latter is equivalent to:

Collection.Where(x => x.Age == 10 && 
                      x.Name == "Fido" &&
                      x.Fat == true)

Now what difference that actually makes depends on the implementation of Where being called. If it's a SQL-based provider, I'd expect the two to end up creating the same SQL. If it's in LINQ to Objects, the second will have fewer levels of indirection (there'll be just two iterators involved instead of four). Whether those levels of indirection are significant in terms of speed is a different matter.

Typically I would use several where clauses if they feel like they're representing significantly different conditions (e.g. one is to do with one part of an object, and one is completely separate) and one where clause when various conditions are closely related (e.g. a particular value is greater than a minimum and less than a maximum). Basically it's worth considering readability before any slight performance difference.

RichTextBox (WPF) does not have string property "Text"

"Extended WPF Toolkit" now provides a richtextbox with the Text property.

You can get or set the text in different formats (XAML, RTF and plaintext).

Here is the link: Extended WPF Toolkit RichTextBox

Pretty print in MongoDB shell as default

Got to the question but could not figure out how to print it from externally-loaded mongo. So:

This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:

db.quizes.find().pretty()

This works in external mongo-loaded javscript:

db.quizes.find().forEach(printjson)

Compare given date with today

One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,

//  input
$var = "2016-11-09 00:00:00.0";

//  check if date is today or in the future
if ( time() <= strtotime($var) ) 
{
    //  This seems right, but if it's ONLY date you are after
    //  then the code might treat $var as past depending on
    //  the time.
}

The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:

//  plain date string
$input = "2016-11-09";

Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.

To fix this, you can simply code, like this:

if (date("Y-m-d") <= $input)
{
    echo "Input date is equal to or greater than today.";
}

Create Windows service from executable

Use NSSM( the non-Sucking Service Manager ) to run a .BAT or any .EXE file as a service.

http://nssm.cc/

  • Step 1: Download NSSM
  • Step 2: Install your sevice with nssm.exe install [serviceName]
  • Step 3: This will open a GUI which you will use to locate your executable

net::ERR_INSECURE_RESPONSE in Chrome

A missing intermediate certificate might be the problem.

You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.

No idea why Chrome (possibly) sometimes has problems validating these certs.

Mark error in form using Bootstrap

Bootstrap V3:

Official Doc Link 1
Official Doc Link 2

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess" />
  <span class="help-block">Woohoo!</span>
</div>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
  <span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>
</div>

How do I set GIT_SSL_NO_VERIFY for specific repos only?

In particular if you need recursive clone

GIT_SSL_NO_VERIFY=true git clone --recursive https://github.com/xx/xx.git

Check if a Bash array contains a value

I came up with this one, which turns out to work only in zsh, but I think the general approach is nice.

arr=( "hello world" "find me" "what?" )
if [[ "${arr[@]/#%find me/}" != "${arr[@]}" ]]; then
    echo "found!"
else
    echo "not found!"
fi

You take out your pattern from each element only if it starts ${arr[@]/#pattern/} or ends ${arr[@]/%pattern/} with it. These two substitutions work in bash, but both at the same time ${arr[@]/#%pattern/} only works in zsh.

If the modified array is equal to the original, then it doesn't contain the element.

Edit:

This one works in bash:

 function contains () {
        local arr=(${@:2})
        local el=$1
        local marr=(${arr[@]/#$el/})
        [[ "${#arr[@]}" != "${#marr[@]}" ]]
    }

After the substitution it compares the length of both arrays. Obly if the array contains the element the substitution will completely delete it, and the count will differ.

How to delete all files and folders in a directory?

 foreach (string file in System.IO.Directory.GetFiles(path))
 {
    System.IO.File.Delete(file);
 }

 foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
 {
     System.IO.Directory.Delete(subDirectory,true); 
 } 

Best practice: PHP Magic Methods __set and __get

You only need to use magic if the object is indeed "magical". If you have a classic object with fixed properties then use setters and getters, they work fine.

If your object have dynamic properties for example it is part of a database abstraction layer, and its parameters are set at runtime then you indeed need the magic methods for convenience.

Why does "npm install" rewrite package-lock.json?

Update 3: As other answers point out as well, the npm ci command got introduced in npm 5.7.0 as additional way to achieve fast and reproducible builds in the CI context. See the documentation and npm blog for further information.


Update 2: The issue to update and clarify the documentation is GitHub issue #18103.


Update 1: The behaviour that was described below got fixed in npm 5.4.2: the currently intended behaviour is outlined in GitHub issue #17979.


Original answer: The behaviour of package-lock.json was changed in npm 5.1.0 as discussed in issue #16866. The behaviour that you observe is apparently intended by npm as of version 5.1.0.

That means that package.json can override package-lock.json whenever a newer version is found for a dependency in package.json. If you want to pin your dependencies effectively, you now must specify the versions without a prefix, e.g., you need to write them as 1.2.0 instead of ~1.2.0 or ^1.2.0. Then the combination of package.json and package-lock.json will yield reproducible builds. To be clear: package-lock.json alone no longer locks the root level dependencies!

Whether this design decision was good or not is arguable, there is an ongoing discussion resulting from this confusion on GitHub in issue #17979. (In my eyes it is a questionable decision; at least the name lock doesn't hold true any longer.)

One more side note: there is also a restriction for registries that don’t support immutable packages, such as when you pull packages directly from GitHub instead of npmjs.org. See this documentation of package locks for further explanation.

Java properties UTF-8 encoding in Eclipse

I recommend you to use Attesoro (http://attesoro.org/). Is simple and easy to use. And is made in java.

How to see my Eclipse version?

Help -> About Eclipse Platform

For Eclipse Mars - you can check Eclipse -> About Eclipse or Help -> Installation Details, then you should see the version:

enter image description here

Convert Year/Month/Day to Day of Year in Python

You could use strftime with a %j format string:

>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'

but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.

How to get the android Path string to a file on Assets folder?

AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.

So, you really can't make stuff that expects a file accept an asset 'file'.

Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:

  File f = new File(getCacheDir()+"/m1.map");
  if (!f.exists()) try {

    InputStream is = getAssets().open("m1.map");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();


    FileOutputStream fos = new FileOutputStream(f);
    fos.write(buffer);
    fos.close();
  } catch (Exception e) { throw new RuntimeException(e); }

  mapView.setMapFile(f.getPath());

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

I also encountered the same problem, I was such a solution.

First of all to be clear: provisioning profile must choose "Automatic" to debug.

If provisioning profile is "adhoc", then you can not debug, and can only export the ".ipa" file, import to iTunes for installation.

JAXB: how to marshall map into <key>value</key>

I have solution without adapter. Transient map converted to xml-elements and vise versa:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "SchemaBasedProperties")
public class SchemaBasedProperties
{
  @XmlTransient
  Map<String, Map<String, String>> properties;

  @XmlAnyElement(lax = true)
  List<Object> xmlmap;

  public Map<String, Map<String, String>> getProperties()
  {
    if (properties == null)
      properties = new LinkedHashMap<String, Map<String, String>>(); // I want same order

    return properties;
  }

  boolean beforeMarshal(Marshaller m)
  {
    try
    {
      if (properties != null && !properties.isEmpty())
      {
        if (xmlmap == null)
          xmlmap = new ArrayList<Object>();
        else
          xmlmap.clear();

        javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.newDocument();
        org.w3c.dom.Element element;

        Map<String, String> attrs;

        for (Map.Entry<String, Map<String, String>> it: properties.entrySet())
        {
          element = doc.createElement(it.getKey());
          attrs = it.getValue();

          if (attrs != null)
            for (Map.Entry<String, String> at: attrs.entrySet())
              element.setAttribute(at.getKey(), at.getValue());

          xmlmap.add(element);
        }
      }
      else
        xmlmap = null;
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return false;
    }

    return true;
  }

  void afterUnmarshal(Unmarshaller u, Object p)
  {
    org.w3c.dom.Node node;
    org.w3c.dom.NamedNodeMap nodeMap;

    String name;
    Map<String, String> attrs;

    getProperties().clear();

    if (xmlmap != null)
      for (Object xmlNode: xmlmap)
        if (xmlNode instanceof org.w3c.dom.Node)
        {
          node = (org.w3c.dom.Node) xmlNode;
          nodeMap = node.getAttributes();

          name = node.getLocalName();
          attrs = new HashMap<String, String>();

          for (int i = 0, l = nodeMap.getLength(); i < l; i++)
          {
            node = nodeMap.item(i);
            attrs.put(node.getNodeName(), node.getNodeValue());
          }

          getProperties().put(name, attrs);
        }

    xmlmap = null;
  }

  public static void main(String[] args)
    throws Exception
  {
    SchemaBasedProperties props = new SchemaBasedProperties();
    Map<String, String> attrs;

    attrs = new HashMap<String, String>();
    attrs.put("ResId", "A_LABEL");
    props.getProperties().put("LABEL", attrs);

    attrs = new HashMap<String, String>();
    attrs.put("ResId", "A_TOOLTIP");
    props.getProperties().put("TOOLTIP", attrs);

    attrs = new HashMap<String, String>();
    attrs.put("Value", "hide");
    props.getProperties().put("DISPLAYHINT", attrs);

    javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(SchemaBasedProperties.class);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(props, new java.io.File("test.xml"));

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    props = (SchemaBasedProperties) unmarshaller.unmarshal(new java.io.File("test.xml"));

    System.out.println(props.getProperties());
  }
}

My output as espected:

<SchemaBasedProperties>
    <LABEL ResId="A_LABEL"/>
    <TOOLTIP ResId="A_TOOLTIP"/>
    <DISPLAYHINT Value="hide"/>
</SchemaBasedProperties>

{LABEL={ResId=A_LABEL}, TOOLTIP={ResId=A_TOOLTIP}, DISPLAYHINT={Value=hide}}

You can use element name/value pair. I need attributes... Have fun!

String array initialization in Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

How to use pip on windows behind an authenticating proxy

I had a similar issue, and found that my company uses NTLM proxy authentication. If you see this error in your pip.log, this is probably the issue:

Could not fetch URL http://pypi.python.org/simple/pyreadline: HTTP Error 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied. )

NTLMaps can be used to interface with the NTLM proxy server by becoming an intermediate proxy.

Download NTLMAPs, update the included server.cfg, run the main.py file, then point pip's proxy setting to 127.0.0.1:.

I also needed to change these default values in the server.cfg file to:

LM_PART:1
NT_PART:1

# Highly experimental option. See research.txt for details.
# LM - 06820000
# NT - 05820000
# LM + NT - 
NTLM_FLAGS: 07820000

http://ntlmaps.sourceforge.net/

How to set the height of table header in UITableView?

@kris answer is helpful for me anyone want it in Objective-C.

Here is the code

-(void)viewDidLayoutSubviews{
     [super viewDidLayoutSubviews];
     [self sizeHeaderToFit];
}

-(void)sizeHeaderToFit{
     UIView *headerView = self.tableView.tableHeaderView;
     [headerView setNeedsLayout];
     [headerView layoutIfNeeded];
     CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
     CGRect frame = headerView.frame;
     frame.size.height = height;
     headerView.frame = frame;
     self.tableView.tableHeaderView = headerView;
}

Dilemma: when to use Fragments vs Activities:

You are free to use one of those.
Basically, you have to evaluate which is the best one to your app. Think about how you will manage the business flow and how to store/manage data preferences.

Think about, how Fragments store garbage data. When you implement the fragment, you have a activity root to fill with fragment(s). So, if your trying to implement a lot of activities with too much fragments, you have to consider performance on your app, coz you're manipulating (coarsely speaks) two context lifecycle, remember the complexity.

Remember: should I use fragments? Why shouldn't I?

regards.

Free tool to Create/Edit PNG Images?

The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

Compile error: package javax.servlet does not exist

This is what I found. Adding /usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar in my environment variable as CLASSPATH. OS is iOS.

if using bash: ~/.bash_profile $CLASSPATH=/usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar

if using zsh: ~/.zshrc export CLASSPATH="usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar"

Force it work right now, run source .bash_profile (or .zshrc) or one can restart computer and it works for the current user.

Comprehensive methods of viewing memory usage on Solaris

Here are the basics. I'm not sure that any of these count as "clear and simple" though.

ps(1)

For process-level view:

$ ps -opid,vsz,rss,osz,args
  PID  VSZ  RSS   SZ COMMAND
 1831 1776 1008  222 ps -opid,vsz,rss,osz,args
 1782 3464 2504  433 -bash
$

vsz/VSZ: total virtual process size (kb)

rss/RSS: resident set size (kb, may be inaccurate(!), see man)

osz/SZ: total size in memory (pages)

To compute byte size from pages:

$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"

vmstat(1M)

$ vmstat 5 5 
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr rm s3 -- --   in   sy   cs us sy id
 0 0 0 535832 219880  1   2  0  0  0  0  0 -0  0  0  0  402   19   97  0  1 99
 0 0 0 514376 203648  1   4  0  0  0  0  0  0  0  0  0  402   19   96  0  1 99
^C

prstat(1M)

   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  1852 martin   4840K 3600K cpu0    59    0   0:00:00 0.3% prstat/1
  1780 martin   9384K 2920K sleep   59    0   0:00:00 0.0% sshd/1
  ...

swap(1)

"Long listing" and "summary" modes:

$ swap -l
swapfile             dev  swaplo blocks   free
/dev/zvol/dsk/rpool/swap 256,1      16 1048560 1048560
$ swap -s 
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$

top(1)

An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.

load averages:  0.02,  0.00,  0.00;                      up 2+12:31:38                                                                                            08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle,  0.0% user,  2.0% kernel,  0.0% iowait,  0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1898 martin     1  54    0 3336K 1808K cpu      0:00  0.96% top
     7 root      11  59    0   10M 7912K sleep    0:09  0.02% svc.startd

sar(1M)

And just what's wrong with sar? :)

Oracle ORA-12154: TNS: Could not resolve service name Error?

Going on the assumption you're using TNSNAMES naming, here's a couple of things to do:

  • Create/modify the tnsnames.ora file in the network/admin subdirectory associated with OraHome90 to include an entry for your oracle database:
> SERVICENAME_alias =
>    (DESCRIPTION =
>     (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.XYZi.com)(PORT = 1521))
>     (CONNECT_DATA = (SERVICE_NAME = SERVICENAME))

This is assuming you're using the standard Oracle port of 1521. Note that servicename_alias can be any name you want to use on the local system. You may also find that you need to specify (SID = SERVICENAME) instead of (SERVICENAME=SERVICENAME).

  • Execute tnsping servicename_alias to verify connectivity. Get this working before going any further. This will tell you if you're past the 12154 error.
  • Assuming a good connection, create an ODBC DSN using the control panel, specifying the ODBC driver for Oracle of your choice (generally there's a Microsoft ODBC driver at least, and it should work adequately as a proof of concept). I'll assume the name you gave of DATASOURCE. Use the servicename_alias as the Server name in the ODBC configuration.
  • At this point you should be able to connect to your database via Access. I am not a VB programmer, but I know you should be able to go to File->Get External Data->Link Tables and connect to your ODBC source. I would assume your code would work as well.

Make the console wait for a user input to close

You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();

How to split a string in Java

With Java 8:

    List<String> stringList = Pattern.compile("-")
            .splitAsStream("004-034556")
            .collect(Collectors.toList());

    stringList.forEach(s -> System.out.println(s));

jquery change class name

I better use the .prop to change the className and it worked perfectly:

$(#td_id).prop('className','newClass');

for this line of code you just have to change the name of newClass, and of course the id of the element, in the next exemple : idelementinyourpage

$(#idelementinyourpage).prop('className','newClass');

By the way, when you want to search which style is applied to any element, you just click F12 on your browser when your page is shown, and then select in the tab of DOM Explorer, the element you want to see. In Styles you now can see what styles are applied to your element and from which class its reading.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.

Create a global variable in TypeScript

globalThis is the future.

First, TypeScript files have two kinds of scopes

global scope

If your file hasn't any import or export line, this file would be executed in global scope that all declaration in it are visible outside this file.

So we would create global variables like this:

// xx.d.ts
declare var age: number

// or 
// xx.ts
// with or without declare keyword
var age: number

// other.ts
globalThis.age = 18 // no error

All magic come from var. Replace var with let or const won't work.

module scope

If your file has any import or export line, this file would be executed within its own scope that we need to extend global by declaration-merging.

// xx[.d].ts
declare global {
  var age: number;
}

// other.ts
globalThis.age = 18 // no error

You can see more about module in official docs

How to vertically align <li> elements in <ul>?

I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.

So you can use display:table-cell and display:table-row like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        .toolbar ul {
            display:table-row;
        }
        .toolbar ul li
        {
            display: table-cell;
            height: 100px;
            list-style-type: none;
            margin: 10px;
            vertical-align: middle;
        }
        .toolbar ul li a {
            display:table-cell;
            vertical-align: middle;
            height:100px;
            border: solid 1px black;
        }
        .toolbar ul li.button a {
            height:50px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <div class="toolbar">
        <ul>
            <li><a href="#">first item<br />
                first item<br />
                first item</a></li>
            <li><a href="#">second item</a></li>
            <li><a href="#">last item</a></li>
            <li class="button"><a href="#">button<br />
                button</a></li>
        </ul>
    </div>
</body>
</html>

How to read a file in other directory in python

For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

should actually be

x_file = open(os.path.join('direct', "5_1.txt"), "r")   

Div side by side without float

You can also use CSS3 flexbox layout, which is well supported nowadays.

.container {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    background:black;
    height:400px;
    width:450px;
}

.left {
    flex: 0 0 300px;
    background:blue;
    height:200px;
}

.right {
    flex: 0 1 100px;
    background:green;
    height:300px;
}

See Example (with legacy styles for maximum compatiblity) & Learn more about flexbox.

How to find text in a column and saving the row number where it is first found - Excel VBA

Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:

Sub find()
    Dim i As Integer
    Dim firstTime As Integer
    Dim bNotFound As Boolean

    i = 1
    bNotFound = True

      Do While bNotFound
        If Cells(i, 2).Value = "ProjTemp" Then
            firstTime = i
            bNotFound = false
        End If
        i = i + 1
    Loop
End Sub

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Make sure the required dlls are exported (or copied manually) to the bin folder when building your application.

Max length UITextField

Swift 5

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let MAX_LENGTH = 4
        let updatedString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        return updatedString.count <= MAX_LENGTH
    }

How to convert from Hex to ASCII in JavaScript?

I found a useful function present in web3 library.

var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)