Programs & Examples On #Silicon

Unexpected token < in first line of HTML

I experienced this error with my WordPress site but I saw that there were two indexes showing in my developer tools sources.

Chrome Developer Tool Error So I had the thought that if there are two indexes starting at the first line of code then there's a replication and they're conflicting with each other. So I thought that then perhaps it's my HTML minification from my caching plugin tool.

So I turned off the HTML minify setting and deleted my cache. And poof! It worked!

How can I parse a YAML file from a Linux shell script?

Given that Python3 and PyYAML are quite easy dependencies to meet nowadays, the following may help:

yaml() {
    python3 -c "import yaml;print(yaml.safe_load(open('$1'))$2)"
}

VALUE=$(yaml ~/my_yaml_file.yaml "['a_key']")

Connect Android Studio with SVN

There is a "Enable Version Control Integration..." option from the VCS popup (control V). Until you do this and select a VCS the VCS system context menus do not show up and the VCS features are not fully integrated. Not sure why this is so hidden?

Enable Version Control Integration

scale fit mobile web content using viewport meta tag

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

Send POST data via raw json with postman

meda's answer is completely legit, but when I copied the code I got an error!

Somewhere in the "php://input" there's an invalid character (maybe one of the quotes?).

When I typed the "php://input" code manually, it worked. Took me a while to figure out!

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

Angularjs dynamic ng-pattern validation

Not taking anything away from Nikos' awesome answer, perhaps you can do this more simply:

<form name="telForm">
  <input name="cb" type='checkbox' data-ng-modal='requireTel'>
  <input name="tel" type="text" ng-model="..." ng-if='requireTel' ng-pattern="phoneNumberPattern" required/>
  <button type="submit" ng-disabled="telForm.$invalid || telForm.$pristine">Submit</button>
</form>

Pay attention to the second input: We can use an ng-if to control rendering and validation in forms. If the requireTel variable is unset, the second input would not only be hidden, but not rendered at all, thus the form will pass validation and the button will become enabled, and you'll get what you need.

LINQ query to find if items in a list are contained in another list

bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;

L1 and L2 are both List<T>

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

The simplest way is to use the below code before you define your Driver.

System.setProperty("webdriver.firefox.bin",
                    "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

Does uninstalling a package with "pip" also remove the dependent packages?

i've successfully removed dependencies of a package using this bash line:

for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done

this worked on pip 1.5.4

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

Finding the source code for built-in Python functions?

As mentioned by @Jim, the file organization is described here. Reproduced for ease of discovery:

For Python modules, the typical layout is:

Lib/<module>.py
Modules/_<module>.c (if there’s also a C accelerator module)
Lib/test/test_<module>.py
Doc/library/<module>.rst

For extension-only modules, the typical layout is:

Modules/<module>module.c
Lib/test/test_<module>.py
Doc/library/<module>.rst

For builtin types, the typical layout is:

Objects/<builtin>object.c
Lib/test/test_<builtin>.py
Doc/library/stdtypes.rst

For builtin functions, the typical layout is:

Python/bltinmodule.c
Lib/test/test_builtin.py
Doc/library/functions.rst

Some exceptions:

builtin type int is at Objects/longobject.c
builtin type str is at Objects/unicodeobject.c
builtin module sys is at Python/sysmodule.c
builtin module marshal is at Python/marshal.c
Windows-only module winreg is at PC/winreg.c

How to set image on QPushButton?

You may also want to set the button size.

QPixmap pixmap("image_path");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
button->setFixedSize(pixmap.rect().size());

How to download all files (but not HTML) from a website using wget?

wget -m -p -E -k -K -np http://site/path/

man page will tell you what those options do.

wget will only follow links, if there is no link to a file from the index page, then wget will not know about its existence, and hence not download it. ie. it helps if all files are linked to in web pages or in directory indexes.

How to input matrix (2D list) in Python?

If you want to take n lines of input where each line contains m space separated integers like:

1 2 3
4 5 6 
7 8 9 

Then you can use:

a=[] // declaration 
for i in range(0,n):   //where n is the no. of lines you want 
 a.append([int(j) for j in input().split()])  // for taking m space separated integers as input

Then print whatever you want like for the above input:

print(a[1][1]) 

O/P would be 5 for 0 based indexing

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

Undefined reference to `pow' and `floor'

All answers above are incomplete, the problem here lies in linker ld rather than compiler collect2: ld returned 1 exit status. When you are compiling your fib.c to object:

$ gcc -c fib.c
$ nm fib.o
0000000000000028 T fibo
                 U floor
                 U _GLOBAL_OFFSET_TABLE_
0000000000000000 T main
                 U pow
                 U printf

Where nm lists symbols from object file. You can see that this was compiled without an error, but pow, floor, and printf functions have undefined references, now if I will try to link this to executable:

$ gcc fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status

Im getting similar output you get. To solve that, I need to tell linker where to look for references to pow, and floor, for this purpose I will use linker -l flag with m which comes from libm.so library.

$ gcc fib.o -lm
$ nm a.out
0000000000201010 B __bss_start
0000000000201010 b completed.7697
                 w __cxa_finalize@@GLIBC_2.2.5
0000000000201000 D __data_start
0000000000201000 W data_start
0000000000000620 t deregister_tm_clones
00000000000006b0 t __do_global_dtors_aux
0000000000200da0 t 
__do_global_dtors_aux_fini_array_entry
0000000000201008 D __dso_handle
0000000000200da8 d _DYNAMIC
0000000000201010 D _edata
0000000000201018 B _end
0000000000000722 T fibo
0000000000000804 T _fini
                 U floor@@GLIBC_2.2.5
00000000000006f0 t frame_dummy
0000000000200d98 t __frame_dummy_init_array_entry
00000000000009a4 r __FRAME_END__
0000000000200fa8 d _GLOBAL_OFFSET_TABLE_
                 w __gmon_start__
000000000000083c r __GNU_EH_FRAME_HDR
0000000000000588 T _init
0000000000200da0 t __init_array_end
0000000000200d98 t __init_array_start
0000000000000810 R _IO_stdin_used
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
0000000000000800 T __libc_csu_fini
0000000000000790 T __libc_csu_init
                 U __libc_start_main@@GLIBC_2.2.5
00000000000006fa T main
                 U pow@@GLIBC_2.2.5
                 U printf@@GLIBC_2.2.5
0000000000000660 t register_tm_clones
00000000000005f0 T _start
0000000000201010 D __TMC_END__

You can now see, functions pow, floor are linked to GLIBC_2.2.5.

Parameters order is important too, unless your system is configured to use shared librares by default, my system is not, so when I issue:

$ gcc -lm fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status

Note -lm flag before object file. So in conclusion, add -lm flag after all other flags, and parameters, to be sure.

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

Get bytes from std::string in C++

Normally, encryption functions take

encrypt(const void *ptr, size_t bufferSize);

as arguments. You can pass c_str and length directly:

encrypt(strng.c_str(), strng.length());

This way, extra space is allocated or wasted.

Angular HttpClient "Http failure during parsing"

I had the same problem and the cause was That at time of returning a string in your backend (spring) you might be returning as return "spring used"; But this isn't parsed right according to spring. Instead use return "\" spring used \""; -Peace out

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

You may access through tab Id as well, But that id is unique for same page. Here is an example for same

$('#product_detail').tab('show');

In above example #product_details is nav tab id

Force flushing of output to a file while bash script is still running

I don't know if it would work, but what about calling sync?

Linux find and grep command together

Or maybe even easier

grep -R put **/*bills*

The ** glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.

How do I install a plugin for vim?

To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?. In order to tell Vim to also look inside ~/.vim/vim-haml you'll want to add

set runtimepath+=$HOME/.vim/vim-haml

to your ~/.vimrc. You'll likely also want the following in your ~/.vimrc to enable all the functionality provided by vim-haml.

filetype plugin indent on
syntax on

You can refer to the 'runtimepath' and :filetype help topics in Vim for more information.

Differences between key, superkey, minimal superkey, candidate key and primary key

Superkey - An attribute or set of attributes that uniquely defines a tuple within a relation. However, a superkey may contain additional attributes that are not necessary for unique identification.

Candidate key - A superkey such that no proper subset is a superkey within the relation. So, basically has two properties: Each candidate key uniquely identifies tuple in the relation ; & no proper subset of the composite key has the uniqueness property.

Composite key - When a candidate key consists of more than one attribute.

Primary key - The candidate key chosen to identify tuples uniquely within the relation.

Alternate key - Candidate key that is not a primary key.

Foreign key - An attribute or set of attributes within a relation that matches the candidate key of some relation.

How to append text to an existing file in Java?

Create a function anywhere in your project and simply call that function where ever you need it.

Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

three lines of code two really since the third actually appends text. :P

GET parameters in the URL with CodeIgniter

You can enable query strings if you really insist. In your config.php you can enable query strings:

$config['enable_query_strings'] = TRUE;

For more info you can look at the bottom of this Wiki page: http://codeigniter.com/user_guide/general/urls.html

Still, learning to work with clean urls is a better suggestion.

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

How to iterate over rows in a DataFrame in Pandas

You can also use df.apply() to iterate over rows and access multiple columns for a function.

docs: DataFrame.apply()

def valuation_formula(x, y):
    return x * y * 0.5

df['price'] = df.apply(lambda row: valuation_formula(row['x'], row['y']), axis=1)

How do I run git log to see changes only for a specific branch?

The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)

After some trial and error, this gave me roughly what I wanted:

git log --graph --decorate --oneline --all ^master^!

MySQL: Selecting multiple fields into multiple variables in a stored procedure

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName

Angular 2 ngfor first, last, index loop

By this you can get any index in *ngFor loop in ANGULAR ...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>

We can use these alias in *ngFor

  • index : number : let i = index to get all index of object.
  • first : boolean : let first = first to get first index of object.
  • last : boolean : let last = last to get last index of object.
  • odd : boolean : let odd = odd to get odd index of object.
  • even : boolean : let even = even to get even index of object.

width:auto for <input> fields

An <input>'s width is generated from its size attribute. The default size is what's driving the auto width.

You could try width:100% as illustrated in my example below.

Doesn't fill width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input style='width:auto' />
</form>

Fills width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input style='width:100%' />
</form>

Smaller size, smaller width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input size='5' />
</form>

UPDATE

Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)

<div style='padding:30px;width:200px;background:red'>
  <form action='' method='post' style='width:200px;background:blue;padding:3px'>
    <input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
    <br /><br />
    <input size='' style='width:100%' />
  </form>
</div>

Joining Multiple Tables - Oracle

While former answer is absolutely correct, I prefer using the JOIN ON syntax to be sure that I know how do I join and on what fields. It would look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order         Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';

This syntax seperates completely the WHERE clause from the JOIN clause, making the statement more readable and easier for you to debug.

Rearrange columns using cut

You may also combine cut and paste:

paste <(cut -f2 file.txt) <(cut -f1 file.txt)

via comments: It's possible to avoid bashisms and remove one instance of cut by doing:

paste file.txt file.txt | cut -f2,3

How to select all instances of selected region in Sublime Text

Even though there are multiple answers, there is an issue using this approach. It selects all the text that matches, not only the whole words like variables.

As per "Sublime Text: Select all instances of a variable and edit variable name" and the answer in "Sublime Text: Select all instances of a variable and edit variable name", we have to start with a empty selection. That is, start using the shortcut Alt+F3 which would help selecting only the whole words.

Convert dictionary values into array

// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

You may convert latitude-longitude to UTM format which is metric format that may help you to calculate distances. Then you can easily decide if point falls into specific location.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection from wget if you're behind a proxy and don't have HTTP_PROXY and HTTPS_PROXY environment variables set correctly. Make sure to set HTTP_PROXY and HTTPS_PROXY to point to your proxy.

This is a common situation if you work for a large corporation.

Execute curl command within a Python script

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

Xcode Objective-C | iOS: delay function / NSTimer help?

Less code is better code.

[NSThread sleepForTimeInterval:0.06];

Swift:

Thread.sleep(forTimeInterval: 0.06)

How to convert string to string[]?

Casting can also help converting string to string[]. In this case, casting the string with ToArray() is demonstrated:

String myString = "My String";
String[] myString.Cast<char>().Cast<string>().ToArray();

How to prevent scanf causing a buffer overflow in C?

Limiting the length of the input is definitely easier. You could accept an arbitrarily-long input by using a loop, reading in a bit at a time, re-allocating space for the string as necessary...

But that's a lot of work, so most C programmers just chop off the input at some arbitrary length. I suppose you know this already, but using fgets() isn't going to allow you to accept arbitrary amounts of text - you're still going to need to set a limit.

Yarn install command error No such file or directory: 'install'

Tried above steps, didn't work on Ubuntu 20. For Ubuntu 20, remove the cmdtest and yarn like suggested above. Install yarn with below commands:

curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

Java get String CompareTo as a comparator object

To generalize the good answer of Mike Nakis with String.CASE_INSENSITIVE_ORDER, you can also use :

Collator.getInstance();

See Collator

No 'Access-Control-Allow-Origin' header in Angular 2 app

Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).

That CORS header will have to be added to that endpoint on the server before you can make ANY requests.

How can I compare time in SQL Server?

SELECT timeEvent 
  FROM tbEvents 
 WHERE CONVERT(VARCHAR,startHour,108) >= '01:01:01'

This tells SQL Server to convert the current date/time into a varchar using style 108, which is "hh:mm:ss". You can also replace '01:01:01' which another convert if necessary.

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

Remove credentials from Git

This approach worked for me and should be agnostic of OS. It's a little heavy-handed, but was quick and allowed me to reenter credentials.

Simply find the remote alias for which you wish to reenter credentials.

$ git remote -v 
origin  https://bitbucket.org/org/~username/your-project.git (fetch)
origin  https://bitbucket.org/org/~username/your-project.git (push)

Copy the project path (https://bitbucket.org/org/~username/your-project.git)

Then remove the remote

$ git remote remove origin

Then add it back

$ git remote add origin https://bitbucket.org/org/~username/your-project.git

How to map with index in Ruby?

module Enumerable
  def map_with_index(&block)
    i = 0
    self.map { |val|
      val = block.call(val, i)
      i += 1
      val
    }
  end
end

["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]

Advantages of std::for_each over for loop

Like many of the algorithm functions, an initial reaction is to think it's more unreadable to use foreach than a loop. It's been a topic of many flame wars.

Once you get used to the idiom you may find it useful. One obvious advantage is that it forces the coder to separate the inner contents of the loop from the actual iteration functionality. (OK, I think it's an advantage. Other's say you're just chopping up the code with no real benifit).

One other advantage is that when I see foreach, I know that either every item will be processed or an exception will be thrown.

A for loop allows several options for terminating the loop. You can let the loop run its full course, or you can use the break keyword to explicitly jump out of the loop, or use the return keyword to exit the entire function mid-loop. In contrast, foreach does not allow these options, and this makes it more readable. You can just glance at the function name and you know the full nature of the iteration.

Here's an example of a confusing for loop:

for(std::vector<widget>::iterator i = v.begin(); i != v.end(); ++i)
{
   /////////////////////////////////////////////////////////////////////
   // Imagine a page of code here by programmers who don't refactor
   ///////////////////////////////////////////////////////////////////////
   if(widget->Cost < calculatedAmountSofar)
   {
        break;
   }
   ////////////////////////////////////////////////////////////////////////
   // And then some more code added by a stressed out juniour developer
   // *#&$*)#$&#(#)$#(*$&#(&*^$#(*$#)($*#(&$^#($*&#)$(#&*$&#*$#*)$(#*
   /////////////////////////////////////////////////////////////////////////
   for(std::vector<widgetPart>::iterator ip = widget.GetParts().begin(); ip != widget.GetParts().end(); ++ip)
   {
      if(ip->IsBroken())
      {
         return false;
      }
   }
}

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Loop through the rows of a particular DataTable

Here's the best way I found:

    For Each row As DataRow In your_table.Rows
        For Each cell As String In row.ItemArray
            'do what you want!
        Next
    Next

How do I mock a class without an interface?

With MoQ, you can mock concrete classes:

var mocked = new Mock<MyConcreteClass>();

but this allows you to override virtual code (methods and properties).

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

To save a package to package.json as dev dependencies:

npm install "$package" --save-dev

When you run npm install it will install both devDependencies and dependencies. To avoid install devDependencies run:

npm install --production

Play audio with Python

In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.

It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.

I've linked the implementation above, but a simplified version follows:

import subprocess

def play(audio_file_path):
    subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])

The -nodisp flag stops ffplay from showing a new window, and the -autoexit flag causes ffplay to exit and return a status code when the audio file is done playing.

edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.

List all environment variables from the command line

Just do:

SET

You can also do SET prefix to see all variables with names starting with prefix.

For example, if you want to read only derbydb from the environment variables, do the following:

set derby 

...and you will get the following:

DERBY_HOME=c:\Users\amro-a\Desktop\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

HTML.ActionLink vs Url.Action in ASP.NET Razor

Html.ActionLink generates an <a href=".."></a> tag automatically.

Url.Action generates only an url.

For example:

@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)

generates:

<a href="/controllerName/actionName/<id>">link text</a>

and

@Url.Action("actionName", "controllerName", new { id = "<id>" }) 

generates:

/controllerName/actionName/<id>

Best plus point which I like is using Url.Action(...)

You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.

<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">

   <img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />

   @Html.DisplayFor(model => model.<SomeModelField>)
</a>

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

Custom pagination view in Laravel 5

If you want to customize your pagination link using next and prev. You can see at Paginator.php Inside it, there's some method I'm using Laravel 7

<a href="{{ $paginator->previousPageUrl() }}" < </a>
<a href="{{ $paginator->nextPageUrl() }}" > </a>

To limit items, in controller using paginate()

$paginator = Model::paginate(int);

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

what is the unsigned datatype?

Bringing my answer from another question.

From the C specification, section 6.7.2:

— unsigned, or unsigned int

Meaning that unsigned, when not specified the type, shall default to unsigned int. So writing unsigned a is the same as unsigned int a.

Postman: sending nested JSON object

Just wanted to add one more problem that some people might find on top of all the other answers. Sending JSON object using RAW data and setting the type to application/json is what is to be done as has been mentioned above.

Even though I had done so, I got error in the POSTMAN request, it was because I accidentally forgot to create a default constructor for both child class.

Say if I had to send a JSON of format:

{
 "firstname" : "John",
 "lastname" : "Doe",
 "book":{
   "name":"Some Book",
   "price":12.2
  }
}

Then just make sure you create a default constructor for Book class.

I know this is a simple and uncommon error, but did certainly help me.

How to use git merge --squash?

You want to merge with the squash option. That's if you want to do it one branch at a time.

git merge --squash feature1

If you want to merge all the branches at the same time as single commits, then first rebase interactively and squash each feature then octopus merge:

git checkout feature1
git rebase -i master

Squash into one commit then repeat for the other features.

git checkout master
git merge feature1 feature2 feature3 ...

That last merge is an "octopus merge" because it's merging a lot of branches at once.

Hope this helps

ImportError: No module named 'pygame'

I had the same problem and discovered that Pygame doesn't work for Python3 at least on the Mac OS, but I also have Tython2 installed in my computer as you probably do too, so when I use Pygame, I switch the path so that it uses python2 instead of python3. I use Sublime Text as my text editor so I just go to Tools > Build Systems > New Build System and enter the following:

{
    "cmd": ["/usr/local/bin/python", "-u", "$file"],    
}

instead of

{
    "cmd": ["/usr/local/bin/python3", "-u", "$file"],   
}

in my case. And when I'm not using pygame, I simply change the path back so that I can use Python3.

How to get base URL in Web API controller?

First you get full URL using HttpContext.Current.Request.Url.ToString(); then replace your method url using Replace("user/login", "").

Full code will be

string host = HttpContext.Current.Request.Url.ToString().Replace("user/login", "")

builtins.TypeError: must be str, not bytes

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

Arrays.asList() of an array

there are two cause of this exception:

1

Arrays.asList(factors) returns a List<int[]> where factors is an int array

2

you forgot to add the type parameter to:

ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));

with:

ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  

resulting in a compile-time error:

found   : java.util.List<int[]>
required: java.util.List<java.lang.Integer>

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

jQuery has deprecated synchronous XMLHTTPRequest

The accepted answer is correct, but I found another cause if you're developing under ASP.NET with Visual Studio 2013 or higher and are sure you didn't make any synchronous ajax requests or define any scripts in the wrong place.

The solution is to disable the "Browser Link" feature by unchecking "Enable Browser Link" in the VS toolbar dropdown indicated by the little refresh icon pointing clockwise. As soon as you do this and reload the page, the warnings should stop!

Disable Browser Link

This should only happen while debugging locally, but it's still nice to know the cause of the warnings.

Unable to find a @SpringBootConfiguration when doing a JpaTest

In addition to what Thomas Kåsene said, you can also add

@SpringBootTest(classes=com.package.path.class)

to the test annotation to specify where it should look for the other class if you didn't want to refactor your file hierarchy. This is what the error message hints at by saying:

Unable to find a @SpringBootConfiguration, you need to use 
@ContextConfiguration or @SpringBootTest(classes=...) ...

check if file exists on remote host with ssh

This also works :

if ssh user@ip "[ -s /path/file_name ]" ;then 
  status=RECEIVED ; 
 else 
  status=MISSING ; 
 fi

Bootstrap modal z-index

The modal dialog can be positioned on top by overriding its z-index property:

.modal.fade {
  z-index: 10000000 !important;
}

Convert varchar into datetime in SQL Server

Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can't convert.

OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly

I got this to work:

cast( right(@date,4) + left(@date,4) as datetime)

You will still get an error message though if you have any that are in a non-standard format like '112009' or some text value or a true out of range date.

Class Not Found: Empty Test Suite in IntelliJ

Interestingly, I've faced this issue many times due to different reasons. For e.g. Invalidating cache and restarting has helped as well.

Last I fixed it by correcting my output path in File -> Project Structure -> Project -> Project Compiler Output to : absolute_path_of_package/out

for e.g. : /Users/random-guy/myWorkspace/src/DummyProject/out

concatenate char array in C

Have a look at the strcat function.

In particular, you could try this:

const char* name = "hello";
const char* extension = ".txt";

char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

How to convert XML to java.util.Map and vice versa

How about XStream? Not 1 class but 2 jars for many use cases including yours, very simple to use yet quite powerful.

Array initializing in Scala

Another way of declaring multi-dimentional arrays:

Array.fill(4,3)("")

res3: Array[Array[String]] = Array(Array("", "", ""), Array("", "", ""),Array("", "", ""), Array("", "", ""))

Generate random numbers uniformly over an entire range

If you are able to, use Boost. I have had good luck with their random library.

uniform_int should do what you want.

Regex match text between tags

Use match instead, and the g flag.

str.match(/<b>(.*?)<\/b>/g);

Disable submit button when form invalid with AngularJS

If you are using Reactive Forms you can use this:

<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>

How to create a popup windows in javafx

The Popup class might be better than the Stage class, depending on what you want. Stage is either modal (you can't click on anything else in your app) or it vanishes if you click elsewhere in your app (because it's a separate window). Popup stays on top but is not modal.

See this Popup Window example.

Force Internet Explorer to use a specific Java Runtime Environment install?

First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.

Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.

To get your old version of Java back you need to reverse these steps.

Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).

The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.

How do I configure Apache 2 to run Perl CGI scripts?

(Google search brought me to this question even though I did not ask for perl)

I had a problem with running scripts (albeit bash not perl). Apache had a config of ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ however Apache error log showed File does not exist: /var/www/cgi-bin/test.html.

Tried putting the script in both /usr/lib/cgi-bin/ and /var/www/cgi-bin/ but neither were working.

After a prolonged googling session what cracked it for me was sudo a2enmod cgi and everything fell into place using /usr/lib/cgi-bin/.

What does enumerate() mean?

It's a builtin function that returns an object that can be iterated over. See the documentation.

In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:

for item in enumerate(["a", "b", "c"]):
    print item

prints

(0, "a")
(1, "b")
(2, "c")

It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.

htaccess remove index.php from url

The original answer is actually correct, but lacks explanation. I would like to add some explanations and modifications.

I suggest reading this short introduction https://httpd.apache.org/docs/2.4/rewrite/intro.html (15mins) and reference these 2 pages while reading.

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html https://httpd.apache.org/docs/2.4/rewrite/flags.html


This is the basic rule to hide index.php from the URL. Put this in your root .htaccess file.

mod_rewrite must be enabled with PHP and this will work for the PHP version higher than 5.2.6.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php/$1 [L]

Think %{REQUEST_FILENAME} as the the path after host.

E.g. https://www.example.com/index.html, %{REQUEST_FILENAME} is /index.html

So the last 3 lines means, if it's not a regular file !-f and not a directory !-d, then do the RewriteRule.

As for RewriteRule formats:

enter image description here

So RewriteRule (.*) /index.php/$1 [L] means, if the 2 RewriteCond are satisfied, it (.*) would match everything after the hostname. . matches any single character , .* matches any characters and (.*) makes this a variables can be references with $1, then replace with /index.php/$1. The final effect is to add a preceding index.php to the whole URL path.

E.g. for https://www.example.com/hello, it would produce, https://www.example.com/index.php/hello internally.

Another key problem is that this indeed solve the question. Internally, (I guess) it always need https://www.example.com/index.php/hello, but with rewriting, you could visit the site without index.php, apache adds that for you internally.


Btw, making an extra .htaccess file is not very recommended by the Apache doc.

Rewriting is typically configured in the main server configuration setting (outside any <Directory> section) or inside <VirtualHost> containers. This is the easiest way to do rewriting and is recommended

How to safely call an async method in C# without await

Typically async method returns Task class. If you use Wait() method or Result property and code throws exception - exception type gets wrapped up into AggregateException - then you need to query Exception.InnerException to locate correct exception.

But it's also possible to use .GetAwaiter().GetResult() instead - it will also wait async task, but will not wrap exception.

So here is short example:

public async Task MyMethodAsync()
{
}

public string GetStringData()
{
    MyMethodAsync().GetAwaiter().GetResult();
    return "test";
}

You might want also to be able to return some parameter from async function - that can be achieved by providing extra Action<return type> into async function, for example like this:

public string GetStringData()
{
    return MyMethodWithReturnParameterAsync().GetAwaiter().GetResult();
}

public async Task<String> MyMethodWithReturnParameterAsync()
{
    return "test";
}

Please note that async methods typically have ASync suffix naming, just to be able to avoid collision between sync functions with same name. (E.g. FileStream.ReadAsync) - I have updated function names to follow this recommendation.

The source was not found, but some or all event logs could not be searched

I recently experienced the error, and none of the solutions worked for me. What resolved the error for me was adding the Application pool user to the Power Users group in computer management. I couldn't use the Administrator group due to a company policy.

How do I correct the character encoding of a file?

If you see question marks in the file or if the accents are already lost, going back to utf8 will not help your cause. e.g. if café became cafe - changing encoding alone will not help (and you'll need original data).

Can you paste some text here, that'll help us answer for sure.

Edit a specific Line of a Text File in C#

the easiest way is :

static void lineChanger(string newText, string fileName, int line_to_edit)
{
     string[] arrLine = File.ReadAllLines(fileName);
     arrLine[line_to_edit - 1] = newText;
     File.WriteAllLines(fileName, arrLine);
}

usage :

lineChanger("new content for this line" , "sample.text" , 34);

clearing select using jquery

use .empty()

 $('select').empty().append('whatever');

you can also use .html() but note

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

alternative: --- If you want only option elements to-be-remove, use .remove()

$('select option').remove();

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

How to remove leading whitespace from each line in a file

Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt

How to serialize an object into a string

You can use the build in classes sun.misc.Base64Decoder and sun.misc.Base64Encoder to convert the binary data of the serialize to a string. You das not need additional classes because it are build in.

svn over HTTP proxy

when you use the svn:// URI it uses port 3690 and probably won't use http proxy

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Try my way :

robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR

Had to put /XD before /MIR while including the full Destination Source directly after /XD.

How to create a responsive image that also scales up in Bootstrap 3

Not sure if it helps you still... but I had to do a small trick to make the image bigger but keeping it responsive

@media screen and (max-width: 368px) {
    img.smallResolution{
        min-height: 150px;
    }

}

Hope it helps P.S. The max width can be anything you like

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem.

As it turned out, I ran mvn clean package install.

Correct way is mvn clean install

Class vs. static method in JavaScript

I use namespaces:

var Foo = {
     element: document.getElementById("id-here"),

     Talk: function(message) {
            alert("talking..." + message);
     },

     ChangeElement: function() {
            this.element.style.color = "red";
     }
};

And to use it:

Foo.Talk("Testing");

Or

Foo.ChangeElement();

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

I had this issue on resx files in my solution. I'm using Onedrive. However none of the above solutions fixed it.

The problem was the icon I used was in the MyWindow.resx files for the windows.

I removed that then grabbed the icon from the App Local Resources resource folder.

 private ResourceManager rm = App_LocalResources.LocalResources.ResourceManager;
 
 ..
 
InitializeComponent();
this.Icon = (Icon)rm.GetObject("IconName");

This happened after an update to VS2019.

How to execute only one test spec with angular-cli

Just small change need in test.ts file inside src folder:

const context = require.context('./', true, /test-example\.spec\.ts$/);

Here, test-example is the exact file name which we need to run

In the same way, if you need to test the service file only you can replace the filename like "/test-example.service"

Html- how to disable <a href>?

<script>
    $(document).ready(function(){
        $('#connectBtn').click(function(e){
            e.preventDefault();
        })
    });
</script>

This will prevent the default action.

How to write file in UTF-8 format?

<?php
function writeUTF8File($filename,$content) { 
        $f=fopen($filename,"w"); 
        # Now UTF-8 - Add byte order mark 
        fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
        fwrite($f,$content); 
        fclose($f); 
} 
?>

How do I return to an older version of our code in Subversion?

Sync to the older version and commit it. This should do the trick.

Here's also an explanation of undoing changes.

How to get a password from a shell script without echoing

You can also prompt for a password without setting a variable in the current shell by doing something like this:

$(read -s;echo $REPLY)

For instance:

my-command --set password=$(read -sp "Password: ";echo $REPLY)

You can add several of these prompted values with line break, doing this:

my-command --set user=$(read -sp "`echo $'\n '`User: ";echo $REPLY) --set password=$(read -sp "`echo $'\n '`Password: ";echo $REPLY)

The apk must be signed with the same certificates as the previous version

My [silly] mistake was that i used app-debug.apk file instead of app-release.apk file. You need to to choose "release" in "Build Variants" frame when you generate signed APK. The app-release.apk file should be located under "app\release" folder in your project root.

Downloading a picture via urllib and python

All the above codes, do not allow to preserve the original image name, which sometimes is required. This will help in saving the images to your local drive, preserving the original image name

    IMAGE = URL.rsplit('/',1)[1]
    urllib.urlretrieve(URL, IMAGE)

Try this for more details.

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

removeEventListener on anonymous functions in JavaScript

I just experienced similiar problem with copy-protection wordpress plugin. The code was:

function disableSelection(target){
 if (typeof target.onselectstart!="undefined") //For IE 
  target.onselectstart=function(){return false}
 else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
  target.style.MozUserSelect="none"
 else //All other route (For Opera)
  target.onmousedown=function(){return false}
target.style.cursor = "default"
}

And then it was initiated by loosely put

<script type="text/javascript">disableSelection(document.body)</script>.

I came around this simply by attaching other annonymous function to this event:

document.body.onselectstart = function() { return true; };

Equivalent to 'app.config' for a library (DLL)

public class ConfigMan
{
    #region Members

    string _assemblyLocation;
    Configuration _configuration;

    #endregion Members

    #region Constructors

    /// <summary>
    /// Loads config file settings for libraries that use assembly.dll.config files
    /// </summary>
    /// <param name="assemblyLocation">The full path or UNC location of the loaded file that contains the manifest.</param>
    public ConfigMan(string assemblyLocation)
    {
        _assemblyLocation = assemblyLocation;
    }

    #endregion Constructors

    #region Properties

    Configuration Configuration
    {
        get
        {
            if (_configuration == null)
            {
                try
                {
                    _configuration = ConfigurationManager.OpenExeConfiguration(_assemblyLocation);
                }
                catch (Exception exception)
                {
                }
            }
            return _configuration;
        }
    }

    #endregion Properties

    #region Methods

    public string GetAppSetting(string key)
    {
        string result = string.Empty;
        if (Configuration != null)
        {
            KeyValueConfigurationElement keyValueConfigurationElement = Configuration.AppSettings.Settings[key];
            if (keyValueConfigurationElement != null)
            {
                string value = keyValueConfigurationElement.Value;
                if (!string.IsNullOrEmpty(value)) result = value;
            }
        }
        return result;
    }

    #endregion Methods
}

Just for something to do, I refactored the top answer into a class. The usage is something like:

ConfigMan configMan = new ConfigMan(this.GetType().Assembly.Location);
var setting = configMan.GetAppSetting("AppSettingsKey");

How can I parse a string with a comma thousand separator to a number?

Replace the comma with an empty string:

_x000D_
_x000D_
var x = parseFloat("2,299.00".replace(",",""))_x000D_
alert(x);
_x000D_
_x000D_
_x000D_

Android Horizontal RecyclerView scroll Direction

XML approach using androidx:

<androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:id="@+id/my_recycler_view"
        android:orientation="horizontal"
        tools:listitem="@layout/my_item"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" 
        android:layout_height="wrap_content">

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

How to escape single quotes within single quoted strings

Since Bash 2.04 syntax $'string' (instead of just 'string'; warning: do not confuse with $('string')) is another quoting mechanism which allows ANSI C-like escape sequences and do expansion to single-quoted version.

Simple example:

  $> echo $'aa\'bb'
  aa'bb

  $> alias myvar=$'aa\'bb'
  $> alias myvar
  alias myvar='aa'\''bb'

In your case:

$> alias rxvt=$'urxvt -fg \'#111111\' -bg \'#111111\''
$> alias rxvt
alias rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''

Common escaping sequences works as expected:

\'     single quote
\"     double quote
\\     backslash
\n     new line
\t     horizontal tab
\r     carriage return

Below is copy+pasted related documentation from man bash (version 4.4):

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:

    \a     alert (bell)
    \b     backspace
    \e
    \E     an escape character
    \f     form feed
    \n     new line
    \r     carriage return
    \t     horizontal tab
    \v     vertical tab
    \\     backslash
    \'     single quote
    \"     double quote
    \?     question mark
    \nnn   the eight-bit character whose value is the octal 
           value nnn (one to three digits)
    \xHH   the eight-bit character whose value is the hexadecimal
           value HH (one or two hex digits)
    \uHHHH the Unicode (ISO/IEC 10646) character whose value is 
           the hexadecimal value HHHH (one to four hex digits)
    \UHHHHHHHH the Unicode (ISO/IEC 10646) character whose value 
               is the hexadecimal value HHHHHHHH (one to eight 
               hex digits)
    \cx    a control-x character

The expanded result is single-quoted, as if the dollar sign had not been present.


See Quotes and escaping: ANSI C like strings on bash-hackers.org wiki for more details. Also note that "Bash Changes" file (overview here) mentions a lot for changes and bug fixes related to the $'string' quoting mechanism.

According to unix.stackexchange.com How to use a special character as a normal one? it should work (with some variations) in bash, zsh, mksh, ksh93 and FreeBSD and busybox sh.

How to change font size in Eclipse for Java text editors?

Try the tarlog plugin. You can change the font through Ctrl++ and Ctrl-- commands with it. A very convenient thing.

https://code.google.com/archive/p/tarlog-plugins/downloads

Adding Permissions in AndroidManifest.xml in Android Studio?

You can add manually in the manifest file within manifest tag by:

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

This permission is required to be able to access the camera device.

Multiple parameters in a List. How to create without a class?

If you do not mind the items being imutable you can use the Tuple class added to .net 4

var list = new List<Tuple<string,int>>();
list.Add(new Tuple<string,int>("hello", 1));

list[0].Item1 //Hello
list[0].Item2 //1

However if you are adding two items every time and one of them is unique id you can use a Dictionary

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

What is a callback in java

Maybe an example would help.

Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.

What is the OR operator in an IF statement

|| is the conditional OR operator in C#

You probably had a hard time finding it because it's difficult to search for something whose name you don't know. Next time try doing a Google search for "C# Operators" and look at the logical operators.

Here is a list of C# operators.

My code is:

if (title == "User greeting" || "User name") {do stuff};

and my error is:

Error 1 Operator '||' cannot be applied to operands of type 'bool' and 'string' C:\Documents and Settings\Sky View Barns\My Documents\Visual Studio 2005\Projects\FOL Ministry\FOL Ministry\Downloader.cs 63 21 FOL Ministry

You need to do this instead:

if (title == "User greeting" || title == "User name") {do stuff};

The OR operator evaluates the expressions on both sides the same way. In your example, you are operating on the expression title == "User greeting" (a bool) and the expression "User name" (a string). These can't be combined directly without a cast or conversion, which is why you're getting the error.

In addition, it is worth noting that the || operator uses "short-circuit evaluation". This means that if the first expression evaluates to true, the second expression is not evaluated because it doesn't have to be - the end result will always be true. Sometimes you can take advantage of this during optimization.

One last quick note - I often write my conditionals with nested parentheses like this:

if ((title == "User greeting") || (title == "User name")) {do stuff};

This way I can control precedence and don't have to worry about the order of operations. It's probably overkill here, but it's especially useful when the logic gets complicated.

How can I read inputs as numbers?

input() (Python 3) and raw_input() (Python 2) always return strings. Convert the result to integer explicitly with int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

Atom menu is missing. How do I re-enable

Same happened to me, I had to go into Packages and re-enable Tabs and Tree-View (both part of core).

C++ Singleton design pattern

Here is an easy implementation.

#include <Windows.h>
#include <iostream>

using namespace std;


class SingletonClass {

public:
    static SingletonClass* getInstance() {

    return (!m_instanceSingleton) ?
        m_instanceSingleton = new SingletonClass : 
        m_instanceSingleton;
    }

private:
    // private constructor and destructor
    SingletonClass() { cout << "SingletonClass instance created!\n"; }
    ~SingletonClass() {}

    // private copy constructor and assignment operator
    SingletonClass(const SingletonClass&);
    SingletonClass& operator=(const SingletonClass&);

    static SingletonClass *m_instanceSingleton;
};

SingletonClass* SingletonClass::m_instanceSingleton = nullptr;



int main(int argc, const char * argv[]) {

    SingletonClass *singleton;
    singleton = singleton->getInstance();
    cout << singleton << endl;

    // Another object gets the reference of the first object!
    SingletonClass *anotherSingleton;
    anotherSingleton = anotherSingleton->getInstance();
    cout << anotherSingleton << endl;

    Sleep(5000);

    return 0;
}

Only one object created and this object reference is returned each and every time afterwords.

SingletonClass instance created!
00915CB8
00915CB8

Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.

N.B. This is not a thread safe one.You have to ensure thread safety.

Difference between FetchType LAZY and EAGER in Java Persistence API?

EAGER loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.

LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)

Converting 'ArrayList<String> to 'String[]' in Java

If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:

List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);

// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);

There are a few more preallocated empty arrays of different types in ArrayUtils.

Also we can trick JVM to create en empty array for us this way:

String[] array = list.toArray(ArrayUtils.toArray());

// or if using static import
String[] array = list.toArray(toArray());

But there's really no advantage this way, just a matter of taste, IMO.

How to display an error message in an ASP.NET Web Application

Roughly you can do it like that :

try
{
    //do something
}
catch (Exception ex)
{
    string script = "<script>alert('" + ex.Message + "');</script>";
    if (!Page.IsStartupScriptRegistered("myErrorScript"))
    {
         Page.ClientScript.RegisterStartupScript("myErrorScript", script);
    }
}

But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.

How does Python return multiple values from a function?

From Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun() returns multiple values, a tuple is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

Though there's no equivalent in you can easily create this behaviour using array's or some Collections like Lists:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

sum = 15
rest = 5

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

x86 Assembly on a Mac

Also, on the Intel Macs, can I use generic x86 asm? or is there a modified instruction set? Any information about post Intel Mac assembly helps.

It's the same instruction set; it's the same chips.

Eclipse "Invalid Project Description" when creating new project from existing source

There are a variety of scenarios, but, in my case, I wanted to retain the folder and it's contents, as it had been checked out from .git. However, I needed to be able to modify the source and other stuff using Eclipse.

I found the problem was that the .cproject and .project files had path information that was very environment specific (and did not match my environment).

What I did was this:

  1. Created a new empty folder(with a different name) and created a new workspace pointing to that folder.
  2. Checked out or copied the .git project/folder into the empty folder.
  3. Then imported, General, Existing projects in Workspace.

The key seemed to be creating the top level empty work space with a different name.

I hope this helps someone.

How to get the previous URL in JavaScript?

<script type="text/javascript">
    document.write(document.referrer);
</script>

document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.

It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

How to watch for form changes in Angular

Expanding on Mark's suggestions...

Method 3

Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.

export class App implements DoCheck {
  person = { first: "Sally", last: "Jones" };
  oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning

  ngDoCheck() {
    // Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
    for (let prop in this.person) {
      if (this.oldPerson[prop] !==  this.person[prop]) {
        console.log(`person.${prop} changed: ${this.person[prop]}`);
        this.oldPerson[prop] = this.person[prop];
      }
    }
  }

Try in Plunker

Angular2 set value for formGroup

As pointed out in comments, this feature wasn't supported at the time this question was asked. This issue has been resolved in angular 2 rc5

"Could not find bundler" error

I had this problem, then I did:

gem install bundle

notice "bundle" not "bundler" solved my problem.

then in your project folder do:

bundle install

and then you can run your project using:

script/rails server

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

How to remove .html from URL?

For those who are using Firebase hosting none of the answers will work on this page. Because you can't use .htaccess in Firebase hosting. You will have to configure the firebase.json file. Just add the line "cleanUrls": true in your file and save it. That's it.

After adding the line firebase.json will look like this :

{
  "hosting": {
    "public": "public",
    "cleanUrls": true, 
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

Bin size in Matplotlib (Histogram)

Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:

plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])

If you just want them equally distributed, you can simply use range:

plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

Added to original answer

The above line works for data filled with integers only. As macrocosme points out, for floats you can use:

import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))

How to find a value in an array and remove it by using PHP array functions?

This solution is the combination of @Peter's solution for deleting multiple occurences and @chyno solution for removing first occurence. That's it what I'm using.

/**
 * @param array $haystack
 * @param mixed $value
 * @param bool $only_first
 * @return array
 */
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
    if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
    if (empty($haystack)) { return $haystack; }

    if ($only_first) { // remove the first found value
        if (($pos = array_search($needle, $haystack)) !== false) {
            unset($haystack[$pos]);
        }
    } else { // remove all occurences of 'needle'
        $haystack = array_diff($haystack, array($needle));
    }

    return $haystack;
}

Also have a look here: PHP array delete by value (not key)

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Create a batch file to run an .exe with an additional parameter

in batch file abc.bat

cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3 

I am assuming that your executible.exe is present in c:\user\ben_dchost\documents\ I am also assuming that the parameters it takes are -flag1 -flag2 -flag3

Edited:

For the command you say you want to execute, do:

cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause

Hope this helps

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

PHP - define constant inside a class

This is and old question, but now on PHP 7.1 you can define constant visibility.

EXAMPLE

<?php
class Foo {
    // As of PHP 7.1.0
    public const BAR = 'bar';
    private const BAZ = 'baz';
}
echo Foo::BAR . PHP_EOL;
echo Foo::BAZ . PHP_EOL;
?>

Output of the above example in PHP 7.1:

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.

More info here

Apache VirtualHost and localhost

For someone doing everything described here and still can't access:

XAMPP with Apache HTTP Server 2.4:

In file httpd-vhost.conf:

<VirtualHost *>
    DocumentRoot "D:/xampp/htdocs/dir"
    ServerName something.dev
   <Directory "D:/xampp/htdocs/dir">
    Require all granted #apache v 2.4.4 uses just this
   </Directory>
</VirtualHost>

There isn't any need for a port, or an IP address here. Apache configures it on its own files. There isn't any need for NameVirtualHost *:80; it's deprecated. You can use it, but it doesn't make any difference.

Then to edit hosts, you must run Notepad as administrator (described bellow). If you were editing the file without doing this, you are editing a pseudo file, not the original (yes, it saves, etc., but it's not the real file)

In Windows:

Find the Notepad icon, right click, run as administrator, open file, go to C:/WINDOWS/system32/driver/etc/hosts, check "See all files", and open hosts.

If you where editing it before, probably you will see it's not the file you were previously editing when not running as administrator.

Then to check if Apache is reading your httpd-vhost.conf, go to folder xampFolder/apache/bin, Shift + right click, open a terminal command here, open XAMPP (as you usually do), start Apache, and then on the command line, type httpd -S. You will see a list of the virtual hosts. Just check if your something.dev is there.

JUnit 4 compare Sets

I like the solution of Hans-Peter Störr... But I think it is not quite correct. Sadly containsInAnyOrder does not accept a Collection of objetcs to compare to. So it has to be a Collection of Matchers:

assertThat(set1, containsInAnyOrder(set2.stream().map(IsEqual::equalTo).collect(toList())))

The import are:

import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.


To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */
}

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */
}

jsFiddle demo


1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Why am I getting ImportError: No module named pip ' right after installing pip?

Follow steps given in https://michlstechblog.info/blog/python-install-python-with-pip-on-windows-by-the-embeddable-zip-file/. Replace x with version number of Python.

  1. Open the pythonxx.__pth file, located in your python folder.
  2. Edit the contents (e.g. D:\Pythonx.x.x to the following):
 D:\Pythonx.x.x 
 D:\Pythonx.x.x\DLLs
 D:\Pythonx.x.x\lib
 D:\Pythonx.x.x\lib\plat-win 
 D:\Pythonx.x.x\lib\site-packages

ASP.NET IIS Web.config [Internal Server Error]

I had the same problem.

Solution:

  1. Click the right button in your site folder in "iis"
  2. "Convert to Application".

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Call of overloaded function is ambiguous

The literal 0 has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.

As your setval function can accept either an int or a char*, the compiler can not decide which overload you meant.

The easiest solution is to just cast the 0 to the right type.
Another option is to ensure the int overload is preferred, for example by making the other one a template:

class huge
{
 private:
  unsigned char data[BYTES];
 public:
  void setval(unsigned int);
  template <class T> void setval(const T *); // not implemented
  template <> void setval(const char*);
};

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

How to return an array from a function?

how can i return a array in a c++ method and how must i declare it? int[] test(void); ??

This sounds like a simple question, but in C++ you have quite a few options. Firstly, you should prefer...

  • std::vector<>, which grows dynamically to however many elements you encounter at runtime, or

  • std::array<> (introduced with C++11), which always stores a number of elements specified at compile time,

...as they manage memory for you, ensuring correct behaviour and simplifying things considerably:

std::vector<int> fn()
{
    std::vector<int> x;
    x.push_back(10);
    return x;
}

std::array<int, 2> fn2()  // C++11
{
    return {3, 4};
}

void caller()
{
    std::vector<int> a = fn();
    const std::vector<int>& b = fn(); // extend lifetime but read-only
                                      // b valid until scope exit/return

    std::array<int, 2> c = fn2();
    const std::array<int, 2>& d = fn2();
}

The practice of creating a const reference to the returned data can sometimes avoid a copy, but normally you can just rely on Return Value Optimisation, or - for vector but not array - move semantics (introduced with C++11).

If you really want to use an inbuilt array (as distinct from the Standard library class called array mentioned above), one way is for the caller to reserve space and tell the function to use it:

void fn(int x[], int n)
{
    for (int i = 0; i < n; ++i)
        x[i] = n;
}

void caller()
{
    // local space on the stack - destroyed when caller() returns
    int x[10];
    fn(x, sizeof x / sizeof x[0]);

    // or, use the heap, lives until delete[](p) called...
    int* p = new int[10];
    fn(p, 10);
}

Another option is to wrap the array in a structure, which - unlike raw arrays - are legal to return by value from a function:

struct X
{
    int x[10];
};

X fn()
{
    X x;
    x.x[0] = 10;
    // ...
    return x;
}

void caller()
{
    X x = fn();
}

Starting with the above, if you're stuck using C++03 you might want to generalise it into something closer to the C++11 std::array:

template <typename T, size_t N>
struct array
{
    T& operator[](size_t n) { return x[n]; }
    const T& operator[](size_t n) const { return x[n]; }
    size_t size() const { return N; }
    // iterators, constructors etc....
  private:
    T x[N];
};

Another option is to have the called function allocate memory on the heap:

int* fn()
{
    int* p = new int[2];
    p[0] = 0;
    p[1] = 1;
    return p;
}

void caller()
{
    int* p = fn();
    // use p...
    delete[] p;
}

To help simplify the management of heap objects, many C++ programmers use "smart pointers" that ensure deletion when the pointer(s) to the object leave their scopes. With C++11:

std::shared_ptr<int> p(new int[2], [](int* p) { delete[] p; } );
std::unique_ptr<int[]> p(new int[3]);

If you're stuck on C++03, the best option is to see if the boost library is available on your machine: it provides boost::shared_array.

Yet another option is to have some static memory reserved by fn(), though this is NOT THREAD SAFE, and means each call to fn() overwrites the data seen by anyone keeping pointers from previous calls. That said, it can be convenient (and fast) for simple single-threaded code.

int* fn(int n)
{
    static int x[2];  // clobbered by each call to fn()
    x[0] = n;
    x[1] = n + 1;
    return x;  // every call to fn() returns a pointer to the same static x memory
}

void caller()
{
    int* p = fn(3);
    // use p, hoping no other thread calls fn() meanwhile and clobbers the values...
    // no clean up necessary...
}

How can I use a reportviewer control in an asp.net mvc 3 razor view?

Here is the complete solution for directly integrating a report-viewer control (as well as any asp.net server side control) in an MVC .aspx view, which will also work on a report with multiple pages (unlike Adrian Toman's answer) and with AsyncRendering set to true, (based on "Pro ASP.NET MVC Framework" by Steve Sanderson).

What one needs to do is basically:

  1. Add a form with runat = "server"

  2. Add the control, (for report-viewer controls it can also sometimes work even with AsyncRendering="True" but not always, so check in your specific case)

  3. Add server side scripting by using script tags with runat = "server"

  4. Override the Page_Init event with the code shown below, to enable the use of PostBack and Viewstate

Here is a demonstration:

<form ID="form1" runat="server">
    <rsweb:ReportViewer ID="ReportViewer1" runat="server" />
</form>
<script runat="server">
    protected void Page_Init(object sender, EventArgs e)
    {
        Context.Handler = Page;
    }
    //Other code needed for the report viewer here        
</script>

It is of course recommended to fully utilize the MVC approach, by preparing all needed data in the controller, and then passing it to the view via the ViewModel.

This will allow reuse of the View!

However this is only said for data this is needed for every post back, or even if they are required only for initialization if it is not data intensive, and the data also has not to be dependent on the PostBack and ViewState values.

However even data intensive can sometimes be encapsulated into a lambda expression and then passed to the view to be called there.

A couple of notes though:

  • By doing this the view essentially turns into a web form with all it's drawbacks, (i.e. Postbacks, and the possibility of non Asp.NET controls getting overriden)
  • The hack of overriding Page_Init is undocumented, and it is subject to change at any time

What is the best way to add options to a select from a JavaScript object with jQuery?

If you don't have to support old IE versions, using the Option constructor is clearly the way to go, a readable and efficient solution:

$(new Option('myText', 'val')).appendTo('#mySelect');

It's equivalent in functionality to, but cleaner than:

$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');

How do I pass command line arguments to a Node.js program?

I extended the getArgs function just to get also commands, as well as flags (-f, --anotherflag) and named args (--data=blablabla):

  1. The module
/**
 * @module getArgs.js
 * get command line arguments (commands, named arguments, flags)
 *
 * @see https://stackoverflow.com/a/54098693/1786393
 *
 * @return {Object}
 *
 */
function getArgs () {
  const commands = []
  const args = {}
  process.argv
    .slice(2, process.argv.length)
    .forEach( arg => {
      // long arg
      if (arg.slice(0,2) === '--') {
        const longArg = arg.split('=')
        const longArgFlag = longArg[0].slice(2,longArg[0].length)
        const longArgValue = longArg.length > 1 ? longArg[1] : true
        args[longArgFlag] = longArgValue
     }
     // flags
      else if (arg[0] === '-') {
        const flags = arg.slice(1,arg.length).split('')
        flags.forEach(flag => {
          args[flag] = true
        })
      }
     else {
      // commands
      commands.push(arg)
     } 
    })
  return { args, commands }
}


// test
if (require.main === module) {
  // node getArgs test --dir=examples/getUserName --start=getUserName.askName
  console.log( getArgs() )
}

module.exports = { getArgs }

  1. Usage example:
$ node lib/getArgs test --dir=examples/getUserName --start=getUserName.askName
{
  args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
  commands: [ 'test' ]
}

$ node lib/getArgs --dir=examples/getUserName --start=getUserName.askName test tutorial
{
  args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
  commands: [ 'test', 'tutorial' ]
}

How to run bootRun with spring profile via gradle task

Simplest way would be to define default and allow it to be overridden. I am not sure what is the use of systemProperty in this case. Simple arguments will do the job.

def profiles = 'prod'

bootRun {
  args = ["--spring.profiles.active=" + profiles]
}

To run dev:

./gradlew bootRun -Pdev

To add dependencies on your task you can do something like this:

task setDevProperties(dependsOn: bootRun) << {
  doFirst {
    System.setProperty('spring.profiles.active', profiles)
  }
}

There are lots of ways achieving this in Gradle.

Edit:

Configure separate configuration files per environment.

if (project.hasProperty('prod')) {
  apply from: 'gradle/profile_prod.gradle'
} else {
  apply from: 'gradle/profile_dev.gradle'
}

Each configuration can override tasks for example:

def profiles = 'prod'
bootRun {
  systemProperty "spring.profiles.active", activeProfile
}

Run by providing prod flag in this case just like that:

./gradlew <task> -Pprod

Store text file content line by line into array

Try this:

String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)          
    arr[i++] = str;

System.out.println(Arrays.toString(arr));

Return empty cell from formula in Excel

This answer does not fully deal with the OP, but there are have been several times I have had a similar problem and searched for the answer.

If you can recreate the formula or the data if needed (and from your description it looks as if you can), then when you are ready to run the portion that requires the blank cells to be actually empty, then you can select the region and run the following vba macro.

Sub clearBlanks()
    Dim r As Range
    For Each r In Selection.Cells
        If Len(r.Text) = 0 Then
            r.Clear
        End If
    Next r
End Sub

this will wipe out off of the contents of any cell which is currently showing "" or has only a formula

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

Removing Duplicate Values from ArrayList

List<String> list = new ArrayList<String>();
        list.add("Krishna");
        list.add("Krishna");
        list.add("Kishan");
        list.add("Krishn");
        list.add("Aryan");
        list.add("Harm");

HashSet<String> hs=new HashSet<>(list);

System.out.println("=========With Duplicate Element========");
System.out.println(list);
System.out.println("=========Removed Duplicate Element========");
System.out.println(hs);

System.Net.WebException HTTP status code

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

Difference between scaling horizontally and vertically for databases

Traditional relational databases were designed as client/server database systems. They can be scaled horizontally but the process to do so tends to be complex and error prone. NewSQL databases like NuoDB are memory-centric distributed database systems designed to scale out horizontally while maintaining the SQL/ACID properties of traditional RDBMS.

For more information on NuoDB, read their technical white paper.

set font size in jquery

Not saying this is better, just another way:

$("#elem")[0].style.fontSize="20px";

How to convert a string of bytes into an int?

A decently speedy method utilizing array.array I've been using for some time:

predefined variables:

offset = 0
size = 4
big = True # endian
arr = array('B')
arr.fromstring("\x00\x00\xff\x00") # 5 bytes (encoding issues) [0, 0, 195, 191, 0]

to int: (read)

val = 0
for v in arr[offset:offset+size][::pow(-1,not big)]: val = (val<<8)|v

from int: (write)

val = 16384
arr[offset:offset+size] = \
    array('B',((val>>(i<<3))&255 for i in range(size)))[::pow(-1,not big)]

It's possible these could be faster though.

EDIT:
For some numbers, here's a performance test (Anaconda 2.3.0) showing stable averages on read in comparison to reduce():

========================= byte array to int.py =========================
5000 iterations; threshold of min + 5000ns:
______________________________________code___|_______min______|_______max______|_______avg______|_efficiency
????????????????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????
    val = 0 \nfor v in arr: val = (val<<8)|v |     5373.848ns |   850009.965ns |     ~8649.64ns |  62.128%
????????????????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????
                  val = reduce( shift, arr ) |     6489.921ns |  5094212.014ns |   ~12040.269ns |  53.902%

This is a raw performance test, so the endian pow-flip is left out.
The shift function shown applies the same shift-oring operation as the for loop, and arr is just array.array('B',[0,0,255,0]) as it has the fastest iterative performance next to dict.

I should probably also note efficiency is measured by accuracy to the average time.

How to stop a function

def player(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over: 
        computer(game_over)  #We are only going to do this if check_winner comes back as False

def check_winner(): 
    check something
    #here needs to be an if / then statement deciding if the game is over, return True if over, false if not
    if score == 100:
        return True
    else:
        return False

def computer(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over:
        player(game_over) #We are only going to do this if check_winner comes back as False

game_over = False   #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over)   #Start your loops, sending in the status of game_over

Above is a pretty simple example... I made up a statement for check_winner using score = 100 to denote the game being over.

You will want to use similar method of passing score into check_winner, using game_over = check_winner(score). Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

My go environment looked similar to yours.

$go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go-1.6"
GOTOOLDIR="/usr/lib/go-1.6/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT="1"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

I resolved it with setting GOPATH to /usr/lib/go. Try it out.

export GOPATH=/usr/lib/go
export PATH=$PATH:$GOPATH/bin

Checking password match while typing

if we use bootstrap our text will be green or red depending on the result

HTML

<div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">New Password</span>
<input type="password" id="txtNewPassword" class="form-control">     
        </label>
        </div>
        <div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">Confirm Password
        </span>
        <input class="form-control" type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();">   
            </label>
        </div>
        <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>

CSS

.text-success {
    color: #28a745;
}
.text-danger {
    color: #dc3545;
}

JS

function checkPasswordMatch() {
        var password = $("#txtNewPassword").val();
        var confirmPassword = $("#txtConfirmPassword").val();

        if (password != confirmPassword)
            $("#divCheckPasswordMatch").html("Passwords do not match!").addClass('text-danger').removeClass('text-success');

        else
            $("#divCheckPasswordMatch").html("Passwords match.").addClass('text-success').removeClass('text-danger');
    }

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

SVN Commit specific files

I make a (sub)folder named "hide", move the file I don't want committed to there. Then do my commit, ignoring complaint about the missing file. Then move the hidden file from hide back to ./

I know of no downside to this tactic.

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

Force DOM redraw/refresh on Chrome/Mac

This solution without timeouts! Real force redraw! For Android and iOS.

var forceRedraw = function(element){
  var disp = element.style.display;
  element.style.display = 'none';
  var trick = element.offsetHeight;
  element.style.display = disp;
};

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

Load an image from a url into a PictureBox

yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"

How to combine date from one field with time from another field - MS SQL Server

  1. If both of your fields are datetime then simply adding those will work.

    eg:

    Declare @d datetime, @t datetime
    set @d = '2009-03-12 00:00:00.000';
    set @t = '1899-12-30 12:30:00.000';
    select @d + @t
    
  2. If you used Date & Time datatype then just cast the time to datetime

    eg:

    Declare @d date, @t time
    set @d = '2009-03-12';
    set @t = '12:30:00.000';
    select @d + cast(@t as datetime)
    

How to create file object from URL object (image)

Use Apache Common IO's FileUtils:

import org.apache.commons.io.FileUtils

FileUtils.copyURLToFile(url, f);

The method downloads the content of url and saves it to f.

$(window).height() vs $(document).height

AFAIK $(window).height(); returns the height of your window and $(document).height(); returns the height of your document

Sort a list of tuples by 2nd item (integer value)

As a python neophyte, I just wanted to mention that if the data did actually look like this:

data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

then sorted() would automatically sort by the second element in the tuple, as the first elements are all identical.

Verify object attribute value with mockito

If you're using Java 8, you can use Lambda expressions to match.

import java.util.Optional;
import java.util.function.Predicate;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;

public class LambdaMatcher<T> extends BaseMatcher<T>
{
    private final Predicate<T> matcher;
    private final Optional<String> description;

    public LambdaMatcher(Predicate<T> matcher)
    {
        this(matcher, null);
    }

    public LambdaMatcher(Predicate<T> matcher, String description)
    {
        this.matcher = matcher;
        this.description = Optional.ofNullable(description);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean matches(Object argument)
    {
        return matcher.test((T) argument);
    }

    @Override
    public void describeTo(Description description)
    {
        this.description.ifPresent(description::appendText);
    }
}

Example call

@Test
public void canFindEmployee()
{
    Employee employee = new Employee("John");
    company.addEmployee(employee);

    verify(mockedDal).registerEmployee(argThat(new LambdaMatcher<>(e -> e.getName()
                                                                         .equals(employee.getName()))));
}

More info: http://source.coveo.com/2014/10/01/java8-mockito/

I'm getting Key error in python

For example, if this is a number :

ouloulou={
    1:US,
    2:BR,
    3:FR
    }
ouloulou[1]()

It's work perfectly, but if you use for example :

ouloulou[input("select 1 2 or 3"]()

it's doesn't work, because your input return string '1'. So you need to use int()

ouloulou[int(input("select 1 2 or 3"))]()

How to create a horizontal loading progress bar?

It is Widget.ProgressBar.Horizontal on my phone, if I set android:indeterminate="true"

How to show live preview in a small popup of linked page on mouse over on link?

HTML structure

<div id="app">
<div class="box">
    <div class="title">How to preview link with iframe and javascript?</div>
    <div class="note"><small>Note: Click to every link on content below to preview</small></div>
    <div id="content">
        We'll first attach all the events to all the links for which we want to <a href="https://htmlcssdownload.com/">preview</a> with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
    </div>
    <h3>Preview the link</h3>
    <div id="result"></div>
</div>

We'll first attach all the events to all the links for which we want to preview with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.

<script type="text/javascript">
(()=>{
    let content = document.getElementById('content');
    let links = content.getElementsByTagName('a');
    for (let index = 0; index < links.length; index++) {
        const element = links[index];
        element.addEventListener('click',(e)=>{
            e.preventDefault();
            openDemoLink(e.target.href);
        })
    }

    function openDemoLink(link){

        let div = document.createElement('div');
        div.classList.add('preview_frame');
        
        let frame = document.createElement('iframe');
        frame.src = link;
        
        let close = document.createElement('a');
        close.classList.add('close-btn');
        close.innerHTML = "Click here to close the example";
        close.addEventListener('click', function(e){
            div.remove();
        })
        
        div.appendChild(frame);
        div.appendChild(close);
        
        document.getElementById('result').appendChild(div);
    }
})()

To see detail at How to live preview link

How to get the Enum Index value in C#

By default the underlying type of each element in the enum is integer.

enum Values
{
   A,
   B,
   C
}

You can also specify custom value for each item:

enum Values
{
   A = 10,
   B = 11,
   C = 12
}
int x = (int)Values.A; // x will be 10;

Note: By default, the first enumerator has the value 0.

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

commands not found on zsh

It's evident that you've managed to mess up your PATH variable. (Your current PATH doesn't contain any location where common utilities are located.)

Try:

PATH=/bin:/usr/bin:/usr/local/bin:${PATH}
export PATH

Alternatively, for "resetting" zsh, specify the complete path to the shell:

exec /bin/zsh

or

exec /usr/bin/zsh

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
    </div>
</div>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->
 ....

  <button type="submit">Submit</button>
</form>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   }
   else {
        alert('Not all fields valid! Do something...');
    }

 }

Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:
!myForm.username.$pristine

You could also use:
myForm.username.$dirty

How to delete specific characters from a string in Ruby?

Using String#gsub with regular expression:

"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "

This will remove surrounding parentheses only.

"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "

How can I make my website's background transparent without making the content (images & text) transparent too?

There is a css3 solution here if that is acceptable. It supports the graceful degradation approach where css3 isn't supported. you just won't have any transparency.

body {
    font-family: tahoma, helvetica, arial, sans-serif;
    font-size: 12px;
    text-align: center;
    background: #000;
    color: #ddd4d4;
    padding-top: 12px;
    line-height: 2;
    background-image: url('images/background.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    background: rgb(0, 0, 0); /* for older browsers */
    background: rgba(0, 0, 0, 0.8); /* R, G, B, A */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#CC000000, endColorstr=#CC0000); /* AA, RR, GG, BB */

}

to get the hex equivalent of 80% (CC) take (pct / 100) * 255 and convert to hex.

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

I believe you need to reference the current HttpContext if you are outside of the controller. The MVC controllers have a base reference to the current context. However, outside of that, you have to explicitly declare you want the current HttpContext

return HttpContext.Current.GetOwinContext().Authentication;

As for it not showing up, a new MVC 5 project template using the code you show above (the IAuthenticationManager) has the following using statements at the top of the account controller:

using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using WebApplication2.Models;

Commenting out each one, it appears the GetOwinContext() is actually a part of the System.Web.Mvc assembly.

refresh both the External data source and pivot tables together within a time schedule

Auto Refresh Workbook for example every 5 sec. Apply to module

Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll

alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"

End Sub

Apply to Workbook on Open

Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub

:)