Programs & Examples On #Xmlrpclib

xmlrpclib is the Python standard library module for transparently handling XML Remote Procedure Call. (Available since v2.2)

Python Script to convert Image into Byte array

i don't know about converting into a byte array, but it's easy to convert it into a string:

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

Source

What is the current choice for doing RPC in Python?

XML-RPC is part of the Python standard library:

How to figure out the SMTP server host?

generally smtp servers name are smtp.yourdomain.com or mail.yourdomain.com open command prompt try to run following two commands

  1. >ping smtp.yourdomain.com
  2. >ping mail.yourdomain.com

you will most probably get response from any one from the above two commands.and that will be your smtp server

If this doesn't work open your cpanel --> go to your mailing accounts -- > click on configure mail account -- > there somewhere in the page you will get the information about your smtp server

it will be written like this way may be :

Incoming Server:    mail.yourdomain.com
IMAP Port: ---
POP3 Port: ---
Outgoing Server:    mail.yourdomain.com
SMTP Port: ---

How to call window.alert("message"); from C#?

You can try this:

Hope it works for you..

`private void validateUserEntry()
{
    // Checks the value of the text.
    if(serverName.Text.Length == 0)
    {
    // Initializes the variables to pass to the MessageBox.Show method.
    string message = "You did not enter a server name. Cancel this operation?";
    string caption = "Error Detected in Input";
    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
    DialogResult result;

    // Displays the MessageBox.
    result = MessageBox.Show(message, caption, buttons);
    if (result == System.Windows.Forms.DialogResult.Yes)
    {
     // Closes the parent form.
        this.Close();
    }
    }
}` 

Access XAMPP Localhost from Internet

I guess you can do this in 5 minute without any further IP/port forwarding, for presenting your local websites temporary.

All you need to do it, go to http://ngrok.com Download small tool extract and run that tool as administrator enter image description here

Enter command
ngrok http 80

You will see it will connect to server and will create a temporary URL for you which you can share to your friend and let him browse localhost or any of its folder.

You can see detailed process here.
How do I access/share xampp or localhost website from another computer

Can pm2 run an 'npm start' script

If you use PM2 via node modules instead of globally, you'll need to set interpreter: 'none' in order for the above solutions to work. Related docs here.

In ecosystem.config.js:

  apps: [
    {
      name: 'myApp',
      script: 'yarn',
      args: 'start',
      interpreter: 'none',
    },
  ],

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

Generate debug APK without dev-server

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

All you've to do is:

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

Listing only directories in UNIX

find specifiedpath -type d

If you don't want to recurse in subdirectories, you can do this instead:

find specifiedpath -type d -mindepth 1 -maxdepth 1

Note that "dot" directories (whose name start with .) will be listed too; but not the special directories . nor ... If you don't want "dot" directories, you can just grep them out:

find specifiedpath -type d -mindepth 1 -maxdepth 1 | grep -v '^\.'

how to display variable value in alert box?

$(document).ready(function(){

//    alert("test");
$("#name").click(function(){
var content = document.getElementById("ghufran").innerHTML ;
   alert(content);
  });

 //var content = $('#one').text();

})

there u go buddy this code actually works

pycharm convert tabs to spaces automatically

Change the code style to use spaces instead of tabs:

spaces

Then select a folder you want to convert in the Project View and use Code | Reformat Code.

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
new Date((new Date("07/06/2012 13:30")).toDateString())
_x000D_
_x000D_
_x000D_

Java, How to get number of messages in a topic in apache kafka

You may use kafkatool. Please check this link -> http://www.kafkatool.com/download.html

Kafka Tool is a GUI application for managing and using Apache Kafka clusters. It provides an intuitive UI that allows one to quickly view objects within a Kafka cluster as well as the messages stored in the topics of the cluster. enter image description here

Line continue character in C#

You must use one of the following ways:

    string s = @"loooooooooooooooooooooooong loooooong
                  long long long";

string s = "loooooooooong loooong" +
           " long long" ;

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

How do I pass multiple ints into a vector at once?

You can do it with initializer list:

std::vector<unsigned int> array;

// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });

Checking if a variable is an integer in PHP

I had a similar problem just now!

You can use the filter_input() function with FILTER_VALIDATE_INT and FILTER_NULL_ON_FAILURE to filter only integer values out of the $_GET variable. Works pretty accurately! :)

Check out my question here: How to check whether a variable in $_GET Array is an integer?

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

How to save picture to iPhone photo library?

Deprecated in iOS 9.0.

There`s much more fast then UIImageWriteToSavedPhotosAlbum way to do it using iOS 4.0+ AssetsLibrary framework

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
    if (error) {
    // TODO: error handling
    } else {
    // TODO: success handling
    }
}];
[library release];

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Try to use another config file (not the one from your project) and RESTART Visual Studio:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.executionengine.x86.exe.config
(32-bit)

or

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.executionengine.exe.config
(64-bit)

Fatal error: Maximum execution time of 30 seconds exceeded

if all the above didn't work for you then add an .htaccess file to the directory where your script is located and put this inside

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

this was the way I solved my problem , neither ini_set('max_execution_time', 86400); nor set_time_limit(86400) solved my problem , but the .htaccess method did.

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

use clear:left; or clear:both in your css.

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


<div id="map"></div>        
<ul id="list"></ul>
<div id ="similar">
 this text should be below, not next to ul.
</div>

Adding double quote delimiters into csv file

Double quotes can be achieved using VBA in one of two ways

First one is often the best

"...text..." & Chr(34) & "...text..."

Or the second one, which is more literal

"...text..." & """" & "...text..."

Location for session files in Apache/PHP

The default session.save_path is set to "" which will evaluate to your system's temp directory. See this comment at https://bugs.php.net/bug.php?id=26757 stating:

The new default for save_path in upcoming releaess (sic) will be the empty string, which causes the temporary directory to be probed.

You can use sys_get_temp_dir to return the directory path used for temporary files

To find the current session save path, you can use

Refer to this answer to find out what the temp path is when this function returns an empty string.

How to change background color in android app

Some times , the text has the same color that background, try with android:background="#CCCCCC" into listview properties and you will can see that.

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

VonC's answer is best, but the part that worked for me was super simple and is kind of buried among a lot of other possible answers. If you are like me, you ran into this issue while running a "getting started with rails" tutorial and you had NOT setup your public/private SSH keys.

If so, try this:

  1. $>cd ~/.ssh

  2. $>ls

  3. If the output of ls is known_hosts and nothing else, visit: http://help.github.com/mac-key-setup/ and start following the instructions from the "Generating a key" section and down.

After running those instructions, my "git push origin master" command worked.

Is there way to use two PHP versions in XAMPP?

You don't need to waste your time with this configurations just use MAMP :)

MAMP have a PHP version selection feature on interface.

Problems with local variable scope. How to solve it?

not Error:

JSONObject json1 = getJsonX();

Error:

JSONObject json2 = null;
if(x == y)
   json2 = getJSONX();

Error: Local variable statement defined in an enclosing scope must be final or effectively final.

But you can write:

JSONObject json2 = (x == y) ? json2 = getJSONX() : null;

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

How do you clear the SQL Server transaction log?

Some of the other answers did not work for me: It was not possible to create the checkpoint while the db was online, because the transaction log was full (how ironic). However, after setting the database to emergency mode, I was able to shrink the log file:

alter database <database_name> set emergency;
use <database_name>;
checkpoint;
checkpoint;
alter database <database_name> set online;
dbcc shrinkfile(<database_name>_log, 200);

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

Clang vs GCC - which produces faster binaries?

Here are some up-to-date albeit narrow findings of mine with GCC 4.7.2 and Clang 3.2 for C++.

UPDATE: GCC 4.8.1 v clang 3.3 comparison appended below.

UPDATE: GCC 4.8.2 v clang 3.4 comparison is appended to that.

I maintain an OSS tool that is built for Linux with both GCC and Clang, and with Microsoft's compiler for Windows. The tool, coan, is a preprocessor and analyser of C/C++ source files and codelines of such: its computational profile majors on recursive-descent parsing and file-handling. The development branch (to which these results pertain) comprises at present around 11K LOC in about 90 files. It is coded, now, in C++ that is rich in polymorphism and templates and but is still mired in many patches by its not-so-distant past in hacked-together C. Move semantics are not expressly exploited. It is single-threaded. I have devoted no serious effort to optimizing it, while the "architecture" remains so largely ToDo.

I employed Clang prior to 3.2 only as an experimental compiler because, despite its superior compilation speed and diagnostics, its C++11 standard support lagged the contemporary GCC version in the respects exercised by coan. With 3.2, this gap has been closed.

My Linux test harness for current coan development processes roughly 70K sources files in a mixture of one-file parser test-cases, stress tests consuming 1000s of files and scenario tests consuming < 1K files. As well as reporting the test results, the harness accumulates and displays the totals of files consumed and the run time consumed in coan (it just passes each coan command line to the Linux time command and captures and adds up the reported numbers). The timings are flattered by the fact that any number of tests which take 0 measurable time will all add up to 0, but the contribution of such tests is negligible. The timing stats are displayed at the end of make check like this:

coan_test_timer: info: coan processed 70844 input_files.
coan_test_timer: info: run time in coan: 16.4 secs.
coan_test_timer: info: Average processing time per input file: 0.000231 secs.

I compared the test harness performance as between GCC 4.7.2 and Clang 3.2, all things being equal except the compilers. As of Clang 3.2, I no longer require any preprocessor differentiation between code tracts that GCC will compile and Clang alternatives. I built to the same C++ library (GCC's) in each case and ran all the comparisons consecutively in the same terminal session.

The default optimization level for my release build is -O2. I also successfully tested builds at -O3. I tested each configuration 3 times back-to-back and averaged the 3 outcomes, with the following results. The number in a data-cell is the average number of microseconds consumed by the coan executable to process each of the ~70K input files (read, parse and write output and diagnostics).

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 231 | 237 |0.97 |
----------|-----|-----|-----|
Clang-3.2 | 234 | 186 |1.25 |
----------|-----|-----|------
GCC/Clang |0.99 | 1.27|

Any particular application is very likely to have traits that play unfairly to a compiler's strengths or weaknesses. Rigorous benchmarking employs diverse applications. With that well in mind, the noteworthy features of these data are:

  1. -O3 optimization was marginally detrimental to GCC
  2. -O3 optimization was importantly beneficial to Clang
  3. At -O2 optimization, GCC was faster than Clang by just a whisker
  4. At -O3 optimization, Clang was importantly faster than GCC.

A further interesting comparison of the two compilers emerged by accident shortly after those findings. Coan liberally employs smart pointers and one such is heavily exercised in the file handling. This particular smart-pointer type had been typedef'd in prior releases for the sake of compiler-differentiation, to be an std::unique_ptr<X> if the configured compiler had sufficiently mature support for its usage as that, and otherwise an std::shared_ptr<X>. The bias to std::unique_ptr was foolish, since these pointers were in fact transferred around, but std::unique_ptr looked like the fitter option for replacing std::auto_ptr at a point when the C++11 variants were novel to me.

In the course of experimental builds to gauge Clang 3.2's continued need for this and similar differentiation, I inadvertently built std::shared_ptr<X> when I had intended to build std::unique_ptr<X>, and was surprised to observe that the resulting executable, with default -O2 optimization, was the fastest I had seen, sometimes achieving 184 msecs. per input file. With this one change to the source code, the corresponding results were these;

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 234 | 234 |1.00 |
----------|-----|-----|-----|
Clang-3.2 | 188 | 187 |1.00 |
----------|-----|-----|------
GCC/Clang |1.24 |1.25 |

The points of note here are:

  1. Neither compiler now benefits at all from -O3 optimization.
  2. Clang beats GCC just as importantly at each level of optimization.
  3. GCC's performance is only marginally affected by the smart-pointer type change.
  4. Clang's -O2 performance is importantly affected by the smart-pointer type change.

Before and after the smart-pointer type change, Clang is able to build a substantially faster coan executable at -O3 optimisation, and it can build an equally faster executable at -O2 and -O3 when that pointer-type is the best one - std::shared_ptr<X> - for the job.

An obvious question that I am not competent to comment upon is why Clang should be able to find a 25% -O2 speed-up in my application when a heavily used smart-pointer-type is changed from unique to shared, while GCC is indifferent to the same change. Nor do I know whether I should cheer or boo the discovery that Clang's -O2 optimization harbours such huge sensitivity to the wisdom of my smart-pointer choices.

UPDATE: GCC 4.8.1 v clang 3.3

The corresponding results now are:

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.1 | 442 | 443 |1.00 |
----------|-----|-----|-----|
Clang-3.3 | 374 | 370 |1.01 |
----------|-----|-----|------
GCC/Clang |1.18 |1.20 |

The fact that all four executables now take a much greater average time than previously to process 1 file does not reflect on the latest compilers' performance. It is due to the fact that the later development branch of the test application has taken on lot of parsing sophistication in the meantime and pays for it in speed. Only the ratios are significant.

The points of note now are not arrestingly novel:

  • GCC is indifferent to -O3 optimization
  • clang benefits very marginally from -O3 optimization
  • clang beats GCC by a similarly important margin at each level of optimization.

Comparing these results with those for GCC 4.7.2 and clang 3.2, it stands out that GCC has clawed back about a quarter of clang's lead at each optimization level. But since the test application has been heavily developed in the meantime one cannot confidently attribute this to a catch-up in GCC's code-generation. (This time, I have noted the application snapshot from which the timings were obtained and can use it again.)

UPDATE: GCC 4.8.2 v clang 3.4

I finished the update for GCC 4.8.1 v Clang 3.3 saying that I would stick to the same coan snaphot for further updates. But I decided instead to test on that snapshot (rev. 301) and on the latest development snapshot I have that passes its test suite (rev. 619). This gives the results a bit of longitude, and I had another motive:

My original posting noted that I had devoted no effort to optimizing coan for speed. This was still the case as of rev. 301. However, after I had built the timing apparatus into the coan test harness, every time I ran the test suite the performance impact of the latest changes stared me in the face. I saw that it was often surprisingly big and that the trend was more steeply negative than I felt to be merited by gains in functionality.

By rev. 308 the average processing time per input file in the test suite had well more than doubled since the first posting here. At that point I made a U-turn on my 10 year policy of not bothering about performance. In the intensive spate of revisions up to 619 performance was always a consideration and a large number of them went purely to rewriting key load-bearers on fundamentally faster lines (though without using any non-standard compiler features to do so). It would be interesting to see each compiler's reaction to this U-turn,

Here is the now familiar timings matrix for the latest two compilers' builds of rev.301:

coan - rev.301 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 428 | 428 |1.00 |
----------|-----|-----|-----|
Clang-3.4 | 390 | 365 |1.07 |
----------|-----|-----|------
GCC/Clang | 1.1 | 1.17|

The story here is only marginally changed from GCC-4.8.1 and Clang-3.3. GCC's showing is a trifle better. Clang's is a trifle worse. Noise could well account for this. Clang still comes out ahead by -O2 and -O3 margins that wouldn't matter in most applications but would matter to quite a few.

And here is the matrix for rev. 619.

coan - rev.619 results

          | -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 210 | 208 |1.01 |
----------|-----|-----|-----|
Clang-3.4 | 252 | 250 |1.01 |
----------|-----|-----|------
GCC/Clang |0.83 | 0.83|

Taking the 301 and the 619 figures side by side, several points speak out.

  • I was aiming to write faster code, and both compilers emphatically vindicate my efforts. But:

  • GCC repays those efforts far more generously than Clang. At -O2 optimization Clang's 619 build is 46% faster than its 301 build: at -O3 Clang's improvement is 31%. Good, but at each optimization level GCC's 619 build is more than twice as fast as its 301.

  • GCC more than reverses Clang's former superiority. And at each optimization level GCC now beats Clang by 17%.

  • Clang's ability in the 301 build to get more leverage than GCC from -O3 optimization is gone in the 619 build. Neither compiler gains meaningfully from -O3.

I was sufficiently surprised by this reversal of fortunes that I suspected I might have accidentally made a sluggish build of clang 3.4 itself (since I built it from source). So I re-ran the 619 test with my distro's stock Clang 3.3. The results were practically the same as for 3.4.

So as regards reaction to the U-turn: On the numbers here, Clang has done much better than GCC at at wringing speed out of my C++ code when I was giving it no help. When I put my mind to helping, GCC did a much better job than Clang.

I don't elevate that observation into a principle, but I take the lesson that "Which compiler produces the better binaries?" is a question that, even if you specify the test suite to which the answer shall be relative, still is not a clear-cut matter of just timing the binaries.

Is your better binary the fastest binary, or is it the one that best compensates for cheaply crafted code? Or best compensates for expensively crafted code that prioritizes maintainability and reuse over speed? It depends on the nature and relative weights of your motives for producing the binary, and of the constraints under which you do so.

And in any case, if you deeply care about building "the best" binaries then you had better keep checking how successive iterations of compilers deliver on your idea of "the best" over successive iterations of your code.

What is the best way to test for an empty string in Go?

This would be more performant than trimming the whole string, since you only need to check for at least a single non-space character existing

// Strempty checks whether string contains only whitespace or not
func Strempty(s string) bool {
    if len(s) == 0 {
        return true
    }

    r := []rune(s)
    l := len(r)

    for l > 0 {
        l--
        if !unicode.IsSpace(r[l]) {
            return false
        }
    }

    return true
}

When do you use Git rebase instead of Git merge?

This answer is widely oriented around Git Flow. The tables have been generated with the nice ASCII Table Generator, and the history trees with this wonderful command (aliased as git lg):

git log --graph --abbrev-commit --decorate --date=format:'%Y-%m-%d %H:%M:%S' --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%ad%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)'

Tables are in reverse chronological order to be more consistent with the history trees. See also the difference between git merge and git merge --no-ff first (you usually want to use git merge --no-ff as it makes your history look closer to the reality):

git merge

Commands:

Time          Branch "develop"             Branch "features/foo"
------- ------------------------------ -------------------------------
15:04   git merge features/foo
15:03                                  git commit -m "Third commit"
15:02                                  git commit -m "Second commit"
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

* 142a74a - YYYY-MM-DD 15:03:00 (XX minutes ago) (HEAD -> develop, features/foo)
|           Third commit - Christophe
* 00d848c - YYYY-MM-DD 15:02:00 (XX minutes ago)
|           Second commit - Christophe
* 298e9c5 - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

git merge --no-ff

Commands:

Time           Branch "develop"              Branch "features/foo"
------- -------------------------------- -------------------------------
15:04   git merge --no-ff features/foo
15:03                                    git commit -m "Third commit"
15:02                                    git commit -m "Second commit"
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

*   1140d8c - YYYY-MM-DD 15:04:00 (XX minutes ago) (HEAD -> develop)
|\            Merge branch 'features/foo' - Christophe
| * 69f4a7a - YYYY-MM-DD 15:03:00 (XX minutes ago) (features/foo)
| |           Third commit - Christophe
| * 2973183 - YYYY-MM-DD 15:02:00 (XX minutes ago)
|/            Second commit - Christophe
* c173472 - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

git merge vs git rebase

First point: always merge features into develop, never rebase develop from features. This is a consequence of the Golden Rule of Rebasing:

The golden rule of git rebase is to never use it on public branches.

In other words:

Never rebase anything you've pushed somewhere.

I would personally add: unless it's a feature branch AND you and your team are aware of the consequences.

So the question of git merge vs git rebase applies almost only to the feature branches (in the following examples, --no-ff has always been used when merging). Note that since I'm not sure there's one better solution (a debate exists), I'll only provide how both commands behave. In my case, I prefer using git rebase as it produces a nicer history tree :)

Between feature branches

git merge

Commands:

Time           Branch "develop"              Branch "features/foo"           Branch "features/bar"
------- -------------------------------- ------------------------------- --------------------------------
15:10   git merge --no-ff features/bar
15:09   git merge --no-ff features/foo
15:08                                                                    git commit -m "Sixth commit"
15:07                                                                    git merge --no-ff features/foo
15:06                                                                    git commit -m "Fifth commit"
15:05                                                                    git commit -m "Fourth commit"
15:04                                    git commit -m "Third commit"
15:03                                    git commit -m "Second commit"
15:02   git checkout -b features/bar
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

*   c0a3b89 - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\            Merge branch 'features/bar' - Christophe
| * 37e933e - YYYY-MM-DD 15:08:00 (XX minutes ago) (features/bar)
| |           Sixth commit - Christophe
| *   eb5e657 - YYYY-MM-DD 15:07:00 (XX minutes ago)
| |\            Merge branch 'features/foo' into features/bar - Christophe
| * | 2e4086f - YYYY-MM-DD 15:06:00 (XX minutes ago)
| | |           Fifth commit - Christophe
| * | 31e3a60 - YYYY-MM-DD 15:05:00 (XX minutes ago)
| | |           Fourth commit - Christophe
* | |   98b439f - YYYY-MM-DD 15:09:00 (XX minutes ago)
|\ \ \            Merge branch 'features/foo' - Christophe
| |/ /
|/| /
| |/
| * 6579c9c - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| |           Third commit - Christophe
| * 3f41d96 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/            Second commit - Christophe
* 14edc68 - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

git rebase

Commands:

Time           Branch "develop"              Branch "features/foo"           Branch "features/bar"
------- -------------------------------- ------------------------------- -------------------------------
15:10   git merge --no-ff features/bar
15:09   git merge --no-ff features/foo
15:08                                                                    git commit -m "Sixth commit"
15:07                                                                    git rebase features/foo
15:06                                                                    git commit -m "Fifth commit"
15:05                                                                    git commit -m "Fourth commit"
15:04                                    git commit -m "Third commit"
15:03                                    git commit -m "Second commit"
15:02   git checkout -b features/bar
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

*   7a99663 - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\            Merge branch 'features/bar' - Christophe
| * 708347a - YYYY-MM-DD 15:08:00 (XX minutes ago) (features/bar)
| |           Sixth commit - Christophe
| * 949ae73 - YYYY-MM-DD 15:06:00 (XX minutes ago)
| |           Fifth commit - Christophe
| * 108b4c7 - YYYY-MM-DD 15:05:00 (XX minutes ago)
| |           Fourth commit - Christophe
* |   189de99 - YYYY-MM-DD 15:09:00 (XX minutes ago)
|\ \            Merge branch 'features/foo' - Christophe
| |/
| * 26835a0 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| |           Third commit - Christophe
| * a61dd08 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/            Second commit - Christophe
* ae6f5fc - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

From develop to a feature branch

git merge

Commands:

Time           Branch "develop"              Branch "features/foo"           Branch "features/bar"
------- -------------------------------- ------------------------------- -------------------------------
15:10   git merge --no-ff features/bar
15:09                                                                    git commit -m "Sixth commit"
15:08                                                                    git merge --no-ff develop
15:07   git merge --no-ff features/foo
15:06                                                                    git commit -m "Fifth commit"
15:05                                                                    git commit -m "Fourth commit"
15:04                                    git commit -m "Third commit"
15:03                                    git commit -m "Second commit"
15:02   git checkout -b features/bar
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

*   9e6311a - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\            Merge branch 'features/bar' - Christophe
| * 3ce9128 - YYYY-MM-DD 15:09:00 (XX minutes ago) (features/bar)
| |           Sixth commit - Christophe
| *   d0cd244 - YYYY-MM-DD 15:08:00 (XX minutes ago)
| |\            Merge branch 'develop' into features/bar - Christophe
| |/
|/|
* |   5bd5f70 - YYYY-MM-DD 15:07:00 (XX minutes ago)
|\ \            Merge branch 'features/foo' - Christophe
| * | 4ef3853 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| | |           Third commit - Christophe
| * | 3227253 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/ /            Second commit - Christophe
| * b5543a2 - YYYY-MM-DD 15:06:00 (XX minutes ago)
| |           Fifth commit - Christophe
| * 5e84b79 - YYYY-MM-DD 15:05:00 (XX minutes ago)
|/            Fourth commit - Christophe
* 2da6d8d - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

git rebase

Commands:

Time           Branch "develop"              Branch "features/foo"           Branch "features/bar"
------- -------------------------------- ------------------------------- -------------------------------
15:10   git merge --no-ff features/bar
15:09                                                                    git commit -m "Sixth commit"
15:08                                                                    git rebase develop
15:07   git merge --no-ff features/foo
15:06                                                                    git commit -m "Fifth commit"
15:05                                                                    git commit -m "Fourth commit"
15:04                                    git commit -m "Third commit"
15:03                                    git commit -m "Second commit"
15:02   git checkout -b features/bar
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

*   b0f6752 - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\            Merge branch 'features/bar' - Christophe
| * 621ad5b - YYYY-MM-DD 15:09:00 (XX minutes ago) (features/bar)
| |           Sixth commit - Christophe
| * 9cb1a16 - YYYY-MM-DD 15:06:00 (XX minutes ago)
| |           Fifth commit - Christophe
| * b8ddd19 - YYYY-MM-DD 15:05:00 (XX minutes ago)
|/            Fourth commit - Christophe
*   856433e - YYYY-MM-DD 15:07:00 (XX minutes ago)
|\            Merge branch 'features/foo' - Christophe
| * 694ac81 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| |           Third commit - Christophe
| * 5fd94d3 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/            Second commit - Christophe
* d01d589 - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

Side notes

git cherry-pick

When you just need one specific commit, git cherry-pick is a nice solution (the -x option appends a line that says "(cherry picked from commit...)" to the original commit message body, so it's usually a good idea to use it - git log <commit_sha1> to see it):

Commands:

Time           Branch "develop"              Branch "features/foo"                Branch "features/bar"
------- -------------------------------- ------------------------------- -----------------------------------------
15:10   git merge --no-ff features/bar
15:09   git merge --no-ff features/foo
15:08                                                                    git commit -m "Sixth commit"
15:07                                                                    git cherry-pick -x <second_commit_sha1>
15:06                                                                    git commit -m "Fifth commit"
15:05                                                                    git commit -m "Fourth commit"
15:04                                    git commit -m "Third commit"
15:03                                    git commit -m "Second commit"
15:02   git checkout -b features/bar
15:01   git checkout -b features/foo
15:00   git commit -m "First commit"

Result:

*   50839cd - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\            Merge branch 'features/bar' - Christophe
| * 0cda99f - YYYY-MM-DD 15:08:00 (XX minutes ago) (features/bar)
| |           Sixth commit - Christophe
| * f7d6c47 - YYYY-MM-DD 15:03:00 (XX minutes ago)
| |           Second commit - Christophe
| * dd7d05a - YYYY-MM-DD 15:06:00 (XX minutes ago)
| |           Fifth commit - Christophe
| * d0d759b - YYYY-MM-DD 15:05:00 (XX minutes ago)
| |           Fourth commit - Christophe
* |   1a397c5 - YYYY-MM-DD 15:09:00 (XX minutes ago)
|\ \            Merge branch 'features/foo' - Christophe
| |/
|/|
| * 0600a72 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| |           Third commit - Christophe
| * f4c127a - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/            Second commit - Christophe
* 0cf894c - YYYY-MM-DD 15:00:00 (XX minutes ago)
            First commit - Christophe

git pull --rebase

I am not sure I can explain it better than Derek Gourlay... Basically, use git pull --rebase instead of git pull :) What's missing in the article though, is that you can enable it by default:

git config --global pull.rebase true

git rerere

Again, nicely explained here. But put simply, if you enable it, you won't have to resolve the same conflict multiple times anymore.

Delete empty lines using sed

I am missing the awk solution:

awk 'NF' file

Which would return:

xxxxxx
yyyyyy
zzzzzz

How does this work? Since NF stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.

What is "Linting"?

lint is a tool that is used to mark the source code with some suspicious and non-structural (may cause bug). It is a static code analysis tool in C at the beginning.Now it became the generic term used to describe the software analysis tool that mark the suspicious code.

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

How to get index of object by its property in JavaScript?

If you're having issues with IE, you could use the map() function which is supported from 9.0 onward:

var index = Data.map(item => item.name).indexOf("Nick");

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

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

I ran into the same situation where commands such as git diff origin or git diff origin master produced the error reported in the question, namely Fatal: ambiguous argument...

To resolve the situation, I ran the command

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master

to set refs/remotes/origin/HEAD to point to the origin/master branch.

Before running this command, the output of git branch -a was:

* master
  remotes/origin/master

After running the command, the error no longer happened and the output of git branch -a was:

* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

(Other answers have already identified that the source of the error is HEAD not being set for origin. But I thought it helpful to provide a command which may be used to fix the error in question, although it may be obvious to some users.)


Additional information:

For anybody inclined to experiment and go back and forth between setting and unsetting refs/remotes/origin/HEAD, here are some examples.

To unset:
git remote set-head origin --delete

To set:
(additional ways, besides the way shown at the start of this answer)
git remote set-head origin master to set origin/head explicitly
OR
git remote set-head origin --auto to query the remote and automatically set origin/HEAD to the remote's current branch.

References:

  • This SO Answer
  • This SO Comment and its associated answer
  • git remote --help see set-head description
  • git symbolic-ref --help

How to access local files of the filesystem in the Android emulator?

You can use the adb command which comes in the tools dir of the SDK:

adb shell

It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:

adb pull /sdcard/the_file_you_want.txt

Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)

How to download Google Play Services in an Android emulator?

If your emulator x86 this method works your me.

Download and install http://opengapps.org/app/opengapps-app-v16.apk. And select nano pack

More info http://opengapps.org/app/

enter image description here

enter image description here

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

Xpath for href element

have you tried:

//a[@id='oldcontent']/u[text()='Re-Call']

Accessing Websites through a Different Port?

It depends.

The web server on the other end will be set to a certain port, usually 80 and will only accept requests on that specific port. Something along the chain will need to be talking to port 80 to the website.

If you control the website, then you can change the port, or get it to accept requests on multiple ports.

If the website is already talking on a different port, you can just use the colon syntax to reference another port (eg: http://server.com:1234 for port 1234).

If you want to use a different port on your client end, but you want to talk to port 80 at the web server end, you'll need to route traffic from port x to port 80. A common way to get this up and running is to use Port Fowarding. ssh can do this for you, see here for a Unix/technical overview or here if you're on Windows.

Hope that helps.

ios simulator: how to close an app

You can also do it with the keyboard shortcut shown under the simulator menu bar (Hardware-> Home).

The shortcut is ?+?+H, but you need to hit H twice in a row for it to simulate the double press that shows the apps.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Add servlet-api.jar file which is present in the lib folder under tomcat folder. You can do this using the following steps:

1.Select project properties
2.Select Java Build Path
3.Select Libraries
4.Select External Jars
5.Select servlet-api.jar
6. Apply & Ok.

The issue should be resolved after these steps.

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

What key shortcuts are to comment and uncomment code?

This is how I did it,

Menu ToolsOptions on the EnvironmentKeyboard window

One can alter the default shortcuts following the below steps

  • Select Edit.CommentSelection in the listbox
  • Click on "Remove" button
  • Select "Text Editor" option in the dropdown under "Use new shortcut in:"
  • Press your own shortcut in the textbox under "Press shortcut keys:" Example: Pressing Ctrl+E and then C will give you Ctrl+E, C
  • Click on "Assign" button
  • Repeat the same for Edit.UnCommentSelection (Ctrl+E, U)

Adding form action in html in laravel

{{ Form::open(array('action' => "WelcomeController@log_in")) }}
...
{{ Form::close() }}

MySQL - ERROR 1045 - Access denied

Try connecting without any password:

mysql -u root

I believe the initial default is no password for the root account (which should obviously be changed as soon as possible).

Triggering a checkbox value changed event in DataGridView

"EditingControlShowing" event doesn't fire on checkbox value change. Because display style of the checkbox cell doesn't not change.

The workaround i have used is as below. (I have used CellContentClick event)

    private void gGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (string.Compare(gGridView1.CurrentCell.OwningColumn.Name, "CheckBoxColumn") == 0)
        {
            bool checkBoxStatus = Convert.ToBoolean(gGridView1.CurrentCell.EditedFormattedValue);
            //checkBoxStatus gives you whether checkbox cell value of selected row for the
            //"CheckBoxColumn" column value is checked or not. 
            if(checkBoxStatus)
            {
                //write your code
            }
            else
            {
               //write your code
            }
        }
    }

The above has worked for me. Please let me know if need more help.

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

Select current element in jQuery

Fortunately, jQuery selectors allow you much more freedom:

$("div a").click( function(event)
{
   var clicked = $(this); // jQuery wrapper for clicked element
   // ... click-specific code goes here ...
});

...will attach the specified callback to each <a> contained in a <div>.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Alternatively, you can use Inner Queries to do so.

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!

How to log request and response body with Retrofit-Android?

call.request().toString();

Screenshot request which is being sent to server: enter image description here

How to count string occurrence in string?

Simple version without regex:

_x000D_
_x000D_
var temp = "This is a string.";_x000D_
_x000D_
var count = (temp.split('is').length - 1);_x000D_
_x000D_
alert(count);
_x000D_
_x000D_
_x000D_

JAXB: How to ignore namespace during unmarshalling XML document?

This is just a modification of lunicon's answer (https://stackoverflow.com/a/24387115/3519572) if you want to replace one namespace for another during parsing. And if you want to see what exactly is going on, just uncomment the output lines and set a breakpoint.

public class XMLReaderWithNamespaceCorrection extends StreamReaderDelegate {

    private final String wrongNamespace;
    private final String correctNamespace;

    public XMLReaderWithNamespaceCorrection(XMLStreamReader reader, String wrongNamespace, String correctNamespace) {
        super(reader);

        this.wrongNamespace = wrongNamespace;
        this.correctNamespace = correctNamespace;
    }

    @Override
    public String getAttributeNamespace(int arg0) {
//        System.out.println("--------------------------\n");
//        System.out.println("arg0: " + arg0);
//        System.out.println("getAttributeName: " + getAttributeName(arg0));
//        System.out.println("super.getAttributeNamespace: " + super.getAttributeNamespace(arg0));
//        System.out.println("getAttributeLocalName: " + getAttributeLocalName(arg0));
//        System.out.println("getAttributeType: " + getAttributeType(arg0));
//        System.out.println("getAttributeValue: " + getAttributeValue(arg0));
//        System.out.println("getAttributeValue(correctNamespace, LN):"
//                + getAttributeValue(correctNamespace, getAttributeLocalName(arg0)));
//        System.out.println("getAttributeValue(wrongNamespace, LN):"
//                + getAttributeValue(wrongNamespace, getAttributeLocalName(arg0)));

        String origNamespace = super.getAttributeNamespace(arg0);

        boolean replace = (((wrongNamespace == null) && (origNamespace == null))
                || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
        return replace ? correctNamespace : origNamespace;
    }

    @Override
    public String getNamespaceURI() {
//        System.out.println("getNamespaceCount(): " + getNamespaceCount());
//        for (int i = 0; i < getNamespaceCount(); i++) {
//            System.out.println(i + ": " + getNamespacePrefix(i));
//        }
//
//        System.out.println("super.getNamespaceURI: " + super.getNamespaceURI());

        String origNamespace = super.getNamespaceURI();

        boolean replace = (((wrongNamespace == null) && (origNamespace == null))
                || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
        return replace ? correctNamespace : origNamespace;
    }
}

usage:

InputStream is = new FileInputStream(xmlFile);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithNamespaceCorrection xr =
    new XMLReaderWithNamespaceCorrection(xsr, "http://wrong.namespace.uri", "http://correct.namespace.uri");
rootJaxbElem = (JAXBElement<SqgRootType>) um.unmarshal(xr);
handleSchemaError(rootJaxbElem, pmRes);

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

Remove the legend on a matplotlib figure

you have to add the following lines of code:

ax = gca()
ax.legend_ = None
draw()

gca() returns the current axes handle, and has that property legend_

Hide/Show components in react native

I would vouch for using the opacity-method if you do not want to remove the component from your page, e.g. hiding a WebView.

<WebView
   style={{opacity: 0}} // Hide component
   source={{uri: 'https://www.google.com/'}}
 />

This is useful if you need to submit a form to a 3rd party website.

Convert char array to string use C

You can use strcpy but remember to end the array with '\0'

char array[20]; char string[100];

array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);

Rubymine: How to make Git ignore .idea files created by Rubymine

Try git rm -r --cached .idea in your terminal. It disables the change tracking.

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

adding .css file to ejs

Your problem is not actually specific to ejs.

2 things to note here

  1. style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.

  2. In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image

it can be done by

app.use(express.static(__dirname + '/public'));

assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like

<link href="/css/style.css" rel="stylesheet" type="text/css">

Here i assume you have put the css file in css folder inside your public folder.

So folder structure would be

.
./app.js
./public
    /css
        /style.css

Load data from txt with pandas

You can use:

data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["a", "b", "c", "etc."]

Add sep=" " in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns is for naming your columns.

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

How to output oracle sql result into a file in windows?

Use the spool:

spool myoutputfile.txt
select * from users;
spool off;

Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.

If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":

tmp.sql:

select * from users;

Command:

sqlplus -s username/password@sid @tmp.sql > output.txt

Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.

How to control the width of select tag?

Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.

How to extract string following a pattern with grep, regex or perl

If the structure of your xml (or text in general) is fixed, the easiest way is using cut. For your specific case:

echo '<table name="content_analyzer" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
  <type="global" />
</table>' | grep name= | cut -f2 -d '"'

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

How do I check if a SQL Server text column is empty?

ISNULL(
case textcolum1
    WHEN '' THEN NULL
    ELSE textcolum1
END 
,textcolum2) textcolum1

Best way to encode Degree Celsius symbol into web page?

Add a metatag to your header

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

This expands the amount of characters you can use.

How to send a JSON object using html form data

you code is fine but never executed, cause of submit button [type="submit"] just replace it by type=button

<input value="Submit" type="button" onclick="submitform()">

inside your script; form is not declared.

let form = document.forms[0];
xhr.open(form.method, form.action, true);

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

Do I use <img>, <object>, or <embed> for SVG files?

Use srcset

Most current browsers today support the srcset attribute, which allows specifying different images to different users. For example, you can use it for 1x and 2x pixel density, and the browser will select the correct file.

In this case, if you specify an SVG in the srcset and the browser doesn't support it, it'll fallback on the src.

<img src="logo.png" srcset="logo.svg" alt="My logo">

This method has several benefits over other solutions:

  1. It's not relying on any weird hacks or scripts
  2. It's simple
  3. You can still include alt text
  4. Browsers that support srcset should know how to handle it so that it only downloads the file it needs.

URLEncoder not able to translate space character

If you want to encode URI path components, you can also use standard JDK functions, e.g.

public static String encodeURLPathComponent(String path) {
    try {
        return new URI(null, null, path, null).toASCIIString();
    } catch (URISyntaxException e) {
        // do some error handling
    }
    return "";
}

The URI class can also be used to encode different parts of or whole URIs.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I used

View.inflate(getContext(), R.layout.whatever, null)

The using of View.inflate prevents the warning of using null at getLayoutInflater().inflate().

Making a cURL call in C#

Don't forget to add System.Net.Http, specially if you receive this error:

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?) 1_default.aspx D:\Projetos\Testes\FacebookAPI\FB-CustomAudience\default.aspx.cs 56 Active

In this case you shoud:

  1. Add System.Net.Http from Nuget: Tools / NuGet Package Manager / Manager NuGet Packages for Solution;
  2. Search for System.Net.Http
  3. Add in the top of your page the follow code: using System.Net.Http;

Converting a pointer into an integer

I think the "meaning" of void* in this case is a generic handle. It is not a pointer to a value, it is the value itself. (This just happens to be how void* is used by C and C++ programmers.)

If it is holding an integer value, it had better be within integer range!

Here is easy rendering to integer:

int x = (char*)p - (char*)0;

It should only give a warning.

show/hide html table columns using css

if you're looking for a simple column hide you can use the :nth-child selector as well.

#tableid tr td:nth-child(3),
#tableid tr th:nth-child(3) {
    display: none;
}

I use this with the @media tag sometimes to condense wider tables when the screen is too narrow.

How can git be installed on CENTOS 5.5?

It looks like the repos for CentOS 5 are disappearing. Most of the ones mentioned in this question are no longer online, don't seem to have Git, or have a really old version of Git. Below is the script I use to build OpenSSL, IDN2, PCRE, cURL and Git from sources. Both the git:// and https:// protocols will be available for cloning.

Over time the names of the archives will need to be updates. For example, as of this writing, openssl-1.0.2k.tar.gz is the latest available in the 1.0.2 family.

Dale Anderson's answer using RHEL repos looks good at the moment, but its a fairly old version. Red Hat provides Git version 1.8, while the script below builds 2.12 from sources.


#!/usr/bin/env bash

# OpenSSL installs into lib64/, while cURL installs into lib/
INSTALL_ROOT=/usr/local
INSTALL_LIB32="$INSTALL_ROOT/lib"
INSTALL_LIB64="$INSTALL_ROOT/lib64"

OPENSSL_TAR=openssl-1.0.2k.tar.gz
OPENSSL_DIR=openssl-1.0.2k

ZLIB_TAR=zlib-1.2.11.tar.gz
ZLIB_DIR=zlib-1.2.11

UNISTR_TAR=libunistring-0.9.7.tar.gz
UNISTR_DIR=libunistring-0.9.7

IDN2_TAR=libidn2-0.16.tar.gz
IDN2_DIR=libidn2-0.16

PCRE_TAR=pcre2-10.23.tar.gz
PCRE_DIR=pcre2-10.23

CURL_TAR=curl-7.53.1.tar.gz
CURL_DIR=curl-7.53.1

GIT_TAR=v2.12.2.tar.gz
GIT_DIR=git-2.12.2

###############################################################################

# I don't like doing this, but...
read -s -p "Please enter password for sudo: " SUDO_PASSWWORD

###############################################################################

echo
echo "********** zLib **********"

wget "http://www.zlib.net/$ZLIB_TAR" -O "$ZLIB_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$ZLIB_DIR" &>/dev/null
tar -xzf "$ZLIB_TAR"
cd "$ZLIB_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** Unistring **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.gnu.org/gnu/libunistring/$UNISTR_TAR" --no-check-certificate -O "$UNISTR_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$UNISTR_DIR" &>/dev/null
tar -xzf "$UNISTR_TAR"
cd "$UNISTR_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** IDN **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://alpha.gnu.org/gnu/libidn/$IDN2_TAR" --no-check-certificate -O "$IDN2_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$IDN2_DIR" &>/dev/null
tar -xzf "$IDN2_TAR"
cd "$IDN2_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** OpenSSL **********"

wget "https://www.openssl.org/source/$OPENSSL_TAR" -O "$OPENSSL_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$OPENSSL_DIR" &>/dev/null
tar -xzf "$OPENSSL_TAR"
cd "$OPENSSL_DIR"

# OpenSSL and enable-ec_nistp_64_gcc_12 option
IS_X86_64=$(uname -m 2>&1 | egrep -i -c "(amd64|x86_64)")

CONFIG=./config
CONFIG_FLAGS=(no-ssl2 no-ssl3 no-comp shared "-Wl,-rpath,$INSTALL_LIB64" --prefix="$INSTALL_ROOT" --openssldir="$INSTALL_ROOT")
if [[ "$IS_X86_64" -eq "1" ]]; then
    CONFIG_FLAGS+=("enable-ec_nistp_64_gcc_128")
fi

"$CONFIG" "${CONFIG_FLAGS[@]}"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make depend
make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install_sw

cd ..

###############################################################################

echo
echo "********** PCRE **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.pcre.org/pub/pcre//$PCRE_TAR" --no-check-certificate -O "$PCRE_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$PCRE_DIR" &>/dev/null
tar -xzf "$PCRE_TAR"
cd "$PCRE_DIR"

make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
    LIBS="-lidn2 -lz -ldl -lpthread" ./configure --enable-shared --enable-pcre2-8 --enable-pcre2-16 --enable-pcre2-32 \
    --enable-unicode-properties --enable-pcregrep-libz --prefix="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make all -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** cURL **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://curl.haxx.se/download/$CURL_TAR" --no-check-certificate -O "$CURL_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$CURL_DIR" &>/dev/null
tar -xzf "$CURL_TAR"
cd "$CURL_DIR"

CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
    LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" \
    ./configure --enable-shared --with-ssl="$INSTALL_ROOT" --with-libidn2="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** Git **********"

wget "https://github.com/git/git/archive/$GIT_TAR" -O "$GIT_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$GIT_DIR" &>/dev/null
tar -xzf "$GIT_TAR"
cd "$GIT_DIR"

make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64,-rpath,$INSTALL_LIB32 -L$INSTALL_LIB64 -L$INSTALL_LIB32" \
    LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" ./configure --with-openssl --with-curl --with-libpcre --prefix="$INSTALL_ROOT"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make all -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

MAKE=make
MAKE_FLAGS=(install)
if [[ ! -z `which asciidoc 2>/dev/null | grep -v 'no asciidoc'` ]]; then
    if [[ ! -z `which xmlto 2>/dev/null | grep -v 'no xmlto'` ]]; then
        MAKE_FLAGS+=("install-doc" "install-html" "install-info")
    fi
fi

echo "$SUDO_PASSWWORD" | sudo -S "$MAKE" "${MAKE_FLAGS[@]}"

cd ..

###############################################################################

echo
echo "********** Cleanup **********"

rm -rf "$OPENSSL_TAR  $OPENSSL_DIR  $UNISTR_TAR  $UNISTR_DIR  $CURL_TAR  $CURL_DIR"
rm -rf "$PCRE_TAR $PCRE_DIR $ZLIB_TAR $ZLIB_DIR $IDN2_TAR $IDN2_DIR $GIT_TAR $GIT_DIR"

[[ "$0" = "$BASH_SOURCE" ]] && exit 0 || return 0

How to get the anchor from the URL using jQuery?

You can use the following "trick" to parse any valid URL. It takes advantage of the anchor element's special href-related property, hash.

With jQuery

function getHashFromUrl(url){
    return $("<a />").attr("href", url)[0].hash.replace(/^#/, "");
}
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

With plain JS

function getHashFromUrl(url){
    var a = document.createElement("a");
    a.href = url;
    return a.hash.replace(/^#/, "");
};
getHashFromUrl("www.example.com/task1/1.3.html#a_1"); // a_1

Enum String Name from Value

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

How to delete an item in a list if it exists?

Eek, don't do anything that complicated : )

Just filter() your tags. bool() returns False for empty strings, so instead of

new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)

you should write

new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))

or better yet, put this logic inside striplist() so that it doesn't return empty strings in the first place.

while-else-loop

I don't see why there is a encapsulation of a while...

Use

//Use the appropriate start and end...
for(int rowIndex = 0, e = 65536; i < e; ++i){        
    if(rowIndex >= dataColLinker.size()) {
         dataColLinker.add(value);
     } else {
        dataColLinker.set(rowIndex, value);
     }    
}

How to override the path of PHP to use the MAMP path?

I found that on Mavericks 10.8 there wasn't a .bash_profile and my paths were located in /etc/paths

In order to have the new path (whether this is a mamp or brew install of php) take effect it needs to be above the default /usr/bin/php in this paths file. eg.

/Applications/MAMP/bin/php/php5.3.6/bin
/usr/bin 

AFter the change, open a new terminal window and run 'which php' that should now point to your updated path

Sorted collection in Java

The most efficient way to implement a sorted list like you want would be to implement an indexable skiplist as in here: Wikipedia: Indexable skiplist. It would allow to have inserts/removals in O(log(n)) and would allow to have indexed access at the same time. And it would also allow duplicates.

Skiplist is a pretty interesting and, I would say, underrated data structure. Unfortunately there is no indexed skiplist implementation in Java base library, but you can use one of open source implementations or implement it yourself. There are regular Skiplist implementations like ConcurrentSkipListSet and ConcurrentSkipListMap

How to make div occupy remaining height?

<div>
  <div id="header">header</div>
  <div id="content">content</div>
  <div id="footer">footer</div>
</div>

#header {
  height: 200px;
}

#content {
  height: 100%;
  margin-bottom: -200px;
  padding-bottom: 200px;
  margin-top: -200px;
  padding-top: 200px;
}

#footer {
  height: 200px;
}

Launching Spring application Address already in use

This error basically happens when the specific port is not free. So there are two solutions, you can free that port by killing or closing the service which is using it or you can run your application (tomcat) on a different port.

Solution 1: Free the port

On a Linux machine you can find the process-id of port's consumer and then kill it. Use the following command (it is assume that the default port is 8080)

netstat -pnltu | grep -i "8080"

The output of the above-mentioned command would be something like:

tcp6   0  0 :::8080    :::*      LISTEN      20674/java 

Then you can easily kill the process with its processid:

kill 20674

On a windows machine to find a processid use netstat -ano -p tcp |find "8080". To kill the process use taskkill /F /PID 1234 (instead of 1234 enter the founded processid).

Solution 2: Change the default port

In the development process developers use the port 8080 that you can change it easily. You need to specify your desired port number in the application.properties file of your project (/src/main/resources/application.properties) by using the following specification:

server.port=8081

You can also set an alternative port number while executing the .jar file

- java -jar spring-boot-application.jar --server.port=8081

Please notice that sometimes (not necessarily) you have to change other ports too like:

management.port=
tomcat.jvmroute=
tomcat.ajp.port=
tomcat.ajp.redirectPort=
etc...

Meaning of = delete after function declaration

= delete is a feature introduce in C++11. As per =delete it will not allowed to call that function.

In detail.

Suppose in a class.

Class ABC{
 Int d;
 Public:
  ABC& operator= (const ABC& obj) =delete
  {

  }
};

While calling this function for obj assignment it will not allowed. Means assignment operator is going to restrict to copy from one object to another.

how to log in to mysql and query the database from linux terminal

To stop or start mysql on most linux systems the following should work:

/etc/init.d/mysqld stop

/etc/init.d/mysqld start

The other answers look good for accessing the mysql client from the command line.

Good luck!

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Matrix multiplication using arrays

The method mults is a procedure(Pascal) or subroutine(Fortran)

The method multMatrix is a function(Pascal,Fortran)

import java.util.*;

public class MatmultE
{
private static Scanner sc = new Scanner(System.in);
  public static void main(String [] args)
  {
    double[][] A={{4.00,3.00},{2.00,1.00}}; 
    double[][] B={{-0.500,1.500},{1.000,-2.0000}};
    double[][] C=multMatrix(A,B);
    printMatrix(A);
    printMatrix(B);    
    printMatrix(C);

    double a[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
    double b[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
    double[][] c=multMatrix(a,b);
    printMatrix(a);
    printMatrix(b);    
    printMatrix(c);

    double[][] a1 = readMatrix();
    double[][] b1 = readMatrix();
    double[][] c1 = new double[a1.length][b1[0].length];
    mults(a1,b1,c1,a1.length,a1[0].length,b1.length,b1[0].length);
    printMatrix(c1);
    printMatrixE(c1);
  }

   public static double[][] readMatrix() {
       int rows = sc.nextInt();
       int cols = sc.nextInt();
       double[][] result = new double[rows][cols];
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
              result[i][j] = sc.nextDouble();
           }
       }
       return result;
   }


  public static void printMatrix(double[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%8.3f " , mat[i][j]);
           }
           System.out.println();
       }
   System.out.println();
  }

  public static void printMatrixE(double[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%9.2e " , mat[i][j]);
           }
           System.out.println();
       }
   System.out.println();
  }


   public static double[][] multMatrix(double a[][], double b[][]){//a[m][n], b[n][p]
   if(a.length == 0) return new double[0][0];
   if(a[0].length != b.length) return null; //invalid dims

   int n = a[0].length;
   int m = a.length;
   int p = b[0].length;

   double ans[][] = new double[m][p];

   for(int i = 0;i < m;i++){
      for(int j = 0;j < p;j++){
         ans[i][j]=0;
         for(int k = 0;k < n;k++){
            ans[i][j] += a[i][k] * b[k][j];
         }
      }
   }
   return ans;
   }

   public static void mults(double a[][], double b[][], double c[][], int r1, 
                        int c1, int r2, int c2){
      for(int i = 0;i < r1;i++){
         for(int j = 0;j < c2;j++){
            c[i][j]=0;
            for(int k = 0;k < c1;k++){
               c[i][j] += a[i][k] * b[k][j];
            }
         }
      }
   }
}

where as input matrix you can enter

inE.txt

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.0 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0

in unix like cmmd line execute the command:

$ java MatmultE < inE.txt > outE.txt

and you get the output

outC.txt

Matrix[2][2]
   4.000    3.000 
   2.000    1.000 

Matrix[2][2]
  -0.500    1.500 
   1.000   -2.000 

Matrix[2][2]
   1.000    0.000 
   0.000    1.000 

Matrix[3][4]
   1.000    2.000   -2.000    0.000 
  -3.000    4.000    7.000    2.000 
   6.000    0.000    3.000    1.000 

Matrix[4][2]
  -1.000    3.000 
   0.000    9.000 
   1.000  -11.000 
   4.000   -5.000 

Matrix[3][2]
  -3.000   43.000 
  18.000  -60.000 
   1.000  -20.000 

Matrix[4][3]
  -7.000   15.000    3.000 
 -36.000   70.000   20.000 
-105.000  189.000   57.000 
-256.000  420.000   96.000 

Matrix[4][3]
-7.00e+00  1.50e+01  3.00e+00 
-3.60e+01  7.00e+01  2.00e+01 
-1.05e+02  1.89e+02  5.70e+01 
-2.56e+02  4.20e+02  9.60e+01 

python pip: force install ignoring dependencies

When I were trying install librosa package with pip (pip install librosa), this error were appeared:

ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

I tried to remove llvmlite, but pip uninstall could not remove it. So, I used capability of ignore of pip by this code:

pip install librosa --ignore-installed llvmlite

Indeed, you can use this rule for ignoring a package you don't want to consider:

pip install {package you want to install} --ignore-installed {installed package you don't want to consider}

c# dictionary How to add multiple values for single key?

Though nearly the same as most of the other responses, I think this is the most efficient and concise way to implement it. Using TryGetValue is faster than using ContainsKey and reindexing into the dictionary as some other solutions have shown.

void Add(string key, string val)
{
    List<string> list;

    if (!dictionary.TryGetValue(someKey, out list))
    {
       values = new List<string>();
       dictionary.Add(key, list);
    }

    list.Add(val);
}

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Better naming in Tuple classes than "Item1", "Item2"

(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.
From Docs https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples

After installing SQL Server 2014 Express can't find local db

I downloaded a different installer "SQL Server 2014 Express with Advanced Services" and found Instance Features in it. Thanks for Alberto Solano's answer, it was really helpful.

My first installer was "SQL Server 2014 Express". It installed only SQL Management Studio and tools without Instance features. After installation "SQL Server 2014 Express with Advanced Services" my LocalDB is now alive!!!

ojdbc14.jar vs. ojdbc6.jar

I have same problem!

Found following in oracle site link text

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

How to use multiprocessing pool.map with multiple arguments?

Another way is to pass a list of lists to a one-argument routine:

import os
from multiprocessing import Pool

def task(args):
    print "PID =", os.getpid(), ", arg1 =", args[0], ", arg2 =", args[1]

pool = Pool()

pool.map(task, [
        [1,2],
        [3,4],
        [5,6],
        [7,8]
    ])

One can than construct a list lists of arguments with one's favorite method.

Logging levels - Logback - rule-of-thumb to assign log levels

My approach, i think coming more from an development than an operations point of view, is:

  • Error means that the execution of some task could not be completed; an email couldn't be sent, a page couldn't be rendered, some data couldn't be stored to a database, something like that. Something has definitively gone wrong.
  • Warning means that something unexpected happened, but that execution can continue, perhaps in a degraded mode; a configuration file was missing but defaults were used, a price was calculated as negative, so it was clamped to zero, etc. Something is not right, but it hasn't gone properly wrong yet - warnings are often a sign that there will be an error very soon.
  • Info means that something normal but significant happened; the system started, the system stopped, the daily inventory update job ran, etc. There shouldn't be a continual torrent of these, otherwise there's just too much to read.
  • Debug means that something normal and insignificant happened; a new user came to the site, a page was rendered, an order was taken, a price was updated. This is the stuff excluded from info because there would be too much of it.
  • Trace is something i have never actually used.

Change Row background color based on cell value DataTable

I Used rowCallBack datatable property it is working fine. PFB :-

"rowCallback": function (row, data, index) {

                        if ((data[colmindx] == 'colm_value')) { 
                            $(row).addClass('OwnClassName');
                        }
                        else if ((data[colmindx] == 'colm_value')) {
                                $(row).addClass('OwnClassStyle');
                            }
                    }

What is href="#" and why is it used?

The href attribute defines the URL of the resource of a link. If the anchor tag does not have href tag then it will not become hyperlink. The href attribute have the following values:

1. Absolute path: move to another site like href="http://www.google.com"
2. Relative path: move to another page within the site like herf ="defaultpage.aspx"
3. Move to an element with a specified id within the page like href="#bottom"
4. href="javascript:void(0)", it does not move anywhere.
5. href="#" , it does not move anywhere but scroll on the top of the current page.
6. href= "" , it will load the current page but some browsers causes forbidden errors.

Note: When we do not need to specified any url inside a anchor tag then use 
<a href="javascript:void(0)">Test1</a>

How can I close a login form and show the main form without my application closing?

public void ShowMain()
  {
       if(auth()) // a method that returns true when the user exists.
       {        
         this.Hide();
         var main = new Main();
         main.Show();
       }
      else
       {
              MessageBox.Show("Invalid login details.");
        }         
   }

OpenJDK availability for Windows OS

You can find the thoroughly tested OpenJDK releases provided by Oracle at http://jdk.java.net .

For example, ready to use builds of OpenJDK 10.0.2 from Oracle for 64-bit Linux, MacOS and Windows can be found at http://jdk.java.net/10/ .

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

Change the image source on rollover using jQuery

A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.

HTML

<img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />

JavaScript

function swap(newImg){
  this.src = newImg;
}

Depending on your setup, maybe something like this would work better (and requires less HTML modification).

HTML

<img src="img1.jpg" id="ref1" />
<img src="img3.jpg" id="ref2" />
<img src="img5.jpg" id="ref3" />

JavaScript / jQuery

// Declare Arrays
  imgList = new Array();
  imgList["ref1"] = new Array();
  imgList["ref2"] = new Array();
  imgList["ref3"] = new Array();

//Set values for each mouse state
  imgList["ref1"]["out"] = "img1.jpg";
  imgList["ref1"]["over"] = "img2.jpg";
  imgList["ref2"]["out"] = "img3.jpg";
  imgList["ref2"]["over"] = "img4.jpg";
  imgList["ref3"]["out"] = "img5.jpg";
  imgList["ref3"]["over"] = "img6.jpg";

//Add the swapping functions
  $("img").mouseover(function(){
    $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
  }

  $("img").mouseout(function(){
    $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
  }

Git: How to commit a manually deleted file?

The answer's here, I think.

It's better if you do git rm <fileName>, though.

Unused arguments in R

The R.utils package has a function called doCall which is like do.call, but it does not return an error if unused arguments are passed.

multiply <- function(a, b) a * b

# these will fail
multiply(a = 20, b = 30, c = 10)
# Error in multiply(a = 20, b = 30, c = 10) : unused argument (c = 10)
do.call(multiply, list(a = 20, b = 30, c = 10))
# Error in (function (a, b)  : unused argument (c = 10)

# R.utils::doCall will work
R.utils::doCall(multiply, args = list(a = 20, b = 30, c = 10))
# [1] 600
# it also does not require the arguments to be passed as a list
R.utils::doCall(multiply, a = 20, b = 30, c = 10)
# [1] 600

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

remove attribute display:none; so the item will be visible

$('#lol').get(0).style.display=''

or..

$('#lol').css('display', '')

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

Nginx no-www to www and www to no-www

Actually you don't even need a rewrite.

server {
    #listen 80 is default
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    #listen 80 is default
    server_name example.com;
    ## here goes the rest of your conf...
}

As my answer is getting more and more up votes but the above as well. You should never use a rewrite in this context. Why? Because nginx has to process and start a search. If you use return (which should be available in any nginx version) it directly stops execution. This is preferred in any context.

Redirect both, non-SSL and SSL to their non-www counterpart:

server {
    listen               80;
    listen               443 ssl;
    server_name          www.example.com;
    ssl_certificate      path/to/cert;
    ssl_certificate_key  path/to/key;

    return 301 $scheme://example.com$request_uri;
}

server {
    listen               80;
    listen               443 ssl;
    server_name          example.com;
    ssl_certificate      path/to/cert;
    ssl_certificate_key  path/to/key;

    # rest goes here...
}

The $scheme variable will only contain http if your server is only listening on port 80 (default) and the listen option does not contain the ssl keyword. Not using the variable will not gain you any performance.

Note that you need even more server blocks if you use HSTS, because the HSTS headers should not be sent over non-encrypted connections. Hence, you need unencrypted server blocks with redirects and encrypted server blocks with redirects and HSTS headers.

Redirect everything to SSL (personal config on UNIX with IPv4, IPv6, SPDY, ...):

#
# Redirect all www to non-www
#
server {
    server_name          www.example.com;
    ssl_certificate      ssl/example.com/crt;
    ssl_certificate_key  ssl/example.com/key;
    listen               *:80;
    listen               *:443 ssl spdy;
    listen               [::]:80 ipv6only=on;
    listen               [::]:443 ssl spdy ipv6only=on;

    return 301 https://example.com$request_uri;
}

#
# Redirect all non-encrypted to encrypted
#
server {
    server_name          example.com;
    listen               *:80;
    listen               [::]:80;

    return 301 https://example.com$request_uri;
}

#
# There we go!
#
server {
    server_name          example.com;
    ssl_certificate      ssl/example.com/crt;
    ssl_certificate_key  ssl/example.com/key;
    listen               *:443 ssl spdy;
    listen               [::]:443 ssl spdy;

    # rest goes here...
}

I guess you can imagine other compounds with this pattern now by yourself.

More of my configs? Go here and here.

How to play a sound using Swift?

First import these libraries

import AVFoundation

import AudioToolbox    

set delegate like this

   AVAudioPlayerDelegate

write this pretty code on button action or something action:

guard let url = Bundle.main.url(forResource: "ring", withExtension: "mp3") else { return }
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
        guard let player = player else { return }

        player.play()
    }catch let error{
        print(error.localizedDescription)
    }

100% working in my project and tested

Remove a string from the beginning of a string

function remove_prefix($text, $prefix) {
    if(0 === strpos($text, $prefix))
        $text = substr($text, strlen($prefix)).'';
    return $text;
}

Is it possible to pull just one file in Git?

@Mawardy's answer worked for me, but my changes were on the remote so I had to specify the origin

git checkout origin/master -- {filename}

Set HTTP header for one request

Try this, perhaps it works ;)

.factory('authInterceptor', function($location, $q, $window) {


return {
    request: function(config) {
      config.headers = config.headers || {};

      config.headers.Authorization = 'xxxx-xxxx';

      return config;
    }
  };
})

.config(function($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
})

And make sure your back end works too, try this. I'm using RESTful CodeIgniter.

class App extends REST_Controller {
    var $authorization = null;

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
            die();
        }

        if(!$this->input->get_request_header('Authorization')){
            $this->response(null, 400);    
        }

        $this->authorization = $this->input->get_request_header('Authorization');
    }

}

Maven – Always download sources and javadocs

Just consolidating and prepared the single command to address source and docs download...

mvn dependency:sources dependency:resolve -Dclassifier=javadoc

Abstraction vs Encapsulation in Java

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

Example where NO information hiding has been applied (Bad Practice):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

Example where field encapsulation has been applied:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

Example of immutable / constructor-only initialization of a field:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re : Abstraction vs Abstract Class

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

Re : Encapsulation vs Information Hiding

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

Quoting Wikipedia:

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

For example, in the statement

I've encapsulated the data access code into its own class

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.


[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

Converting a JToken (or string) to a given Type

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

--EDIT--

Uzair, Here is a complete example just to show you they work

string json = @"{
        ""id"" : 77239923,
        ""username"" : ""UzEE"",
        ""email"" : ""[email protected]"",
        ""name"" : ""Uzair Sajid"",
        ""twitter_screen_name"" : ""UzEE"",
        ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
        ""timezone"" : 5.5,
        ""access_token"" : {
            ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
            ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
            ""expires"" : 57723
        },
        ""friends"" : [{
            ""id"" : 2347484,
            ""name"" : ""Bruce Wayne""
        },
        {
            ""id"" : 996236,
            ""name"" : ""Clark Kent""
        }]
    }";

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

Make child visible outside an overflow:hidden parent

You can use the clearfix to do "layout preserving" the same way overflow: hidden does.

.clearfix:before,
.clearfix:after {
    content: ".";    
    display: block;    
    height: 0;    
    overflow: hidden; 
}
.clearfix:after { clear: both; }
.clearfix { zoom: 1; } /* IE < 8 */

add class="clearfix" class to the parent, and remove overflow: hidden;

How to kill/stop a long SQL query immediately?

I Have Been suffering from same thing since long time. It specially happens when you're connected to remote server(Which might be slow), or you have poor network connection. I doubt if Microsoft knows what the right answer is.

But since I've tried to find the solution. Only 1 layman approach worked

  • Click the close button over the tab of query which you are being suffered of. After a while (If Microsoft is not harsh on you !!!) you might get a window asking this

"The query is currently executing. Do you want to cancel the query?"

  • Click on "Yes"

  • After a while it will ask to whether you want to save this query or not?

  • Click on "Cancel"

And post that, may be you're studio is stable again to execute your query.

What it does in background is disconnecting your query window with the connection. So for running the query again, it will take time for connecting the remote server again. But trust me this trade-off is far better than the suffering of seeing that timer which runs for eternity.

PS: This works for me, Kudos if works for you too. !!!

Jersey client: How to add a list as query parameter

If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {
        super();
    }

    @GET
    @Path("/withlist")
    @Produces(MediaType.TEXT_PLAIN)
    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();
    }
}

Your client would send a request corresponding to:

GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye

Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'

Java: get all variable names in a class

As mentioned by few users, below code can help find all the fields in a given class.

TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
    String name=method.getName();
    if(name.startsWith("get"))
    {
        System.out.println(name.substring(3));
    }else if(name.startsWith("is"))
    {
        System.out.println(name.substring(2));
    }
}

However a more interesting approach is below:

With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)

TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();

Map<String,Object> props = m.convertValue(testObject, Map.class);

for(Map.Entry<String, Object> entry : props.entrySet()){
    if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
}

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

Printing Even and Odd using two Threads in Java

import java.util.concurrent.Semaphore;


public class PrintOddAndEven {

private static class OddThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;
    private int value = 1;

    public  OddThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire odd semaphore
                semaphore.acquire();
                System.out.println(" Odd Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


private static class EvenThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;

    private int value = 2;

    public  EvenThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire even semaphore
                semaphore.acquire();
                System.out.println(" Even Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


public static void main(String[] args) {
    //Initialize oddSemaphore with permit 1
    Semaphore oddSemaphore = new Semaphore(1);
    //Initialize evenSempahore with permit 0
    Semaphore evenSempahore = new Semaphore(0);
    OddThread oddThread = new OddThread(oddSemaphore, evenSempahore);
    EvenThread evenThread = new EvenThread(evenSempahore, oddSemaphore);
    oddThread.start();
    evenThread.start();
    }
}

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

You're missing a reference to System.Linq.

Add

using System.Linq

to get access to the ToList() function on the current code file.


To give a little bit of information over why this is necessary, Enumerable.ToList<TSource> is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq namespace.

Could not resolve '...' from state ''

As answered by Magus :

the full path must me specified

Abstract states can be used to add a prefix to all child state urls. But note that abstract still needs a ui-view for its children to populate. To do so you can simply add it inline.

.state('app', {
   url: "/app",
   abstract: true,
   template: '<ui-view/>'
})

For more information see documentation : https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views

How to compile the finished C# project and then run outside Visual Studio?

On your project folder, open up the bin\Debug subfolder and you'll see the compiled result.

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Path of assets in CSS files in Symfony 2

The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:

  • Reference the CSS files in the web folder (after: console assets:install --symlink web)

    {% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
    
  • Use the cssembed filter to embed images in the CSS like this.

    {% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
    

How do I convert a float to an int in Objective C?

what's wrong with:

int myInt = myFloat;

bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)

Hibernate SessionFactory vs. JPA EntityManagerFactory

SessionFactory vs. EntityManagerFactory

As I explained in the Hibernate User Guide, the Hibernate SessionFactory extends the JPA EntityManagerFactory, as illustrated by the following diagram:

JPA and Hibernate relationship

So, the SessionFactory is also a JPA EntityManagerFactory.

Both the SessionFactory and the EntityManagerFactory contain the entity mapping metadata and allow you to create a Hibernate Session or a EntityManager.

Session vs. EntityManager

Just like the SessionFactory and EntityManagerFactory, the Hibernate Session extends the JPA EntityManager. So, all methods defined by the EntityManager are available in the Hibernate Session.

The Session and the `EntityManager translate entity state transitions into SQL statements, like SELECT, INSERT, UPDATE, and DELETE.

Hibernate vs. JPA bootstrap

When bootstrapping a JPA or Hibernate application, you have two choices:

  1. You can bootstrap via the Hibernate native mechanism, and create a SessionFactory via the BootstrapServiceRegistryBuilder. If you're using Spring, the Hibernate bootstrap is done via the LocalSessionFactoryBean, as illustrated by this GitHub example.
  2. Or, you can create a JPA EntityManagerFactory via the Persistence class or the EntityManagerFactoryBuilder. If you're using Spring, the JPA bootstrap is done via the LocalContainerEntityManagerFactoryBean, as illustrated by this GitHub example.

Bootstrapping via JPA is to be preferred. That's because the JPA FlushModeType.AUTO is a much better choice than the legacy FlushMode.AUTO, which breaks read-your-writes consistency for native SQL queries.

Unwrapping JPA to Hibernate

Also, if you bootstrap via JPA, and you have injected the EntityManagerFactory via the @PersistenceUnit annotation:

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

You can easily get access to the underlying Sessionfactory using the unwrap method:

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

The same can be done with the JPA EntityManager. If you inject the EntityManager via the @PersistenceContext annotation:

@PersistenceContext
private EntityManager entityManager;

You can easily get access to the underlying Session using the unwrap method:

Session session = entityManager.unwrap(Session.class);

Conclusion

So, you should bootstrap via JPA, use the EntityManagerFactory and EntityManager, and only unwrap those to their associated Hibernate interfaces when you want to get access to some Hibernate-specific methods that are not available in JPA, like fetching the entity via its natural identifier.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

If table exists drop table then create it, if it does not exist just create it

Well... Huh. For years nobody mentioned one subtle thing.

Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... ); seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.

The better way is to create brand new table and swap it with an old one (table contents are lost):

CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
  • You should check the result of CREATE ... and do not continue in case of error, because failure means that other thread didn't finish the same script: either because it crashed in the middle or just didn't finish yet -- it's a good idea to inspect things by yourself.
  • Then, you should check the result of first RENAME ... and do not continue in case of success: whole operation is successfully completed; even more, running next RENAME ... can (and will) be unsafe if another thread has already started same sequence (it's better to cover this case than not to cover, see locking note below).
  • Second RENAME ... atomically replaces table definition, refer to MySQL manual for details.
  • At last, DROP ... just cleans up the old table, obviously.

Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade'); allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.

If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ... statement, which is not always possible automatically, e.g. when columns are renamed.

Side note 1: You can deal with views using the same approach, in this case CREATE/DROP TABLE merely transforms to CREATE/DROP VIEW while RENAME TABLE remains unchanged. In fact you can even turn table into view and vice versa.

CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;

Side note 2: MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW, which already cares about subject problem and it's fine points.

How to run function of parent window when child window closes?

I know this post is old, but I found that this really works well:

window.onunload = function() {
    window.opener.location.href = window.opener.location.href;
};

The window.onunload part was the hint I found googling this page. Thanks, @jerjer!

How do you get a directory listing in C?

You can find the sample code on the wikibooks link

/**************************************************************
 * A simpler and shorter implementation of ls(1)
 * ls(1) is very similar to the DIR command on DOS and Windows.
 **************************************************************/
#include <stdio.h>
#include <dirent.h>

int listdir(const char *path) 
{
  struct dirent *entry;
  DIR *dp;

  dp = opendir(path);
  if (dp == NULL) 
  {
    perror("opendir");
    return -1;
  }

  while((entry = readdir(dp)))
    puts(entry->d_name);

  closedir(dp);
  return 0;
}

int main(int argc, char **argv) {
  int counter = 1;

  if (argc == 1)
    listdir(".");

  while (++counter <= argc) {
    printf("\nListing %s...\n", argv[counter-1]);
    listdir(argv[counter-1]);
  }

  return 0;
}

Finding an element in an array in Java

With Java 8, you can do this:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

Link a .css on another folder

check this quick reminder of file path

Here is all you need to know about relative file paths:

  • Starting with "/" returns to the root directory and starts there
  • Starting with "../" moves one directory backwards and starts there
  • Starting with "../../" moves two directories backwards and starts there (and so on...)
  • To move forward, just start with the first subdirectory and keep moving forward

Get current category ID of the active page

Alternative -

 $catID = the_category_ID($echo=false);

EDIT: Above function is deprecated please use get_the_category()

Javascript - Get Image height

Try this:

var curHeight;
var curWidth;

function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
curHeight = newImg.height;
curWidth = newImg.width;

}

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.

How to dismiss a Twitter Bootstrap popover by clicking outside?

jQuery("#menu").click(function(){ return false; });
jQuery(document).one("click", function() { jQuery("#menu").fadeOut(); });

Are 2 dimensional Lists possible in c#?

I used:

List<List<String>> List1 = new List<List<String>>
var List<int> = new List<int>();
List.add("Test");
List.add("Test2");
List1.add(List);
var List<int> = new List<int>();
List.add("Test3");
List1.add(List);

that equals:

List1
(
[0] => List2 // List1[0][x]
    (
        [0] => Test  // List[0][0] etc.
        [1] => Test2

    )
[1] => List2
    (
        [0] => Test3

How do you set the max number of characters for an EditText in Android?

Kotlin way

editText.filters = arrayOf(InputFilter.LengthFilter(maxLength))

How to create dispatch queue in Swift 3

Compiled in XCode 8, Swift 3 https://github.com/rpthomas/Jedisware

 @IBAction func tap(_ sender: AnyObject) {

    let thisEmail = "emailaddress.com"
    let thisPassword = "myPassword" 

    DispatchQueue.global(qos: .background).async {

        // Validate user input

        let result = self.validate(thisEmail, password: thisPassword)

        // Go back to the main thread to update the UI
        DispatchQueue.main.async {
            if !result
            {
                self.displayFailureAlert()
            }

        }
    }

}

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

Confirm deletion in modal / dialog using Twitter Bootstrap?

I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:

    bootbox.confirm("Are you sure to want to delete , function(result) {

    //here result will be true
    // delete process code goes here

    });

Offical bootboxjs site

How to avoid "Permission denied" when using pip with virtualenv

If you created virtual environment using root then use this command

sudo su

it will give you the root access and then activate your virtual environment using this

source /root/.env/ENV_NAME/bin/activate

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

Since people will be coming from Google, make sure you're in the right database.

Running SQL in the 'master' database will often return this error.

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Sometimes, this issue is resolved simply by running flutter pub get once again...

packages get to make sure that all packages are considered...

as when moving the project from one computer to another, this may happen, that the packages are not taken into consideration, so flutter pub get and there you go !!!

Pass mouse events through absolutely-positioned element

There is a javascript version available which manually redirects events from one div to another.

I cleaned it up and made it into a jQuery plugin.

Here's the Github repository: https://github.com/BaronVonSmeaton/jquery.forwardevents

Unfortunately, the purpose I was using it for - overlaying a mask over Google Maps did not capture click and drag events, and the mouse cursor does not change which degrades the user experience enough that I just decided to hide the mask under IE and Opera - the two browsers which dont support pointer events.

Where's my invalid character (ORA-00911)

Of the top of my head, can you try to use the 'q' operator for the string literal

something like

insert all
  into domo_queries values (q'[select 
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;

Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.

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

TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;

Or this can be done using a CssClass (recommended):

.highlight
{
  color:red;
  font-weight:bold;
}

TextBox1.CssClass = "highlight";

Or the styles can be added inline:

TextBox1.Attributes["style"] = "color:red; font-weight:bold;";

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

DataTrigger where value is NOT null?

You can use an IValueConverter for this:

<TextBlock>
    <TextBlock.Resources>
        <conv:IsNullConverter x:Key="isNullConverter"/>
    </TextBlock.Resources>
    <TextBlock.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding SomeField, Converter={StaticResource isNullConverter}}" Value="False">
                    <Setter Property="TextBlock.Text" Value="It's NOT NULL Baby!"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Where IsNullConverter is defined elsewhere (and conv is set to reference its namespace):

public class IsNullConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (value == null);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new InvalidOperationException("IsNullConverter can only be used OneWay.");
    }
}

A more general solution would be to implement an IValueConverter that checks for equality with the ConverterParameter, so you can check against anything, and not just null.

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers

Why do this() and super() have to be the first statement in a constructor?

So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.

Actually you can execute logic with several expessions, you just have to wrap your code in a static function and call it in the super statement.

Using your example:

public class MySubClassC extends MyClass {
    public MySubClassC(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(createList(item));  // OK
    }

    private static List createList(item) {
        List list = new ArrayList();
        list.add(item);
        return list;
    }
}

Android: how to refresh ListView contents?

In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged() in RunOnUiThread().

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
                mAdapter.notifyDataSetChanged();
        }
    });
}

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

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

This works on Windows:

java -cp "lib/*" %MAINCLASS%

where %MAINCLASS% of course is the class containing your main method.

Alternatively:

java -cp "lib/*" -jar %MAINJAR%

where %MAINJAR% is the jar file to launch via its internal manifest.

TabLayout tab selection

With the TabLayout provided by the Material Components Library just use the selectTab method:

TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.selectTab(tabLayout.getTabAt(index));

enter image description here

It requires version 1.1.0.

Send array with Ajax to PHP script

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

Difference between __getattr__ vs __getattribute__

A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.

You almost certainly want __getattr__.

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

Could not open input file: composer.phar

dont use php composer.phar self-update
First go to Your project directory
simply use composer.phar self-update
This works for me

Failed to find 'ANDROID_HOME' environment variable

I had this issue before.
You need to add sdks\tools and sdks\build-tools to your environment path.

ldap query for group members

The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).

How to get the URL of the current page in C#

a tip for people who needs the path/url in global.asax file;

If you need to run this in global.asax > Application_Start and you app pool mode is integrated then you will receive the error below:

Request is not available in this context exception in Application_Start.

In that case you need to use this:

System.Web.HttpRuntime.AppDomainAppVirtualPath

Hope will help others..

Permutation of array

Do like this...

import java.util.ArrayList;
import java.util.Arrays;

public class rohit {

    public static void main(String[] args) {
        ArrayList<Integer> a=new ArrayList<Integer>();
        ArrayList<Integer> b=new ArrayList<Integer>();
        b.add(1);
        b.add(2);
        b.add(3);
        permu(a,b);
    }

    public static void permu(ArrayList<Integer> prefix,ArrayList<Integer> value) {
        if(value.size()==0) {
            System.out.println(prefix);
        } else {
            for(int i=0;i<value.size();i++) {
                ArrayList<Integer> a=new ArrayList<Integer>();
                a.addAll(prefix);
                a.add(value.get(i));

                ArrayList<Integer> b=new ArrayList<Integer>();

                b.addAll(value.subList(0, i));
                b.addAll(value.subList(i+1, value.size()));

                permu(a,b);
            }
        }
    }

}

How to store token in Local or Session Storage in Angular 2?

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

multiple figure in latex with captions

Below is an example of multiple figures that I used recently in Latex. You need to call these packages

\usepackage{graphicx}
\usepackage{subfig})


\begin{figure}[H]%

    \centering

    \subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%

    \subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%

    \subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
    \hfill
    \subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%

    \subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%

    \caption{Multiple figures in latex.}%

    \label{fig:MFL}%

\end{figure}

JavaScript - onClick to get the ID of the clicked button

<button id="1" class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>

<script>
$('.clickMe').click(function(){
    alert(this.id);
});
</script>

Running an outside program (executable) in Python?

Try

import subprocess
subprocess.call(["C:/Documents and Settings/flow_model/flow.exe"])

How do I get Maven to use the correct repositories?

Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.

The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.

How does String substring work in Swift

Swift 5 Extension:

extension String {
    subscript(_ range: CountableRange<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        let end = index(start, offsetBy: min(self.count - range.lowerBound, 
                                             range.upperBound - range.lowerBound))
        return String(self[start..<end])
    }

    subscript(_ range: CountablePartialRangeFrom<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
         return String(self[start...])
    }
}

Usage:

let s = "hello"
s[0..<3] // "hel"
s[3...]  // "lo"

Or unicode:

let s = ""
s[0..<1] // ""

How to print Two-Dimensional Array like table

You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".

What are .NET Assemblies?

An assembly is a collection of types and resources that forms a logical unit of functionality. All types in the .NET Framework must exist in assemblies; the common language runtime does not support types outside of assemblies. Each time you create a Microsoft Windows® Application, Windows Service, Class Library, or other application with Visual Basic .NET, you're building a single assembly. Each assembly is stored as an .exe or .dll file.

Source : https://msdn.microsoft.com/en-us/library/ms973231.aspx#assenamesp_topic4

For those with Java background like me hope following diagram clarifies concepts -

Assemblies are just like jar files (containing multiple .class files). Your code can reference an existing assemblie or you code itself can be published as an assemblie for other code to reference and use (you can think this as jar files in Java that you can add in your project dependencies).

At the end of the day an assembly is a compiled code that can be run on any operating system with CLR installed. This is same as saying .class file or bundled jar can run on any machine with JVM installed.

enter image description here

Error: Unexpected value 'undefined' imported by the module

None of the above solutions worked for me, but simply stopping and running "ng serve" again.

Fatal error: Call to undefined function mcrypt_encrypt()

One more thing: if you are serving PHP via a web server such as Apache, try restarting the web server. This will "reset" any PHP modules that might be present, activating the new configuration.

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

json parsing error syntax error unexpected end of input

spoiler: possible Server Side Problem

Here is what i've found, my code expected the responce from my server, when the server returned just 200 code, it wasnt enough herefrom json parser thrown the error error unexpected end of input

fetch(url, {
        method: 'POST',
        body: JSON.stringify(json),
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => res.json()) // here is my code waites the responce from the server
        .then((res) => {
          toastr.success('Created Type is sent successfully');
        })
        .catch(err => {
          console.log('Type send failed', err);
          toastr.warning('Type send failed');
        })

Ubuntu, how do you remove all Python 3 but not 2

Its simple just try: sudo apt-get remove python3.7 or the versions that you want to remove

Android changing Floating Action Button color

Thanks to autocomplete. I got lucky after a few hit and trials:

    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:backgroundTint="@color/whicheverColorYouLike"

-- or -- (both are basically the same thing)

    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:backgroundTint="@color/whicheverColorYouLike"

This worked for me on API Version 17 with design library 23.1.0.

How to validate phone number in laravel 5.2?

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How would I run an async Task<T> method synchronously?

In your code, your first wait for task to execute but you haven't started it so it waits indefinitely. Try this:

Task<Customer> task = GetCustomers();
task.RunSynchronously();

Edit:

You say that you get an exception. Please post more details, including stack trace.
Mono contains the following test case:

[Test]
public void ExecuteSynchronouslyTest ()
{
        var val = 0;
        Task t = new Task (() => { Thread.Sleep (100); val = 1; });
        t.RunSynchronously ();

        Assert.AreEqual (1, val);
}

Check if this works for you. If it does not, though very unlikely, you might have some odd build of Async CTP. If it does work, you might want to examine what exactly the compiler generates and how Task instantiation is different from this sample.

Edit #2:

I checked with Reflector that the exception you described occurs when m_action is null. This is kinda odd, but I'm no expert on Async CTP. As I said, you should decompile your code and see how exactly Task is being instantiated any how come its m_action is null.

How does HttpContext.Current.User.Identity.Name know which usernames exist?

Also check that

<modules>
      <remove name="FormsAuthentication"/>
</modules>

If you found anything like this just remove:

<remove name="FormsAuthentication"/>

Line from web.config and here you go it will work fine I have tested it.

Constants in Objective-C

There is also one thing to mention. If you need a non global constant, you should use static keyword.

Example

// In your *.m file
static NSString * const kNSStringConst = @"const value";

Because of the static keyword, this const is not visible outside of the file.


Minor correction by @QuinnTaylor: static variables are visible within a compilation unit. Usually, this is a single .m file (as in this example), but it can bite you if you declare it in a header which is included elsewhere, since you'll get linker errors after compilation

Java - removing first character of a string

My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.

 public static String removeLeadingChar(String str, char ch) {
    int idx = 0;
    while ((idx < str.length()) && (str.charAt(idx) == ch))
        idx++;
    return str.substring(idx);
}