Programs & Examples On #Large data

Large data is data that is difficult to process and manage because its size is usually beyond the limits of the software being used to perform the analysis.

What causes a Python segmentation fault?

Looks like you are out of stack memory. You may want to increase it as Davide stated. To do it in python code, you would need to run your "main()" using threading:

def main():
    pass # write your code here

sys.setrecursionlimit(2097152)    # adjust numbers
threading.stack_size(134217728)   # for your needs

main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()

Source: c1729's post on codeforces. Runing it with PyPy is a bit trickier.

"Large data" workflows using pandas

I think the answers above are missing a simple approach that I've found very useful.

When I have a file that is too large to load in memory, I break up the file into multiple smaller files (either by row or cols)

Example: In case of 30 days worth of trading data of ~30GB size, I break it into a file per day of ~1GB size. I subsequently process each file separately and aggregate results at the end

One of the biggest advantages is that it allows parallel processing of the files (either multiple threads or processes)

The other advantage is that file manipulation (like adding/removing dates in the example) can be accomplished by regular shell commands, which is not be possible in more advanced/complicated file formats

This approach doesn't cover all scenarios, but is very useful in a lot of them

git: can't push (unpacker error) related to permission issues

This problem can also occur after Ubuntu upgrades that require a reboot.

If the file /var/run/reboot-required exists, do or schedule a restart.

Access parent's parent from javascript object

I used something that resembles singleton pattern:

function myclass() = {
    var instance = this;

    this.Days = function() {
        var days = ["Piatek", "Sobota", "Niedziela"];
        return days;
    }

    this.EventTime = function(day, hours, minutes) {
        this.Day = instance.Days()[day];
        this.Hours = hours;
        this.minutes = minutes;
        this.TotalMinutes = day*24*60 + 60*hours + minutes;
    }
}

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Difference between dangling pointer and memory leak

Pointer helps to create user defined scope to a variable, which is called Dynamic variable. Dynamic Variable can be single variable or group of variable of same type (array) or group of variable of different types (struct). Default local variable scope starts when control enters into a function and ends when control comes out of that function. Default global vairable scope starts at program execution and ends once program finishes.

But scope of a dynamic variable which holds by a pointer can start and end at any point in a program execution, which has to be decided by a programmer. Dangling and memory leak comes into picture only if a programmer doesnt handle the end of scope.

Memory leak will occur if a programmer, doesnt write the code (free of pointer) for end of scope for dynamic variables. Any way once program exits complete process memory will be freed, at that time this leaked memory also will get freed. But it will cause a very serious problem for a process which is running long time.

Once scope of dynamic variable comes to end(freed), NULL should be assigned to pointer variable. Otherwise if the code wrongly accesses it undefined behaviour will happen. So dangling pointer is nothing but a pointer which is pointing a dynamic variable whose scope is already finished.

Modifying the "Path to executable" of a windows service

Open Run(win+R) , type "Regedit.exe" , to open "Registry Editor", go to

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services

find "Apache2.4" open the folder find the "ImagePath" in the right side, open "ImagePath" under "value Data" put the following path:

"C:\xampp\apache\bin\httpd.exe" -k runservice foe XAMPP for others point to the location where Apache is installed and inside locate the bin folder "C:(Apache installed location)\bin\httpd.exe" -k runservice

Gradle Build Android Project "Could not resolve all dependencies" error

  1. Install android sdk manager
  2. check if building tools installed. install api 23.
  3. from the Android SDK Manager download the 'Android Support Repository'
  4. remove cordova-plugin-android-support-v4
  5. build

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %> and <%- and -%> are for any Ruby code, but doesn't output the results (e.g. if statements). the two are the same.

<%= %> is for outputting the results of Ruby code

<%# %> is an ERB comment

Here's a good guide: http://api.rubyonrails.org/classes/ActionView/Base.html

How to print pandas DataFrame without index

The line below would hide the index column of DataFrame when you print

df.style.hide_index()

Update: tested w Python 3.7

phpmyadmin "Not Found" after install on Apache, Ubuntu

Try this

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin.conf
sudo systemctl restart apache2

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

How do you query for "is not null" in Mongo?

An alternative that has not been mentioned, but that may be a more efficient option for some (won't work with NULL entries) is to use a sparse index (entries in the index only exist when there is something in the field). Here is a sample data set:

db.foo.find()
{ "_id" : ObjectId("544540b31b5cf91c4893eb94"), "imageUrl" : "http://example.com/foo.jpg" }
{ "_id" : ObjectId("544540ba1b5cf91c4893eb95"), "imageUrl" : "http://example.com/bar.jpg" }
{ "_id" : ObjectId("544540c51b5cf91c4893eb96"), "imageUrl" : "http://example.com/foo.png" }
{ "_id" : ObjectId("544540c91b5cf91c4893eb97"), "imageUrl" : "http://example.com/bar.png" }
{ "_id" : ObjectId("544540ed1b5cf91c4893eb98"), "otherField" : 1 }
{ "_id" : ObjectId("544540f11b5cf91c4893eb99"), "otherField" : 2 }

Now, create the sparse index on imageUrl field:

db.foo.ensureIndex( { "imageUrl": 1 }, { sparse: true } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Now, there is always a chance (and in particular with a small data set like my sample) that rather than using an index, MongoDB will use a table scan, even for a potential covered index query. As it turns out that gives me an easy way to illustrate the difference here:

db.foo.find({}, {_id : 0, imageUrl : 1})
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }
{ "imageUrl" : "http://example.com/bar.png" }
{  }
{  }

OK, so the extra documents with no imageUrl are being returned, just empty, not what we wanted. Just to confirm why, do an explain:

db.foo.find({}, {_id : 0, imageUrl : 1}).explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 6,
    "nscannedObjects" : 6,
    "nscanned" : 6,
    "nscannedObjectsAllPlans" : 6,
    "nscannedAllPlans" : 6,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "server" : "localhost:31100",
    "filterSet" : false
}

So, yes, a BasicCursor equals a table scan, it did not use the index. Let's force the query to use our sparse index with a hint():

db.foo.find({}, {_id : 0, imageUrl : 1}).hint({imageUrl : 1})
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/bar.png" }
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }

And there is the result we were looking for - only documents with the field populated are returned. This also only uses the index (i.e. it is a covered index query), so only the index needs to be in memory to return the results.

This is a specialized use case and can't be used generally (see other answers for those options). In particular it should be noted that as things stand you cannot use count() in this way (for my example it will return 6 not 4), so please only use when appropriate.

Safely limiting Ansible playbooks to a single machine?

AWS users using the EC2 External Inventory Script can simply filter by instance id:

ansible-playbook sample-playbook.yml --limit i-c98d5a71 --list-hosts

This works because the inventory script creates default groups.

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

In general Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes testability etc.

Tightly Coupled Object is an object need to know quite a bit about each other and are usually highly dependent on each other interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects, In small application we can easily identify the changes and there is less chance to miss anything. But in large applications these inter-dependencies are not always known by every programmer or chance is there to miss changes. But each set of loosely coupled objects are not dependent on others.

In short we can say, loose coupling is a design goal that seeks to reduce the interdependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component. Loose coupling is a much more generic concept intended to increase the flexibility of a system, make it more maintainable, and make the entire framework more 'stable'.

Coupling refers to the degree of direct knowledge that one element has of another. we can say an eg: A and B, only B change its behavior only when A change its behavior. A loosely coupled system can be easily broken down into definable elements.

Webfont Smoothing and Antialiasing in Firefox and Opera

I found the solution with this link : http://pixelsvsbytes.com/blog/2013/02/nice-web-fonts-for-every-browser/

Step by step method :

  • send your font to a WebFontGenerator and get the zip
  • find the TTF font on the Zip file
  • then, on linux, do this command (or install by apt-get install ttfautohint):
    ttfautohint --strong-stem-width=g neosansstd-black.ttf neosansstd-black.changed.ttf
  • then, one more, send the new TTF file (neosansstd-black.changed.ttf) on the WebFontGenerator
  • you get a perfect Zip with all your webfonts !

I hope this will help.

How to verify Facebook access token?

Exchange Access Token for Mobile Number and Country Code (Server Side OR Client Side)

You can get the mobile number with your access_token with this API https://graph.accountkit.com/v1.1/me/?access_token=xxxxxxxxxxxx. Maybe, once you have the mobile number and the id, you can work with it to verify the user with your server & database.

xxxxxxxxxx above is the Access Token

Example Response :

{
   "id": "61940819992708",
   "phone": {
      "number": "+91XX82923912",
      "country_prefix": "91",
      "national_number": "XX82923912"
   }
}


Exchange Auth Code for Access Token (Server Side)

If you have an Auth Code instead, you can first get the Access Token with this API - https://graph.accountkit.com/v1.1/access_token?grant_type=authorization_code&code=xxxxxxxxxx&access_token=AA|yyyyyyyyyy|zzzzzzzzzz

xxxxxxxxxx, yyyyyyyyyy and zzzzzzzzzz above are the Auth Code, App ID and App Secret respectively.

Example Response

{
   "id": "619XX819992708",
   "access_token": "EMAWdcsi711meGS2qQpNk4XBTwUBIDtqYAKoZBbBZAEZCZAXyWVbqvKUyKgDZBniZBFwKVyoVGHXnquCcikBqc9ROF2qAxLRrqBYAvXknwND3dhHU0iLZCRwBNHNlyQZD",
   "token_refresh_interval_sec": XX92000
}

Note - This is preferred on the server-side since the API requires the APP Secret which is not meant to be shared for security reasons.

Good Luck.

Extract text from a string

If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]" does the matching, result will be in $Matches[0]

How to quickly clear a JavaScript Object?

ES5

ES5 solution can be:

// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
  delete obj[prop];
});

ES6

And ES6 solution can be:

// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
  delete obj[prop];
}

Performance

Regardless of the specs, the quickest solutions will generally be:

// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
  delete obj[props[i]];
}

// for enumerable properties of shallow/plain object
for (var key in obj) {
  // this check can be safely omitted in modern JS engines
  // if (obj.hasOwnProperty(key))
    delete obj[key];
}

The reason why for..in should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for with Object.getOwnPropertyNames is a better choice.

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

"Could not find acceptable representation" using spring-boot-starter-web

For me, the problem was trying to pass a filename in a url, with a dot. For example

"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'

It could be solved by not passing the .jpg extension, or sending it all in a request body.

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

Calculate AUC in R?

Without any additional packages:

true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)

getROC_AUC = function(probs, true_Y){
    probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
    val = unlist(probsSort$x)
    idx = unlist(probsSort$ix)  

    roc_y = true_Y[idx];
    stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
    stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)    

    auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
    return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}

aList = getROC_AUC(probs, true_Y) 

stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)

plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")

enter image description here

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

Considering that (x != x) is not always guaranteed for NaN (such as if using the -ffast-math option), I've been using:

#define IS_NAN(x) (((x) < 0) == ((x) >= 0))

Numbers can't be both < 0 and >= 0, so really this check only passes if the number is neither less than, nor greater than or equal to zero. Which is basically no number at all, or NaN.

You could also use this if you prefer:

#define IS_NAN(x) (!((x)<0) && !((x)>=0)

I'm not sure how this is affected by -ffast-math though, so your mileage may vary.

Re-sign IPA (iPhone)

I think the easiest is to use Fastlane:

sudo gem install fastlane -NV
hash -r # for bash
rehash # for zsh
fastlane sigh resign ./path/app.ipa --signing_identity "Apple Distribution: Company Name" -p "my.mobileprovision"

Unzip All Files In A Directory

The following bash script extracts all zip files in the current directory into new dirs with the filename of the zip file, i.e.:

The following files:

myfile1.zip
myfile2.zip 

Will be extracted to:

./myfile1/files...
./myfile2/files...

Shell script:

#!/bin/sh
for zip in *.zip
do
  dirname=`echo $zip | sed 's/\.zip$//'`
  if mkdir "$dirname"
  then
    if cd "$dirname"
    then
      unzip ../"$zip"
      cd ..
      # rm -f $zip # Uncomment to delete the original zip file
    else
      echo "Could not unpack $zip - cd failed"
    fi
  else
    echo "Could not unpack $zip - mkdir failed"
  fi
done

When should you NOT use a Rules Engine?

I get very nervous when I see people using very large rule sets (e.g., on the order of thousands of rules in a single rule set). This often happens when the rules engine is a singleton sitting in the center of the enterprise in the hope that keeping rules DRY will make them accessible to many apps that require them. I would defy anyone to tell me that a Rete rules engine with that many rules is well-understood. I'm not aware of any tools that can check to ensure that conflicts don't exist.

I think partitioning rules sets to keep them small is a better option. Aspects can be a way to share a common rule set among many objects.

I prefer a simpler, more data driven approach wherever possible.

How to split one string into multiple variables in bash shell?

Sounds like a job for set with a custom IFS.

IFS=-
set $STR
var1=$1
var2=$2

(You will want to do this in a function with a local IFS so you don't mess up other parts of your script where you require IFS to be what you expect.)

WPF ListView turn off selection

Okay, little late to the game, but none of these solutions quite did what I was trying to do. These solutions have a couple problems

  1. Disable the ListViewItem, which screws up the styles and disables all the children controls
  2. Remove from the hit-test stack, i.e. children controls never get a mouse-over or click
  3. Make it not focusable, this just plain didn't work for me?

I wanted a ListView with the grouping headers, and each ListViewItem should just be 'informational' without selection or hover over, but the ListViewItem has a button in it that I want to be click-able and have hover-over.

So, really what I want is the ListViewItem to not be a ListViewItem at all, So, I over rode the ListViewItem's ControlTemplate and just made it a simple ContentControl.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <ContentControl Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}"/>
                </ControlTemplate>
            </Setter.Value>
         </Setter>
     </Style>
</ListView.ItemContainerStyle>

Why AVD Manager options are not showing in Android Studio

Should be something to do with your Platform Settings. Try the below steps

  1. Go to Project Structure -> Platform Settings -> SDKs
  2. Select available SDK's as shown in screenshots
  3. Re-start the Android Studio
  4. Android will detect the framework in the right corner. Click on it
  5. Then click ok as shown in second screenshot

SDK's Setup Frameworks

Update MongoDB field using value of another field

You should iterate through. For your specific case:

db.person.find().snapshot().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

React - Component Full Screen (with height 100%)

html, body, #app, #app>div {
  height: 100%
}

This will ensure all the chain to be height: 100%

Git undo local branch delete

If you know the last SHA1 of the branch, you can try

git branch branchName <SHA1>

You can find the SHA1 using git reflog, described in the solution --defect link--.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Convert Mat to Array/Vector in OpenCV

If the memory of the Mat mat is continuous (all its data is continuous), you can directly get its data to a 1D array:

std::vector<uchar> array(mat.rows*mat.cols*mat.channels());
if (mat.isContinuous())
    array = mat.data;

Otherwise, you have to get its data row by row, e.g. to a 2D array:

uchar **array = new uchar*[mat.rows];
for (int i=0; i<mat.rows; ++i)
    array[i] = new uchar[mat.cols*mat.channels()];

for (int i=0; i<mat.rows; ++i)
    array[i] = mat.ptr<uchar>(i);

UPDATE: It will be easier if you're using std::vector, where you can do like this:

std::vector<uchar> array;
if (mat.isContinuous()) {
  // array.assign(mat.datastart, mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign(mat.data, mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels());
  }
}

p.s.: For cv::Mats of other types, like CV_32F, you should do like this:

std::vector<float> array;
if (mat.isContinuous()) {
  // array.assign((float*)mat.datastart, (float*)mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign((float*)mat.data, (float*)mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i)+mat.cols*mat.channels());
  }
}

UPDATE2: For OpenCV Mat data continuity, it can be summarized as follows:

  • Matrices created by imread(), clone(), or a constructor will always be continuous.
  • The only time a matrix will not be continuous is when it borrows data (except the data borrowed is continuous in the big matrix, e.g. 1. single row; 2. multiple rows with full original width) from an existing matrix (i.e. created out of an ROI of a big mat).

Please check out this code snippet for demonstration.

How to use Git for Unity3D source control?

Edit -> Project Settings -> Editor

Set Version Control to meta files. Set Asset Serialization to force text.

I think this is what you want.

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

What is a Memory Heap?

You probably mean heap memory, not memory heap.

Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.

It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.

How to get Exception Error Code in C#

Another method would be to get the error code from the exception class directly. For example:

catch (Exception ex)
{
    if (ex.InnerException is ServiceResponseException)
       {
        ServiceResponseException srex = ex.InnerException as ServiceResponseException;
        string ErrorCode = srex.ErrorCode.ToString();
       }
}

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

I am using Windows 10 Home edition.

I tried various combination,

netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork

and also,

Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...

But still cannot activate WiFi hotspot.

While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:

[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]

Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.

C# - Making a Process.Start wait until the process has start-up

public static class WinApi
{

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    public static class Windows
    {
        public const int NORMAL = 1;
        public const int HIDE = 0;
        public const int RESTORE = 9;
        public const int SHOW = 5;
        public const int MAXIMIXED = 3;
    }

}

App

String process_name = "notepad"
Process process;
process = Process.Start( process_name );

while (!WinApi.ShowWindow(process.MainWindowHandle, WinApi.Windows.NORMAL))
{
    Thread.Sleep(100);
    process.Refresh();
}

// Done!
// Continue your code here ...

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

Checking if a website is up via Python

The HTTPConnection object from the httplib module in the standard library will probably do the trick for you. BTW, if you start doing anything advanced with HTTP in Python, be sure to check out httplib2; it's a great library.

"Cannot update paths and switch to branch at the same time"

It causes by that your local branch doesn't track remote branch. As ssasi said,you need use these commands:

git remote update
git fetch
git checkout -b branch_nameA origin/branch_nameB

I solved my problem just now....

What is the fastest way to compare two sets in Java?

I think method reference with equals method can be used. We assume that the object type without a shadow of a doubt has its own comparison method. Plain and simple example is here,

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));

Set<String> set2 = new HashSet<>();
set2.addAll(Arrays.asList("hanks","leo","bale"));

Predicate<Set> pred = set::equals;
boolean result = pred.test(set2);
System.out.println(result);   // true

Correct way to use Modernizr to detect IE?

CSS tricks have a good solution to target IE 11:

http://css-tricks.com/ie-10-specific-styles/

The .NET and Trident/7.0 are unique to IE so can be used to detect IE version 11.

The code then adds the User Agent string to the html tag with the attribute 'data-useragent', so IE 11 can be targeted specifically...

How to get text of an element in Selenium WebDriver, without including child element text?

Here's a general solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:

return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element) 

I'm actually using this code in a test suite.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

How to get to a particular element in a List in java?

You have about 98% right. The only issue is that you're trying to print out an String[] which does not print the way you'd like. Instead try this...

for (String[] s : myEntries) {
    System.out.print("Next item: " + s[0]);
    for(int i = 1; i < s.length; i++) {
        System.out.print(", " + s[i]);
    }
    System.out.println("");
}

This way you're accessing each string in the array instead of the array itself.

Hope this helps!

Python function global variables?

Here is one case that caught me out, using a global as a default value of a parameter.

globVar = None    # initialize value of global variable

def func(param = globVar):   # use globVar as default value for param
    print 'param =', param, 'globVar =', globVar  # display values

def test():
    global globVar
    globVar = 42  # change value of global
    func()

test()
=========
output: param = None, globVar = 42

I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.

def func(param = eval('globVar')):       # this seems to work
    print 'param =', param, 'globVar =', globVar  # display values

Or, if you want to be safe,

def func(param = None)):
    if param == None:
        param = globVar
    print 'param =', param, 'globVar =', globVar  # display values

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

Getting a machine's external IP address with Python

The most simple (non python) working solution I can think of is

wget -q -O- icanhazip.com

I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.

from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])

You can of course add some error checking, a timeout condition and some convenience:

#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json

try:
    url = 'http://api.hostip.info/get_json.php'
    info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
    print(info['ip'])
except URLError as e:
    print(e.reason, end=' ') # e.g. 'timed out'
    print('(are you connected to the internet?)')
except KeyboardInterrupt:
    pass

Appending output of a Batch file To log file

This is not an answer to your original question: "Appending output of a Batch file To log file?"

For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"

(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")

Timeout:

Example (1 second):

TIMEOUT /T 1000 /NOBREAK

Sleep:

Example (1 second):

sleep -m 1000

Alternative methods:

Here's an answer to your 2nd followup question: "Along with the Timestamp?"

Create a date and time stamp in your batch files

Example:

echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

remove item from stored array in angular 2

That work for me

 this.array.pop(index);

 for example index = 3 

 this.array.pop(3);

JavaFX How to set scene background image

One of the approaches may be like this:

1) Create a CSS file with name "style.css" and define an id selector in it:

#pane{
    -fx-background-image: url("background_image.jpg");
    -fx-background-repeat: stretch;   
    -fx-background-size: 900 506;
    -fx-background-position: center center;
    -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); 
}

2) Set the id of the most top control (or any control) in the scene with value defined in CSS and load this CSS file into the scene:

  public class Test extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        root.setId("pane");
        Scene scene = new Scene(root, 300, 250);
        scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

You can also give an id to the control in a FXML file:

<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample">
    <children>
    </children>
</StackPane>

For more info about JavaFX CSS Styling refer to this guide.

How to use jQuery to select a dropdown option?

How about

$('select>option:eq(3)').attr('selected', true);

example at http://www.jsfiddle.net/gaby/CWvwn/


for modern versions of jquery you should use the .prop() instead of .attr()

$('select>option:eq(3)').prop('selected', true);

example at http://jsfiddle.net/gaby/CWvwn/1763/

How to automatically generate a stacktrace when my program crashes

You did not specify your operating system, so this is difficult to answer. If you are using a system based on gnu libc, you might be able to use the libc function backtrace().

GCC also has two builtins that can assist you, but which may or may not be implemented fully on your architecture, and those are __builtin_frame_address and __builtin_return_address. Both of which want an immediate integer level (by immediate, I mean it can't be a variable). If __builtin_frame_address for a given level is non-zero, it should be safe to grab the return address of the same level.

How does "cat << EOF" work in bash?

A little extension to the above answers. The trailing > directs the input into the file, overwriting existing content. However, one particularly convenient use is the double arrow >> that appends, adding your new content to the end of the file, as in:

cat <<EOF >> /etc/fstab
data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
data_server:/var/sharedServer/cert   /var/sharedFolder/sometin/vsdc/cert nfs
EOF

This extends your fstab without you having to worry about accidentally modifying any of its contents.

Plotting with C#

See Samples Environment for Microsoft Chart Controls:

The samples environment for Microsoft Chart Controls for .NET Framework contains over 200 samples for both ASP.NET and Windows Forms. The samples cover every major feature in Chart Controls for .NET Framework. They enable you to see the Chart controls in action as well as use the code as templates for your own web and windows applications.

Seems to be more business oriented, but may be of some value to science students and scientists.

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

How do you upload a file to a document library in sharepoint?

With SharePoint 2013 new library, I managed to do something like this:

private void UploadToSharePoint(string p, out string newUrl)  //p is path to file to load
{
    string siteUrl = "https://myCompany.sharepoint.com/site/";
    //Insert Credentials
    ClientContext context = new ClientContext(siteUrl);

    SecureString passWord = new SecureString();
    foreach (var c in "mypassword") passWord.AppendChar(c);
    context.Credentials = new SharePointOnlineCredentials("myUserName", passWord);
    Web site = context.Web;

    //Get the required RootFolder
    string barRootFolderRelativeUrl = "Shared Documents/foo/bar";
    Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);

    //Create new subFolder to load files into
    string newFolderName = baseName + DateTime.Now.ToString("yyyyMMddHHmm");
    barFolder.Folders.Add(newFolderName);
    barFolder.Update();

    //Add file to new Folder
    Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
    FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };
    currentRunFolder.Files.Add(newFile);
    currentRunFolder.Update();

    context.ExecuteQuery();

    //Return the URL of the new uploaded file
    newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
}

Get values from an object in JavaScript

In ES2017 you can use Object.values():

Object.values(data)

At the time of writing support is limited (FireFox and Chrome).All major browsers except IE support this now.

In ES2015 you can use this:

Object.keys(data).map(k => data[k])

Most efficient way to see if an ArrayList contains an object in Java

There are three basic options:

1) If retrieval performance is paramount and it is practical to do so, use a form of hash table built once (and altered as/if the List changes).

2) If the List is conveniently sorted or it is practical to sort it and O(log n) retrieval is sufficient, sort and search.

3) If O(n) retrieval is fast enough or if it is impractical to manipulate/maintain the data structure or an alternate, iterate over the List.

Before writing code more complex than a simple iteration over the List, it is worth thinking through some questions.

  • Why is something different needed? (Time) performance? Elegance? Maintainability? Reuse? All of these are okay reasons, apart or together, but they influence the solution.

  • How much control do you have over the data structure in question? Can you influence how it is built? Managed later?

  • What is the life cycle of the data structure (and underlying objects)? Is it built up all at once and never changed, or highly dynamic? Can your code monitor (or even alter) its life cycle?

  • Are there other important constraints, such as memory footprint? Does information about duplicates matter? Etc.

Tool to Unminify / Decompress JavaScript

Most of the IDEs also offer auto-formatting features. For example in NetBeans, just press CTRL+K.

C++ Compare char array with string

There is more stable function, also gets rid of string folding.

// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
    /*
     * This function wraps string comparison with string pointers
     * (and also works around 'string folding', as I said).
     * Converts pointers to std::string
     * for make use of string equality operator (==).
     * Parameters use 'const' for prevent possible object corruption.
     */
    std::string var0 = (std::string) arg0;
    std::string var1 = (std::string) arg1;
    if (var0 == var1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

And add declaration to header

// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);

For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.

if (string_equal (var1, "dev"))
{
    // It is equal, do what needed here.
}
else
{
    // It is not equal, do what needed here (optional).
}

Source: sinatramultimedia/fl32 codec (it's written by myself)

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

You are confusing 'sets' and 'lists'. A set does not guarantee order, but lists do.

Sets are declared using curly brackets: {}. In contrast, lists are declared using square brackets: [].

mySet = {a, b, c, c}

Does not guarantee order, but list does:

myList = [a, b, c]

How to shut down the computer from C#

System.Diagnostics.Process.Start("shutdown", "/s /t 0")

Should work.

For restart, it's /r

This will restart the PC box directly and cleanly, with NO dialogs.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

HttpClientModule needs to be in the imports array, and remove it from providers. That section is for you to tell Angular which services the module has (written by you and not imported from a library).

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

I have encountered similar mistakes, and later found that my password is wrong.

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

Importing packages in Java

You should use

import Dan.Vik;

This makes the class visible and the its public methods available.

Copying files from one directory to another in Java

you use renameTo() – not obvious, I know ... but it's the Java equivalent of move ...

How to save/restore serializable object to/from file?

**1. Convert the json string to base64string and Write or append it to binary file. 2. Read base64string from binary file and deserialize using BsonReader. **

 public static class BinaryJson
{
    public static string SerializeToBase64String(this object obj)
    {
        JsonSerializer jsonSerializer = new JsonSerializer();
        MemoryStream objBsonMemoryStream = new MemoryStream();
        using (BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream))
        {
            jsonSerializer.Serialize(bsonWriterObject, obj);
            return Convert.ToBase64String(objBsonMemoryStream.ToArray());
        }           
        //return Encoding.ASCII.GetString(objBsonMemoryStream.ToArray());
    }
    public static T DeserializeToObject<T>(this string base64String)
    {
        byte[] data = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(data);
        using (BsonReader reader = new BsonReader(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }
    }
}

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

There is no wheel (prebuilt package) for Python 3.7 on Windows (there is one for Python 2.7 and 3.4 up to 3.6) so you need to prepare build environment on your PC to use this package. Easier would be finding the wheel for 3.7 as some packages are quite hard to build on Windows.

Christoph Gohlke (University of California) hosts Windows wheels for most popular packages for nearly all modern Python versions, including latest PyAudio. You can find it here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ (download can be quite slow). After download, just type pip install <downloaded file here>.

There is no difference between python -m pip install, and pip install as long as you're using default installation settings and single python installation. python pip actually tries to run file pip in the current directory.

Edit. See the pipwin comment for automated way of using Mr Goblke's libs . Note that I've not used it myself and I'm not sure about selecting different package flavors like vanilla and mkl versions of numpy.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

this error happens when you are going to bind a bounded service. so, sol should be :-

  1. in service connection add serviceBound as below:

    private final ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // your work here.
    
        serviceBound = true;
    
    }
    
    @Override
    public void onServiceDisconnected(ComponentName name) {
    
        serviceBound = false;
    }
    

    };

  2. unbind service onDestroy

        if (serviceBound) {
            unbindService(serviceConnection);
        }
    

PHP function ssh2_connect is not working

For WHM Panel

Menu > Server Configuration > Terminal:

yum install libssh2-devel -y

Menu > Software > Module Installers

  1. PHP PECL Manage Click
  2. ssh2 Install Now Click

Menu > Restart Services > HTTP Server (Apache)

Are you sure you wish to restart this service?

Yes

ssh2_connect() Work!

How do I commit case-sensitive only filename changes in Git?

You can use git mv:

git mv -f OldFileNameCase newfilenamecase

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

Convert between UIImage and Base64 string

Decoding using convenience initialiser - Swift 5

extension UIImage {
    convenience init?(base64String: String) {
        guard let data = Data(base64Encoded: base64String) else { return nil }
        self.init(data: data)
    }
} 

Clearing a text field on button click

Something like this will add a button and let you use it to clear the values

<div>           
<input type="text" id="textfield1" size="5"/>         
</div>

<div>          
<input type="text" id="textfield2" size="5"/>           
</div>

<div>
    <input type="button" onclick="clearFields()" value="Clear">
</div>


<script type="text/javascript">
function clearFields() {
    document.getElementById("textfield1").value=""
    document.getElementById("textfield2").value=""
}
</script>

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

Can't bind to 'formGroup' since it isn't a known property of 'form'

Import ReactiveFormsModule in the corresponded module

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

How do I update zsh to the latest version?

If you have Homebrew installed, you can do this.

# check the zsh info
brew info zsh

# install zsh
brew install --without-etcdir zsh

# add shell path
sudo vim /etc/shells

# add the following line into the very end of the file(/etc/shells)
/usr/local/bin/zsh

# change default shell
chsh -s /usr/local/bin/zsh

Hope it helps, thanks.

How do I use the lines of a file as arguments of a command?

I suggest using:

command $(echo $(tr '\n' ' ' < parameters.cfg))

Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.

How do I upgrade PHP in Mac OS X?

best way to upgrade is compile it from source

see this tutorial that may be helful for you

http://www.computersnyou.com/2012/09/how-to-upgrade-php-in-mac-osx-compiling.html

In PowerShell, how can I test if a variable holds a numeric value?

If you want to check if a string has a numeric value, use this code:

$a = "44.4"
$b = "ad"
$rtn = ""
[double]::TryParse($a,[ref]$rtn)
[double]::TryParse($b,[ref]$rtn)

Credits go here

How to empty a file using Python

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass

Generate an integer that is not among four billion given ones

Check the size of the input file, then output any number which is too large to be represented by a file that size. This may seem like a cheap trick, but it's a creative solution to an interview problem, it neatly sidesteps the memory issue, and it's technically O(n).

void maxNum(ulong filesize)
{
    ulong bitcount = filesize * 8; //number of bits in file

    for (ulong i = 0; i < bitcount; i++)
    {
        Console.Write(9);
    }
}

Should print 10 bitcount - 1, which will always be greater than 2 bitcount. Technically, the number you have to beat is 2 bitcount - (4 * 109 - 1), since you know there are (4 billion - 1) other integers in the file, and even with perfect compression they'll take up at least one bit each.

Parsing huge logfiles in Node.js - read in line-by-line

import * as csv from 'fast-csv';
import * as fs from 'fs';
interface Row {
  [s: string]: string;
}
type RowCallBack = (data: Row, index: number) => object;
export class CSVReader {
  protected file: string;
  protected csvOptions = {
    delimiter: ',',
    headers: true,
    ignoreEmpty: true,
    trim: true
  };
  constructor(file: string, csvOptions = {}) {
    if (!fs.existsSync(file)) {
      throw new Error(`File ${file} not found.`);
    }
    this.file = file;
    this.csvOptions = Object.assign({}, this.csvOptions, csvOptions);
  }
  public read(callback: RowCallBack): Promise < Array < object >> {
    return new Promise < Array < object >> (resolve => {
      const readStream = fs.createReadStream(this.file);
      const results: Array < any > = [];
      let index = 0;
      const csvStream = csv.parse(this.csvOptions).on('data', async (data: Row) => {
        index++;
        results.push(await callback(data, index));
      }).on('error', (err: Error) => {
        console.error(err.message);
        throw err;
      }).on('end', () => {
        resolve(results);
      });
      readStream.pipe(csvStream);
    });
  }
}
import { CSVReader } from '../src/helpers/CSVReader';
(async () => {
  const reader = new CSVReader('./database/migrations/csv/users.csv');
  const users = await reader.read(async data => {
    return {
      username: data.username,
      name: data.name,
      email: data.email,
      cellPhone: data.cell_phone,
      homePhone: data.home_phone,
      roleId: data.role_id,
      description: data.description,
      state: data.state,
    };
  });
  console.log(users);
})();

Hidden Columns in jqGrid

To hide the grid column

jQuery("#validGrid").jqGrid('hideCol',str);

How to pass a function as a parameter in Java?

You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.

import java.lang.reflect.Method;

public class Demo {

    public static void main(String[] args) throws Exception{
        Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        Method method1 = Demo.class.getMethod("method1", parameterTypes);

        Demo demo = new Demo();
        demo.method2(demo, method1, "Hello World");
    }

    public void method1(String message) {
        System.out.println(message);
    }

    public void method2(Object object, Method method, String message) throws Exception {
        Object[] parameters = new Object[1];
        parameters[0] = message;
        method.invoke(object, parameters);
    }

}

How to delete a row from GridView?

Please try this code.....

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
   GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

display: inline-block extra margin

There are a number of workarounds for this issue which involve word-spacing or font size but this article suggests removing the margin with a right margin of -4px;

http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/

What are C++ functors and their uses?

Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

Convert List<Object> to String[] in Java

Java 8 has the option of using streams like:

List<Object> lst = new ArrayList<>();
String[] strings = lst.stream().toArray(String[]::new);

How to split one text file into multiple *.txt files?

$ split -l 100 input_file output_file

where -l is the number of lines in each files. This will create:

  • output_fileaa
  • output_fileab
  • output_fileac
  • output_filead
  • ....

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

Style the left column with position: fixed. (You'll presumably want to use top and left styles to control where exactly it occurs.)

How do you install an APK file in the Android emulator?

From Windows 7 Onwards ,

Shift + Right click in your apk file folder.

Select Open Command Window Here

Type & Hit "adb install AppName.apk"

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Have a look at ImmutableMap JavaDoc: doc

There is information about that there:

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

How to display raw html code in PRE or something like it but without escaping it

echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';

I think that's what you're looking for?

In other words, use htmlspecialchars() in PHP

Codeigniter how to create PDF

TCPDF is PHP class for generating pdf documents.Here we will learn TCPDF integration with CodeIgniter.we will use following step for TCPDF integration with CodeIgniter.

Step 1

To Download TCPDF Click Here.

Step 2

Unzip the above download inside application/libraries/tcpdf.

Step 3

Create a new file inside application/libraries/Pdf.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{ function __construct() { parent::__construct(); }
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */

Step 4

Create Controller file inside application/controllers/pdfexample.php.

 <?php
    class pdfexample extends CI_Controller{ 
    function __construct()
    { parent::__construct(); } function index() {
    $this->load->library('Pdf');
    $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetTitle('Pdf Example');
    $pdf->SetHeaderMargin(30);
    $pdf->SetTopMargin(20);
    $pdf->setFooterMargin(20);
    $pdf->SetAutoPageBreak(true);
    $pdf->SetAuthor('Author');
    $pdf->SetDisplayMode('real', 'default');
    $pdf->Write(5, 'CodeIgniter TCPDF Integration');
    $pdf->Output('pdfexample.pdf', 'I'); }
    }
    ?>

It is working for me. I have taken reference from http://www.tutsway.com/codeignitertcpdf.php

Simple URL GET/POST function in Python

You could use this to wrap urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

That will return a Request object that has result data and response codes.

Volatile boolean vs AtomicBoolean

volatile keyword guarantees happens-before relationship among threads sharing that variable. It doesn't guarantee you that 2 or more threads won't interrupt each other while accessing that boolean variable.

Using npm behind corporate proxy .pac

OS: Windows 7

Steps which worked for me:

  1. npm config get proxy
  2. npm config get https-proxy

  3. Comments: I executed this command to know my proxy settings
    npm config rm proxy

  4. npm config rm https-proxy
  5. npm config set registry=http://registry.npmjs.org/
  6. npm install

Formatting a Date String in React Native

Write below function to get date in string, convert and return in string format.

getParsedDate(strDate){
    var strSplitDate = String(strDate).split(' ');
    var date = new Date(strSplitDate[0]);
    // alert(date);
    var dd = date.getDate();
    var mm = date.getMonth() + 1; //January is 0!

    var yyyy = date.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    date =  dd + "-" + mm + "-" + yyyy;
    return date.toString();
}

Print it where you required: Date : {this.getParsedDate(stringDate)}

Does it make sense to use Require.js with Angular.js?

Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.

I made an Angular Seed with RequireJS on Server Side. Very simple one. I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.

I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.

For more information go on my github Angular Seed : https://github.com/matohawk/angular-seed-requirejs

Check list of words in another string

Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTM's answer, depending on the context.

1) use a regular expression:

import re
words_re = re.compile("|".join(list_of_words))

if words_re.search('some one long two phrase three'):
   # do logic you want to perform

2) You could use sets if you want to match whole words, e.g. you do not want to find the word "the" in the phrase "them theorems are theoretical":

word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
    # do stuff

Of course you can also do whole word matches with regex using the "\b" token.

The performance of these and Kenny's solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change. If performance is not an issue then go for the simplest, which is probably Kenny's.

Is std::vector copying the objects with a push_back?

if you want not the copies; then the best way is to use a pointer vector(or another structure that serves for the same goal). if you want the copies; use directly push_back(). you dont have any other choice.

Updating GUI (WPF) using a different thread

You can use Dispatcher.Invoke to update your GUI from a secondary thread.

Here is an example:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
    }
    public void DoSomething()
    {
        for (int i = 0; i < 100000000; i++)
        {
               this.Dispatcher.Invoke(()=>{
               textbox.Text=i.ToString();
               });    
        } 
    }

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

Removing duplicate values from a PowerShell array

$a | sort -unique

This works with case-insensitive, therefore removing duplicates strings with differing cases. Solved my problem.

$ServerList = @(
    "FS3",
    "HQ2",
    "hq2"
) | sort -Unique

$ServerList

The above outputs:

FS3
HQ2

How to stop mongo DB in one command

mongod --dbpath /path/to/your/db --shutdown

More info at official: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/

How do I use MySQL through XAMPP?

XAMPP Apache + MariaDB + PHP + Perl (X -any OS)

  • After successful installation execute xampp-control.exe in XAMPP folder
  • Start Apache and MySQL enter image description here

  • Open browser and in url type localhost or 127.0.0.1

  • then you are welcomed with dashboard

By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).

For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'

How to run multiple SQL commands in a single SQL connection?

No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:

using (SqlConnection conn = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
                comm.Connection = conn;
                comm.CommandText = @"update table ... where myparam=@myparam1 ; " +
                                    "update table ... where myparam=@myparam2 ";
                comm.Parameters.AddWithValue("@myparam1", myparam1);
                comm.Parameters.AddWithValue("@myparam2", myparam2);
                conn.Open();
                comm.ExecuteNonQuery();

        }
    }

How to implement class constants?

Either use readOnly modifier with the constant one needs to declare or one might declare a constant outside the class and use it specifically only in the required class using get operator.

Convert list to dictionary using linq and not worrying about duplicates

The issue with most of the other answers is that they use Distinct, GroupBy or ToLookup, which creates an extra Dictionary under the hood. Equally ToUpper creates extra string. This is what I did, which is an almost an exact copy of Microsoft's code except for one change:

    public static Dictionary<TKey, TSource> ToDictionaryIgnoreDup<TSource, TKey>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null) =>
        source.ToDictionaryIgnoreDup(keySelector, i => i, comparer);

    public static Dictionary<TKey, TElement> ToDictionaryIgnoreDup<TSource, TKey, TElement>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer = null)
    {
        if (keySelector == null)
            throw new ArgumentNullException(nameof(keySelector));
        if (elementSelector == null)
            throw new ArgumentNullException(nameof(elementSelector));
        var d = new Dictionary<TKey, TElement>(comparer ?? EqualityComparer<TKey>.Default);
        foreach (var element in source)
            d[keySelector(element)] = elementSelector(element);
        return d;
    }

Because a set on the indexer causes it to add the key, it will not throw, and will also do only one key lookup. You can also give it an IEqualityComparer, for example StringComparer.OrdinalIgnoreCase

What data type to use for hashed password field and what length?

Hashes are a sequence of bits (128 bits, 160 bits, 256 bits, etc., depending on the algorithm). Your column should be binary-typed, not text/character-typed, if MySQL allows it (SQL Server datatype is binary(n) or varbinary(n)). You should also salt the hashes. Salts may be text or binary, and you will need a corresponding column.

passing several arguments to FUN of lapply (and others *apply)

You can do it in the following way:

 myfxn <- function(var1,var2,var3){
      var1*var2*var3

    }

    lapply(1:3,myfxn,var2=2,var3=100)

and you will get the answer:

[[1]] [1] 200

[[2]] [1] 400

[[3]] [1] 600

Recover unsaved SQL query scripts

For SSMS 18, I found the files at:

C:\Users\YourUserName\Documents\Visual Studio 2017\Backup Files\Solution1

For SSMS 17, It was used to be at:

C:\Users\YourUserName\Documents\Visual Studio 2015\Backup Files\Solution1

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

How to list the certificates stored in a PKCS12 keystore with keytool?

You can also use openssl to accomplish the same thing:

$ openssl pkcs12 -nokeys -info \
    -in </path/to/file.pfx> \
    -passin pass:<pfx's password>

MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
    localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
    friendlyName: jedis-server
subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1
issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE-----
...
...
...
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048

Location of the mongodb database on mac

I had the same problem, with version 3.4.2

to run it (if you installed it with homebrew) run the process like this:

$ mongod --dbpath /usr/local/var/mongodb

Migrating from VMWARE to VirtualBox

I will suggest something totally different, we used it at work for many years ago on real computers and it worked perfect.

Boot both old and new machine on linux rescue Cd.

read the disk from one, and write it down to the other one, block by block, effectively copying the dist over the network.

You have to play around a little bit with the command line, but it worked so well that both machine complained about IP-conflict when they both booted :-) :-)

cat /dev/sda | ssh user@othermachine cat - > /dev/sda

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

My use case made insets unmanageable:

  1. background image on button stays consistent
  2. dynamic text and image changes where the string length and image size varies

This is what I ended up doing and I'm pretty happy with it:

  • Create the button on the storyboard with a background image (round circle with blur and color).

  • Declare a UIImageView in my class:

    @implementation BlahViewController {
        UIImageView *_imageView;
    }
    
  • Create image view instance on init:

    -(id)initWithCoder:(NSCoder *)aDecoder {
        self = [super initWithCoder:aDecoder];
        if (self) {
            _imageView = [[UIImageView alloc] initWithCoder:aDecoder];
         }
         return self;
     }
    
  • In viewDidLoad add a new layer to the button for our image view and set text alignment:

    [self.btn addSubview:_imageView];
    [self.btn.titleLabel setTextAlignment:NSTextAlignmentCenter];
    
  • In the button click method add my chosen overlay image to the image view, size it to fit the image and center it in the button but move it up 15 so I can put the text offset below it:

    [_imageView setImage:[UIImage imageNamed:@"blahImageBlah]];
    [_imageView sizeToFit];
    _imageView.center = CGPointMake(ceilf(self.btn.bounds.size.width / 2.0f),
             ceilf((self.btn.bounds.size.height / 2.0f) - 15));
    [self.btn setTitle:@"Some new text" forState:UIControlStateNormal];
    

Note: ceilf() is important to ensure it's on a pixel boundary for image quality.

How to change the name of an iOS app?

Its very easy to change in XCode 8, enter the app name in the "Display Name" field in Project Target -> General Identity section.

enter image description here

how to add picasso library in android studio

Add the Picasso library in Dependency

dependencies {
       ...
       implementation 'com.squareup.picasso:picasso:2.71828'
       ...
    }

Sync The Project Create one imageview in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

Add the Internet permission in Manifest file

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

//Initialize ImageView

ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.get()
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

Change arrow colors in Bootstraps carousel

In bootstrap 4 if you are just changing the colour of the controls you can use the sass variables, typically in custom.scss:

$carousel-control-color: #7b277d;

As highlighted in this github issue note: https://github.com/twbs/bootstrap/issues/21985#issuecomment-281402443

How to check string length with JavaScript

Basically: assign a keyup handler to the <textarea> element, in it count the length of the <textarea> and write the count to a separate <div> if its length is shorter than a minimum value.

Here's is an example-

_x000D_
_x000D_
var min = 15;_x000D_
document.querySelector('#tst').onkeyup = function(e){_x000D_
 document.querySelector('#counter').innerHTML = _x000D_
               this.value.length < min _x000D_
               ? (min - this.value.length)+' to go...'_x000D_
               : '';_x000D_
}_x000D_
    
_x000D_
body {font: normal 0.8em verdana, arial;}_x000D_
#counter {color: grey}
_x000D_
<textarea id="tst" cols="60" rows="10"></textarea>_x000D_
<div id="counter"></div>
_x000D_
_x000D_
_x000D_

How to re import an updated package while in Python Interpreter?

See here for a good explanation of how your dependent modules won't be reloaded and the effects that can have:

http://pyunit.sourceforge.net/notes/reloading.html

The way pyunit solved it was to track dependent modules by overriding __import__ then to delete each of them from sys.modules and re-import. They probably could've just reload'ed them, though.

JavaScript displaying a float to 2 decimal places

You could try mixing Number() and toFixed().

Have your target number converted to a nice string with X digits then convert the formated string to a number.

Number( (myVar).toFixed(2) )


See example below:

_x000D_
_x000D_
var myNumber = 5.01;_x000D_
var multiplier = 5;_x000D_
$('#actionButton').on('click', function() {_x000D_
  $('#message').text( myNumber * multiplier );_x000D_
});_x000D_
_x000D_
$('#actionButton2').on('click', function() {_x000D_
  $('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<button id="actionButton">Weird numbers</button>_x000D_
<button id="actionButton2">Nice numbers</button>_x000D_
_x000D_
<div id="message"></div>
_x000D_
_x000D_
_x000D_

NOT IN vs NOT EXISTS

I have a table which has about 120,000 records and need to select only those which does not exist (matched with a varchar column) in four other tables with number of rows approx 1500, 4000, 40000, 200. All the involved tables have unique index on the concerned Varchar column.

NOT IN took about 10 mins, NOT EXISTS took 4 secs.

I have a recursive query which might had some untuned section which might have contributed to the 10 mins, but the other option taking 4 secs explains, atleast to me that NOT EXISTS is far better or at least that IN and EXISTS are not exactly the same and always worth a check before going ahead with code.

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

Change private static final field using Java reflection

The whole point of a final field is that it cannot be reassigned once set. The JVM uses this guarentee to maintain consistency in various places (eg inner classes referencing outer variables). So no. Being able to do so would break the JVM!

The solution is not to declare it final in the first place.

The listener supports no services

for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address

alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;

Centering brand logo in Bootstrap Navbar

Updated 2018

Bootstrap 3

See if this example helps: http://bootply.com/mQh8DyRfWY

The brand is centered using..

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
}

Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner.

EDIT - Another approach is using transform: translateX(-50%);

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

http://www.bootply.com/V7vKDfk46G

Bootstrap 4

In Bootstrap 4, mx-auto or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.

Also see:

Bootstrap NavBar with left, center or right aligned items

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

font-weight is not working properly?

i was also facing the same issue, I resolved it by after selecting the Google's font that i was using, then I clicked on (Family-Selected) minimized tab and then clicked on "CUSTOMIZE" button. Then I selected the font weights that I want and then embedded the updated link in my html..

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

Which HTTP methods match up to which CRUD methods?

Right now (2016) the latest HTTP verbs are GET, POST, PATCH, PUT and DELETE

Overview

  • HTTP GET - SELECT/Request
  • HTTP PUT - UPDATE
  • HTTP POST - INSERT/Create
  • HTTP PATCH - When PUTting a complete resource representation is cumbersome and utilizes more bandwidth, e.g.: when you have to update partially a column
  • HTTP DELETE - DELETE

Hope this helps!

If you are interested on designing REST APIs this is an ansewome reading to have! website online version github repository

How to get the pure text without HTML element using JavaScript?

You can use this:

var element = document.getElementById('txt');
var text = element.innerText || element.textContent;
element.innerHTML = text;

Depending on what you need, you can use either element.innerText or element.textContent. They differ in many ways. innerText tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent sort of just strips the html tags and gives you what's left.

innerText also has compatability with old IE browsers (came from there).

How to escape % in String.Format?

Here's an option if you need to escape multiple %'s in a string with some already escaped.

(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])

To sanitise the message before passing it to String.format, you can use the following

Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);

StringBuffer buf = new StringBuffer();
while (m1.find())
    m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));

// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();

This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.

It will leave any already escaped characters alone (e.g. %%, %%%% etc.)

Trim leading and trailing spaces from a string in awk

If it is safe to assume only one set of spaces in column two (which is the original example):

awk '{print $1$2}' /tmp/input.txt

Adding another field, e.g. awk '{print $1$2$3}' /tmp/input.txt will catch two sets of spaces (up to three words in column two), and won't break if there are fewer.

If you have an indeterminate (large) number of space delimited words, I'd use one of the previous suggestions, otherwise this solution is the easiest you'll find using awk.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

C#: How to access an Excel cell?

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

How set background drawable programmatically in Android

setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));

CSS center content inside div

You just need

.parent-div { text-align: center }

How to POST request using RestSharp

I added this helper method to handle my POST requests that return an object I care about.

For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.

Helper Method:

    public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
    {
        //Note: Ideally the RestClient isn't created for each request. 
        var restClient = new RestClient("http://localhost:999");

        var restRequest = new RestRequest(relativeUri, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        restRequest.AddBody(postBody);

        var result = restClient.Post<TResponse>(restRequest);

        if (!result.IsSuccessful)
        {
            throw new HttpException($"Item not found: {result.ErrorMessage}");
        }

        return result.Data;
    }

Usage:

    public List<WhateverReturnType> GetFromApi()
    {
        var idsForLookup = new List<int> {1, 2, 3, 4, 5};

        var relativeUri = "/api/idLookup";

        var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);

        return restResponse;
    }

Catch checked change event of a checkbox

Use below code snippet to achieve this.:

$('#checkAll').click(function(){
  $("#checkboxes input").attr('checked','checked');
});

$('#UncheckAll').click(function(){
  $("#checkboxes input").attr('checked',false);
});

Or you can do the same with single check box:

$('#checkAll').click(function(e) {
  if($('#checkAll').attr('checked') == 'checked') {
    $("#checkboxes input").attr('checked','checked');
    $('#checkAll').val('off');
  } else {
    $("#checkboxes input").attr('checked', false);
    $('#checkAll').val('on'); 
  }
});

For demo: http://jsfiddle.net/creativegala/hTtxe/

How to execute only one test spec with angular-cli

If you want to be able to control which files are selected from the command line, I managed to do this for Angular 7.

In summary, you need to install @angular-devkit/build-angular:browser and then create a custom webpack plugin to pass the test file regex through. For example:

angular.json - change the test builder from @angular-devkit/build-angular:browser and set a custom config file:

...

        "test": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js"
            },
...

extra-webpack.config.js - create a webpack configuration that reads the regex from the command line:

const webpack = require('webpack');
const FILTER = process.env.KARMA_FILTER;
let KARMA_SPEC_FILTER = '/.spec.ts$/';
if (FILTER) {
  KARMA_SPEC_FILTER = `/${FILTER}.spec.ts$/`;
}
module.exports = {
  plugins: [new webpack.DefinePlugin({KARMA_SPEC_FILTER})]
}

test.ts - edit the spec

...
// Then we find all the tests.
declare const KARMA_CONTEXT_SPEC: any;
const context = require.context('./', true, KARMA_CONTEXT_SPEC);

Then use as follows to override the default:

KARMA_FILTER='somefile-.*\.spec\.ts$' npm run test

I documented the backstory here, apologies in advance for types and mis-links. Credit to the answer above by @Aish-Anu for pointing me in the right direction.

Setting environment variable in react-native?

you can also have different env scripts: production.env.sh development.env.sh production.env.sh

And then source them in when starting to work [which is just tied to an alias] so all the sh file has is export for each env variable:

export SOME_VAR=1234
export SOME_OTHER=abc

And then adding babel-plugin-transform-inline-environment-variables will allow access them in the code:

export const SOME_VAR: ?string = process.env.SOME_VAR;
export const SOME_OTHER: ?string = process.env.SOME_OTHER;

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

Android SQLite: Update Statement

The SQLiteDatabase object depends on the type of operation on the database.

More information, visit the official website:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

It explains how to manipulate consultations on the SQLite database.

INSERT ROW

Gets the data repository in write mode

SQLiteDatabase db = mDbHelper.getWritableDatabase();

Create a new map of values, where column names are the keys

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

Insert the new row, returning the primary key value of the new row

long newRowId;
newRowId = db.insert(
     FeedEntry.TABLE_NAME,
     FeedEntry.COLUMN_NAME_NULLABLE,
     values);

UPDATE ROW

Define 'where' part of query.

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

Specify arguments in placeholder order.

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

New value for one column

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

Which row to update, based on the ID

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
    int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

How to print (using cout) a number in binary form?

Is this what you're looking for?

std::cout << std::hex << val << std::endl;

SQL Server: SELECT only the rows with MAX(DATE)

select OrderNo,PartCode,Quantity
from dbo.Test t1
WHERE EXISTS(SELECT 1
         FROM dbo.Test t2
         WHERE t2.OrderNo = t1.OrderNo
           AND t2.PartCode = t1.PartCode
         GROUP BY t2.OrderNo,
                  t2.PartCode
         HAVING t1.DateEntered = MAX(t2.DateEntered))

This is the fastest of all the queries supplied above. The query cost came in at 0.0070668.

The preferred answer above, by Mikael Eriksson, has a query cost of 0.0146625

You may not care about the performance for such a small sample, but in large queries, it all adds up.

How to break long string to multiple lines

you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing

SqlQueryString = "Insert into Employee values(" 
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"

Sibling package imports

in your main file add this:

import sys
import os 
sys.path.append(os.path.abspath(os.path.join(__file__,mainScriptDepth)))

mainScriptDepth = the depth of the main file from the root of the project.

Here in your case mainScriptDepth = "../../".

How to start new activity on button click

An old question but if the goal is to switch displayed pages, I just have one activity and call setContentView() when I want to switch pages (usually in response to user clicking on a button). This allows me to simply call from one page's contents to another. No Intent insanity of extras parcels bundles and whatever trying to pass data back and forth.

I make a bunch of pages in res/layout as usual but don't make an activity for each. Just use setContentView() to switch them as needed.

So my one-and-only onCreate() has:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater layoutInflater = getLayoutInflater();

    final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
    setContentView (mainPage);
    Button openMenuButton = findViewById(R.id.openMenuButton);

    final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
    Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);

    openMenuButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            setContentView(menuPage);
        }
    });

    someMenuButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            do-something-interesting;
            setContentView(mainPage);
        }
    }
}

If you want the Back button to go back through your internal pages before exiting the app, just wrap setContentView() to save pages in a little Stack of pages, and pop those pages in onBackPressed() handler.

Integration Testing POSTing an entire object to Spring MVC controller

I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject") to @RequestBody. Like this:

@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestBody NewObject newObject) {
        // ...
    }
}

Then in your tests you can simply say:

NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject  

mockMvc.perform(MockMvcRequestBuilders.post(uri)
  .content(asJsonString(newObjectInstance))
  .contentType(MediaType.APPLICATION_JSON)
  .accept(MediaType.APPLICATION_JSON));

Where the asJsonString method is just:

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}  

Hide Twitter Bootstrap nav collapse on click

$(function() {
    $('.nav a').on('click touchstart', function(){ 
        if($('.navbar-toggle').css('display') !='none'){
            $(".navbar-toggle").trigger( "click" );
        }
    });
});

// NOTE I added the "touchstart" for mobile touch. touchstart/end has no delay

How to open maximized window with Javascript?

If I use Firefox then screen.width and screen.height works fine but in IE and Chrome they don't work properly instead it opens with the minimum size.

And yes I tried giving too large numbers too like 10000 for both height and width but not exactly the maximized effect.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How to calculate mean, median, mode and range from a set of numbers

    public static Set<Double> getMode(double[] data) {
            if (data.length == 0) {
                return new TreeSet<>();
            }
            TreeMap<Double, Integer> map = new TreeMap<>(); //Map Keys are array values and Map Values are how many times each key appears in the array
            for (int index = 0; index != data.length; ++index) {
                double value = data[index];
                if (!map.containsKey(value)) {
                    map.put(value, 1); //first time, put one
                }
                else {
                    map.put(value, map.get(value) + 1); //seen it again increment count
                }
            }
            Set<Double> modes = new TreeSet<>(); //result set of modes, min to max sorted
            int maxCount = 1;
            Iterator<Integer> modeApperance = map.values().iterator();
            while (modeApperance.hasNext()) {
                maxCount = Math.max(maxCount, modeApperance.next()); //go through all the value counts
            }
            for (double key : map.keySet()) {
                if (map.get(key) == maxCount) { //if this key's value is max
                    modes.add(key); //get it
                }
            }
            return modes;
        }

        //std dev function for good measure
        public static double getStandardDeviation(double[] data) {
            final double mean = getMean(data);
            double sum = 0;
            for (int index = 0; index != data.length; ++index) {
                sum += Math.pow(Math.abs(mean - data[index]), 2);
            }
            return Math.sqrt(sum / data.length);
        }


        public static double getMean(double[] data) {
        if (data.length == 0) {
            return 0;
        }
        double sum = 0.0;
        for (int index = 0; index != data.length; ++index) {
            sum += data[index];
        }
        return sum / data.length;
    }

//by creating a copy array and sorting it, this function can take any data.
    public static double getMedian(double[] data) {
        double[] copy = Arrays.copyOf(data, data.length);
        Arrays.sort(copy);
        return (copy.length % 2 != 0) ? copy[copy.length / 2] : (copy[copy.length / 2] + copy[(copy.length / 2) - 1]) / 2;
    }

Using CMake with GNU Make: How can I see the exact commands?

Or simply export VERBOSE environment variable on the shell like this: export VERBOSE=1

Counting the Number of keywords in a dictionary in python

In order to count the number of keywords in a dictionary:

def dict_finder(dict_finders):
    x=input("Enter the thing you want to find: ")
    if x in dict_finders:
        print("Element found")
    else:
        print("Nothing found:")

New to MongoDB Can not run command mongo

This worked for me (if it applies that you also see the lock file):

first>youridhere@ubuntu:/var/lib/mongodb$ sudo service mongodb start 
then >youridhere@ubuntu:/var/lib/mongodb$ sudo rm mongod.lock*

Delete a dictionary item if the key exists

There is also:

try:
    del mydict[key]
except KeyError:
    pass

This only does 1 lookup instead of 2. However, except clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.

Delete certain lines in a txt file via a batch file

Use the following:

type file.txt | findstr /v ERROR | findstr /v REFERENCE

This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.

See the following transcript for it in operation:

C:\>type file.txt
Good Line of data
bad line of C:\Directory\ERROR\myFile.dll
Another good line of data
bad line: REFERENCE
Good line

C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE
Good Line of data
Another good line of data
Good line

JBoss vs Tomcat again

I'd certainly look to TomEE since the idea behind is to keep Tomcat bringing all the JavaEE 6 integration missing by default. That's a kind of very good compromise

ASP.NET Core - Swashbuckle not creating swagger.json file

After watching the answers and checking the recommendations, I end up having no clue what was going wrong.

I literally tried everything. So if you end up in the same situation, understand that the issue might be something else, completely irrelevant from swagger.

In my case was a OData exception.

Here's the procedure:

1) Navigate to the localhost:xxxx/swagger
2) Open Developer tools
3) Click on the error shown in the console and you will see the inner exception that is causing the issue.

Calculating the difference between two Java date instances

The following is one solution, as there are numerous ways we can achieve this:

  import java.util.*; 
   int syear = 2000;
   int eyear = 2000;
   int smonth = 2;//Feb
   int emonth = 3;//Mar
   int sday = 27;
   int eday = 1;
   Date startDate = new Date(syear-1900,smonth-1,sday);
   Date endDate = new Date(eyear-1900,emonth-1,eday);
   int difInDays = (int) ((endDate.getTime() - startDate.getTime())/(1000*60*60*24));

Error "package android.support.v7.app does not exist"

For those who migrated to androidx, here is a list of mappings to new packages: https://developer.android.com/jetpack/androidx/migrate#class_mappings

Use implementation 'androidx.appcompat:appcompat:1.0.0'

Instead support library implementation 'com.android.support:appcompat-v7:28.0.0'

Differences between Microsoft .NET 4.0 full Framework and Client Profile

Cameron MacFarland nailed it.

I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Create an xml file any name (say progressBar.xml) in drawable and add <color name="silverGrey">#C0C0C0</color> in color.xml.

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="720" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="6"
        android:useLevel="false" >
        <size
            android:height="200dip"
            android:width="300dip" />

        <gradient
            android:angle="0"
            android:endColor="@color/silverGrey"
            android:startColor="@android:color/transparent"
            android:type="sweep"
            android:useLevel="false" />

    </shape>
</rotate>

Now in your xml file where you have your listView add this code:

 <ListView
            android:id="@+id/list_form_statusMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>

        <ProgressBar
            android:id="@+id/progressBar"
            style="@style/CustomAlertDialogStyle"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_centerInParent="true"
            android:layout_gravity="center_horizontal"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/circularprogress"
            android:visibility="gone"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>

In AsyncTask in the method:

@Override
protected void onPreExecute()
{
    progressbar_view.setVisibility(View.VISIBLE);

    // your code
}

And in onPostExecute:

@Override
protected void onPostExecute(String s)
{
    progressbar_view.setVisibility(View.GONE);

    //your code
}

Link entire table row?

I think this might be the simplest solution:

<tr onclick="location.href='http://www.mywebsite.com'" style="cursor: pointer">
<td>...</td>
<td>...</td>
</tr>

The cursor CSS property sets the type of cursor, if any, to show when the mouse pointer is over an element.

The inline css defines that for that element the cursor will be formatted as a pointer, so you don't need the 'hover'.

How can I export Excel files using JavaScript?

To answer your question with a working example:

<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = new Array();

        for (var index in array[i]) {
           line.push('"' + array[i][index] + '"');
        }

        str += line.join(';');
        str += '\r\n';
    }
    window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>

Angularjs - display current date

A solution similar to the one of @Nick G. by using filter, but make the parameter meaningful:

Implement an filter called relativedate which calculate the date relative to current date by the given parameter as diff. As a result, (0 | relativedate) means today and (1 | relativedate) means tomorrow.

.filter('relativedate', ['$filter', function ($filter) {
  return function (rel, format) {
    let date = new Date();
    date.setDate(date.getDate() + rel);
    return $filter('date')(date, format || 'yyyy-MM-dd')
  };
}]);

and your html:

<div ng-app="myApp">
    <div>Yesterday: {{-1 | relativedate}}</div>
    <div>Today: {{0 | relativedate}}</div>
    <div>Tomorrow: {{1 | relativedate}}</div>
</div>

Make an image width 100% of parent div, but not bigger than its own width

I would use the property display: table-cell

Here is the link

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to disable back swipe gesture in UINavigationController on iOS 7

This is the way on Swift 3

works for me

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

What does "if (rs.next())" mean?

As to the concrete problem with that SQLException, you need to replace

ResultSet rs = stmt.executeQuery(sql);

by

ResultSet rs = stmt.executeQuery();

because you're using the PreparedStatement subclass instead of Statement. When using PreparedStatement, you've already passed in the SQL string to Connection#prepareStatement(). You just have to set the parameters on it and then call executeQuery() method directly without re-passing the SQL string.

See also:


As to the concrete question about rs.next(), it shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false. In combination with the if statement (instead of the while) this means that the programmer is expecting or interested in only one row, the first row.

See also:

Getting a Request.Headers value

string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;

if "true" than true
if "false" or anything else ("fooBar") than false

or

string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);

if "true" than true
if "false" than false
else ("fooBar") than null

:before and background-image... should it work?

you can set an image URL for the content prop instead of the background-image.

content: url(/img/border-left3.png);