Programs & Examples On #Dllregistration

How do I register a .NET DLL file in the GAC?

  • Run Developer Command Prompt For V2012 or any version installed in your system

  • gacutil /i pathofDll

  • Enter

Done!!!

ActiveX component can't create object

I had this problem too. I was trying to run an old 32-bit dll in a 64 bit system. I got it working by copying the .dll to the C:\Windows\SysWoW64\ directory and running this:

%systemroot%\SysWoW64\regsvr32 "C:\Windows\SysWoW64\thenameofyourdll.dll"

And also enabling IIS to run 32 bit apps

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

How to repair COMException error 80040154?

I had the same issue in a Windows Service. All keys where in the right place in the registry. The build of the service was done for x86 and I still got the exception. I found out about CorFlags.exe

Run this on your service.exe without flags to verify if you run under 32 bit. If not run it with the flag /32BIT+ /Force (Force only for signed assemblies)

If you have UAC turned you can get the following error: corflags : error CF001 : Could not open file for writing Give the user full control on the assemblies.

Console output

How do I register a DLL file on Windows 7 64-bit?

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type: regsvr32 MyComobject.dll

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.

I had a command button on a row of a datatable (the extended version, so <hx:datatable>) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).

I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope. The data backing the table itself was in a sort of ViewScope (in reality, temporarily in SessionScope).

If the row display was increased via the control which value was also bound to the datatable's rows attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.

Placing this attribute in the same scope as the table data itself fixed the problem.

I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

For Android Mobile Devices

LDPI- icon-36x36, splash-426x320 (now with correct values)


MDPI- icon-48x48, splash-470x320


HDPI- icon 72x72, splash- 640x480


XHDPI- icon-96x96, splash- 960x720


XXHDPI- icon- 144x144

All in pixels.

For Android Tablet Devices

LDPI:
    Portrait: 200x320px
    Landscape: 320x200px
MDPI:
    Portrait: 320x480px
    Landscape: 480x320px
HDPI:
    Portrait: 480x800px
    Landscape: 800x480px
XHDPI:
    Portrait: 720px1280px
    Landscape: 1280x720px

How to filter (key, value) with ng-repeat in AngularJs?

It is kind of late, but I looked for e similar filter and ended using something like this:

<div ng-controller="TestCtrl">
 <div ng-repeat="(k,v) in items | filter:{secId: '!!'}">
   {{k}} {{v.pos}}
 </div>
</div>

Hidden features of Windows batch files

FIND as a replacement for grep.
I hacked a little "phonebook" for myself with find. Very usefull:

@echo off
:begin
set /p term=Enter query: 
type phonebookfile.txt |find /i "%term%"
if %errorlevel% == 0 GOTO :choose
echo No entry found
set /p new_entry=Add new entry: 
echo %new_entry% >> phonebookfile.txt 
:choose
set /p action=(q)uit, (n)ew query or (e)dit? [q] 
if "%action%"=="n" GOTO anfang
if "%action%"=="e" (
    notepad phonebookfile.txt
    goto :choose
)

Very fast and effective.

How to update /etc/hosts file in Docker image during "docker build"

Since this still comes up as a first answer in Google I'll contribute possible solution.

Command taken from here suprisingly worked for me (Docker 1.13.1, Ubuntu 16.04) :

docker exec -u 0 <container-name> /bin/sh -c "echo '<ip> <name> >> /etc/hosts"

Javascript: Load an Image from url and display

Are you after something like this:

 <html>
 <head>
    <title>Z Test</title>
 </head>
 <body>

<div id="img_home"></div>

<button onclick="addimage()" type="button">Add an image</button>

<script>
function addimage() {
    var img = new Image();
    img.src = "https://www.google.com/images/srpr/logo4w.png"
    img_home.appendChild(img);
}
</script>
</body>

How to do encryption using AES in Openssl

Check out this link it has a example code to encrypt/decrypt data using AES256CBC using EVP API.

https://github.com/saju/misc/blob/master/misc/openssl_aes.c

Also you can check the use of AES256 CBC in a detailed open source project developed by me at https://github.com/llubu/mpro

The code is detailed enough with comments and if you still need much explanation about the API itself i suggest check out this book Network Security with OpenSSL by Viega/Messier/Chandra (google it you will easily find a pdf of this..) read chapter 6 which is specific to symmetric ciphers using EVP API.. This helped me a lot actually understanding the reasons behind using various functions and structures of EVP.

and if you want to dive deep into the Openssl crypto library, i suggest download the code from the openssl website (the version installed on your machine) and then look in the implementation of EVP and aeh api implementation.

One more suggestion from the code you posted above i see you are using the api from aes.h instead use EVP. Check out the reason for doing this here OpenSSL using EVP vs. algorithm API for symmetric crypto nicely explained by Daniel in one of the question asked by me..

CSS disable text selection

Use a wild card selector * for this purpose.

#div * { /* Narrowing, to specific elements, like  input, textarea is PREFFERED */
 -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

Now, every element inside a div with id div will have no selection.

Demo

Add Whatsapp function to website, like sms, tel

This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

How do you check what version of SQL Server for a database using TSQL?

Here's a bit of script I use for testing if a server is 2005 or later

declare @isSqlServer2005 bit
select @isSqlServer2005 = case when CONVERT(int, SUBSTRING(CONVERT(varchar(15), SERVERPROPERTY('productversion')), 0, CHARINDEX('.', CONVERT(varchar(15), SERVERPROPERTY('productversion'))))) < 9 then 0 else 1 end
select @isSqlServer2005

Note : updated from original answer (see comment)

Undefined behavior and sequence points

This is a follow up to my previous answer and contains C++11 related material..


Pre-requisites : An elementary knowledge of Relations (Mathematics).


Is it true that there are no Sequence Points in C++11?

Yes! This is very true.

Sequence Points have been replaced by Sequenced Before and Sequenced After (and Unsequenced and Indeterminately Sequenced) relations in C++11.


What exactly is this 'Sequenced before' thing?

Sequenced Before(§1.9/13) is a relation which is:

between evaluations executed by a single thread and induces a strict partial order1

Formally it means given any two evaluations(See below) A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced 2.

Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which3.

[NOTES]
1 : A strict partial order is a binary relation "<" over a set P which is asymmetric, and transitive, i.e., for all a, b, and c in P, we have that:
........(i). if a < b then ¬ (b < a) (asymmetry);
........(ii). if a < b and b < c then a < c (transitivity).
2 : The execution of unsequenced evaluations can overlap.
3 : Indeterminately sequenced evaluations cannot overlap, but either could be executed first.


What is the meaning of the word 'evaluation' in context of C++11?

In C++11, evaluation of an expression (or a sub-expression) in general includes:

  • value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and

  • initiation of side effects.

Now (§1.9/14) says:

Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.

  • Trivial example:

    int x; x = 10; ++x;

    Value computation and side effect associated with ++x is sequenced after the value computation and side effect of x = 10;


So there must be some relation between Undefined Behaviour and the above-mentioned things, right?

Yes! Right.

In (§1.9/15) it has been mentioned that

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced4.

For example :

int main()
{
     int num = 19 ;
     num = (num << 3) + (num >> 3);
} 
  1. Evaluation of operands of + operator are unsequenced relative to each other.
  2. Evaluation of operands of << and >> operators are unsequenced relative to each other.

4: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations.

(§1.9/15) The value computations of the operands of an operator are sequenced before the value computation of the result of the operator.

That means in x + y the value computation of x and y are sequenced before the value computation of (x + y).

More importantly

(§1.9/15) If a side effect on a scalar object is unsequenced relative to either

(a) another side effect on the same scalar object

or

(b) a value computation using the value of the same scalar object.

the behaviour is undefined.

Examples:

int i = 5, v[10] = { };
void  f(int,  int);
  1. i = i++ * ++i; // Undefined Behaviour
  2. i = ++i + i++; // Undefined Behaviour
  3. i = ++i + ++i; // Undefined Behaviour
  4. i = v[i++]; // Undefined Behaviour
  5. i = v[++i]: // Well-defined Behavior
  6. i = i++ + 1; // Undefined Behaviour
  7. i = ++i + 1; // Well-defined Behaviour
  8. ++++i; // Well-defined Behaviour
  9. f(i = -1, i = -1); // Undefined Behaviour (see below)

When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [Note: Value computations and side effects associated with different argument expressions are unsequenced. — end note]

Expressions (5), (7) and (8) do not invoke undefined behaviour. Check out the following answers for a more detailed explanation.


Final Note :

If you find any flaw in the post please leave a comment. Power-users (With rep >20000) please do not hesitate to edit the post for correcting typos and other mistakes.

How to maintain aspect ratio using HTML IMG tag

None of the methods listed scale the image to the largest possible size that fits in a box while retaining the desired aspect ratio.

This cannot be done with the IMG tag (at least not without a bit of JavaScript), but it can be done as follows:

 <div style="background:center no-repeat url(...);background-size:contain;width:...;height:..."></div>

How to print out more than 20 items (documents) in MongoDB's shell?

From the shell if you want to show all results you could do db.collection.find().toArray() to get all results without it.

Is JavaScript a pass-by-reference or pass-by-value language?

I have found the extend method of the Underscore.js library very useful when I want to pass in an object as a parameter which may either be modified or replaced entirely.

function replaceOrModify(aObj) {
  if (modify) {

    aObj.setNewValue('foo');

  } else {

   var newObj = new MyObject();
   // _.extend(destination, *sources) 
   _.extend(newObj, aObj);
  }
}

Countdown timer using Moment js

Timezones. You have to deal with them, by using getTimezoneOffset() if you want your visitors from around the wolrd to get the same time.

Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.

var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT

var eventTime = new Date();
eventTime.setTime(366549200);

var Offset = new Date(eventTime.getTimezoneOffset()*60000)

var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
  $('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);

Django 1.7 - makemigrations not detecting changes

Following worked for me:

  1. Add the app name to settings.py
  2. use 'python manage.py makemigrations'
  3. use 'python manage.py migrate'

Worked for me: Python 3.4, Django 1.10

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

How to make a Java Generic method static?

I'll explain it in a simple way.

Generics defined at Class level are completely separate from the generics defined at the (static) method level.

class Greet<T> {

    public static <T> void sayHello(T obj) {
        System.out.println("Hello " + obj);
    }
}

When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.

class Greet<T> {

    public static <E> void sayHello(E obj) {
        System.out.println("Hello " + obj);
    }
}

Why the static method needs to have its own generics separate from those of the Class?

This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.

So, whenever you are calling the static method,

Greet.sayHello("Bob");
Greet.sayHello(123);

JVM interprets it as the following.

Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);

Both giving the same outputs.

Hello Bob
Hello 123

How do I create a Bash alias?

create a bash_profile at your user root - ex

/user/username/.bash_profile

open file

vim ~/.bash_profile

add alias as ex. (save and exit)

alias mydir="cd ~/Documents/dirname/anotherdir"

in new terminal just type mydir - it should open

/user/username/Documents/dirname/anotherdir

Reduce left and right margins in matplotlib plot

All you need is

plt.tight_layout()

before your output.

In addition to cutting down the margins, this also tightly groups the space between any subplots:

x = [1,2,3]
y = [1,4,9]
import matplotlib.pyplot as plt
fig = plt.figure()
subplot1 = fig.add_subplot(121)
subplot1.plot(x,y)
subplot2 = fig.add_subplot(122)
subplot2.plot(y,x)
fig.tight_layout()
plt.show()

How to find list of possible words from a letter matrix [Boggle Solver]

Here is my java implementation: https://github.com/zouzhile/interview/blob/master/src/com/interview/algorithms/tree/BoggleSolver.java

Trie build took 0 hours, 0 minutes, 1 seconds, 532 milliseconds
Word searching took 0 hours, 0 minutes, 0 seconds, 92 milliseconds

eel eeler eely eer eke eker eld eleut elk ell 
elle epee epihippus ere erept err error erupt eurus eye 
eyer eyey hip hipe hiper hippish hipple hippus his hish 
hiss hist hler hsi ihi iphis isis issue issuer ist 
isurus kee keek keeker keel keeler keep keeper keld kele 
kelek kelep kelk kell kelly kelp kelper kep kepi kept 
ker kerel kern keup keuper key kyl kyle lee leek 
leeky leep leer lek leo leper leptus lepus ler leu 
ley lleu lue lull luller lulu lunn lunt lunule luo 
lupe lupis lupulus lupus lur lure lurer lush lushly lust 
lustrous lut lye nul null nun nupe nurture nurturer nut 
oer ore ort ouphish our oust out outpeep outpeer outpipe 
outpull outpush output outre outrun outrush outspell outspue outspurn outspurt 
outstrut outstunt outsulk outturn outusure oyer pee peek peel peele 
peeler peeoy peep peeper peepeye peer pele peleus pell peller 
pelu pep peplus pepper pepperer pepsis per pern pert pertussis 
peru perule perun peul phi pip pipe piper pipi pipistrel 
pipistrelle pipistrellus pipper pish piss pist plup plus plush ply 
plyer psi pst puerer pul pule puler pulk pull puller 
pulley pullus pulp pulper pulu puly pun punt pup puppis 
pur pure puree purely purer purr purre purree purrel purrer 
puru purupuru pus push puss pustule put putt puture ree 
reek reeker reeky reel reeler reeper rel rely reoutput rep 
repel repeller repipe reply repp reps reree rereel rerun reuel 
roe roer roey roue rouelle roun roup rouper roust rout 
roy rue ruelle ruer rule ruler rull ruller run runt 
rupee rupert rupture ruru rus rush russ rust rustre rut 
shi shih ship shipper shish shlu sip sipe siper sipper 
sis sish sisi siss sissu sist sistrurus speel speer spelk 
spell speller splurt spun spur spurn spurrer spurt sput ssi 
ssu stre stree streek streel streeler streep streke streperous strepsis 
strey stroup stroy stroyer strue strunt strut stu stue stull 
stuller stun stunt stupe stupeous stupp sturnus sturt stuss stut 
sue suer suerre suld sulk sulker sulky sull sully sulu 
sun sunn sunt sunup sup supe super superoutput supper supple 
supplely supply sur sure surely surrey sus susi susu susurr 
susurrous susurrus sutu suture suu tree treey trek trekker trey 
troupe trouper trout troy true truer trull truller truly trun 
trush truss trust tshi tst tsun tsutsutsi tue tule tulle 
tulu tun tunu tup tupek tupi tur turn turnup turr 
turus tush tussis tussur tut tuts tutu tutulus ule ull 
uller ulu ululu unreel unrule unruly unrun unrust untrue untruly 
untruss untrust unturn unurn upper upperer uppish uppishly uppull uppush 
upspurt upsun upsup uptree uptruss upturn ure urn uro uru 
urus urushi ush ust usun usure usurer utu yee yeel 
yeld yelk yell yeller yelp yelper yeo yep yer yere 
yern yoe yor yore you youl youp your yourn yoy 

Note: I used the dictionary and character matrix at the beginning of this thread. The code was run on my MacBookPro, below is some information about the machine.

Model Name: MacBook Pro
Model Identifier: MacBookPro8,1
Processor Name: Intel Core i5
Processor Speed: 2.3 GHz
Number Of Processors: 1
Total Number Of Cores: 2
L2 Cache (per core): 256 KB
L3 Cache: 3 MB
Memory: 4 GB
Boot ROM Version: MBP81.0047.B0E
SMC Version (system): 1.68f96

ES6 Map in Typescript

With the lib config option your are able to cherry pick Map into your project. Just add es2015.collection to your lib section. When you have no lib config add one with the defaults and add es2015.collection.

So when you have target: es5, change tsconfig.json to:

"target": "es5",
"lib": [ "dom", "es5", "scripthost", "es2015.collection" ],

Python: Adding element to list while iterating

You can do this.

bonus_rows = []
for a in myarr:
  if somecond(a):
      bonus_rows.append(newObj())
myarr.extend( bonus_rows )

How to convert unix timestamp to calendar date moment.js

moment(1454521239279).toDate()
moment(1454521239279).format()

grant remote access of MySQL database from any IP address

To remotely access database Mysql server 8:

CREATE USER 'root'@'%' IDENTIFIED BY 'Pswword@123';

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

FLUSH PRIVILEGES;

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

How to get the previous page URL using 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.

For vs. while in C programming?

You should use such a loop, that most fully conforms to your needs. For example:

for(int i = 0; i < 10; i++)
{
    print(i);
}

//or

int i = 0;
while(i < 10)
{
    print(i);
    i++;
}

Obviously, in such situation, "for" looks better, than "while". And "do while" shoud be used when some operations must be done already before the moment when condition of your loop will be checked.

Sorry for my bad english).

Deleting Row in SQLite in Android

Guys this is a generic method you can use for all your tables, Worked perfectly in my case.

public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
    String whereClause = columnName + "=?";
    String[] whereArgs = new String[]{String.valueOf(keyValue)};
    yourDatabase.delete(tableName, whereClause, whereArgs);
}

How do you embed binary data in XML?

You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject.

Handling Binary Data in XML Documents

How to get Top 5 records in SqLite?

select * from [Table_Name] limit 5

What is a 'NoneType' object?

In Python, to represent the absence of a value, you can use the None value types.NoneType.None

Change visibility of ASP.NET label with JavaScript

If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:

<asp:Label runat="server" id="Label1" style="display: none;" />

Then, you could make it visible on the client side with:

document.getElementById('Label1').style.display = 'inherit';

You could make it hidden again with:

document.getElementById('Label1').style.display = 'none';

Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.

Why are C++ inline functions in the header?

The c++ inline keyword is misleading, it doesn't mean "inline this function". If a function is defined as inline, it simply means that it can be defined multiple times as long as all definitions are equal. It's perfectly legal for a function marked inline to be a real function that is called instead of getting code inlined at the point where it's called.

Defining a function in a header file is needed for templates, since e.g. a templated class isn't really a class, it's a template for a class which you can make multiple variations of. In order for the compiler to be able to e.g. make a Foo<int>::bar() function when you use the Foo template to create a Foo class, the actual definition of Foo<T>::bar() must be visible.

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

make *** no targets specified and no makefile found. stop

If you create Makefile in the VSCode, your makefile doesnt run. I don't know the cause of this issue. Maybe the configuration of the file is not added to system. But I solved this way. delete created makefile, then go to project directory and right click mouse later create a file and named Makefile. After fill the Makefile and run it. It will work.

java.io.InvalidClassException: local class incompatible:

If you are using oc4j to deploy the ear.

Make sure you set in the project the correct path for deploy.home=

You can fiind deploy.home in common.properties file

The oc4j needs to reload the new created class in the ear so that the server class and the client class have the same serialVersionUID

How to convert int to float in python?

You can literally convert it into float using:


float_value = float(integer_value)

Likewise, you can convert an integer back to float datatype with:


integer_value = int(float_value)

Hope it helped. I advice you to read "Build-In Functions of Python" at this link: https://docs.python.org/2/library/functions.html

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

How to pass parameter to a promise function

You can use .bind() to pass the param(this) to the function.

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));

How to generate a unique hash code for string input in android...?

Let's take a look at the stock hashCode() method:

public int hashCode() {
    int h = hash;
    if (h == 0 && count > 0) {
        for (int i = 0; i < count; i++) {
            h = 31 * h + charAt(i);
        }
        hash = h;
    }
    return h;
}

The block of code above comes from the java.lang.String class. As you can see it is a 32 bit hash code which fair enough if you are using it on a small scale of data. If you are looking for hash code with more than 32 bit, you might wanna checkout this link: http://www.javamex.com/tutorials/collections/strong_hash_code_implementation.shtml

How to reset the state of a Redux store?

From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage, IndexedDB, Web SQL, etc) and do a hard refresh of the page using window.location.reload(). It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.

(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)

C# string reference type?

As others have stated, the String type in .NET is immutable and it's reference is passed by value.

In the original code, as soon as this line executes:

test = "after passing";

then test is no longer referring to the original object. We've created a new String object and assigned test to reference that object on the managed heap.

I feel that many people get tripped up here since there's no visible formal constructor to remind them. In this case, it's happening behind the scenes since the String type has language support in how it is constructed.

Hence, this is why the change to test is not visible outside the scope of the TestI(string) method - we've passed the reference by value and now that value has changed! But if the String reference were passed by reference, then when the reference changed we will see it outside the scope of the TestI(string) method.

Either the ref or out keyword are needed in this case. I feel the out keyword might be slightly better suited for this particular situation.

class Program
{
    static void Main(string[] args)
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(out test);
        Console.WriteLine(test);
        Console.ReadLine();
    }

    public static void TestI(out string test)
    {
        test = "after passing";
    }
}

How can I rename a conda environment?

You can rename your Conda env by just renaming the env folder. Here is the proof:

Conda env renaming

You can find your Conda env folder inside of C:\ProgramData\Anaconda3\envs or you can enter conda env list to see the list of conda envs and its location.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

I was with the same problem in devices with SDK < 22, but for me the reason is the MultiDex, the MultiDex.install must be in the attachBaseContext method.

If you are using MultiDex, try this:

public class YourApplication extends Application {

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this); //initialize other plugins 

    }
}

app/build.gradle:

android {

    compileSdkVersion 24
    buildToolsVersion "24.0.2"

    defaultConfig {
        applicationId "com.test.app"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }

....
}

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])

        compile 'com.android.support:appcompat-v7:24.2.1'
        ...
        compile 'com.google.firebase:firebase-messaging:9.6.1'
        compile 'com.google.android.gms:play-services:9.6.1'
        compile 'com.android.support:multidex:1.0.1'

    }
...

SQL query for getting data for last 3 months

Last 3 months

SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(mm,-3,GETDATE())),0)

Today

SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)

How store a range from excel into a Range variable?

Declare your dim as a variant, and pull the data as you would from an array. i.e.

Dim y As Variant
y = Range("A1:B2")

Now your excel range is all 1 variable (array), y

To pull the data, call the array position in the range "A1:B2" or whatever you choose. e.g.:

Msgbox y(1, 1)

This will return the top left box in the "A1:B2" range.

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Fastest way to ping a network range and return responsive hosts?

Try this for a unique list.

ping -c 5 -b 10.10.0.255 | grep 'bytes from' | awk '{ print $4 }' | sort | uniq

another method (fetches live hosts):

fping -ag 192.168.1.0/24

Can anyone explain me StandardScaler?

The idea behind StandardScaler is that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).

Pandas: drop a level from a multi-level column index?

Another way to drop the index is to use a list comprehension:

df.columns = [col[1] for col in df.columns]

   b  c
0  1  2
1  3  4

This strategy is also useful if you want to combine the names from both levels like in the example below where the bottom level contains two 'y's:

cols = pd.MultiIndex.from_tuples([("A", "x"), ("A", "y"), ("B", "y")])
df = pd.DataFrame([[1,2, 8 ], [3,4, 9]], columns=cols)

   A     B
   x  y  y
0  1  2  8
1  3  4  9

Dropping the top level would leave two columns with the index 'y'. That can be avoided by joining the names with the list comprehension.

df.columns = ['_'.join(col) for col in df.columns]

    A_x A_y B_y
0   1   2   8
1   3   4   9

That's a problem I had after doing a groupby and it took a while to find this other question that solved it. I adapted that solution to the specific case here.

Django model "doesn't declare an explicit app_label"

I had the same problem just now. I've fixed mine by adding a namespace on the app name. Hope someone find this helpful.

apps.py

from django.apps import AppConfig    

class SalesClientConfig(AppConfig):
        name = 'portal.sales_client'
        verbose_name = 'Sales Client'

Convert a string to a double - is this possible?

Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Code verified to work in Hibernate 4.3.0. Notice you can remove the XML filename parameter, or else provide your own path there. This is similar to (but typos corrected) other posts here, but this one is correct.

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;    


Configuration configuration = new Configuration();
configuration.configure("/com/rtw/test/hiber/hibernate.cfg.xml");
ServiceRegistry  serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();        
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

How to concatenate two strings in SQL Server 2005

I got a easy solution which will select from database table and let you do easily.

SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'

You can easily add a space there if you try

SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'

Here you can combine as much as your table have.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.

How to replace blank (null ) values with 0 for all records?

UPDATE table SET column=0 WHERE column IS NULL

Is Visual Studio Community a 30 day trial?

In my case it was most trivial solution - I just needed to run Vistual Studio as Administrator.

It's trivial thing, but i didn't see this mentioned anywhere.

Why doesn't Mockito mock static methods?

I seriously do think that it is code smell if you need to mock static methods, too.

  • Static methods to access common functionality? -> Use a singleton instance and inject that
  • Third party code? -> Wrap it into your own interface/delegate (and if necessary make it a singleton, too)

The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies. I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems
(e.g. https://code.google.com/p/powermock/issues/detail?id=355)

PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...

UILabel with text of two different colors

The way to do it is to use NSAttributedString like this:

NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];
[label setAttributedText: text];

I created a UILabel extension to do it.

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

Adding asterisk to required fields in Bootstrap 3

This CSS worked for me:

.form-group.required.control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -10px;
}

and this HTML:

<div class="form-group required control-label">
  <label for="emailField">Email</label>
  <input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>

Laravel - Model Class not found

Make sure to be careful when editing your model file. For example, in your post model:

<?php 
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $table = 'posts';    
}

You need to pay close attention to the class Post extend Model line. The class Post defined here will be your namespace for your controller.

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

javascript regular expression to check for IP addresses

Try this one.. Source from here.

"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

Why use 'virtual' for class properties in Entity Framework model definitions?

The virtual keyword in C# enables a method or property to be overridden by child classes. For more information please refer to the MSDN documentation on the 'virtual' keyword

UPDATE: This doesn't answer the question as currently asked, but I'll leave it here for anyone looking for a simple answer to the original, non-descriptive question asked.

Best way to run scheduled tasks

Create a custom Windows Service.

I had some mission-critical tasks set up as scheduled console apps and found them difficult to maintain. I created a Windows Service with a 'heartbeat' that would check a schedule in my DB every couple of minutes. It's worked out really well.

Having said that, I still use scheduled console apps for most of my non-critical maintenance tasks. If it ain't broke, don't fix it.

How to populate HTML dropdown list with values from database

My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?

<select name="owner">
<?php 
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

Is there a way to detect if a browser window is not currently active?

The Chromium team is currently developing the Idle Detection API. It is available as an origin trial since Chrome 88, which is already the 2nd origin trial for this feature. An earlier origin trial went from Chrome 84 through Chrome 86.

It can also be enabled via a flag:

Enabling via chrome://flags

To experiment with the Idle Detection API locally, without an origin trial token, enable the #enable-experimental-web-platform-features flag in chrome://flags.

A demo can be found here:

https://idle-detection.glitch.me/

It has to be noted though that this API is permission-based (as it should be, otherwise this could be misused to monitor a user's behaviour!).

What are the -Xms and -Xmx parameters when starting JVM?

-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.

-Xmx maximal heap size

Dynamically adding elements to ArrayList in Groovy

The Groovy way to do this is

def list = []
list << new MyType(...)

which creates a list and uses the overloaded leftShift operator to append an item

See the Groovy docs on Lists for lots of examples.

How to extract .war files in java? ZIP vs JAR

If you look at the JarFile API you'll see that it's a subclass of the ZipFile class.

The jar-specific classes mostly just add jar-specific functionality, like direct support for manifest file attributes and so on.

It's OOP "in action"; since jar files are zip files, the jar classes can use zip functionality and provide additional utility.

SQL Query Multiple Columns Using Distinct on One Column Only

you have various ways to distinct values on one column or multi columns.

  • using the GROUP BY

    SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
       o.tblFruit_FruitType,
       MAX(o.tblFruit_FruitName)
    FROM   tblFruit  AS o
    GROUP BY
         tblFruit_FruitType
    
  • using the subquery

    SELECT b.tblFruit_ID,
       b.tblFruit_FruitType,
       b.tblFruit_FruitName
    FROM   (
           SELECT DISTINCT(tblFruit_FruitType),
                  MIN(tblFruit_ID) tblFruit_ID
           FROM   tblFruit
           GROUP BY
                  tblFruit_FruitType
       ) AS a
       INNER JOIN tblFruit b
            ON  a.tblFruit_ID = b.tblFruit_I
    
  • using the join with subquery

    SELECT t1.tblFruit_ID,
        t1.tblFruit_FruitType,
        t1.tblFruit_FruitName
    FROM   tblFruit  AS t1
       INNER JOIN (
                SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                       tblFruit_FruitType
                FROM   tblFruit
                GROUP BY
                       tblFruit_FruitType
            )  AS t2
            ON  t1.tblFruit_ID = t2.tblFruit_ID 
    
  • using the window functions only one column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
        rn
           FROM   tblFruit
        ) t
        WHERE  rn = 1 
    
  • using the window functions multi column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
        ORDER BY tblFruit_ID) rn
              FROM   tblFruit
         ) t
        WHERE  rn = 1 
    

Html: Difference between cell spacing and cell padding

CellSpacing as the name suggests it is the Space between the Adjacent cells and CellPadding on the other hand means the padding around the cell content.

How to auto import the necessary classes in Android Studio with shortcut?

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

Screenshot

Parse large JSON file in Nodejs

I wrote a module that can do this, called BFJ. Specifically, the method bfj.match can be used to break up a large stream into discrete chunks of JSON:

const bfj = require('bfj');
const fs = require('fs');

const stream = fs.createReadStream(filePath);

bfj.match(stream, (key, value, depth) => depth === 0, { ndjson: true })
  .on('data', object => {
    // do whatever you need to do with object
  })
  .on('dataError', error => {
    // a syntax error was found in the JSON
  })
  .on('error', error => {
    // some kind of operational error occurred
  })
  .on('end', error => {
    // finished processing the stream
  });

Here, bfj.match returns a readable, object-mode stream that will receive the parsed data items, and is passed 3 arguments:

  1. A readable stream containing the input JSON.

  2. A predicate that indicates which items from the parsed JSON will be pushed to the result stream.

  3. An options object indicating that the input is newline-delimited JSON (this is to process format B from the question, it's not required for format A).

Upon being called, bfj.match will parse JSON from the input stream depth-first, calling the predicate with each value to determine whether or not to push that item to the result stream. The predicate is passed three arguments:

  1. The property key or array index (this will be undefined for top-level items).

  2. The value itself.

  3. The depth of the item in the JSON structure (zero for top-level items).

Of course a more complex predicate can also be used as necessary according to requirements. You can also pass a string or a regular expression instead of a predicate function, if you want to perform simple matches against property keys.

Printing tuple with string formatting in Python

t = (1, 2, 3)

# the comma (,) concatenates the strings and adds a space
print "this is a tuple", (t)

# format is the most flexible way to do string formatting
print "this is a tuple {0}".format(t)

# classic string formatting
# I use it only when working with older Python versions
print "this is a tuple %s" % repr(t)
print "this is a tuple %s" % str(t)

The openssl extension is required for SSL/TLS protection

I had the same problem. I tried everything listed on this page. When I re-installed Composer it worked like before. I had a PHP version mismatch that was corrected with a new install establishing the dependencies with the PHP path installed in my system environment variables.

I DO NOT RECOMMEND the composer config -g -- disable-tls true approach.

By the way the way to reverse this is composer config -g -- disable-tls false.

Refresh Fragment at reload

   MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
        getSupportFragmentManager().beginTransaction().detach(fragment).attach(fragment).commit();

this will only work if u use FragmentManager to initialize the fragment. If u have it as a <fragment ... /> in XML, it won't call the onCreateView again. Wasted my 30 minutes to figure this out.

Convert wchar_t to char

Technically, 'char' could have the same range as either 'signed char' or 'unsigned char'. For the unsigned characters, your range is correct; theoretically, for signed characters, your condition is wrong. In practice, very few compilers will object - and the result will be the same.

Nitpick: the last && in the assert is a syntax error.

Whether the assertion is appropriate depends on whether you can afford to crash when the code gets to the customer, and what you could or should do if the assertion condition is violated but the assertion is not compiled into the code. For debug work, it seems fine, but you might want an active test after it for run-time checking too.

Oracle query to identify columns having special characters

You can use regular expressions for this, so I think this is what you want:

select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

How to create virtual column using MySQL SELECT?

Try this one if you want to create a virtual column "age" within a select statement:

select brand, name, "10" as age from cars...

How to run shell script on host from docker container?

The solution I use is to connect to the host over SSH and execute the command like this:

ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"

UPDATE

As this answer keeps getting up votes, I would like to remind (and highly recommend), that the account which is being used to invoke the script should be an account with no permissions at all, but only executing that script as sudo (that can be done from sudoers file).

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

You also can use Gnuplot which is also available from gretl. Put your x y z data on a text file an insert the following

splot 'test.txt' using 1:2:3 with points palette pointsize 3 pointtype 7

Then you can set labels, etc. using

set xlabel "xxx" rotate parallel
set ylabel "yyy" rotate parallel
set zlabel "zzz" rotate parallel
set grid
show grid
unset key

addEventListener in Internet Explorer

I would use these polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

What's a good IDE for Python on Mac OS X?

I usually use either komodo edit or aquamacs with ropemacs. Although I should warn you, IDE features won't be what you're used to if you're coming from a Java or C# background. I personally find that powerful IDEs get in my way more than they help.

UPDATE: I should also point out that if you have the money Komodo IDE is worth it. It's the paid version of Komodo Edit.

Print series of prime numbers in python

Adding to the accepted answer, further optimization can be achieved by using a list to store primes and printing them after generation.

import math
Primes_Upto = 101
Primes = [2]
for num in range(3,Primes_Upto,2):
    if all(num%i!=0 for i in Primes):
       Primes.append(num)
for i in Primes:
    print i

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Override valueof() and toString() in Java enum

I don't think your going to get valueOf("Start Here") to work. But as far as spaces...try the following...

static private enum RandomEnum {
    R("Start There"), 
    G("Start Here"); 
    String value;
    RandomEnum(String s) {
        value = s;
    }
}

System.out.println(RandomEnum.G.value);
System.out.println(RandomEnum.valueOf("G").value);

Start Here
Start Here

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

How do I load an HTML page in a <div> using JavaScript?

If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

For ex : <iframe src="home.html" width="100" height="100"/>

PHP cURL HTTP CODE return 0

What is the exact contents you are passing into $html_brand?

If it is has an invalid URL syntax, you will very likely get the HTTP code 0.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I had the same problem and the only thing that works for my was to uninstall entity framework package from each project using Uninstall-Package. And then intall it again in the whole solution. It will ask you to choose in which project you want to install it, you shall select all.

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

Min / Max Validator in Angular 2 Final

This question has already been answered. I'd like to extend the answer from @amd. Sometimes you might need a default value.

For example, to validate against a specific value, I'd like to provide it as follows-

<input integerMinValue="20" >

But the minimum value of a 32 bit signed integer is -2147483648. To validate against this value, I don't like to provide it. I'd like to write as follows-

<input integerMinValue >

To achieve this you can write your directive as follows

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, Validators} from '@angular/forms';

@Directive({
    selector: '[integerMinValue]',
    providers: [{provide: NG_VALIDATORS, useExisting: IntegerMinValidatorDirective, multi: true}]
})
export class IntegerMinValidatorDirective implements Validator {

    private minValue = -2147483648;

    @Input('integerMinValue') set min(value: number) {
        if (value) {
            this.minValue = +value;
        }
    }

    validate(control: AbstractControl): ValidationErrors | null {
        return Validators.min(this.minValue)(control);
    }

}

How to convert a string from uppercase to lowercase in Bash?

If you define your variable using declare (old: typeset) then you can state the case of the value throughout the variable's use.

$ declare -u FOO=AbCxxx
$ echo $FOO
ABCXXX

"-l" does lc.

How do you resize a form to fit its content automatically?

From MSDN:

To maximize productivity, the Windows Forms Designer shadows the AutoSize property for the Form class. At design time, the form behaves as though the AutoSize property is set to false, regardless of its actual setting. At runtime, no special accommodation is made, and the AutoSize property is applied as specified by the property setting.

What is a user agent stylesheet?

Regarding the concept “user agent style sheet”, consult section Cascade in the CSS 2.1 spec.

User agent style sheets are overridden by anything that you set in your own style sheet. They are just the rock bottom: in the absence of any style sheets provided by the page or by the user, the browser still has to render the content somehow, and the user agent style sheet just describes this.

So if you think you have a problem with a user agent style sheet, then you really have a problem with your markup, or your style sheet, or both (about which you wrote nothing).

How to show form input fields based on select value?

Demo on JSFiddle

$(document).ready(function () {
    toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
    // this will call our toggleFields function every time the selection value of our other field changes
    $("#dbType").change(function () {
        toggleFields();
    });

});
// this toggles the visibility of other server
function toggleFields() {
    if ($("#dbType").val() === "other")
        $("#otherServer").show();
    else
        $("#otherServer").hide();
}

HTML:

    <p>Choose type</p>
    <p>Server:
        <select id="dbType" name="dbType">
          <option>Choose Database Type</option>
          <option value="oracle">Oracle</option>
          <option value="mssql">MS SQL</option>
          <option value="mysql">MySQL</option>
          <option value="other">Other</option>
        </select>
    </p>
    <div id="otherServer">
        <p>Server:
            <input type="text" name="server_name" />
        </p>
        <p>Port:
            <input type="text" name="port_no" />
        </p>
    </div>
    <p align="center">
        <input type="submit" value="Submit!" />
    </p>

Asp.net - Add blank item at top of dropdownlist

Do your databinding and then add the following:

Dim liFirst As New ListItem("", "")
drpList.Items.Insert(0, liFirst)

How to get some values from a JSON string in C#?

Following code is working for me.

Usings:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

Code:

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

I had the same error. In my case, using Appium, I had two versions of ADB

$ /usr/local/bin/adb version 36

and

$ /Users/user/Library/Android/sdk/platform-tools/adb version 39

The solution was:

  1. be sure that your $PATH in bash_profile is pointing to: /Users/user/Library/Android/sdk/platform-tools/

  2. stop the adb server: adb kill-server and check Appium is stopped.

  3. delete the adb version 36 (or you can rename it to have a backup): rm /usr/local/bin/adb

  4. start adb server: adb start-server or just starting Appium

Why is IoC / DI not common in Python?

Haven't used Python in several years, but I would say that it has more to do with it being a dynamically typed language than anything else. For a simple example, in Java, if I wanted to test that something wrote to standard out appropriately I could use DI and pass in any PrintStream to capture the text being written and verify it. When I'm working in Ruby, however, I can dynamically replace the 'puts' method on STDOUT to do the verify, leaving DI completely out of the picture. If the only reason I'm creating an abstraction is to test the class that's using it (think File system operations or the clock in Java) then DI/IoC creates unnecessary complexity in the solution.

refresh leaflet map: map container is already initialized

use the redrawAll() function rather than renderAll().

What are unit tests, integration tests, smoke tests, and regression tests?

  • Unit test: an automatic test to test the internal workings of a class. It should be a stand-alone test which is not related to other resources.
  • Integration test: an automatic test that is done on an environment, so similar to unit tests but with external resources (db, disk access)
  • Regression test: after implementing new features or bug fixes, you re-test scenarios which worked in the past. Here you cover the possibility in which your new features break existing features.
  • Smoke testing: first tests on which testers can conclude if they will continue testing.

What is the native keyword in Java for?

Straight from the Java Language Specification:

A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN,or assembly language. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.

jQuery val is undefined?

You probably included your JavaScript before the HTML: example.

You should either execute your JavaScript when the window loads (or better, when the DOM is fully loaded), or you should include your JavaScript after your HTML: example.

How to download an entire directory and subdirectories using wget?

use the command

wget -m www.ilanni.com/nexus/content/

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

Hash function that produces short hashes?

You could use an existing hash algorithm that produces something short, like MD5 (128 bits) or SHA1 (160). Then you can shorten that further by XORing sections of the digest with other sections. This will increase the chance of collisions, but not as bad as simply truncating the digest.

Also, you could include the length of the original data as part of the result to make it more unique. For example, XORing the first half of an MD5 digest with the second half would result in 64 bits. Add 32 bits for the length of the data (or lower if you know that length will always fit into fewer bits). That would result in a 96-bit (12-byte) result that you could then turn into a 24-character hex string. Alternately, you could use base 64 encoding to make it even shorter.

How to make Git "forget" about a file that was tracked but is now in .gitignore?

Use this when:

1. You want to untrack a lot of files, or

2. You updated your gitignore file

Source link: http://www.codeblocq.com/2016/01/Untrack-files-already-added-to-git-repository-based-on-gitignore/

Let’s say you have already added/committed some files to your git repository and you then add them to your .gitignore; these files will still be present in your repository index. This article we will see how to get rid of them.

Step 1: Commit all your changes

Before proceeding, make sure all your changes are committed, including your .gitignore file.

Step 2: Remove everything from the repository

To clear your repo, use:

git rm -r --cached .
  • rm is the remove command
  • -r will allow recursive removal
  • –cached will only remove files from the index. Your files will still be there.

The rm command can be unforgiving. If you wish to try what it does beforehand, add the -n or --dry-run flag to test things out.

Step 3: Re add everything

git add .

Step 4: Commit

git commit -m ".gitignore fix"

Your repository is clean :)

Push the changes to your remote to see the changes effective there as well.

How to auto-size an iFrame?

My solution, (using jquery):

<iframe id="Iframe1" class="tabFrame" width="100%" height="100%" scrolling="no" src="http://samedomain" frameborder="0" >
</iframe>  
<script type="text/javascript">
    $(function () {

        $('.tabFrame').load(function () {
            var iframeContentWindow = this.contentWindow;
            var height = iframeContentWindow.$(document).height();
            this.style.height = height + 'px';
        });
    });
</script>

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x, it is not guaranteed at all:

>>> False = 5
>>> 0 == False
False

So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.

In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1, but on Python 3.x, this will always be the case, no matter what.

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

Correct way to use get_or_create?

Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:

customer.source, _ = Source.objects.get_or_create(name="Website")

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

Different ways of clearing lists

If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.

a = [1, 3, 5, 6]
del a # This will entirely delete a(the list).

But in case, you need it again, you can reinitialize it. Or just simply clear its elements by

del a[:]

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

How do you know a variable type in java?

If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:

boolean b = a instanceof String

Change SVN repository URL

In my case, the svn relocate command (as well as svn switch --relocate) failed for some reason (maybe the repo was not moved correctly, or something else). I faced this error:

$ svn relocate NEW_SERVER
svn: E195009: The repository at 'NEW_SERVER' has uuid 'e7500204-160a-403c-b4b6-6bc4f25883ea', but the WC has '3a8c444c-5998-40fb-8cb3-409b74712e46'

I did not want to redownload the whole repository, so I found a workaround. It worked in my case, but generally I can imagine a lot of things can get broken (so either backup your working copy, or be ready to re-checkout the whole repo if something goes wrong).

The repo address and its UUID are saved in the .svn/wc.db SQLite database file in your working copy. Just open the database (e.g. in SQLite Browser), browse table REPOSITORY, and change the root and uuid column values to the new ones. You can find the UUID of the new repo by issuing svn info NEW_SERVER.

Again, treat this as a last resort method.

How to send a GET request from PHP?

Remember that if you are using a proxy you need to do a little trick in your php code:

(PROXY WITHOUT AUTENTICATION EXAMPLE)

<?php
$aContext = array(
    'http' => array(
        'proxy' => 'proxy:8080',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;
?>

Getting the actual usedrange

Here's another one. It looks for the first and last non empty cell and builds are range from those. This also handles cases where your data is not rectangular and does not start in A1. Furthermore it handles merged cells as well, which .Find skips when executed from a macro, used on .Cells on a worksheet.

Function getUsedRange(ByRef sheet As Worksheet) As Range
' finds used range by looking for non empty cells
' works around bug in .Find that skips merged cells
' by starting at with the UsedRange (that may be too big)

' credit to https://contexturesblog.com/archives/2012/03/01/select-actual-used-range-in-excel-sheet/
' for the .Find commands

Dim excelsUsedRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim lastCell As Range
Dim firstRow As Long
Dim firstCol As Long
Dim firstCell As Range

Set excelsUsedRange = ActiveSheet.UsedRange

lastRow = excelsUsedRange.Find(What:="*", _
                               LookIn:=xlValues, SearchOrder:=xlRows, _
                               SearchDirection:=xlPrevious).Row
lastCol = excelsUsedRange.Find(What:="*", _
                               LookIn:=xlValues, SearchOrder:=xlByColumns, _
                               SearchDirection:=xlPrevious).Column
Set lastCell = sheet.Cells(lastRow, lastCol)

firstRow = excelsUsedRange.Find(What:="*", After:=lastCell, _
                                LookIn:=xlValues, SearchOrder:=xlRows, _
                                SearchDirection:=xlNext).Row
firstCol = excelsUsedRange.Find(What:="*", After:=lastCell, _
                                LookIn:=xlValues, SearchOrder:=xlByColumns, _
                                SearchDirection:=xlNext).Row
Set firstCell = sheet.Cells(firstRow, firstCol)
Set getUsedRange = sheet.Range(firstCell, lastCell)
End Function

How to find index of STRING array in Java from a given value?

Refactoring the above methods and showing with the use:

private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
   for (int i = 0; i < arr.length; i++)
      if(arr[i].equals(str)) return i;
   return -1;
}
indexOf(languages, "en")

npm ERR! network getaddrinfo ENOTFOUND

Make sure to use the latest npm version while installing packages using npm.

While installing JavaScript, mention the latest version of NodeJS. For example, while installing JavaScript using devtools, use the below code:

devtools i --javascript nodejs:10.15.1

This will download and install the mentioned NodeJS version. Try installing the packages with npm after updating the version. This worked for me.

How does one make random number between range for arc4random_uniform()?

I believe you should do

dice1 = arc4random_uniform(6) + 1;

to get the range 1 - 6. I don't do iOS objective C nor have I any knowledge on swift-language though. The random method should return a value between 0 and 5, and + 1 will make it a value between 1 and 6.

If you need a range between lets say 10 - 30 then just do

int random = arc4random_uniform(21) + 10;

error: src refspec master does not match any

It happened to me and I discovered that github was trying to verify my account. So you need these 2 commands:

git config --global user.email <your github email>
git config --global user.name <your github username>

Is it possible to read from a InputStream with a timeout?

I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.

Under what conditions is a JSESSIONID created?

For links generated in a JSP with custom tags, I had to use

<%@ page session="false" %>

in the JSP

AND

request.getSession().invalidate();

in the Struts action

Make Adobe fonts work with CSS3 @font-face in IE9

I tried the ttfpatch tool and it didn't work form me. Internet Exploder 9 and 10 still complained.

I found this nice Git gist and it solved my issues. https://gist.github.com/stefanmaric/a5043c0998d9fc35483d

Just copy and paste the code in your css.

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

C# "as" cast vs classic cast

You use the "as" statement to avoid the possibility of an exception, e.g. you can handle the cast failure gracefully via logic. Only use the cast when you are sure that the object is of the desired type. I almost always use the "as" and then check for null.

How to specify table's height such that a vertical scroll bar appears?

This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.

In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.

#the-table {
  display: block;
  background: white; /* optional */
}

#the-table thead {
  text-align: left; /* optional */
}

#the-table tbody {
  display: block;
  max-height: 400px;
  overflow-y: scroll;
}

How do you log content of a JSON object in Node.js?

This will work with any object:

    var util = require("util");
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

on win7 64:

git-gui gives a good answer: a previous git has crashed and left a lock file. Manually remove. In my case, this was in .git/ref/heads/branchname.lock.

delete, and error 128 goes away. It surprises that tortoisegit doesn't give such an easy explanation.

Need to install urllib2 for Python 3.5.1

Acording to the docs:

Note The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request.

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

Gradle: Execution failed for task ':processDebugManifest'

Try changing:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
...
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="16" />

To:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
...
<uses-sdk xmlns:tools="http://schemas.android.com/tools"
    android:minSdkVersion="14" android:targetSdkVersion="16" />

Reason to Pass a Pointer by Reference in C++?

I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL

 int iSizeOfArray(int* &piArray) {
    piArray = new int[iNumberOfElements];
    ...
    return iNumberOfElements;
 }

It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.

How to set conditional breakpoints in Visual Studio?

  1. Set breakpoint on the line
  2. Right clik on RED ball
  3. Chose conditioal breakpoint
  4. Setup condition

CSS Layout - Dynamic width DIV

This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

<div style="width:100%;">
    <div style="width: 50px; float: left;">Left Side</div>
    <div style="width: 50px; float: right;">Right Side</div>
    <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>

How to check if an integer is within a range of numbers in PHP?

I created a function to check if times in an array overlap somehow:

    /**
     * Function to check if there are overlapping times in an array of \DateTime objects.
     *
     * @param $ranges
     *
     * @return \DateTime[]|bool
     */
    public function timesOverlap($ranges) {
        foreach ($ranges as $k1 => $t1) {
            foreach ($ranges as $k2 => $t2) {
                if ($k1 != $k2) {
                    /* @var \DateTime[] $t1 */
                    /* @var \DateTime[] $t2 */
                    $a = $t1[0]->getTimestamp();
                    $b = $t1[1]->getTimestamp();
                    $c = $t2[0]->getTimestamp();
                    $d = $t2[1]->getTimestamp();

                    if (($c >= $a && $c <= $b) || $d >= $a && $d <= $b) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

How to delete a module in Android Studio

After doing what's referred in [this answer]: https://stackoverflow.com/a/24592192/82788

Select the module(since it's still visible on the Project view),pressing Delete button on the keyboard can delete this module on disk.(Before doing what's referred in that answer, the Delete button has no effect.)

How do I remove duplicates from a C# array?

strINvalues = "1,1,2,2,3,3,4,4";
strINvalues = string.Join(",", strINvalues .Split(',').Distinct().ToArray());
Debug.Writeline(strINvalues);

Kkk Not sure if this is witchcraft or just beautiful code

1 strINvalues .Split(',').Distinct().ToArray()

2 string.Join(",", XXX);

1 Splitting the array and using Distinct [LINQ] to remove duplicates 2 Joining it back without the duplicates.

Sorry I never read the text on StackOverFlow just the code. it make more sense than the text ;)

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Set column as unique in SQL Server from the GUI:

They really make you run around the barn to do it with the GUI:

Make sure your column does not violate the unique constraint before you begin.

  1. Open SQL Server Management Studio.
  2. Right click your Table, click "Design".
  3. Right click the column you want to edit, a popup menu appears, click Indexes/Keys.
  4. Click the "Add" Button.
  5. Expand the "General" tab.
  6. Make sure you have the column you want to make unique selected in the "columns" box.
  7. Change the "Type" box to "Unique Key".
  8. Click "Close".
  9. You see a little asterisk in the file window, this means changes are not yet saved.
  10. Press Save or hit Ctrl+s. It should save, and your column should be unique.

Or set column as unique from the SQL Query window:

alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);

Changes take effect immediately:

Command(s) completed successfully.

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Responsive font size in CSS

The "vw" solution has a problem when going to very small screens. You can set the base size and go up from there with calc():

font-size: calc(16px + 0.4vw);

Could not load NIB in bundle

In my case the spellings of XIB was incorrect. Please make sure the spellings are correct. Bundle.main.loadNibName("XIB_Name" , owner : self , options :nil)

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

Cast Double to Integer in Java

double a = 13.34;
int b = (int) a;

System.out.println(b); //prints 13

Why check both isset() and !empty()

"Empty": only works on variables. Empty can mean different things for different variable types (check manual: http://php.net/manual/en/function.empty.php).

"isset": checks if the variable exists and checks for a true NULL or false value. Can be unset by calling "unset". Once again, check the manual.

Use of either one depends of the variable type you are using.

I would say, it's safer to check for both, because you are checking first of all if the variable exists, and if it isn't really NULL or empty.

How do you get the logical xor of two variables in Python?

You can always use the definition of xor to compute it from other logical operations:

(a and not b) or (not a and b)

But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is:

bool(a) ^ bool(b)

The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since bool is just a subclass of int, but is implemented to only have the values 0 and 1. And logical xor is equivalent to bitwise xor when the domain is restricted to 0 and 1.

So the logical_xor function would be implemented like:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

Credit to Nick Coghlan on the Python-3000 mailing list.

How to extract a substring using regex

add apache.commons dependency on your pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

And below code works.

StringUtils.substringBetween(String mydata, String "'", String "'")

How to get system time in Java without creating a new Date

This should work:

System.currentTimeMillis();

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

How to assign from a function which returns more than one value?

With R 3.6.1, I can do the following

fr2v <- function() { c(5,3) }
a_b <- fr2v()
(a_b[[1]]) # prints "5"
(a_b[[2]]) # prints "3"

How to correctly iterate through getElementsByClassName

I had a similar issue with the iteration and I landed here. Maybe someone else is also doing the same mistake I did.

In my case, the selector was not the problem at all. The problem was that I had messed up the javascript code: I had a loop and a subloop. The subloop was also using i as a counter, instead of j, so because the subloop was overriding the value of i of the main loop, this one never got to the second iteration.

var dayContainers = document.getElementsByClassName('day-container');
for(var i = 0; i < dayContainers.length; i++) { //loop of length = 2
        var thisDayDiv = dayContainers[i];
        // do whatever

        var inputs = thisDayDiv.getElementsByTagName('input');

        for(var j = 0; j < inputs.length; j++) { //loop of length = 4
            var thisInput = inputs[j];
            // do whatever

        };

    };

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

How to use PHP to connect to sql server

$dbhandle = sqlsrv_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer"); 

Hope it help.

Printing leading 0's in C

If you need to store the ZIP Code in a character array, zipcode[], you can use this:

snprintf(zipcode, 6, "%05.5d", atoi(zipcode));

what's the easiest way to put space between 2 side-by-side buttons in asp.net

There is another way of doing so:

<span style="width: 10px"></span>

You can adjust the amount of space using the width property.

Your code would be:

<div style="text-align: center"> 
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
    <span style="width: 10px"></span>
    <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>

How to drop a unique constraint from table column?

I had the same problem. I'm using DB2. What I have done is a bit not too professional solution, but it works in every DBMS:

  1. Add a column with the same definition without the unique contraint.
  2. Copy the values from the original column to the new
  3. Drop the original column (so DBMS will remove the constraint as well no matter what its name was)
  4. And finally rename the new one to the original
  5. And a reorg at the end (only in DB2)
ALTER TABLE USERS ADD COLUMN LOGIN_OLD VARCHAR(50) NOT NULL DEFAULT '';
UPDATE USERS SET LOGIN_OLD=LOGIN;
ALTER TABLE USERS DROP COLUMN LOGIN;
ALTER TABLE USERS RENAME COLUMN LOGIN_OLD TO LOGIN;

CALL SYSPROC.ADMIN_CMD('REORG TABLE USERS');

The syntax of the ALTER commands may be different in other DBMS

how to create dynamic two dimensional array in java?

Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

How to find files modified in last x minutes (find -mmin does not work as expected)

To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:

$ find /target_directory -type f -mmin -60

To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):

$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r

Read MS Exchange email in C#

  1. The currently preferred (Exchange 2013 and 2016) API is EWS. It is purely HTTP based and can be accessed from any language, but there are .Net and Java specific libraries.

    You can use EWSEditor to play with the API.

  2. Extended MAPI. This is the native API used by Outlook. It ends up using the MSEMS Exchange MAPI provider, which can talk to Exchange using RPC (Exchange 2013 no longer supports it) or RPC-over-HTTP (Exchange 2007 or newer) or MAPI-over-HTTP (Exchange 2013 and newer).

    The API itself can only be accessed from unmanaged C++ or Delphi. You can also use Redemption (any language) - its RDO family of objects is an Extended MAPI wrapper. To use Extended MAPI, you need to install either Outlook or the standalone (Exchange) version of MAPI (on extended support, and it does not support Unicode PST and MSG files and cannot access Exchange 2016). Extended MAPI can be used in a service.

    You can play with the API using OutlookSpy or MFCMAPI.

  3. Outlook Object Model - not Exchange specific, but it allows access to all data available in Outlook on the machine where the code runs. Cannot be used in a service.

  4. Exchange Active Sync. Microsoft no longer invests any significant resources into this protocol.

  5. Outlook used to install CDO 1.21 library (it wraps Extended MAPI), but it had been deprecated by Microsoft and no longer receives any updates.

  6. There used to be a third-party .Net MAPI wrapper called MAPI33, but it is no longer being developed or supported.

  7. WebDAV - deprecated.

  8. Collaborative Data Objects for Exchange (CDOEX) - deprecated.

  9. Exchange OLE DB Provider (EXOLEDB) - deprecated.

JAVA_HOME and PATH are set but java -version still shows the old one

There is an easy way, just remove the symbolic link from "/usr/bin". It will work.

setOnItemClickListener on custom ListView

I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..

  1. listviewdemo.xml

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="30dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />
    

  2. listviewcontent.xml - note that TextView - android:id="@+id/txtLstItem"

    <LinearLayout
        android:id="@+id/listviewcontentlayout"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="horizontal">
    
        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/txtLstItem"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:shadowColor="@android:color/black"
                android:shadowRadius="5"
                android:textColor="@android:color/white" />
    
        </LinearLayout>
    
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    </LinearLayout>
    

  3. ListViewActivity.java - Note that view.findViewById(R.id.txtLstItem) - as we setting the value to TextView by setText() method we getting text from TextView by View object returned by onItemClick method. OnItemClick() returns the current view.

    TextView v=(TextView) view.findViewById(R.id.txtLstItem);
    Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
    

    Using this simple logic we can get other values like CheckBox, RadioButton, ImageView etc.

    ListView List = (ListView) findViewById(R.id.listview);
    cursor = cr.query(CONTENT_URI,projection,null,null,null);
    adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
    
    cursor.moveToFirst();
    
    // Let activity manage the cursor
    startManagingCursor(cursor);
    
    List.setAdapter(adapter);
    List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
                // TODO Auto-generated method stub
                TextView v = (TextView) view.findViewById(R.id.txtLstItem);
                Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
            }
        }
    );
    

How to check if a file exists in Go?

To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename):

if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err) {
  // path/to/whatever does not exist
}

To check if a file exists, equivalent to Python's if os.path.exists(filename):

Edited: per recent comments

if _, err := os.Stat("/path/to/whatever"); err == nil {
  // path/to/whatever exists

} else if os.IsNotExist(err) {
  // path/to/whatever does *not* exist

} else {
  // Schrodinger: file may or may not exist. See err for details.

  // Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence


}

Make docker use IPv4 for port binding

As @daniel-t points out in the comment: github.com/docker/docker/issues/2174 is about showing binding only to IPv6 in netstat, but that is not an issue. As that github issues states:

When setting up the proxy, Docker requests the loopback address '127.0.0.1', Linux realises this is an address that exists in IPv6 (as ::0) and opens on both (but it is formally an IPv6 socket). When you run netstat it sees this and tells you it is an IPv6 - but it is still listening on IPv4. If you have played with your settings a little, you may have disabled this trick Linux does - by setting net.ipv6.bindv6only = 1.

In other words, just because you see it as IPv6 only, it is still able to communicate on IPv4 unless you have IPv6 set to only bind on IPv6 with the net.ipv6.bindv6only setting. To be clear, net.ipv6.bindv6only should be 0 - you can run sysctl net.ipv6.bindv6only to verify.

How to replace case-insensitive literal substrings in Java

Just make it simple without third party libraries:

    final String source = "FooBar";
    final String target = "Foo";
    final String replacement = "";
    final String result = Pattern.compile(target, Pattern.LITERAL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(source)
.replaceAll(Matcher.quoteReplacement(replacement));

Can RDP clients launch remote applications and not desktops

RDP will not do that natively.

As other answers have said -- you'll need to do some scripting and make policy changes as a kludge to make it hard for RDP logins to run anything but the intended application.

However, as of 2008, Microsoft has released application virtualization technology via Terminal Services that will allow you to do this seamlessly.

Scroll Element into View with Selenium

def scrollToElement(element: WebElement) = {
  val location = element.getLocation
  driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

Eclipse shows errors but I can't find them

I just removed all the private libraries in JavaBuildPath and added the jars again.. It worked

How to center align the cells of a UICollectionView?

Based on user3676011 answer, I can suggest more detailed one with small correction. This solution works great on Swift 2.0.

enum CollectionViewContentPosition {
    case Left
    case Center
}

var collectionViewContentPosition: CollectionViewContentPosition = .Left

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
    insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    if collectionViewContentPosition == .Left {
        return UIEdgeInsetsZero
    }

    // Center collectionView content

    let itemsCount: CGFloat = CGFloat(collectionView.numberOfItemsInSection(section))
    let collectionViewWidth: CGFloat = collectionView.bounds.width

    let itemWidth: CGFloat = 40.0
    let itemsMargin: CGFloat = 10.0

    let edgeInsets = (collectionViewWidth - (itemsCount * itemWidth) - ((itemsCount-1) * itemsMargin)) / 2

    return UIEdgeInsetsMake(0, edgeInsets, 0, 0)
}

There was an issue in

(CGFloat(elements.count) * 10))

where should be additional -1 mentioned.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

If the range of the numbers is limited (there can be only mod 2 8 digit numbers, or only 10 different 8 digit numbers for example), then you could write an optimized sorting algorithm. But if you want to sort all possible 8 digit numbers, this is not possible with that low amount of memory.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How to set 24-hours format for date on java?

This will give you the date in 24 hour format.

    Date date = new Date();
    date.setHours(date.getHours() + 8);
    System.out.println(date);
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("kk:mm:ss");
    System.out.println(simpDate.format(date));

Difference between sh and bash

The Differences in as easy as much possible: After having a basic understanding, the other comments posted above will be easier to catch.

Shell - "Shell" is a program, which facilitates the interaction between the user and the operating system (kernel). There are many shell implementation available, like sh, bash, csh, zsh...etc.

Using any of the Shell programs, we will be able to execute commands that are supported by that shell program.

Bash - It derived from Bourne-again Shell. Using this program, we will be able to execute all the commands specified by Shell. Also, we will be able to execute some commands that are specifically added to this program. Bash has backward compatibility with sh.

Sh - It derived from Bourne Shell. "sh" supports all the commands specified in the shell. Means, Using this program, we will be able to execute all the commands specified by Shell.

For more information, do: - https://man.cx/sh - https://man.cx/bash

How to remove a newline from a string in Bash

Using bash:

echo "|${COMMAND/$'\n'}|"

(Note that the control character in this question is a 'newline' (\n), not a carriage return (\r); the latter would have output REBOOT| on a single line.)

Explanation

Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}:

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.

Also uses the $'' ANSI-C quoting construct to specify a newline as $'\n'. Using a newline directly would work as well, though less pretty:

echo "|${COMMAND/
}|"

Full example

#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|

Or, using newlines:

#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|

Focus Next Element In Tab Index

Here's something I build for this purpose:

focusNextElement: function () {
    //add all elements we want to include in our selection
    var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
    if (document.activeElement && document.activeElement.form) {
        var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
        function (element) {
            //check for visibility while always include the current activeElement 
            return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
        });
        var index = focussable.indexOf(document.activeElement);
        if(index > -1) {
           var nextElement = focussable[index + 1] || focussable[0];
           nextElement.focus();
        }                    
    }
}

Features:

  • configurable set of focusable elements
  • no jQuery needed
  • works in all modern browsers
  • fast & lightweight

Why should I use a container div in HTML?

THis method allows you to have more flexibility of styling your entire content. Effectivly creating two containers that you can style. THe HTML Body tag which serves as your background, and the div with an id of container which contains your content.

This then allows you to position your content within the page, while styling a background or other effects without issue. THink of it as a "Frame" for the content.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.

How much faster is C++ than C#?

C++ (or C for that matter) gives you fine-grained control over your data structures. If you want to bit-twiddle you have that option. Large managed Java or .NET apps (OWB, Visual Studio 2005) that use the internal data structures of the Java/.NET libraries carry the baggage with them. I've seen OWB designer sessions using over 400 MB of RAM and BIDS for cube or ETL design getting into the 100's of MB as well.

On a predictable workload (such as most benchmarks that repeat a process many times) a JIT can get you code that is optimised well enough that there is no practical difference.

IMO on large applications the difference is not so much the JIT as the data structures that the code itself is using. Where an application is memory-heavy you will get less efficient cache usage. Cache misses on modern CPUs are quite expensive. Where C or C++ really win is where you can optimise your usage of data structures to play nicely with the CPU cache.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!