Programs & Examples On #Rational rose

The Rational Rose Family of products is the Market-leading UML modeling tools for software design. One can Design C++, Visual Studio .NET and J2EE applications using UML v1.4.

Serialize JavaScript object into JSON string

Below is another way by which we can JSON data with JSON.stringify() function

var Utils = {};
Utils.MyClass1 = function (id, member) {
    this.id = id;
    this.member = member;
}
var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") };
alert(JSON.stringify(myobject));

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

Compiler error: "initializer element is not a compile-time constant"

A global variable has to be initialized to a constant value, like 4 or 0.0 or @"constant string" or nil. A object constructor, such as init, does not return a constant value.

If you want to have a global variable, you should initialize it to nil and then return it using a class method:

NSImage *segment = nil;

+ (NSImage *)imageSegment
{
    if (segment == nil) segment = [[NSImage alloc] initWithContentsOfFile:@"/user/asd.jpg"];
    return segment;
}

How to get nth jQuery element

If you already have the jquery object in a variable, you can also just treat it as a normal indexed array, without the use of jquery:

var all_rows = $("tr");
for(var i=0; i < all_rows.length; i++){
   var row = all_rows[i];
   //additionally, you can use it again in a jquery selector
   $(row).css("background-color","black");
}

Although the above example is not useful in any way, it is representing how you can treat objects created by jquery as indexed arrays.

Proper use of errors

Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.

EvalError --- Creates an instance representing an error that occurs regarding the global function eval().

InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().

TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

What is the difference between id and class in CSS, and when should I use them?

A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot. An example would be if you wanted to give all the paragraphs on your webpage the same styling, you would use classes.

Standards specify that any given ID name can only be referenced once within a page or document. Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.

Is there Selected Tab Changed Event in the standard WPF Tab Control

I tied this in the handler to make it work:

void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
      //do work when tab is changed
    }
}

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

In my case:

  1. /etc/init.d/mysql stop
  2. mysqld_safe --skip-grant-tables &

(in new window)

  1. mysql -u root
  2. mysql> use mysql;
  3. mysql> update user set authentication_string=password('password') where user='root';
  4. mysql>flush privileges;
  5. mysql> quit
  6. /etc/init.d/mysql restart

Changing the default title of confirm() in JavaScript?

Not possible. You can however use a third party javascript library that emulates a popup window, and it will probably look better as well and be less intrusive.

How do I convert an interval into a number of hours with postgres?

If you want integer i.e. number of days:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int

SVN: Is there a way to mark a file as "do not commit"?

This is late to the game, but I found the most awesome-est command line command for this problem. Done using bash. Enjoy.

svn status | grep -v excluding | sed 's/^A */"/g; s/$/"/g' | tr '\n' ' ' | xargs svn commit -m "My Message"

Ok, so here's an explanation of the command. Some things will need to be changed based on your use case.

svn status

I get a list of all the files. They'll all start with those status characters (?, !, A, etc). Each is on its own lines

grep -v excluding

I use grep to filter the list. It can either be used normally (to include) or with the -v flag (to exclude). In this case, it's being used to exclude, with a phrase "excluding" being what will be excluded.

sed 's/^. */"/g; s/$/"/g'

Now I remove the status character and whitespace at the beginning of each line, and then quote each line, using sed. Some of my filenames have spaces in them, hence the quoting.

tr '\n' ' '

Using tr, I replace all newlines with spaces. Now my entire list of files to commit is on one line.

xargs svn commit -m "My Message"

Lastly, I use xargs to execute my commit command with the message. It does the commit, and drops my quoted file list as the last argument.

The result is that everything ultimately works the way that I want it to. I still kind of hate svn for forcing me to jump through these goddamn hoops, but I can live with this. I guess.

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

Capturing a single image from my webcam in Java or Python

Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.

Example code:

Webcam webcam = Webcam.getDefault();
webcam.open();
try {
  ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
  e.printStackTrace();
} finally {
  webcam.close();
}

How to store Emoji Character in MySQL Database

The main point hasn't been mentioned in the above answers that,

We need to pass query string with the options "useUnicode=yes" and "characterEncoding=UTF-8" in connection string

Something like this

mysql://USERNAME:PASSWORD@HOSTNAME:PORT/DATABASE_NAME?useUnicode=yes&characterEncoding=UTF-8

LocalDate to java.util.Date and vice versa simplest conversion?

Date to LocalDate

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate to Date

LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Good way of getting the user's location in Android

I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.

Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."

And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.

Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.

https://developer.android.com/training/location/index.html

And finally, remember things like this:

I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).

I needed to add dependencies like this one: implementation 'com.google.android.gms:play-services-location:11.8.0', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).

update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.

MySQL - UPDATE query with LIMIT

You should highly consider using an ORDER BY if you intend to LIMIT your UPDATE, because otherwise it will update in the ordering of the table, which might not be correct.

But as Will A said, it only allows limit on row_count, not offset.

There was no endpoint listening at (url) that could accept the message

Short answer but did you have Skype open? This interferes specifically with ASP.NET by default (and localhosts in general) using port:80.

In Windows: Go to Tools -> Options -> Advanced -> Connection and uncheck the box "use port 80 and 443 as alternatives for incoming connections".

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

you can use indexing if your enumerable type is string like below

((string[])MyEnumerableStringList)[0]

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

From the data you gathered, I would tend to say that encoded "/" in an uri are meant to be seen as "/" again at application/cgi level.

That's to say, that if you're using apache with mod_rewrite for instance, it will not match pattern expecting slashes against URI with encoded slashes in it. However, once the appropriate module/cgi/... is called to handle the request, it's up to it to do the decoding and, for instance, retrieve a parameter including slashes as the first component of the URI.

If your application is then using this data to retrieve a file (whose filename contains a slash), that's probably a bad thing.

To sum up, I find it perfectly normal to see a difference of behaviour in "/" or "%2F" as their interpretation will be done at different levels.

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

How to set width of mat-table column in angular?

As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"

for example :

<mat-table #table [dataSource]="dataSource" matSortDisableClear>
    <ng-container matColumnDef="productId">
        <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="productName">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let product">
            <button (click)="view(product)">
                <mat-icon>visibility</mat-icon>
            </button>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

here matColumnDef is productId, productName and action

now we apply width by matColumnDef

styling

.mat-column-productId {
    flex: 0 0 10%;
}
.mat-column-productName {
    flex: 0 0 50%;
}

and remaining width is equally allocated to other columns

Shorthand for if-else statement

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N';

The ternary operator lets us write shorthand if..else statements exactly like you want.

It looks like:

(name === 'true') - our condition

? - the ternary operator itself

'Y' - the result if the condition evaluates to true

'N' - the result if the condition evaluates to false

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

PHP: Show yes/no confirmation dialog

I was also looking for a way to do it and figured it out like this using forms and the formaction attribute:

<input type="submit" name="del_something" formaction="<addresstothispage>" value="delete" />
<?php if(isset($_POST['del_something'])) print '<div>Are you sure? <input type="submit" name="del_confirm" value="yes!" formaction="action.php" />
<input type="submit" name="del_no" value="no!" formaction="<addresstothispage>" />';?>

action.php would check for isset($_POST['del_confirm']) and call the corresponding php script (for database actions or whatever). Voilà, no javascript needed. Using the formaction attribute, the delete button can be part of any form and still call a different form action (such as refer back to the same page, but with the button set).

If the button was pressed, the confirm buttons will show.

How to write and read java serialized objects into a file

if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.

Serialization:

LinkedList<YourObject> listOfObjects = <something>;
try {
    FileOutputStream file = new FileOutputStream(<filePath>);
    ObjectOutputStream writer = new ObjectOutputStream(file);
    for (YourObject obj : listOfObjects) {
        writer.writeObject(obj);
    }
    writer.close();
    file.close();
} catch (Exception ex) {
    System.err.println("failed to write " + filePath + ", "+ ex);
}

De-serialization:

try {
    FileInputStream file = new FileInputStream(<filePath>);
    ObjectInputStream reader = new ObjectInputStream(file);
    while (true) {
        try { 
            YourObject obj = (YourObject)reader.readObject();
            System.out.println(obj)
        } catch (Exception ex) {
            System.err.println("end of reader file ");
            break;
        }
    }
} catch (Exception ex) {
    System.err.println("failed to read " + filePath + ", "+ ex);
}

json Uncaught SyntaxError: Unexpected token :

That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

Getting result of dynamic SQL into a variable for sql-server

 vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE'' 
    AND OBJECT_NAME  =''' || vTBL_CLIENT_MASTER || '''';
    PRINT_STRING(VMYQUERY);
    EXECUTE IMMEDIATE  vMYQUERY INTO VCOUNTTEMP ;

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

Use .ignore plugin: https://plugins.jetbrains.com/plugin/7495--ignore

It manages a lot of paths/patterns for you automatically and also has many useful extra features. It's compatible with:

  • IntelliJ IDEA
  • PhpStorm
  • WebStorm
  • PyCharm
  • RubyMine
  • AppCode
  • CLion
  • GoLand
  • DataGrip
  • Rider
  • MPS
  • Android Studio

How can I recover a lost commit in Git?

This happened to me just today, so I am writing what came out as a lifesaver for me. My answer is very similar to @Amber 's answer.

First, I did a git reflog and searched for that particular commit's hash, then just copied that hash and did a git cherry-pick <hash> from that branch. This brought all the change from that lost commit to my current branch, and restored my faith on GIT.

Have a nice day!

Favicon dimensions?

The simplest solution in 2021 is to use one(!) PNG image

Simply add this to the head of your document:

<link rel="shortcut icon" type="image/png" href="/img/icon-192x192.png">
<link rel="shortcut icon" sizes="192x192" href="/img/icon-192x192.png">
<link rel="apple-touch-icon" href="/img/icon-192x192.png">

The last link is for Apple (home screen), the second one for Android (home screen) and the first one for the rest.

Note that this solution does not support "tiles" in Windows 8/10. It does, however, support images in shortcuts, bookmarks and browser-tabs.

The size is exactly the size the Android home screen uses. The Apple home screen icon size is 60px (3x), so 180px and will be scaled down. Other platforms use the default shortcut icon, which will be scaled down too.

How to change Git log date formats

After a long time looking for a way to get git log output the date in the format YYYY-MM-DD in a way that would work in less, I came up with the following format:

%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08

along with the switch --date=iso.

This will print the date in ISO format (a long one), and then print 14 times the backspace character (0x08), which, in my terminal, effectively removes everything after the YYYY-MM-DD part. For example:

git log --date=iso --pretty=format:'%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%aN %s'

This gives something like:

2013-05-24 bruno This is the message of the latest commit.
2013-05-22 bruno This is an older commit.
...

What I did was create an alias named l with some tweaks on the format above. It shows the commit graph to the left, then the commit's hash, followed by the date, the shortnames, the refnames and the subject. The alias is as follows (in ~/.gitconfig):

[alias]
        l = log --date-order --date=iso --graph --full-history --all --pretty=format:'%x08%x09%C(red)%h %C(cyan)%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08 %C(bold blue)%aN%C(reset)%C(bold yellow)%d %C(reset)%s'

Open two instances of a file in a single Visual Studio session

When working with Visual Studio 2013 and VB.NET I found that you can quite easily customize the menu and add the "New Window" command - there is no need to mess with the registry!

God only knows why Microsoft chose not to include the command for some languages...?

How do I tell Python to convert integers into words

Well, the dead-simple way to do it is to make a list of all the numbers you're interested in:

numbers = ["zero", "one", "two", "three", "four", "five", ... 
           "ninety-eight", "ninety-nine"]

(The ... indicates where you'd type the text representations of other numbers. No, Python isn't going to magically fill that in for you, you'd have to type all of them to use that technique.)

And then to print the number, just print numbers[i]. Easy peasy.

Of course, that list is a lot of typing, so you might wonder about an easy way to generate it. English unfortunately has a lot of irregularities so you'd have to manually put in the first twenty (0-19), but you can use regularities to generate the rest up to 99. (You can also generate some of the teens, but only some of them, so it seems easiest to just type them in.)

numbers = "zero one two three four five six seven eight nine".split()
numbers.extend("ten eleven twelve thirteen fourteen fifteen sixteen".split())
numbers.extend("seventeen eighteen nineteen".split())
numbers.extend(tens if ones == "zero" else (tens + "-" + ones) 
    for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split()
    for ones in numbers[0:10])

print numbers[42]  # "forty-two"

Another approach is to write a function that puts together the correct string each time. Again you'll have to hard-code the first twenty numbers, but after that you can easily generate them from scratch as needed. This uses a little less memory (a lot less once you start working with larger numbers).

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

How to verify if a file exists in a batch file?

You can use IF EXIST to check for a file:

IF EXIST "filename" (
  REM Do one thing
) ELSE (
  REM Do another thing
)

If you do not need an "else", you can do something like this:

set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=

Here's a working example of searching for a file or a folder:

REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file    

IF EXIST "filename" (
  ECHO file filename exists
) ELSE (
  ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
  ECHO file filename2.txt exists
) ELSE (
  ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash    

REM finds folder

IF EXIST "foldername\" (
  ECHO folder foldername exists
) ELSE (
  ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
  ECHO folder filename exists
) ELSE (
  ECHO folder filename does not exist
)

Check if a value is in an array (C#)

Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.

I would like to add an extending answer referring to different C# versions and because of two reasons:

  • The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.

  • No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).

Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.

Since .NET 3.5 there also exists a generic method Array<T>.Exists() :

public void PrinterSetup(string[] printer)
{
   if (Array.Exists(printer, x => x == "jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:

// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
   if (printer.ArrayContains("jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
   // If you want this to find "null" values, you could change the code here
   return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}

In this case this ArrayContains() method is used and not the Contains method of Linq.

The elsewhere mentioned .Contains methods refer to List<T>.Contains (since C# 2.0) or ArrayList.Contains (since C# 1.1), but not to arrays itself directly.

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

jquery dialog save cancel button styling

These solutions are all very well if you only have one dialog in the page at any one time, however if you want to style multiple dialogs at once then try:

$("#element").dialog({
    buttons: {
        'Save': function() {},
        'Cancel': function() {}
    }
})
.dialog("widget")
.find(".ui-dialog-buttonpane button")
.eq(0).addClass("btnSave").end()
.eq(1).addClass("btnCancel").end();

Instead of globally selecting buttons, this gets the widget object and finds it's button pane, then individually styles each button. This saves lot's of pain when you have several dialogs on one page

MongoDB vs Firebase

Firebase is a suite of features .

  • Realtime Database
  • Hosting
  • Authentication
  • Storage
  • Cloud Messaging
  • Remote Config
  • Test Lab
  • Crash Reporting
  • Notifications
  • App Indexing
  • Dynamic Links
  • Invites
  • AdWords
  • AdMob

I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .

When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .

  1. Are there many aggregation queries that gets executed .(Like in case of reporting tool or BI tool ) . If Yes dont go for Firebase
  2. Do i need to perform lot of transaction . (If yes then i would not like to go with firebase) (Tranactions are somewhat easy though after introduction of functions but that is also a overhead if lot of transactions needs to be maintained)
  3. What timeline do i have to get things up and running .(Firebase is very easy to setup and integrate ).
  4. Do i have expertise to scale up the DB and trouble shoot DB related stuffs . (Firebase is more like SAAS so no need to worry about scaleability)

How to implement the factory method pattern in C++ correctly

Loki has both a Factory Method and an Abstract Factory. Both are documented (extensively) in Modern C++ Design, by Andei Alexandrescu. The factory method is probably closer to what you seem to be after, though it's still a bit different (at least if memory serves, it requires you to register a type before the factory can create objects of that type).

Android: How to change CheckBox size?

Assume your original xml is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/tick_img" />
    <item android:state_checked="false"
        android:drawable="@drawable/untick_img" />
</selector>

then simply remove android:button="@drawable/xml_above" in your checkbox xml, and do drawable scaling programmatically in java (decrease the 150 big size to your desired dp):

CheckBox tickRememberPasswd = findViewById(R.id.remember_tick);

//custom selector size
Drawable drawableTick = ContextCompat.getDrawable(this, R.drawable.tick_img);
Drawable drawableUntick = ContextCompat.getDrawable(this, R.drawable.untick_img);
Bitmap bitmapTick = null;
if (drawableTick != null && drawableUntick != null) {
    int desiredPixels = Math.round(convertDpToPixel(150, this));

    bitmapTick = ((BitmapDrawable) drawableTick).getBitmap();
    Drawable dTick = new BitmapDrawable(getResources()
            , Bitmap.createScaledBitmap(bitmapTick, desiredPixels, desiredPixels, true));

    Bitmap bitmapUntick = ((BitmapDrawable) drawableUntick).getBitmap();
    Drawable dUntick = new BitmapDrawable(getResources()
            , Bitmap.createScaledBitmap(bitmapUntick, desiredPixels, desiredPixels, true));

    final StateListDrawable statesTick = new StateListDrawable();
    statesTick.addState(new int[] {android.R.attr.state_checked},
            dTick);
    statesTick.addState(new int[] { }, //else state_checked false
            dUntick);
    tickRememberPasswd.setButtonDrawable(statesTick);
}

the convertDpToPixel method:

public static float convertDpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}

How to get the entire document HTML as a string?

I always use

document.getElementsByTagName('html')[0].innerHTML

Probably not the right way but I can understand it when I see it.

How should I edit an Entity Framework connection string?

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

Xcode warning: "Multiple build commands for output file"

Commenting use_frameworks! in PodFile worked for me.

#use_frameworks!

Note: Did this on XCode 10.1, pod version 1.8.4

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

How do I test if a variable is a number in Bash?

This is a little rough around the edges but a little more novice friendly.

if [ $number -ge 0 ]
then
echo "Continue with code block"
else
echo "We matched 0 or $number is not a number"
fi

This will cause an error and print "Illegal number:" if $number is not a number but it will not break out of the script. Oddly there is not a test option I could find to just test for an integer. The logic here will match any number that is greater than or equal to 0.

Find object by id in an array of JavaScript objects

Performance

Today 2020.06.20 I perform test on MacOs High Sierra on Chrome 81.0, Firefox 77.0 and Safari 13.1 for chosen solutions.

Conclusions for solutions which use precalculations

Solutions with precalculations (K,L) are (much much) faster than other solutions and will not be compared with them - probably they are use some special build-in browser optimisations

  • surprisingly on Chrome and Safari solution based on Map (K) are much faster than solution based on object {} (L)
  • surprisingly on Safari for small arrays solution based on object {} (L) is slower than traditional for (E)
  • surprisingly on Firefox for small arrays solution based on Map (K) is slower than traditional for (E)

Conclusions when searched objects ALWAYS exists

  • solution which use traditional for (E) is fastest for small arrays and fast for big arrays
  • solution using cache (J) is fastest for big arrays - surprisingly for small arrays is medium fast
  • solutions based on find (A) and findIndex (B) are fast for small arras and medium fast on big arrays
  • solution based on $.map (H) is slowest on small arrays
  • solution based on reduce (D) is slowest on big arrays

enter image description here

Conclusions when searched objects NEVER exists

  • solution based on traditional for (E) is fastest on small and big arrays (except Chrome-small arrays where it is second fast)
  • solution based on reduce (D) is slowest on big arrays
  • solution which use cache (J) is medium fast but can be speed up if we save in cache also keys which have null values (which was not done here because we want to avoid unlimited memory consumption in cache in case when many not existing keys will be searched)

enter image description here

Details

For solutions

  • without precalculations: A B C D E F G H I J (the J solution use 'inner' cache and it speed depend on how often searched elements will repeat)
  • with precalculations K L

I perform four tests. In tests I want to find 5 objects in 10 loop iterations (the objects ID not change during iterations) - so I call tested method 50 times but only first 5 times have unique id values:

  • small array (10 elements) and searched object ALWAYS exists - you can perform it HERE
  • big array (10k elements) and searched object ALWAYS exist - you can perform it HERE
  • small array (10 elements) and searched object NEVER exists - you can perform it HERE
  • big array (10k elements) and searched object NEVER exists - you can perform it HERE

Tested codes are presented below

_x000D_
_x000D_
function A(arr, id) {
  return arr.find(o=> o.id==id);
}

function B(arr, id) {
  let idx= arr.findIndex(o=> o.id==id);
  return arr[idx];
}

function C(arr, id) {
  return arr.filter(o=> o.id==id)[0];
}

function D(arr, id) {
  return arr.reduce((a, b) => (a.id==id && a) || (b.id == id && b));
}

function E(arr, id) {
  for (var i = 0; i < arr.length; i++) if (arr[i].id==id) return arr[i];
  return null;
}

function F(arr, id) {
  var retObj ={};
  $.each(arr, (index, obj) => {
    if (obj.id == id) { 
      retObj = obj;
      return false;
    }
  });
  return retObj;
}

function G(arr, id) {
  return $.grep(arr, e=> e.id == id )[0];
}

function H(arr, id) {
  return $.map(myArray, function(val) {
    return val.id == id ? val : null;
  })[0];
}

function I(arr, id) {
  return _.find(arr, o => o.id==id);
}

let J = (()=>{
  let cache = new Map();
  return function J(arr,id,el=null) { 
    return cache.get(id) || (el=arr.find(o=> o.id==id), cache.set(id,el), el);
  }
})();

function K(arr, id) {
  return mapK.get(id)
}

function L(arr, id) {
  return mapL[id];
}



// -------------
// TEST
// -------------

console.log('Find id=5');

myArray = [...Array(10)].map((x,i)=> ({'id':`${i}`, 'foo':`bar_${i}`}));
const mapK = new Map( myArray.map(el => [el.id, el]) );
const mapL = {}; myArray.forEach(el => mapL[el.id]=el);



[A,B,C,D,E,F,G,H,I,J,K,L].forEach(f=> console.log(`${f.name}: ${JSON.stringify(f(myArray, '5'))}`));

console.log('Whole array',JSON.stringify(myArray));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

This snippet only presents tested codes
_x000D_
_x000D_
_x000D_

Example tests results for Chrome for small array where searched objects always exists

enter image description here

What is tail call optimization?

TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space. The only situation in which this happens is if the last instruction executed in a function f is a call to a function g (Note: g can be f). The key here is that f no longer needs stack space - it simply calls g and then returns whatever g would return. In this case the optimization can be made that g just runs and returns whatever value it would have to the thing that called f.

This optimization can make recursive calls take constant stack space, rather than explode.

Example: this factorial function is not TCOptimizable:

def fact(n):
    if n == 0:
        return 1
    return n * fact(n-1)

This function does things besides call another function in its return statement.

This below function is TCOptimizable:

def fact_h(n, acc):
    if n == 0:
        return acc
    return fact_h(n-1, acc*n)

def fact(n):
    return fact_h(n, 1)

This is because the last thing to happen in any of these functions is to call another function.

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Inline SVG in CSS

You can also just do this:

_x000D_
_x000D_
<svg viewBox="0 0 32 32">
      <path d="M11.333 13.173c0-2.51 2.185-4.506 4.794-4.506 2.67 0 4.539 2.053 4.539 4.506 0 2.111-0.928 3.879-3.836 4.392v0.628c0 0.628-0.496 1.141-1.163 1.141s-1.163-0.513-1.163-1.141v-1.654c0-0.628 0.751-1.141 1.419-1.141 1.335 0 2.571-1.027 2.571-2.224 0-1.255-1.092-2.224-2.367-2.224-1.335 0-2.367 1.027-2.367 2.224 0 0.628-0.546 1.141-1.214 1.141s-1.214-0.513-1.214-1.141zM15.333 23.333c-0.347 0-0.679-0.143-0.936-0.404s-0.398-0.597-0.398-0.949 0.141-0.689 0.398-0.949c0.481-0.488 1.39-0.488 1.871 0 0.257 0.26 0.398 0.597 0.398 0.949s-0.141 0.689-0.398 0.949c-0.256 0.26-0.588 0.404-0.935 0.404zM16 26.951c-6.040 0-10.951-4.911-10.951-10.951s4.911-10.951 10.951-10.951c6.040 0 10.951 4.911 10.951 10.951s-4.911 10.951-10.951 10.951zM16 3.333c-6.984 0-12.667 5.683-12.667 12.667s5.683 12.667 12.667 12.667c6.984 0 12.667-5.683 12.667-12.667s-5.683-12.667-12.667-12.667z"></path>
</svg>
_x000D_
_x000D_
_x000D_

How to plot vectors in python using matplotlib

This may also be achieved using matplotlib.pyplot.quiver, as noted in the linked answer;

plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()

mpl output

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

This is why I wrote Picky: http://picky.readthedocs.io/

It's a python package that tracks packages installed with either pip or conda in either virtualenvs and conda envs.

Styling an input type="file" button

I found this approach the simplest and lightest.

Here is the working example: http://codepen.io/c3zar22/pen/QNoYXN

Below are the explanations:

  • this would be the markup:

    <label for="attach-project-file">
        <span id="remove-project-file" class="close">x</span>
        <div class="filename" id="attached-project-file">Click to select a file</div>
    </label>
    <input id="attach-project-file" type="file">
    
  • hide the input in a hacky way like this:

    #attach-project-file {
        width: 0.1px;
        height: 0.1px;
        opacity: 0;
        overflow: hidden;
        position: absolute;
        z-index: -1;
    }
    
  • style the corresponding label instead

    [for="attach-project-file"] {
        /* your styles here */
    }
    
  • style "remove file" button

    .close {
        font-size: 16px;
        padding: 10px;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        font-style: normal;
    }
    
  • .filename element will be used to display the selected file

  • below is the commented JS code needed (using jQuery) to make it work:

    var $attach = $('#attach-project-file'),
        $remove = $('#remove-project-file'),
        $name = $('#attached-project-file');
    
    // initially hide the remove button
    $remove.hide();
    
    // do this when file input has changed
    // i.e.: a file has been selected
    $attach.on('change', function() {
        var val = $(this).val();
        if (val !== '') {
            // if value different than empty
    
            // show the file name as text
            // hide/text/fadeIn creates a nice effect when changing the text
            $name
                .hide()
                .text(val)
                .fadeIn();
    
            // show the remove button
            $remove.fadeIn();
        } else {
            // if value empty, means the file has been removed
    
            // show the default text
            $name
                .hide()
                .text('Click to select a file')
                .fadeIn();
    
            // hide remove button
            $remove.fadeOut();
        }
    });
    
    // remove selected file when clicking the remove button
    // prevent click bubbling to the parent label and triggering file selection
    $remove.on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
    
        $attach
            .val('')
            .change(); // trigger change event
    });
    

How to get jSON response into variable from a jquery script

You should use data.response in your JS instead of json.response.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

For those who are using this format all the timme like me I did an extension method. I just wanted to share because I think it can be usefull to you.

     /// <summary>
    /// Convert a date to a human readable ISO datetime format. ie. 2012-12-12 23:01:12
    /// this method must be put in a static class. This will appear as an available function
    /// on every datetime objects if your static class namespace is declared.
    /// </summary>
    public static string ToIsoReadable(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd HH':'mm':'ss");
    }

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

ValueError: math domain error

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

The error is due to corrupt or missing SSL chain certificate files in the PKI directory. You’ll need to make sure the files ca-bundle, following steps: In your console/terminal:

mkdir /usr/src/ca-certificates && cd /usr/src/ca-certificates

Enter this site: https://rpmfind.net/linux/rpm2html/search.php?query=ca-certificates , get your ca-certificate, for yout SO, for example: ftp://rpmfind.net/linux/fedora/linux/updates/24/x86_64/c/ca-certificates-2016.2.8-1.0.fc24.noarch.rpm << CentOS. Copy url of download and paste in url: wget your_url_donwload_ca-ceritificated.rpm now, install yout rpm:

rpm2cpio your_url_donwload_ca-ceritificated.rpm | cpio -idmv

now restart your service: my example this command:

sudo service2 httpd restart

very great good look

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I have solved above problem Applying below steps

enter image description here

And after you made thses changes, do following changes in your web.config

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />

bootstrap datepicker today as default

This question is about bootstrap date picker. But all of the above answers are for the jquery date picker. For Bootstrap datepicker, you just need to provide the defaut date in the value of the input element. Like this.

<input class="form-control datepicker" value=" <?= date("Y-m-d") ?>">

Want to upgrade project from Angular v5 to Angular v6

I had to re-run ng update @angular/cli for angular-cli.json to be changed to angular.json

Error in finding last used cell in Excel with VBA

I wonder that nobody has mentioned this, But the easiest way of getting the last used cell is:

Function GetLastCell(sh as Worksheet) As Range
    GetLastCell = sh.Cells(1,1).SpecialCells(xlLastCell)
End Function

This essentially returns the same cell that you get by Ctrl + End after selecting Cell A1.

A word of caution: Excel keeps track of the most bottom-right cell that was ever used in a worksheet. So if for example you enter something in B3 and something else in H8 and then later on delete the contents of H8, pressing Ctrl + End will still take you to H8 cell. The above function will have the same behavior.

Call multiple functions onClick ReactJS

Maybe you can use arrow function (ES6+) or the simple old function declaration.

Normal function declaration type (Not ES6+):

<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>

Anonymous function or arrow function type (ES6+)

<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>

The second one is the shortest road that I know. Hope it helps you!

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I programmatically provide required input files to GNUPlot executable and invoke it using system() function. It is suitable to my situation since I only want to visualize my data during research. But if you want the plotting functionality integrated into your executable file, maybe this is not for you :)

Get custom product attributes in Woocommerce

Edited: The woocommerce_get_product_terms is deprecated since Woocommerce version 3

Go with the following as @datafeedr wrote in his answer:

global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );

or even more compact:

global $product;
$koostis = $product->get_attribute( 'pa_koostis' );

Original answer:

$result = array_shift(woocommerce_get_product_terms($product->id, 'pa_koostis', 'names'));

Dynamically create and submit form

Steps to take:

  1. First you need to create the form element.
  2. With the form you have to pass the URL to which you wants to navigate.
  3. Specify the method type for the form.
  4. Add the form body.
  5. Finally call the submit() method on the form.

Code:

var Form = document.createElement("form");
Form.action = '/DashboardModule/DevicesInfo/RedirectToView?TerminalId='+marker.data;
Form.method = "post";
var formToSubmit = document.body.appendChild(Form);
formToSubmit.submit();

How do I get the XML SOAP request of an WCF Web service request?

I think you meant that you want to see the XML at the client, not trace it at the server. In that case, your answer is in the question I linked above, and also at How to Inspect or Modify Messages on the Client. But, since the .NET 4 version of that article is missing its C#, and the .NET 3.5 example has some confusion (if not a bug) in it, here it is expanded for your purpose.

You can intercept the message before it goes out using an IClientMessageInspector:

using System.ServiceModel.Dispatcher;
public class MyMessageInspector : IClientMessageInspector
{ }

The methods in that interface, BeforeSendRequest and AfterReceiveReply, give you access to the request and reply. To use the inspector, you need to add it to an IEndpointBehavior:

using System.ServiceModel.Description;
public class InspectorBehavior : IEndpointBehavior
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }
}

You can leave the other methods of that interface as empty implementations, unless you want to use their functionality, too. Read the how-to for more details.

After you instantiate the client, add the behavior to the endpoint. Using default names from the sample WCF project:

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.Endpoint.Behaviors.Add(new InspectorBehavior());
client.GetData(123);

Set a breakpoint in MyMessageInspector.BeforeSendRequest(); request.ToString() is overloaded to show the XML.

If you are going to manipulate the messages at all, you have to work on a copy of the message. See Using the Message Class for details.

Thanks to Zach Bonham's answer at another question for finding these links.

How do I schedule a task to run at periodic intervals?

Advantage of ScheduledExecutorService over Timer

I wish to offer you an alternative to Timer using - ScheduledThreadPoolExecutor, an implementation of the ScheduledExecutorService interface. It has some advantages over the Timer class, according to "Java in Concurrency":

A Timer creates only a single thread for executing timer tasks. If a timer task takes too long to run, the timing accuracy of other TimerTask can suffer. If a recurring TimerTask is scheduled to run every 10 ms and another Timer-Task takes 40 ms to run, the recurring task either (depending on whether it was scheduled at fixed rate or fixed delay) gets called four times in rapid succession after the long-running task completes, or "misses" four invocations completely. Scheduled thread pools address this limitation by letting you provide multiple threads for executing deferred and periodic tasks.

Another problem with Timer is that it behaves poorly if a TimerTask throws an unchecked exception. Also, called "thread leakage"

The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread. Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.

And another recommendation if you need to build your own scheduling service, you may still be able to take advantage of the library by using a DelayQueue, a BlockingQueue implementation that provides the scheduling functionality of ScheduledThreadPoolExecutor. A DelayQueue manages a collection of Delayed objects. A Delayed has a delay time associated with it: DelayQueue lets you take an element only if its delay has expired. Objects are returned from a DelayQueue ordered by the time associated with their delay.

Is Unit Testing worth the effort?

Best way to convince... find a bug, write a unit test for it, fix the bug.

That particular bug is unlikely to ever appear again, and you can prove it with your test.

If you do this enough, others will catch on quickly.

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

Xampp Access Forbidden php

I got the same error because somehow deleted the index.php and accessing the folder without index.php gave same error.

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

Get all attributes of an element using jQuery

Here is a one-liner for you.

JQuery Users:

Replace $jQueryObject with your jQuery object. i.e $('div').

Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

Vanilla Javascript Users:

Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').

Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

Cheers!!

Run Jquery function on window events: load, resize, and scroll?

just call your function inside the events.

load:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

$(window).resize(function () {
    topInViewport($(mydivname));
});

scroll:

$(window).scroll(function () {
    topInViewport($(mydivname));
});

or bind all event in one function

$(window).on("load scroll resize",function(e){

How to get the background color code of an element in hex?

My beautiful non-standard solution

HTML

<div style="background-color:#f5b405"></div>

jQuery

$(this).attr("style").replace("background-color:", "");

Result

#f5b405

linq query to return distinct field values from a list of objects

Assuming you want the full object, but only want to deal with distinctness by typeID, there's nothing built into LINQ to make this easy. (If you just want the typeID values, it's easy - project to that with Select and then use the normal Distinct call.)

In MoreLINQ we have the DistinctBy operator which you could use:

var distinct = list.DistinctBy(x => x.typeID);

This only works for LINQ to Objects though.

You can use a grouping or a lookup, it's just somewhat annoying and inefficient:

var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());

How to write multiple conditions in Makefile.am with "else if"

ifeq ($(CHIPSET),8960)
   BLD_ENV_BUILD_ID="8960"
else ifeq ($(CHIPSET),8930)
   BLD_ENV_BUILD_ID="8930"
else ifeq ($(CHIPSET),8064)
   BLD_ENV_BUILD_ID="8064"
else ifeq ($(CHIPSET), 9x15)
   BLD_ENV_BUILD_ID="9615"
else
   BLD_ENV_BUILD_ID=
endif

How to make a Div appear on top of everything else on the screen?

you should use position:fixed to make z-index values to apply to your div

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Opening A Specific File With A Batch File?

If the file that you want to open is in the same folder as your batch(.bat) file then you can simply try:

start filename.filetype

example: start image.png

Call jQuery Ajax Request Each X Minutes

You can use the built-in javascript setInterval.

var ajax_call = function() {
  //your jQuery ajax code
};

var interval = 1000 * 60 * X; // where X is your every X minutes

setInterval(ajax_call, interval);

or if you are the more terse type ...

setInterval(function() {
  //your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes

How to float a div over Google Maps?

Just set the position of the div and you may have to set the z-index.

ex.

div#map-div {
    position: absolute;
    left: 10px;
    top: 10px;
}
div#cover-div {
    position:absolute;
    left:10px;
    top: 10px;
    z-index:3;
}

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

How can I remove text within parentheses with a regex?

If you can stand to use sed (possibly execute from within your program, it'd be as simple as:

sed 's/(.*)//g'

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

Do AJAX requests retain PHP Session info?

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

WindowsError: [Error 126] The specified module could not be found

problem solved for me. I changed version from pytorch=1.5.1 to pytorch=1.4 and typed the below command in anaconda prompt window

conda install pytorch==1.4.0 torchvision==0.5.0 -c pytorch

how do I create an array in jquery?

Not completely clear what you mean. Perhaps:

<script type="text/javascript"> 
$(document).ready(function() {
  $("a").click(function() {
    var params = {};
    params['pageNo'] = $(this).text();
    params['sortBy'] = $("#sortBy").val();
    $("#results").load( "jquery-routing.php", params );
    return false;
  });
}); 
</script>

How to print a two dimensional array?

You should loop by rows and then columns with a structure like

for ...row index...
  for ...column index...
    print

but I guess this is homework so just try it out yourself.

Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.

Prevent users from submitting a form by hitting Enter

Using Javascript (without checking any input field):

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
}, true);
</script>

If someone wants to apply this on specific fields, for example input type text:

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
            e.preventDefault();
            return false;
        }
    }
}, true);
</script>

This works well in my case.

How to get a jqGrid cell value when editing

Try this, it will give you particular column's value

onSelectRow: function(id) {
    var rowData = jQuery(this).getRowData(id); 
    var temp= rowData['name'];//replace name with you column
    alert(temp);
}

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

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

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Matplotlib figure facecolor (background color)

I had to use the transparent keyword to get the color I chose with my initial

fig=figure(facecolor='black')

like this:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)

Quick way to list all files in Amazon S3 bucket?

For Scala developers, here it is recursive function to execute a full scan and map the contents of an AmazonS3 bucket using the official AWS SDK for Java

import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{S3ObjectSummary, ObjectListing, GetObjectRequest}
import scala.collection.JavaConversions.{collectionAsScalaIterable => asScala}

def map[T](s3: AmazonS3Client, bucket: String, prefix: String)(f: (S3ObjectSummary) => T) = {

  def scan(acc:List[T], listing:ObjectListing): List[T] = {
    val summaries = asScala[S3ObjectSummary](listing.getObjectSummaries())
    val mapped = (for (summary <- summaries) yield f(summary)).toList

    if (!listing.isTruncated) mapped.toList
    else scan(acc ::: mapped, s3.listNextBatchOfObjects(listing))
  }

  scan(List(), s3.listObjects(bucket, prefix))
}

To invoke the above curried map() function, simply pass the already constructed (and properly initialized) AmazonS3Client object (refer to the official AWS SDK for Java API Reference), the bucket name and the prefix name in the first parameter list. Also pass the function f() you want to apply to map each object summary in the second parameter list.

For example

val keyOwnerTuples = map(s3, bucket, prefix)(s => (s.getKey, s.getOwner))

will return the full list of (key, owner) tuples in that bucket/prefix

or

map(s3, "bucket", "prefix")(s => println(s))

as you would normally approach by Monads in Functional Programming

How to test web service using command line curl

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl https://api.twitter.com/1/help/configuration.xml  | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

sql select with column name like

You need to use view INFORMATION_SCHEMA.COLUMNS

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = my_table_name AND COLUMN_NAME like 'a%'

TO inline rows you can use PIVOT and for execution EXEC() function.

How to find the files that are created in the last hour in unix

Check out this link for more details.

To find files which are created in last one hour in current directory, you can use -amin

find . -amin -60 -type f

This will find files which are created with in last 1 hour.

What is the best way to left align and right align two div tags?

As an alternative way to floating:

<style>
    .wrapper{position:relative;}
    .right,.left{width:50%; position:absolute;}
    .right{right:0;}
    .left{left:0;}
</style>
...
<div class="wrapper">
    <div class="left"></div>
    <div class="right"></div>
</div>

Considering that there's no necessity to position the .left div as absolute (depending on your direction, this could be the .right one) due to that would be in the desired position in natural flow of html code.

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

Setting up a JavaScript variable from Spring model by using Thymeleaf

If you need to display your variable unescaped, use this format:

<script th:inline="javascript">
/*<![CDATA[*/

    var message = /*[(${message})]*/ 'default';

/*]]>*/
</script>

Note the [( brackets which wrap the variable.

How to replace url parameter with javascript/jquery?

I have get best solution to replace the URL parameter.

Following function will replace room value to 3 in the following URL.

http://example.com/property/?min=50000&max=60000&room=1&property_type=House

var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);

function replaceUrlParam(paramName, paramValue){
    var url = window.location.href;

    if (paramValue == null) {
        paramValue = '';
    }

    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }

    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Output

http://example.com/property/?min=50000&max=60000&room=3&property_type=House

I/O error(socket error): [Errno 111] Connection refused

Its seems that server is not running properly so ensure that with terminal by

telnet ip port

example

telnet localhost 8069

It will return connected to localhost so it indicates that there is no problem with the connection Else it will return Connection refused it indicates that there is problem with the connection

Add content to a new open window

Here is what you can try

  • Write a function say init() inside mypage.html that do the html thing ( append or what ever)
  • instead of OpenWindow.document.write(output); call OpenWindow.init() when the dom is ready

So the parent window will have

    OpenWindow.onload = function(){
       OpenWindow.init('test');
    }

and in the child

    function init(txt){
        $('#test').text(txt);
    }

What is the meaning of "Failed building wheel for X" in pip install?

Yesterday, I got the same error: Failed building wheel for hddfancontrol when I ran pip3 install hddfancontrol. The result was Failed to build hddfancontrol. The cause was error: invalid command 'bdist_wheel' and Running setup.py bdist_wheel for hddfancontrol ... error. The error was fixed by running the following:

 pip3 install wheel

(From here.)

Alternatively, the "wheel" can be downloaded directly from here. When downloaded, it can be installed by running the following:

pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"

Full examples of using pySerial package

http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

#!/usr/bin/python

import serial, time
#initialization and open the port

#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #give the serial port sometime to receive the data

       numOfLines = 0

       while True:
          response = ser.readline()
          print("read data: " + response)

        numOfLines = numOfLines + 1

        if (numOfLines >= 5):
            break

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

How to get a user's time zone?

Swift 4, 4.2 & 5

var timeZone : String = String()

override func viewDidLoad() {
    super.viewDidLoad()
    timeZone = getCurrentTimeZone()
    print(timeZone)
}

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let items = (localTimeZoneAbbreviation / 3600)
        return "\(items)"
}

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

nano error: Error opening terminal: xterm-256color

  1. edit your .bash_profile file

    vim .bash_profile

  2. commnet

    #export TERM=xterm-256color

  3. add this

    export TERMINFO=/usr/share/terminfo

    export TERM=xterm-basic

    to your .bash_profile

  4. finally

    run:

    source .bash_profile

What is the most efficient way to loop through dataframes with pandas?

I believe the most simple and efficient way to loop through DataFrames is using numpy and numba. In that case, looping can be approximately as fast as vectorized operations in many cases. If numba is not an option, plain numpy is likely to be the next best option. As has been noted many times, your default should be vectorization, but this answer merely considers efficient looping, given the decision to loop, for whatever reason.

For a test case, let's use the example from @DSM's answer of calculating a percentage change. This is a very simple situation and as a practical matter you would not write a loop to calculate it, but as such it provides a reasonable baseline for timing vectorized approaches vs loops.

Let's set up the 4 approaches with a small DataFrame, and we'll time them on a larger dataset below.

import pandas as pd
import numpy as np
import numba as nb

df = pd.DataFrame( { 'close':[100,105,95,105] } )

pandas_vectorized = df.close.pct_change()[1:]

x = df.close.to_numpy()
numpy_vectorized = ( x[1:] - x[:-1] ) / x[:-1]
        
def test_numpy(x):
    pct_chng = np.zeros(len(x))
    for i in range(1,len(x)):
        pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
    return pct_chng

numpy_loop = test_numpy(df.close.to_numpy())[1:]

@nb.jit(nopython=True)
def test_numba(x):
    pct_chng = np.zeros(len(x))
    for i in range(1,len(x)):
        pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
    return pct_chng
    
numba_loop = test_numba(df.close.to_numpy())[1:]

And here are the timings on a DataFrame with 100,000 rows (timings performed with Jupyter's %timeit function, collapsed to a summary table for readability):

pandas/vectorized   1,130 micro-seconds
numpy/vectorized      382 micro-seconds
numpy/looped       72,800 micro-seconds
numba/looped          455 micro-seconds

Summary: for simple cases, like this one, you would go with (vectorized) pandas for simplicity and readability, and (vectorized) numpy for speed. If you really need to use a loop, do it in numpy. If numba is available, combine it with numpy for additional speed. In this case, numpy + numba is almost as fast as vectorized numpy code.

Other details:

  • Not shown are various options like iterrows, itertuples, etc. which are orders of magnitude slower and really should never be used.
  • The timings here are fairly typical: numpy is faster than pandas and vectorized is faster than loops, but adding numba to numpy will often speed numpy up dramatically.
  • Everything except the pandas option requires converting the DataFrame column to a numpy array. That conversion is included in the timings.
  • The time to define/compile the numpy/numba functions was not included in the timings, but would generally be a negligible component of the timing for any large dataframe.

In Java how does one turn a String into a char or a char into a String?

I like to do something like this:

String oneLetter = "" + someChar;

Check if Key Exists in NameValueCollection

queryItems.AllKeys.Contains(key)

Be aware that key may not be unique and that the comparison is usually case sensitive. If you want to just get the value of the first matching key and not bothered about case then use this:

        public string GetQueryValue(string queryKey)
        {
            foreach (string key in QueryItems)
            {
                if(queryKey.Equals(key, StringComparison.OrdinalIgnoreCase))
                    return QueryItems.GetValues(key).First(); // There might be multiple keys of the same name, but just return the first match
            }
            return null;
        }

How to view the stored procedure code in SQL Server Management Studio

The other answers that recommend using the object explorer and scripting the stored procedure to a new query editor window and the other queries are solid options.

I personally like using the below query to retrieve the stored procedure definition/code in a single row (I'm using Microsoft SQL Server 2014, but looks like this should work with SQL Server 2008 and up)

SELECT definition 
FROM sys.sql_modules 
WHERE object_id = OBJECT_ID('yourSchemaName.yourStoredProcedureName')

More info on sys.sql_modules:

https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-sql-modules-transact-sql

Getting a list of associative array keys

I am currently using Rob de la Cruz's reply:

Object.keys(obj)

And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.

if (!Object.keys) {
    Object.keys = function(object) {
        var keys = [];
        for (var o in object) {
            if (object.hasOwnProperty(o)) {
                keys.push(o);
            }
        }
        return keys;
    };
}

I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.

Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.

How to change the font and font size of an HTML input tag?

In your 'head' section, add this code:

<style>
input[type='text'] { font-size: 24px; }
</style>

Or you can only add the:

input[type='text'] { font-size: 24px; }

to a CSS file which can later be included.

You can also change the font face by using the CSS property: font-family

font-family: monospace;

So you can have a CSS code like this:

input[type='text'] { font-size: 24px; font-family: monospace; }

You can find further help at the W3Schools website.

I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.

Inserting an item in a Tuple

one way is to convert it to list

>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)

jQuery function to get all unique elements from an array?

If anyone is using knockoutjs try:

ko.utils.arrayGetDistinctValues()

BTW have look at all ko.utils.array* utilities.

How do I open a second window from the first window in WPF?

This helped me: The Owner method basically ties the window to another window in case you want extra windows with the same ones.

LoadingScreen lc = new LoadingScreen();
lc.Owner = this;
lc.Show();

Consider this as well.

this.WindowState = WindowState.Normal;
this.Activate();

C - function inside struct

You can pass the struct pointer to function as function argument. It called pass by reference.

If you modify something inside that pointer, the others will be updated to. Try like this:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;
};

pno AddClient(client_t *client)
{
        /* this will change the original client value */
        client.password = "secret";
}

int main()
{
    client_t client;

    //code ..

    AddClient(&client);
}

Compiling with g++ using multiple cores

make will do this for you. Investigate the -j and -l switches in the man page. I don't think g++ is parallelizable.

Redirect stderr to stdout in C shell

I think this is the correct answer for csh.

xxx >/dev/stderr

Note most csh are really tcsh in modern environments:

rmockler> ls -latr /usr/bin/csh

lrwxrwxrwx 1 root root 9 2011-05-03 13:40 /usr/bin/csh -> /bin/tcsh

using a backtick embedded statement to portray this as follows:

echo "`echo 'standard out1'` `echo 'error out1' >/dev/stderr` `echo 'standard out2'`" | tee -a /tmp/test.txt ; cat /tmp/test.txt

if this works for you please bump up to 1. The other suggestions don't work for my csh environment.

Write HTML file using Java

If you want to do that yourself, without using any external library, a clean way would be to create a template.html file with all the static content, like for example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>$title</title>
</head>
<body>$body
</body>
</html>

Put a tag like $tag for any dynamic content and then do something like this:

File htmlTemplateFile = new File("path/template.html");
String htmlString = FileUtils.readFileToString(htmlTemplateFile);
String title = "New Page";
String body = "This is Body";
htmlString = htmlString.replace("$title", title);
htmlString = htmlString.replace("$body", body);
File newHtmlFile = new File("path/new.html");
FileUtils.writeStringToFile(newHtmlFile, htmlString);

Note: I used org.apache.commons.io.FileUtils for simplicity.

Display Yes and No buttons instead of OK and Cancel in Confirm box?

There is the Jquery alert plugin

$.alerts.okButton = ' Yes ';
$.alerts.cancelButton = ' No ';

How to remove leading zeros from alphanumeric text?

Using Regexp with groups:

Pattern pattern = Pattern.compile("(0*)(.*)");
String result = "";
Matcher matcher = pattern.matcher(content);
if (matcher.matches())
{
      // first group contains 0, second group the remaining characters
      // 000abcd - > 000, abcd
      result = matcher.group(2);
}

return result;

Definitive way to trigger keypress events with jQuery

console.log( String.fromCharCode(event.charCode) );

no need to map character i guess.

pandas: best way to select all columns whose names start with X

My solution. It may be slower on performance:

a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
a.sort_index()


   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Can you use @Autowired with static fields?

Disclaimer This is by no means standard and there could very well be a better spring way of doing this. None of the above answers address the issues of wiring a public static field.

I wanted to accomplish three things.

  1. Use spring to "Autowire" (Im using @Value)
  2. Expose a public static value
  3. Prevent modification

My object looks like this

private static String BRANCH = "testBranch";

@Value("${content.client.branch}")
public void finalSetBranch(String branch) {
    BRANCH = branch;
}

public static String BRANCH() {
    return BRANCH;
}

We have checked off 1 & 2 already now how do we prevent calls to the setter, since we cannot hide it.

@Component
@Aspect
public class FinalAutowiredHelper {

@Before("finalMethods()")
public void beforeFinal(JoinPoint joinPoint) {
    throw new FinalAutowiredHelper().new ModifySudoFinalError("");
}

@Pointcut("execution(* com.free.content.client..*.finalSetBranch(..))")
public void finalMethods() {}


public class ModifySudoFinalError extends Error {
    private String msg;

    public ModifySudoFinalError(String msg) {
        this.msg = msg;
    }

    @Override
    public String getMessage() {
        return "Attempted modification of a final property: " + msg;
    }
}

This aspect will wrap all methods beginning with final and throw an error if they are called.

I dont think this is particularly useful, but if you are ocd and like to keep you peas and carrots separated this is one way to do it safely.

Important Spring does not call your aspects when it calls a function. Made this easier, to bad I worked out the logic before figuring that out.

Percentage width in a RelativeLayout

I have solved this creating a custom View:

public class FractionalSizeView extends View {
  public FractionalSizeView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public FractionalSizeView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width * 70 / 100, 0);
  }
}

This is invisible strut I can use to align other views within RelativeLayout.

Android: Internet connectivity change listener

This my implementation which you can providing in application scope:

class NetworkStateHelper @Inject constructor(
        private val context: Context
) {
    private val cache: BehaviorSubject<Boolean> = BehaviorSubject.create()

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(c: Context?, intent: Intent?) {
            cache.onNext(isOnlineOrConnecting())
        }
    }

    init {
        val intentFilter = IntentFilter()
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        context.registerReceiver(receiver, intentFilter)
        cache.onNext(isOnlineOrConnecting())
    }

    fun subscribe(): Observable<Boolean> {
        return cache
    }

    fun isOnlineOrConnecting(): Boolean {
        val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val netInfo = cm.activeNetworkInfo
        return netInfo != null && netInfo.isConnectedOrConnecting
    }
}

I used this rxjava and dagger2 libraies

pip install failing with: OSError: [Errno 13] Permission denied on directory

We should really stop advising the use of sudo with pip install. It's better to first try pip install --user. If this fails then take a look at the top post here.

The reason you shouldn't use sudo is as follows:

When you run pip with sudo, you are running arbitrary Python code from the Internet as a root user, which is quite a big security risk. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine.

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

  1. Start oracleserviceorcl service. (From services in Task Manager)
  2. Set ORACLE_SID variable with orcl value. (In environment variables)

Java: Converting String to and from ByteBuffer and associated problems

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

Using NSPredicate to filter an NSArray based on NSDictionary keys

Looking at the NSPredicate reference, it looks like you need to surround your substitution character with quotes. For example, your current predicate reads: (SPORT == Football) You want it to read (SPORT == 'Football'), so your format string needs to be @"(SPORT == '%@')".

SelectSingleNode returning null for known good xml node path using XPath

Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.

XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";
vinDoc.LoadXml(vinInfo);

vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"http://tempuri.org\/\", "");

How to remove a directory from git repository?

I usually use git add --all to remove files / folders from remote repositories

rm -r folder_name
git add --all
git commit -m "some comment"
git push origin master

master can be replaced by any other branch of the repository.

Invert match with regexp

Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').

^((?!foo).)*$

This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

I encountered a similar issue trying to use xlrd in jupyter notebook. I notice you are using a virtual environment and that was the key to my issue as well. I had xlrd installed in my venv, but I had not properly installed a kernel for that virtual environment in my notebook.

To get it to work, I created my virtual environment and activated it.

Then... pip install ipykernel

And then... ipython kernel install --user --name=myproject

Finally, start jupyter notebooks and when you create a new notebook, select the name you created (in this example, 'myproject')

Hope that helps.

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

What is the syntax to insert one list into another list in python?

Do you mean append?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]

Or merge?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6] 

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?

  • Check the other server's network configuration in SQL Server.
  • Check the other machines FIREWALL. SQL Server does not open ports automatically, so the windows firewall normally blocks access..

Emulate/Simulate iOS in Linux

The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.

It works pretty good for testing.

Create an ArrayList of unique values

I use helper class. Not sure it's good or bad

public class ListHelper<T> {
    private final T[] t;

    public ListHelper(T[] t) {
        this.t = t;
    }

    public List<T> unique(List<T> list) {
       Set<T> set = new HashSet<>(list);
        return Arrays.asList(set.toArray(t));
    }
}

Usage and test:

import static org.assertj.core.api.Assertions.assertThat;


public class ListHelperTest {

    @Test
    public void unique() {
        List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
        List<String> unique = new ListHelper<>(new String[0]).unique(s);
        assertThat(unique).hasSize(3);
    }
}

Or Java8 version:

public class ListHelper<T> {
    public Function<List<T>, List<T>> unique() {
        return l -> l.stream().distinct().collect(Collectors.toList());
    }
}

public class ListHelperTest {
    @Test
    public void unique() {
        List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
        assertThat(new ListHelper<String>().unique().apply(s)).hasSize(3);
    }
}

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

Render Partial View Using jQuery in ASP.NET MVC

Another thing you can try (based on tvanfosson's answer) is this:

<div class="renderaction fade-in" 
    data-actionurl="@Url.Action("details","user", new { id = Model.ID } )"></div>

And then in the scripts section of your page:

<script type="text/javascript">
    $(function () {
        $(".renderaction").each(function (i, n) {
            var $n = $(n),
                url = $n.attr('data-actionurl'),
                $this = $(this);

            $.get(url, function (data) {
                $this.html(data);
            });
        });
    });

</script>

This renders your @Html.RenderAction using ajax.

And to make it all fansy sjmansy you can add a fade-in effect using this css:

/* make keyframes that tell the start state and the end state of our object */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

.fade-in {
    opacity: 0; /* make things invisible upon start */
    -webkit-animation: fadeIn ease-in 1; /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
    -moz-animation: fadeIn ease-in 1;
    -o-animation: fadeIn ease-in 1;
    animation: fadeIn ease-in 1;
    -webkit-animation-fill-mode: forwards; /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -o-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -webkit-animation-duration: 1s;
    -moz-animation-duration: 1s;
    -o-animation-duration: 1s;
    animation-duration: 1s;
}

Man I love mvc :-)

Strip last two characters of a column in MySQL

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt

Does --disable-web-security Work In Chrome Anymore?

The new tag for recent Chrome and Chromium browsers is :

--disable-web-security --user-data-dir=c:\my\data

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Please incre max_iter to 10000 as default value is 1000. Possibly, increasing no. of iterations will help algorithm to converge. For me it converged and solver was -'lbfgs'

log_reg = LogisticRegression(solver='lbfgs',class_weight='balanced', max_iter=10000)

How do you append to an already existing string?

teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

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

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Content is not allowed in Prolog SAXParserException

This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.

You will find a possible solution here.

JavaScript associative array to JSON

You might want to push the object into the array

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);

Why is document.write considered a "bad practice"?

Chrome may block document.write that inserts a script in certain cases. When this happens, it will display this warning in the console:

A Parser-blocking, cross-origin script, ..., is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity.

References:

onchange file input change img src and change image color

Try with this code, you will get the image preview while uploading

<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />

 function readURL(input){
 var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) 
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}else{
     $('#img').attr('src', '/assets/no_preview.png');
}
}

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

What is the mouse down selector in CSS?

I figured out that this behaves like a mousedown event:

button:active:hover {}

Get string character by index - Java

You could use the String.charAt(int index) method result as the parameter for String.valueOf(char c).

String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.

Where does Jenkins store configuration files for the jobs it runs?

For the sake of completeness: macOS High Sierra, Jenkins 2.x, installation via Homebrew
~/.jenkins/jobs/{project_name}/config.xml

Complete overview about jenkins home: https://wiki.jenkins.io/display/JENKINS/Administering+Jenkins

Setting the number of map tasks and reduce tasks

  • Use -D property=value rather than -D property = value (eliminate extra whitespaces). Thus -D mapred.reduce.tasks=value would work fine.

  • Setting number of map tasks doesnt always reflect the value you have set since it depends on split size and InputFormat used.

  • Setting the number of reduces will definitely override the number of reduces set on cluster/client-side configuration.

Adding to a vector of pair

Or you can use initialize list:

revenue.push_back({"string", map[i].second});

How to place a JButton at a desired location in a JFrame using Java

Following line should be called before you add your component

pnlButton.setLayout(null);

Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds method.

In general I wouldn't recommend using absolute layout.

C++ static virtual members?

It is possible. Make two functions: static and virtual

struct Object{     
  struct TypeInformation;
  static  const TypeInformation &GetTypeInformationStatic() const 
  { 
      return GetTypeInformationMain1();
  }
  virtual const TypeInformation &GetTypeInformation() const
  { 
      return GetTypeInformationMain1();
  }
protected:
  static const TypeInformation &GetTypeInformationMain1(); // Main function
};

struct SomeObject : public Object {     
  static  const TypeInformation &GetTypeInformationStatic() const 
  { 
      return GetTypeInformationMain2();
  }
  virtual const TypeInformation &GetTypeInformation() const
  { 
      return GetTypeInformationMain2();
  }
protected:
  static const TypeInformation &GetTypeInformationMain2(); // Main function
};

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

Is there a quick change tabs function in Visual Studio Code?

for linux... I use ctrl+pageUp or pageDown

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

Add numpy array as column to Pandas data frame

Consider using a higher dimensional datastructure (a Panel), rather than storing an array in your column:

In [11]: p = pd.Panel({'df': df, 'csc': csc})

In [12]: p.df
Out[12]: 
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

In [13]: p.csc
Out[13]: 
   0  1  2
0  0  1  0
1  0  0  1
2  1  0  0

Look at cross-sections etc, etc, etc.

In [14]: p.xs(0)
Out[14]: 
   csc  df
0    0   1
1    1   2
2    0   3

See the docs for more on Panels.

Javascript array sort and unique

How about:

array.sort().filter(function(elem, index, arr) {
  return index == arr.length - 1 || arr[index + 1] != elem
})

This is similar to @loostro answer but instead of using indexOf which will reiterate the array for each element to verify that is the first found, it just checks that the next element is different than the current.

Maintaining the final state at end of a CSS3 animation

If you are using more animation attributes the shorthand is:

animation: bubble 2s linear 0.5s 1 normal forwards;

This gives:

  • bubble animation name
  • 2s duration
  • linear timing-function
  • 0.5s delay
  • 1 iteration-count (can be 'infinite')
  • normal direction
  • forwards fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})

C# Error "The type initializer for ... threw an exception

This problem can occur if a class tries to get value of a non-existent key in web.config.

For example, the class has a static variable ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.config doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

How to disable sort in DataGridView?

foreach (DataGridViewColumn column in dataGridView.Columns)
{
    column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

Unfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array

The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.

Good luck!

Setting cursor at the end of any text of a textbox

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

Check if int is between two numbers

It's just the syntax. '<' is a binary operation, and most languages don't make it transitive. They could have made it like the way you say, but then somebody would be asking why you can't do other operations in trinary as well. "if (12 < x != 5)"?

Syntax is always a trade-off between complexity, expressiveness and readability. Different language designers make different choices. For instance, SQL has "x BETWEEN y AND z", where x, y, and z can individually or all be columns, constants, or bound variables. And I'm happy to use it in SQL, and I'm equally happy not to worry about why it's not in Java.

How to make background of table cell transparent

Just set the opacity for the inner table. You can do inline CSS if you want it just for a specific table element, so it doesn't apply to the entire table.

style="opacity: 0%;"

Pad a number with leading zeros in JavaScript

This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0.

function ZeroPadNumber ( nValue )
{
    if ( nValue < 10 )
    {
        return ( '000' + nValue.toString () );
    }
    else if ( nValue < 100 )
    {
        return ( '00' + nValue.toString () );
    }
    else if ( nValue < 1000 )
    {
        return ( '0' + nValue.toString () );
    }
    else
    {
        return ( nValue );
    }
}

This function is also hardcoded to your particular need (4 digit padding), so it's not generic.

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

With a React Native running in the emulator,
Press ctrl+m (for Linux, I suppose it's the same for Windows and ?+m for Mac OS X) or run the following in terminal:

adb shell input keyevent 82

A potentially dangerous Request.Path value was detected from the client (*)

When dealing with Uniform Resource Locator(URL) s there are certain syntax standards, in this particular situation we are dealing with Reserved Characters.

As up to RFC 3986, Reserved Characters may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm; And asterisk(*) is a Reserved Character.

The best practice is to use Unreserved Characters in URLs or you can try encoding it.

Keep digging :

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

The next() moves the cursor froward one row from its current position in the resultset. so its evident that if(rs.next()) means that if the next row is not null (means if it exist), Go Ahead.

Now w.r.t your problem,

ResultSet rs = stmt.executeQuery(sql);  //This is wrong
                                  ^       

note that executeQuery(String) is used in case you use a sql-query as string.

Whereas when you use a PreparedStatement, use executeQuery() which executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Solution :

Use : ResultSet rs = stmt.executeQuery();

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

How to compare character ignoring case in primitive types

The Character class of Java API has various functions you can use.

You can convert your char to lowercase at both sides:

Character.toLowerCase(name1.charAt(i)) == Character.toLowerCase(name2.charAt(j))

There are also a methods you can use to verify if the letter is uppercase or lowercase:

Character.isUpperCase('P')
Character.isLowerCase('P') 

Spring MVC + JSON = 406 Not Acceptable

Today I too gone through the same issue. In my case, in web.xml I have

   <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

my url is having .html extension. Ex:.../getUsers.html. But I am returning JSON data in controller. .html extension will by default set accept type as html.

So I changed to the following:

web.xml:

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.html</url-pattern>
    <url-pattern>*.json</url-pattern>
</servlet-mapping>

URL:

.../getUsers.json

Everything is working fine now. Hope it helps.

jQuery UI Accordion Expand/Collapse All

In the end I found this to be the best solution considering the requirements:

// Expand/Collapse all
$('.accordion-expand-collapse a').click(function() {
    $('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideToggle();
    $(this).text($(this).text() == 'Expand all' ? 'Collapse all' : 'Expand all');
    $(this).toggleClass('collapse');
    return false;
});

Updated JSFiddle Link: http://jsfiddle.net/ccollins1544/r8j105de/4/

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get the actual access_token, you can also do pro grammatically via the following PHP code:

 require 'facebook.php';

 $facebook = new Facebook(array(
   'appId'  => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 ));

 // Get User ID
 $user = $facebook->getUser();

 if ($user) {
   try {
     $user_profile = $facebook->api('/me');
     $access_token = $facebook->getAccessToken();
   } catch (FacebookApiException $e) {
     error_log($e);
     $user = null;
   }
 }

Cannot refer to a non-final variable inside an inner class defined in a different method

To avoid strange side-effects with closures in java variables referenced by an anonymous delegate must be marked as final, so to refer to lastPrice and price within the timer task they need to be marked as final.

This obviously won't work for you because you wish to change them, in this case you should look at encapsulating them within a class.

public class Foo {
    private PriceObject priceObject;
    private double lastPrice;
    private double price;

    public Foo(PriceObject priceObject) {
        this.priceObject = priceObject;
    }

    public void tick() {
        price = priceObject.getNextPrice(lastPrice);
        lastPrice = price;
    }
}

now just create a new Foo as final and call .tick from the timer.

public static void main(String args[]){
    int period = 2000;
    int delay = 2000;

    Price priceObject = new Price();
    final Foo foo = new Foo(priceObject);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            foo.tick();
        }
    }, delay, period);
}

Replace a newline in TSQL

If your column data type is 'text' then you will get an error message as

Msg 8116, Level 16, State 1, Line 2 Argument data type text is invalid for argument 1 of replace function.

In this case you need to cast the text as nvarchar and then replace

SELECT REPLACE(REPLACE(cast(@str as nvarchar(max)), CHAR(13), ''), CHAR(10), '')

Embed Youtube video inside an Android app

Refer to this answer: How can we play YouTube embeded code in an Android application using webview?

It uses WebViews and loads an iframe in it... and yes it works.

After installation of Gulp: “no command 'gulp' found”

Tried with sudo and it worked !!

sudo npm install --global gulp-cli

Is it possible to set a custom font for entire of application?

Yes, its possible to set the font to the entire application.

The easiest way to accomplish this is to package the desired font(s) with your application.

To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets.

You might, for example, create assets/fonts/ and put your TTF files in there.

public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);

Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}

How can I get date and time formats based on Culture Info?

You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:

CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;

CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;

If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:

string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

Using :: in C++

You're pretty much right about cout and cin. They are objects (not functions) defined inside the std namespace. Here are their declarations as defined by the C++ standard:

Header <iostream> synopsis

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;

  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

:: is known as the scope resolution operator. The names cout and cin are defined within std, so we have to qualify their names with std::.

Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:

class foo
{
  public:
    foo();
    void bar();
};

The constructor named foo is a member of the class named foo. They have the same name because its the constructor. The function bar is also a member of foo.

Because they are members of foo, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar outside the class, you need to do it like so:

foo::foo()
{
  // Implement the constructor
}

void foo::bar()
{
  // Implement bar
}

This is because they are being defined outside the class. If you had not put the foo:: qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo. For example, this is entirely different bar:

void bar()
{
  // Implement different bar
}

It's allowed to have the same name as the function in the foo class because it's in a different scope. This bar is in the global scope, whereas the other bar belonged to the foo class.

Shorthand if/else statement Javascript

y = (y != undefined) ? y : x;

The parenthesis are not necessary, I just add them because I think it's easier to read this way.

Convert array into csv

A slight adaptation to the solution above by kingjeffrey for when you want to create and echo the CSV within a template (Ie - most frameworks will have output buffering enabled and you are required to set headers etc in controllers.)

// Create Some data
<?php
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );


// Create a stream opening it with read / write mode
$stream = fopen('data://text/plain,' . "", 'w+');

// Iterate over the data, writting each line to the text stream
foreach ($data as $val) {
    fputcsv($stream, $val);
}

// Rewind the stream
rewind($stream);

// You can now echo it's content
echo stream_get_contents($stream);

// Close the stream 
fclose($stream);

Credit to Kingjeffrey above and also to this blog post where I found the information about creating text streams.

how to do bitwise exclusive or of two strings in python?

If the strings are not even of equal length, you can use this

def strxor(a, b):     # xor two strings of different lengths
    if len(a) > len(b):
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
    else:
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

Change keystore password from no password to a non blank password

this way worked better for me:

echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt

machine running:

[root@rhel80-68]# cat /etc/redhat-release 
Red Hat Enterprise Linux release 8.1 (Ootpa)