Programs & Examples On #Fileserver

In computing, a file server is a computer attached to a network that has the primary purpose of providing a location for shared disk access, i.e. shared storage of computer files (such as documents, sound files, photographs, movies, images, databases, etc.) that can be accessed by the workstations that are attached to the computer network.

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

Node.js quick file server (static files over HTTP)

For people wanting a server runnable from within NodeJS script:

You can use expressjs/serve-static which replaces connect.static (which is no longer available as of connect 3):

myapp.js:

var http = require('http');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');

var serve = serveStatic("./");

var server = http.createServer(function(req, res) {
  var done = finalhandler(req, res);
  serve(req, res, done);
});

server.listen(8000);

and then from command line:

  • $ npm install finalhandler serve-static
  • $ node myapp.js

How can I get the root domain URI in ASP.NET?

This works also:

string url = HttpContext.Request.Url.Authority;

Saving a select count(*) value to an integer (SQL Server)

[update] -- Well, my own foolishness provides the answer to this one. As it turns out, I was deleting the records from myTable before running the select COUNT statement.

How did I do that and not notice? Glad you asked. I've been testing a sql unit testing platform (tsqlunit, if you're interested) and as part of one of the tests I ran a truncate table statement, then the above. After the unit test is over everything is rolled back, and records are back in myTable. That's why I got a record count outside of my tests.

Sorry everyone...thanks for your help.

Git says remote ref does not exist when I delete remote branch

git push origin --delete origin/test 

should work as well

python: creating list from string

More concise than others:

def parseString(string):
    try:
        return int(string)
    except ValueError:
        return string

b = [[parseString(s) for s in clause.split(', ')] for clause in a]

Alternatively if your format is fixed as <string>, <int>, <int>, you can be even more concise:

def parseClause(a,b,c):
    return [a, int(b), int(c)]

b = [parseClause(*clause) for clause in a]

ETag vs Header Expires

In my view, With Expire Header, server can tell the client when my data would be stale, while with Etag, server would check the etag value for client' each request.

MSBUILD : error MSB1008: Only one project can be specified

Try to remove the trailing backslash or slash at the end of you publish path and install url

/p:PublishDir="\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest"
/p:InstallUrl="https://www.benesys.net/benesys.net/TotalEducationTest"

You must have hit a special sequence of characters with the \" and (or) /", but I don't know enough in cmd.exe to figure out.

I personnaly always use Powershell : it's way more friendly and powerful!

Hope it helps!

How to remove element from array in forEach loop?

Here is how you should do it:

review.forEach(function(p,index,object){
   if(review[index] === '\u2022 \u2022 \u2022'){
      console.log('YippeeeE!!!!!!!!!!!!!!!!')
      review.splice(index, 1);
   }
});

How to check if a String contains any of some strings

As a string is a collection of characters, you can use LINQ extension methods on them:

if (s.Any(c => c == 'a' || c == 'b' || c == 'c')) ...

This will scan the string once and stop at the first occurance, instead of scanning the string once for each character until a match is found.

This can also be used for any expression you like, for example checking for a range of characters:

if (s.Any(c => c >= 'a' && c <= 'c')) ...

How do I make an HTML button not reload the page

I can't comment yet, so I'm posting this as an answer. Best way to avoid reload is how @user2868288 said: using the onsubmit on the form tag.

From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page. For example:

<form id="frmData" onsubmit="return false">
 <input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
 <input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
 <input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
  $(document).ready(function(){
    $('#btnSubmit').click(function() {
        var tel = $("#txtTel").val();
        var email = $("#txtEmail").val();
        $.post("scripts/contact.php", {
            tel1: tel,
            email1: email
        })
        .done(function(data) {
            $('#lblEstatus').append(data); // Appends status
            if (data == "Received") {
                $("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
            }
        })
        .fail(function(xhr, textStatus, errorThrown) { 
            $('#lblEstatus').append("Error. Try later."); 
        });
     });
   }); 
</script>

How to format numbers by prepending 0 to single-digit numbers?

Here's the easiest solution I found:-

let num = 9; // any number between 0 & 99
let result = ( '0' + num ).substr( -2 );

Creating and playing a sound in swift

Here's a bit of code I've got added to FlappySwift that works:

import SpriteKit
import AVFoundation

class GameScene: SKScene {

    // Grab the path, make sure to add it to your project!
    var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
    var audioPlayer = AVAudioPlayer()

    // Initial setup
    override func didMoveToView(view: SKView) {
        audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
        audioPlayer.prepareToPlay()
    }

    // Trigger the sound effect when the player grabs the coin
    func didBeginContact(contact: SKPhysicsContact!) {
        audioPlayer.play()
    }

}

HTML Image not displaying, while the src url works

Your file needs to be located inside your www directory. For example, if you're using wamp server on Windows, j3evn.jpg should be located,

C:/wamp/www/img/j3evn.jpg

and you can access it in html via

<img class="sealImage" alt="Image of Seal" src="../img/j3evn.jpg">

Look for the www, public_html, or html folder belonging to your web server. Place all your files and resources inside that folder.

Hope this helps!

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

I have done the following steps to get rid of this issue. Login into the MySQL in your machine using (sudo mysql -p -u root) and hit the following queries.

1. CREATE USER 'jack'@'localhost' IDENTIFIED WITH mysql_native_password BY '<<any password>>';

2. GRANT ALL PRIVILEGES ON *.* TO 'jack'@'localhost';

3. SELECT user,plugin,host FROM mysql.user WHERE user = 'root';
+------+-------------+-----------+
| user | plugin      | host      |

+------+-------------+-----------+

| root | auth_socket | localhost |

+------+-------------+-----------+

4. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<<any password>>';

5. FLUSH PRIVILEGES;

Please try it once if you are still getting the error. I hope this code will help you a lot !!

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Foreign Key to non-primary key

Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

Show Curl POST Request Headers? Is there a way to do this?

You can see the information regarding the transfer by doing:

curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);

before the request, and

$information = curl_getinfo($curl_exect);

after the request

View: http://www.php.net/manual/en/function.curl-getinfo.php

You can also use the CURLOPT_HEADER in your curl_setopt

curl_setopt($curl_exect, CURLOPT_HEADER, true);

$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);

return $httpcode == 200;

These are just some methods of using the headers.

How do I install cygwin components from the command line?

Dawid Ferenczy's answer is pretty complete but after I tried almost all of his options I've found that the Chocolatey’s cyg-get was the best (at least the only one that I could get to work).

I was wanting to install wget, the steps was this:

choco install cyg-get

Then:

cyg-get wget

Is it possible to Turn page programmatically in UIPageViewController?

What about using methods from dataSource?

UIViewController *controller = [pageViewController.dataSource pageViewController:self.pageViewController viewControllerAfterViewController:pageViewController.viewControllers.firstObject];
[pageViewController setViewControllers:@[controller] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

Analogically for backward.

This could be due to the service endpoint binding not using the HTTP protocol

I figured out the problem. It ended up being a path to my config file was wrong. The errors for WCF are so helpful sometimes.

Find duplicate records in MySQL

I tried the best answer chosen for this question, but it confused me somewhat. I actually needed that just on a single field from my table. The following example from this link worked out very well for me:

SELECT COUNT(*) c,title FROM `data` GROUP BY title HAVING c > 1;

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

Disabled href tag

I see there are already a ton of answers posted here, but I don’t think there’s any clear one yet that combines the already mentioned approaches into the one I’ve found to work. This is to make the link both appear disabled, and also not redirect the user to another page.

This answer assumes you’re using jquery and bootstrap, and uses another property to temporarily store the href property while disabled.

//situation where link enable/disable should be toggled
function toggle_links(enable) {
    if (enable) {
        $('.toggle-link')
        .removeClass('disabled')
        .prop('href', $(this).attr('data-href'))
    }
    else {
        $('.toggle-link')
        .addClass('disabled')
        .prop('data-href', $(this).prop('href'))
        .prop('href','#')
    }
a.disabled {
  cursor: default;
}

How to update each dependency in package.json to the latest version?

This works as of npm 1.3.15.

"dependencies": {
  "foo": "latest"
}

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

How do I edit SSIS package files?

Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx

SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.

Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.

This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016

Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Try using the passive command before using ls.

From FTP client, to check if the FTP server supports passive mode, after login, type quote PASV.

Following are connection examples to a vsftpd server with passive mode on and off

vsftpd with pasv_enable=NO:

# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
550 Permission denied.
ftp> 

vsftpd with pasv_enable=YES:

# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
227 Entering Passive Mode (127,0,0,1,173,104).
ftp> 

How to find all combinations of coins when given some dollar value

This blog entry of mine solves this knapsack like problem for the figures from an XKCD comic. A simple change to the items dict and the exactcost value will yield all solutions for your problem too.

If the problem were to find the change that used the least cost, then a naive greedy algorithm that used as much of the highest value coin might well fail for some combinations of coins and target amount. For example if there are coins with values 1, 3, and 4; and the target amount is 6 then the greedy algorithm might suggest three coins of value 4, 1, and 1 when it is easy to see that you could use two coins each of value 3.

  • Paddy.

VBA equivalent to Excel's mod function

But if you just want to tell the difference between an odd iteration and an even iteration, this works just fine:

If i Mod 2 > 0 then 'this is an odd 
   'Do Something
Else 'it is even
   'Do Something Else
End If

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

Adding a SVN repository in Eclipse

You might want to check if the websecurity of vpn client is the issue. I uninstalled it and it worked fine..Found the solution here https://superuser.com/questions/471089/svn-connection-not-successful

Avoid dropdown menu close on click inside

I did it with this:

$(element).on({
    'mouseenter': function(event) {
        $(event.currentTarget).data('mouseover', true);
    },
    'mouseleave': function(event) {
        $(event.currentTarget).data('mouseover', false);
    },
    'hide.bs.dropdown': function (event) {
        return !$(event.currentTarget).data('mouseover');
    }
});

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

I found a new tool that makes this Really REALLY easy.

Use IE9 Developer mode. push F12.

Up in the File Menu, you can see Browser Version: IE9, click here and you can change the browser version all the way back to 7. For 6 you will still need a virtual PC.

Getting only Month and Year from SQL DATE

RIGHT(CONVERT(VARCHAR(10), reg_dte, 105), 7) 

SqlDataAdapter vs SqlDataReader

The answer to that can be quite broad.

Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.

Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.

WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.

Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:

Using cn As New SqlConnection("..."), _
      cmd As New SqlCommand("...", cn)

    cn.Open()
    Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            ''# ...
        End While
    End Using
End Using     

equivalent C#:

using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
    cn.Open();
    using(var rdr = cmd.ExecuteReader())
    {
        while(rdr.Read())
        {
            //...
        }
    }
}

Inline Form nested within Horizontal Form in Bootstrap 3

To make it work in Chrome (and bootply) i had to change code in this way:

<form class="form-horizontal">
  <div class="form-group">
    <label for="name" class="col-xs-2 control-label">Name</label>
    <div class="col-xs-10">
      <input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
    </div>
  </div>

  <div class="form-group">
    <label for="birthday" class="col-xs-2 control-label">Birthday</label>
    <div class="col-xs-10">
      <div class="form-inline">
        <input type="text" class="form-control" placeholder="year" />
        <input type="text" class="form-control" placeholder="month" />
        <input type="text" class="form-control" placeholder="day" />
      </div>
    </div>
  </div>
</form>

How to align content of a div to the bottom

try with:

div.myclass { margin-top: 100%; }

try changing the % to fix it. Example: 120% or 90% ...etc.

typeof !== "undefined" vs. != null

You can also use the void operator to obtain an undefined value:

if (input !== void 0) {
    // do stuff    
}

(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0 for testing global variables or adding var input.)

Method to get all files within folder and subfolders that will return a list

String[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories);

How to use a switch case 'or' in PHP

The best way might be if else with requesting. Also, this can be easier and clear to use.

Example:

<?php 
$go = $_REQUEST['go'];
?>
<?php if ($go == 'general_information'){?>
<div>
echo "hello";
}?>

Instead of using the functions that won't work well with PHP, especially when you have PHP in HTML.

Disable sorting on last column when using jQuery DataTables

This would be useful for v1.10+ of datatables. Set column number for which you want to remove sorting for e.g 1st column would be like:

columnDefs: [
   { orderable: false, targets: 0 }
]

For multiple columns(1st,second and third):

columnDefs: [
   { orderable: false, targets: [0,1,2] }
]

How to change the background color on a Java panel?

You could call:


getContentPane().setBackground(Color.black);

Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call


setBackground(Color.black);

on the JPanel to set the background color.

Customize UITableView header section

call this delegate method

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

return @"Some Title";
}

this will give a chance to automatically add a default header with dynamic title .

You may use reusable and customizable header / footer .

https://github.com/sourov2008/UITableViewCustomHeaderFooterSection

How to install a node.js module without using npm?

You need to download their source from the github. Find the main file and then include it in your main file.

An example of this can be found here > How to manually install a node.js module?

Usually you need to find the source and go through the package.json file. There you can find which is the main file. So that you can include that in your application.

To include example.js in your app. Copy it in your application folder and append this on the top of your main js file.

var moduleName = require("path/to/example.js")

Fastest way to add an Item to an Array

It depends on how often you insert or read. You can increase the array by more than one if needed.

numberOfItems = ??

' ...

If numberOfItems+1 >= arr.Length Then
    Array.Resize(arr, arr.Length + 10)
End If

arr(numberOfItems) = newItem
numberOfItems += 1

Also for A, you only need to get the array if needed.

Dim list As List(Of Integer)(arr) ' Do this only once, keep a reference to the list
                                  ' If you create a new List everything you add an item then this will never be fast

'...

list.Add(newItem)
arrayWasModified = True

' ...

Function GetArray()

    If arrayWasModified Then
        arr = list.ToArray()
    End If

    Return Arr
End Function

If you have the time, I suggest you convert it all to List and remove arrays.

* My code might not compile

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to retrieve all keys (or values) from a std::map and put them into a vector?

Based on @rusty-parks solution, but in c++17:

std::map<int, int> items;
std::vector<int> itemKeys;

for (const auto& [key, _] : items) {
    itemKeys.push_back(key);
}

IIS Express Windows Authentication

Building upon the answer from booij boy, check if you checked the "windows authentication" feature in Control Panel -> Programs -> Turn windows features on or of -> Internet Information Services -> World Wide Web Services -> Security

Also, there seems to be a big difference when using firefox or internet explorer. After enabeling the "windows authentication" it works for me but only in IE.

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

How to embed new Youtube's live video permanent URL?

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
            </iframe>
        </div>
    </div>
</div>

Tweak however you'd like!

Where is git.exe located?

type in the command line:

where git.exe

Exit while loop by user hitting ENTER key

Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.

  1. If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
  2. If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.

Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link

I think the following links would also help you to understand in much better way.

  1. python cross platform listening for keypresses

  2. How do I get a single keypress at a time

  3. Useful routines from the MS VC++ runtime

I hope this helps you to get your job done.

Proper way to initialize C++ structs

In C++ classes/structs are identical (in terms of initialization).

A non POD struct may as well have a constructor so it can initialize members.
If your struct is a POD then you can use an initializer.

struct C
{
    int x; 
    int y;
};

C  c = {0}; // Zero initialize POD

Alternatively you can use the default constructor.

C  c = C();      // Zero initialize using default constructor
C  c{};          // Latest versions accept this syntax.
C* c = new C();  // Zero initialize a dynamically allocated object.

// Note the difference between the above and the initialize version of the constructor.
// Note: All above comments apply to POD structures.
C  c;            // members are random
C* c = new C;    // members are random (more officially undefined).

I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).

As a side note:
A lot of beginners try to value init:

C c(); // Unfortunately this is not a variable declaration.
C c{}; // This syntax was added to overcome this confusion.

// The correct way to do this is:
C c = C();

A quick search for the "Most Vexing Parse" will provide a better explanation than I can.

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

How to submit a form when the return key is pressed?

I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:

<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
    border: 0 none;
    height: 0;
    width: 0;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.

Update

I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

Concatenate chars to form String in java

You can use StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.append('a');
    sb.append('b');
    sb.append('c');
    String str = sb.toString()

Or if you already have the characters, you can pass a character array to the String constructor:

String str = new String(new char[]{'a', 'b', 'c'});

python - find index position in list based of partial string

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

How to play a local video with Swift?

Swift 3

if let filePath = Bundle.main.path(forResource: "small", ofType: ".mp4") {
    let filePathURL = NSURL.fileURL(withPath: filePath)

    let player = AVPlayer(url: filePathURL)
    let playerController = AVPlayerViewController()
    playerController.player = player
    self.present(playerController, animated: true) {
        player.play()
    }
}

Can two or more people edit an Excel document at the same time?

No, sadly:

The Excel 2010 client application does not support co-authoring workbooks in SharePoint Server 2010. However, the Excel client application does support non-real-time co-authoring workbooks stored locally or on network (UNC) paths by using the Shared Workbook feature. Co-authoring workbooks in SharePoint is supported by using the Microsoft Excel Web App, included with Office Web Apps

From Co-authoring overview (SharePoint Server 2010)

...and not for SharePoint 2013 either. Though it works for pretty much all other Office documents. Go figure.

Write to .txt file?

FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

Android translate animation - permanently move View to new position using AnimationListener

This is what worked for me perfectly:-

// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){

    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
    animation.setDuration(100);
    llDomestic.setVisibility(View.GONE);
    animation.start();

}

// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
    llDomestic.setVisibility(View.VISIBLE);
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",   0f);
    animation.setDuration(100);
    animation.start();
}

llDomestic : The view which you want to hide. view: The view which you want to move down or up.

Using setattr() in python

To add to the other answers, a common use case I have found for setattr() is when using configs. It is common to parse configs from a file (.ini file or whatever) into a dictionary. So you end up with something like:

configs = {'memory': 2.5, 'colour': 'red', 'charge': 0, ... }

If you want to then assign these configs to a class to be stored and passed around, you could do simple assignment:

MyClass.memory = configs['memory']
MyClass.colour = configs['colour']
MyClass.charge = configs['charge']
...

However, it is much easier and less verbose to loop over the configs, and setattr() like so:

for name, val in configs.items():
    setattr(MyClass, name, val)

As long as your dictionary keys have the proper names, this works very well and is nice and tidy.

*Note, the dict keys need to be strings as they will be the class object names.

JavaScript validation for empty input field

Customizing the input message using HTML validation when clicking on Javascript button

_x000D_
_x000D_
function msgAlert() {
  const nameUser = document.querySelector('#nameUser');
  const passUser = document.querySelector('#passUser');

  if (nameUser.value === ''){
    console.log('Input name empty!');
    nameUser.setCustomValidity('Insert a name!');
  } else {
    nameUser.setCustomValidity('');
    console.log('Input name ' + nameUser.value);
  }
}

const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
_x000D_
.container{display:flex;max-width:960px;}
.w-auto {
    width: auto!important;
}
.p-3 {
    padding: 1rem!important;
}
.align-items-center {
    -ms-flex-align: center!important;
    align-items: center!important;
}
.form-row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;
}
.mb-2, .my-2 {
    margin-bottom: .5rem!important;
}
.d-flex {
    display: -ms-flexbox!important;
    display: flex!important;
}
.d-inline-block {
    display: inline-block!important;
}
.col {
    -ms-flex-preferred-size: 0;
    flex-basis: 0;
    -ms-flex-positive: 1;
    flex-grow: 1;
    max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
    margin-right: .5rem!important;
}
label {
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    color: #007081;
    font-weight: 400;
    letter-spacing: 1px;
    text-transform: uppercase;
}
label {
    display: inline-block;
    margin-bottom: .5rem;
}
.x-input {
    background-color: #eaf3f8;
    font-family: "Montserrat", sans-serif;
    font-size: 14px;
}
.login-input {
    border: none !important;
    width: 100%;
}
.p-4 {
    padding: 1.5rem!important;
}
.form-control {
    display: block;
    width: 100%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
    overflow: visible;
    margin: 0;
}
.form-row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
    padding-right: 5px;
    padding-left: 5px;
}
.col-lg-12 {
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.mt-1, .my-1 {
    margin-top: .25rem!important;
}
.mt-2, .my-2 {
    margin-top: .5rem!important;
}
.mb-2, .my-2 {
    margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
    cursor: pointer;
}
.btn-petroleo {
    background-color: #007081;
    color: white;
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    text-transform: uppercase;
    padding: 8px 30px;
    letter-spacing: 2px;
}
.btn-xg {
    padding: 20px 100px;
    width: 100%;
    display: block;
}
.btn {
    display: inline-block;
    font-weight: 400;
    color: #212529;
    text-align: center;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    border-radius: .25rem;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
    -webkit-writing-mode: horizontal-tb !important;
    text-rendering: auto;
    color: -internal-light-dark(black, white);
    letter-spacing: normal;
    word-spacing: normal;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
    display: inline-block;
    text-align: start;
    appearance: textfield;
    background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
    -webkit-rtl-ordering: logical;
    cursor: text;
    margin: 0em;
    font: 400 13.3333px Arial;
    padding: 1px 2px;
    border-width: 2px;
    border-style: inset;
    border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
    border-image: initial;
}
_x000D_
<div class="container">
              <form name="myFormLogin" class="w-auto p-3 mw-10">
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="nameUser">Usuário</label><br>
                    <input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
                           name="nameUser" placeholder="Name" required>
                  </div>
                </div>
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="passUser">Senha</label><br>
                    <input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
                           name="passUser" placeholder="Password" required>
                    <div class="help">Esqueci meu usuário ou senha</div>
                  </div>
                </div>
                <div class="form-row d-flex align-items-center">
                  <div class="col-lg-12 my-1 mt-2 mb-2">
                    <button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
                  </div>
                </div>
                <div class="form-row align-items-center d-flex">
                  <div class="col-lg-12 my-1">
                    <div class="nova-conta">Ainda não é cadastrado? <a href="">Crie seu acesso</a></div>
                  </div>
                </div>
              </form>
            </div>
_x000D_
_x000D_
_x000D_

SSIS how to set connection string dynamically from a config file

First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName

In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:

"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath]
+ @[User::FileName]  + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"

This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

How to apply two CSS classes to a single element

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

"getaddrinfo failed", what does that mean?

The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.

Removing the http_proxy environment variable fixed the problem.

Re-doing a reverted merge in Git

To revert a revert in GIT:

git revert <commit-hash-of-previous-revert>

Why does flexbox stretch my image rather than retaining aspect ratio?

Adding margin to align images:

Since we wanted the image to be left-aligned, we added:

img {
  margin-right: auto;
}

Similarly for image to be right-aligned, we can add margin-right: auto;. The snippet shows a demo for both types of alignment.

Good Luck...

_x000D_
_x000D_
div {_x000D_
  display:flex; _x000D_
  flex-direction:column;_x000D_
  border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  text-align: center;_x000D_
}_x000D_
hr {_x000D_
  border: 1px black solid;_x000D_
  width: 100%_x000D_
}_x000D_
img.one {_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
  <h1>Flex Box</h1>_x000D_
  _x000D_
  <hr />_x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="one" _x000D_
  />_x000D_
  _x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="two" _x000D_
  />_x000D_
  _x000D_
  <hr />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Grant SELECT on multiple tables oracle

If you want to grant to both tables and views try:

SELECT DISTINCT
    || OWNER
    || '.'
    || TABLE_NAME
    || ' to db_user;'
FROM
    ALL_TAB_COLS 
WHERE
    TABLE_NAME LIKE 'TABLE_NAME_%';

For just views try:

SELECT
    'grant select on '
    || OWNER
    || '.'
    || VIEW_NAME
    || ' to REPORT_DW;'
FROM
    ALL_VIEWS
WHERE
    VIEW_NAME LIKE 'VIEW_NAME_%';

Copy results and execute.

How do I wait for a promise to finish before returning the variable of a function?

What do I need to do to make this function wait for the result of the promise?

Use async/await (NOT Part of ECMA6, but available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN

    async function waitForPromise() {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:

    async function waitForPromise(): Promise<string> {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

How to resolve merge conflicts in Git repository?

Try Visual Studio Code for editing if you aren't already. What it does is after you try merging(and land up in merge conflicts).VS code automatically detects the merge conflicts.

It can help you very well by showing what are the changes made to the original one and should you accept incoming or

current change(meaning original one before merging)'?.

It helped for me and it can work for you too !

PS: It will work only if you've configured git with with your code and Visual Studio Code.

PHP is_numeric or preg_match 0-9 validation

is_numeric checks whether it is any sort of number, while your regex checks whether it is an integer, possibly with leading 0s. For an id, stored as an integer, it is quite likely that we will want to not have leading 0s. Following Spudley's answer, we can do:

/^[1-9][0-9]*$/

However, as Spudley notes, the resulting string may be too large to be stored as a 32-bit or 64-bit integer value. The maximum value of an signed 32-bit integer is 2,147,483,647 (10 digits), and the maximum value of an signed 64-bit integer is 9,223,372,036,854,775,807 (19 digits). However, many 10 and 19 digit integers are larger than the maximum 32-bit and 64-bit integers respectively. A simple regex-only solution would be:

/^[1-9][0-9]{0-8}$/ 

or

/^[1-9][0-9]{0-17}$/

respectively, but these "solutions" unhappily restrict each to 9 and 19 digit integers; hardly a satisfying result. A better solution might be something like:

$expr = '/^[1-9][0-9]*$/';
if (preg_match($expr, $id) && filter_var($id, FILTER_VALIDATE_INT)) {
    echo 'ok';
} else {
    echo 'nok';
}

How can I express that two values are not equal to eachother?

Just put a '!' in front of the boolean expression

Better way to sum a property value in an array

can also use Array.prototype.forEach()

let totalAmount = 0;
$scope.traveler.forEach( data => totalAmount = totalAmount + data.Amount);
return totalAmount;

How to open existing project in Eclipse

File > Import > General > Existing Projects into workspace. Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish. This should work just fine.

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

TypeError: can only concatenate list (not "str") to list

I think what you want to do is add a new item to your list, so you have change the line newinv=inventory+str(add) with this one:

newinv = inventory.append(add)

What you are doing now is trying to concatenate a list with a string which is an invalid operation in Python.

However I think what you want is to add and delete items from a list, in that case your if/else block should be:

if selection=="use":
    print(inventory)
    remove=input("What do you want to use? ")
    inventory.remove(remove)
    print(inventory)

elif selection=="pickup":
    print(inventory)
    add=input("What do you want to pickup? ")
    inventory.append(add)
    print(inventory)

You don't need to build a new inventory list every time you add a new item.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I disagree with the selected answer, and as davidxxx correctly pointed out, getReference does not provide such behaviour of dynamic updations without select. I asked a question concerning the validity of this answer, see here - cannot update without issuing select on using setter after getReference() of hibernate JPA.

I quite honestly haven't seen anybody who's actually used that functionality. ANYWHERE. And i don't understand why it's so upvoted.

Now first of all, no matter what you call on a hibernate proxy object, a setter or a getter, an SQL is fired and the object is loaded.

But then i thought, so what if JPA getReference() proxy doesn't provide that functionality. I can just write my own proxy.

Now, we can all argue that selects on primary keys are as fast as a query can get and it's not really something to go to great lengths to avoid. But for those of us who can't handle it due to one reason or another, below is an implementation of such a proxy. But before i you see the implementation, see it's usage and how simple it is to use.

USAGE

Order example = ProxyHandler.getReference(Order.class, 3);
example.setType("ABCD");
example.setCost(10);
PersistenceService.save(example);

And this would fire the following query -

UPDATE Order SET type = 'ABCD' and cost = 10 WHERE id = 3;

and even if you want to insert, you can still do PersistenceService.save(new Order("a", 2)); and it would fire an insert as it should.

IMPLEMENTATION

Add this to your pom.xml -

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>

Make this class to create dynamic proxy -

@SuppressWarnings("unchecked")
public class ProxyHandler {

public static <T> T getReference(Class<T> classType, Object id) {
    if (!classType.isAnnotationPresent(Entity.class)) {
        throw new ProxyInstantiationException("This is not an entity!");
    }

    try {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(classType);
        enhancer.setCallback(new ProxyMethodInterceptor(classType, id));
        enhancer.setInterfaces((new Class<?>[]{EnhancedProxy.class}));
        return (T) enhancer.create();
    } catch (Exception e) {
        throw new ProxyInstantiationException("Error creating proxy, cause :" + e.getCause());
    }
}

Make an interface with all the methods -

public interface EnhancedProxy {
    public String getJPQLUpdate();
    public HashMap<String, Object> getModifiedFields();
}

Now, make an interceptor which will allow you to implement these methods on your proxy -

import com.anil.app.exception.ProxyInstantiationException;
import javafx.util.Pair;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Anil Kumar
*/
public class ProxyMethodInterceptor implements MethodInterceptor, EnhancedProxy {

private Object target;
private Object proxy;
private Class classType;
private Pair<String, Object> primaryKey;
private static HashSet<String> enhancedMethods;

ProxyMethodInterceptor(Class classType, Object id) throws IllegalAccessException, InstantiationException {
    this.classType = classType;
    this.target = classType.newInstance();
    this.primaryKey = new Pair<>(getPrimaryKeyField().getName(), id);
}

static {
    enhancedMethods = new HashSet<>();
    for (Method method : EnhancedProxy.class.getDeclaredMethods()) {
        enhancedMethods.add(method.getName());
    }
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    //intercept enhanced methods
    if (enhancedMethods.contains(method.getName())) {
        this.proxy = obj;
        return method.invoke(this, args);
    }
    //else invoke super class method
    else
        return proxy.invokeSuper(obj, args);
}

@Override
public HashMap<String, Object> getModifiedFields() {
    HashMap<String, Object> modifiedFields = new HashMap<>();
    try {
        for (Field field : classType.getDeclaredFields()) {

            field.setAccessible(true);

            Object initialValue = field.get(target);
            Object finalValue = field.get(proxy);

            //put if modified
            if (!Objects.equals(initialValue, finalValue)) {
                modifiedFields.put(field.getName(), finalValue);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return modifiedFields;
}

@Override
public String getJPQLUpdate() {
    HashMap<String, Object> modifiedFields = getModifiedFields();
    if (modifiedFields == null || modifiedFields.isEmpty()) {
        return null;
    }
    StringBuilder fieldsToSet = new StringBuilder();
    for (String field : modifiedFields.keySet()) {
        fieldsToSet.append(field).append(" = :").append(field).append(" and ");
    }
    fieldsToSet.setLength(fieldsToSet.length() - 4);
    return "UPDATE "
            + classType.getSimpleName()
            + " SET "
            + fieldsToSet
            + "WHERE "
            + primaryKey.getKey() + " = " + primaryKey.getValue();
}

private Field getPrimaryKeyField() throws ProxyInstantiationException {
    for (Field field : classType.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Id.class))
            return field;
    }
    throw new ProxyInstantiationException("Entity class doesn't have a primary key!");
}
}

And the exception class -

public class ProxyInstantiationException extends RuntimeException {
public ProxyInstantiationException(String message) {
    super(message);
}

A service to save using this proxy -

@Service
public class PersistenceService {

@PersistenceContext
private EntityManager em;

@Transactional
private void save(Object entity) {
    // update entity for proxies
    if (entity instanceof EnhancedProxy) {
        EnhancedProxy proxy = (EnhancedProxy) entity;
        Query updateQuery = em.createQuery(proxy.getJPQLUpdate());
        for (Entry<String, Object> entry : proxy.getModifiedFields().entrySet()) {
            updateQuery.setParameter(entry.getKey(), entry.getValue());
        }
        updateQuery.executeUpdate();
    // insert otherwise
    } else {
        em.persist(entity);
    }

}
}

Parsing boolean values with argparse

Simplest way would be to use choices:

parser = argparse.ArgumentParser()
parser.add_argument('--my-flag',choices=('True','False'))

args = parser.parse_args()
flag = args.my_flag == 'True'
print(flag)

Not passing --my-flag evaluates to False. The required=True option could be added if you always want the user to explicitly specify a choice.

Press TAB and then ENTER key in Selenium WebDriver

In python this work for me

self.set_your_value = "your value"

def your_method_name(self):      
    self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

You can use "ComboBoxItem.PreviewMouseDown" event. So each time when mouse is down on some item this event will be fired.

To add this event in XAML use "ComboBox.ItemContainerStyle" like in next example:

   <ComboBox x:Name="MyBox"
        ItemsSource="{Binding MyList}"
        SelectedValue="{Binding MyItem, Mode=OneWayToSource}" >
        <ComboBox.ItemContainerStyle>
            <Style>
                <EventSetter Event="ComboBoxItem.PreviewMouseDown"
                    Handler="cmbItem_PreviewMouseDown"/>
            </Style>
        </ComboBox.ItemContainerStyle>
   </ComboBox>

and handle it as usual

void cmbItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    //...do your item selection code here...
}

Thanks to MSDN

How get sound input from microphone in python, and process it on the fly?

If you are using LINUX, you can use pyALSAAUDIO. For windows, we have PyAudio and there is also a library called SoundAnalyse.

I found an example for Linux here:

#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:

import alsaaudio, time, audioop

# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)

# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)

while True:
    # Read data from device
    l,data = inp.read()
    if l:
        # Return the maximum of the absolute value of all samples in a fragment.
        print audioop.max(data, 2)
    time.sleep(.001)

Brackets.io: Is there a way to auto indent / format <html>

Beautify does a good job. It provides a "Beautify on save" option, so that you may use ctrl+s to reformate html, less, css, etc

jQuery $(document).ready and UpdatePanels?

<script type="text/javascript">

        function BindEvents() {
            $(document).ready(function() {
                $(".tr-base").mouseover(function() {
                    $(this).toggleClass("trHover");
                }).mouseout(function() {
                    $(this).removeClass("trHover");
                });
         }
</script>

The area which is going to be updated.

<asp:UpdatePanel...
<ContentTemplate
     <script type="text/javascript">
                    Sys.Application.add_load(BindEvents);
     </script>
 *// Staff*
</ContentTemplate>
    </asp:UpdatePanel>

Error: [ng:areq] from angular controller

you forgot to include the controller in your index.html. The controller doesn't exist.

<script src="js/controllers/Controller.js"></script>

How to do a newline in output

Actually you don't even need the block:

  Dir.chdir 'C:/Users/name/Music'
  music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
  puts 'what would you like to call the playlist?'
  playlist_name = gets.chomp + '.m3u'

  File.open(playlist_name, 'w').puts(music)

error: RPC failed; curl transfer closed with outstanding read data remaining

It happens more often than not, I am on a slow internet connection and I have to clone a decently-huge git repository. The most common issue is that the connection closes and the whole clone is cancelled.

Cloning into 'large-repository'...
remote: Counting objects: 20248, done.
remote: Compressing objects: 100% (10204/10204), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining 
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

After a lot of trial and errors and a lot of “remote end hung up unexpectedly” I have a way that works for me. The idea is to do a shallow clone first and then update the repository with its history.

$ git clone http://github.com/large-repository --depth 1
$ cd large-repository
$ git fetch --unshallow

Convert SVG to image (JPEG, PNG, etc.) in the browser

Svg to png can be converted depending on conditions:

  1. If svg is in format SVG (string) paths:
  • create canvas
  • create new Path2D() and set svg as parameter
  • draw path on canvas
  • create image and use canvas.toDataURL() as src.

example:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let svgText = 'M10 10 h 80 v 80 h -80 Z';
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.stroke(p);
let url = canvas.toDataURL();
const img = new Image();
img.src = url;

Note that Path2D not supported in ie and partially supported in edge. Polyfill solves that: https://github.com/nilzona/path2d-polyfill

  1. Create svg blob and draw on canvas using .drawImage():
  • make canvas element
  • make a svgBlob object from the svg xml
  • make a url object from domUrl.createObjectURL(svgBlob);
  • create an Image object and assign url to image src
  • draw image into canvas
  • get png data string from canvas: canvas.toDataURL();

Nice description: https://web.archive.org/web/20200125162931/http://ramblings.mcpher.com:80/Home/excelquirks/gassnips/svgtopng

Note that in ie you will get exception on stage of canvas.toDataURL(); It is because IE has too high security restriction and treats canvas as readonly after drawing image there. All other browsers restrict only if image is cross origin.

  1. Use canvg JavaScript library. It is separate library but has useful functions.

Like:

ctx.drawSvg(rawSvg);
var dataURL = canvas.toDataURL();

Getting a browser's name client-side

EDIT: Since the answer is not valid with newer versions of jquery As jQuery.browser is deprecated in ver 1.9, So Use Jquery Migrate Plugin for that matter.


Original Answer

jQuery.browser

jQuery.browser and jQuery.browser.version

is your way to go...

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

How to turn on WCF tracing?

Instead of you manual adding the tracing enabling bit into web.config you can also try using the WCF configuration editor which comes with VS SDK to enable tracing

https://stackoverflow.com/a/16715631/2218571

How to set time to 24 hour format in Calendar

You can set the calendar to use only AM or PM using

calendar.set(Calendar.AM_PM, int);

0 = AM

1 = PM

Hope this helps

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.

Foreign key constraint may cause cycles or multiple cascade paths?

I would point out that (functionally) there's a BIG difference between cycles and/or multiple paths in the SCHEMA and the DATA. While cycles and perhaps multipaths in the DATA could certainly complicated processing and cause performance problems (cost of "properly" handling), the cost of these characteristics in the schema should be close to zero.

Since most apparent cycles in RDBs occur in hierarchical structures (org chart, part, subpart, etc.) it is unfortunate that SQL Server assumes the worst; i.e., schema cycle == data cycle. In fact, if you're using RI constraints you can't actually build a cycle in the data!

I suspect the multipath problem is similar; i.e., multiple paths in the schema don't necessarily imply multiple paths in the data, but I have less experience with the multipath problem.

Of course if SQL Server did allow cycles it'd still be subject to a depth of 32, but that's probably adequate for most cases. (Too bad that's not a database setting however!)

"Instead of Delete" triggers don't work either. The second time a table is visited, the trigger is ignored. So, if you really want to simulate a cascade you'll have to use stored procedures in the presence of cycles. The Instead-of-Delete-Trigger would work for multipath cases however.

Celko suggests a "better" way to represent hierarchies that doesn't introduce cycles, but there are tradeoffs.

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2) as a simple alternative. Here's a more advanced mtext() example:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
     yaxt="n", ylab="", 
     xlab="Regular boring x", 
     pch=16,
     col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)

enter image description here

You may need to adjust the line= option to get the optimal positioning of the text but apart from that it's really easy to use.

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

Pods stuck in Terminating status

I found this command more straightforward:

for p in $(kubectl get pods | grep Terminating | awk '{print $1}'); do kubectl delete pod $p --grace-period=0 --force;done

It will delete all pods in Terminating status in default namespace.

phpMyAdmin on MySQL 8.0

If you are using the official mysql docker container, there is a simple solution:

Add the following line to your docker-compose service:

command: --default-authentication-plugin=mysql_native_password

Example configuration:

mysql:
     image: mysql:8
     networks:
       - net_internal
     volumes:
       - mysql_data:/var/lib/mysql
     environment:
       - MYSQL_ROOT_PASSWORD=root
       - MYSQL_DATABASE=db
     command: --default-authentication-plugin=mysql_native_password

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

"SSL certificate verify failed" using pip to install packages

 pip3 install --trusted-host pypi.org --trusted-host files.pythonhosted.org <app>

How do I add a custom script to my package.json file that runs a javascript file?

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.

Google maps Places API V3 autocomplete - select first option on enter

I had the same issue when implementing autocomplete on a site I worked on recently. This is the solution I came up with:

$("input").focusin(function () {
    $(document).keypress(function (e) {
        if (e.which == 13) {
            var firstResult = $(".pac-container .pac-item:first").text();

            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({"address":firstResult }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var lat = results[0].geometry.location.lat(),
                        lng = results[0].geometry.location.lng(),
                        placeName = results[0].address_components[0].long_name,
                        latlng = new google.maps.LatLng(lat, lng);

                        $(".pac-container .pac-item:first").addClass("pac-selected");
                        $(".pac-container").css("display","none");
                        $("#searchTextField").val(firstResult);
                        $(".pac-container").css("visibility","hidden");

                    moveMarker(placeName, latlng);

                }
            });
        } else {
            $(".pac-container").css("visibility","visible");
        }

    });
});

http://jsfiddle.net/dodger/pbbhH/

Python: Fetch first 10 results from a list

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item

Generating a PNG with matplotlib when DISPLAY is undefined

To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:

import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
    matplotlib.use('Agg')

# now import other things from matplotlib
import matplotlib.pyplot as plt

Credit: https://stackoverflow.com/a/45756291/207661

Java - How to access an ArrayList of another class?

Put them in an arrayList in your first class like:

import java.util.ArrayList;
    public class numbers {

    private int number1 = 50;
    private int number2 = 100;

    public ArrayList<int> getNumberList() {
        ArrayList<int> numbersList= new ArrayList<int>();
        numbersList.add(number1);
        numberList.add(number2);
        ....
        return numberList;
    }
}

Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

You can also access a variable declared in one class from another simply like

numbers.numberList;

if you have it declared there as public.

But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

How to call a MySQL stored procedure from within PHP code?

<?php
    $res = mysql_query('SELECT getTreeNodeName(1) AS result');
    if ($res === false) {
        echo mysql_errno().': '.mysql_error();
    }
    while ($obj = mysql_fetch_object($res)) {
        echo $obj->result;
    }

Get last dirname/filename in a file path argument in Bash

The following approach can be used to get any path of a pathname:

some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))

Output:

c
b
a

Printing out a linked list using toString

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

If the above solutions don't work on ubuntu/linux then you can try this

sudo fuser -k -n tcp port

Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command

Android webview launches browser when calling loadurl

I just found out that it depends on the formatting of the URL:

My code just uses

webview.loadUrl(url)

no need to set

webView.setWebViewClient(new WebViewClient())

at least in my case. Maybe that's useful for some of you.

Understanding React-Redux and mapStateToProps()

Yes, it is correct. Its just a helper function to have a simpler way to access your state properties

Imagine you have a posts key in your App state.posts

state.posts //
/*    
{
  currentPostId: "",
  isFetching: false,
  allPosts: {}
}
*/

And component Posts

By default connect()(Posts) will make all state props available for the connected Component

const Posts = ({posts}) => (
  <div>
    {/* access posts.isFetching, access posts.allPosts */}
  </div> 
)

Now when you map the state.posts to your component it gets a bit nicer

const Posts = ({isFetching, allPosts}) => (
  <div>
    {/* access isFetching, allPosts directly */}
  </div> 
)

connect(
  state => state.posts
)(Posts)

mapDispatchToProps

normally you have to write dispatch(anActionCreator())

with bindActionCreators you can do it also more easily like

connect(
  state => state.posts,
  dispatch => bindActionCreators({fetchPosts, deletePost}, dispatch)
)(Posts)

Now you can use it in your Component

const Posts = ({isFetching, allPosts, fetchPosts, deletePost }) => (
  <div>
    <button onClick={() => fetchPosts()} />Fetch posts</button>
    {/* access isFetching, allPosts directly */}
  </div> 
)

Update on actionCreators..

An example of an actionCreator: deletePost

const deletePostAction = (id) => ({
  action: 'DELETE_POST',
  payload: { id },
})

So, bindActionCreators will just take your actions, wrap them into dispatch call. (I didn't read the source code of redux, but the implementation might look something like this:

const bindActionCreators = (actions, dispatch) => {
  return Object.keys(actions).reduce(actionsMap, actionNameInProps => {
    actionsMap[actionNameInProps] = (...args) => dispatch(actions[actionNameInProps].call(null, ...args))
    return actionsMap;
  }, {})
}

jQuery "blinking highlight" effect on div?

<script>
$(document).ready(function(){
    var count = 0;
    do {
        $('#toFlash').fadeOut(500).fadeIn(500);
        count++;
    } while(count < 10);/*set how many time you want it to flash*/
});
</script

iOS 7 status bar overlapping UI

Try going into the app's (app name)-Info.plist file in XCode and add the key

view controller-based status bar appearance: NO
status bar is initially hidden : YES

This seems to work for me without problem.

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<style>
a{
cursor: default;
}
</style>

In the above code [cursor:default] is used. Default is the usual arrow cursor that appears.

And if you use [cursor: pointer] then you can access to the hand like cursor that appears when you hover over a link.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

How can I get session id in php and show it?

Before getting a session id you need to start a session and that is done by using: session_start() function.

Now that you have started a session you can get a session id by using: session_id().

/* A small piece of code for setting, displaying and destroying session in PHP */

<?php
session_start();
$r=session_id();

/* SOME PIECE OF CODE TO AUTHENTICATE THE USER, MOSTLY SQL QUERY... */

/* now registering a session for an authenticated user */
$_SESSION['username']=$username;

/* now displaying the session id..... */
echo "the session id id: ".$r;
echo " and the session has been registered for: ".$_SESSION['username'];


/* now destroying the session id */

if(isset($_SESSION['username']))
{
    $_SESSION=array();
    unset($_SESSION);
    session_destroy();
    echo "session destroyed...";
}
?>

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

jQuery: find element by text

You can use the :contains selector to get elements based on their content.

Demo here

_x000D_
_x000D_
$('div:contains("test")').css('background-color', 'red');
_x000D_
<div>This is a test</div>_x000D_
<div>Another Div</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I make XSLT work in chrome?

I started testing this and ran into the local file / Chrome security issue. A very simple workaround is put the XML and XSL file in, say, Dropbox public folder and get links to both files. Put the link to the XSL transform in the XML head. Use the XML link in Chrome AND IT WORKS!

Pass Javascript variable to PHP via ajax

$(document).ready(function() {
            $(".clickable").click(function() {
                var userID = $(this).attr('id'); // you can add here your personal ID
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'logtime.php',
                    data : {
                        action : 'my_action',
                        userID : userID 
                    },
                    success: function(data)
                    {
                        alert("success!");
                        console.log(data);
                    }
                });
            });
        });


 $uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
 echo $uid;

$uid add in your functions

note: if $ is not supperted than add jQuery where $ defined

What is the cleanest way to disable CSS transition effects temporarily?

I would advocate disabling animation as suggested by DaneSoul, but making the switch global:

/*kill the transitions on any descendant elements of .notransition*/
.notransition * { 
  -webkit-transition: none !important; 
  -moz-transition: none !important; 
  -o-transition: none !important; 
  -ms-transition: none !important; 
  transition: none !important; 
} 

.notransition can be then applied to the body element, effectively overriding any transition animation on the page:

$('body').toggleClass('notransition');

Use of min and max functions in C++

You're missing the entire point of fmin and fmax. It was included in C99 so that modern CPUs could use their native (read SSE) instructions for floating point min and max and avoid a test and branch (and thus a possibly mis-predicted branch). I've re-written code that used std::min and std::max to use SSE intrinsics for min and max in inner loops instead and the speed-up was significant.

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

How do I split a string with multiple separators in JavaScript?

Another simple but effective method is to use split + join repeatedly.

"a=b,c:d".split('=').join(',').split(':').join(',').split(',')

Essentially doing a split followed by a join is like a global replace so this replaces each separator with a comma then once all are replaced it does a final split on comma

The result of the above expression is:

['a', 'b', 'c', 'd']

Expanding on this you could also place it in a function:

function splitMulti(str, tokens){
        var tempChar = tokens[0]; // We can use the first token as a temporary join character
        for(var i = 1; i < tokens.length; i++){
            str = str.split(tokens[i]).join(tempChar);
        }
        str = str.split(tempChar);
        return str;
}

Usage:

splitMulti('a=b,c:d', ['=', ',', ':']) // ["a", "b", "c", "d"]

If you use this functionality a lot it might even be worth considering wrapping String.prototype.split for convenience (I think my function is fairly safe - the only consideration is the additional overhead of the conditionals (minor) and the fact that it lacks an implementation of the limit argument if an array is passed).

Be sure to include the splitMulti function if using this approach to the below simply wraps it :). Also worth noting that some people frown on extending built-ins (as many people do it wrong and conflicts can occur) so if in doubt speak to someone more senior before using this or ask on SO :)

    var splitOrig = String.prototype.split; // Maintain a reference to inbuilt fn
    String.prototype.split = function (){
        if(arguments[0].length > 0){
            if(Object.prototype.toString.call(arguments[0]) == "[object Array]" ) { // Check if our separator is an array
                return splitMulti(this, arguments[0]);  // Call splitMulti
            }
        }
        return splitOrig.apply(this, arguments); // Call original split maintaining context
    };

Usage:

var a = "a=b,c:d";
    a.split(['=', ',', ':']); // ["a", "b", "c", "d"]

// Test to check that the built-in split still works (although our wrapper wouldn't work if it didn't as it depends on it :P)
        a.split('='); // ["a", "b,c:d"] 

Enjoy!

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Probably late to the party. You can use Jackson and convert it into a Properties object. This is suited for Nested classes and if you want the key in the for a.b.c=value.

JavaPropsMapper mapper = new JavaPropsMapper();
Properties properties = mapper.writeValueAsProperties(sct);
Map<Object, Object> map = properties;

if you want some suffix, then just do

SerializationConfig config = mapper.getSerializationConfig()
                .withRootName("suffix");
mapper.setConfig(config);

need to add this dependency

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-properties</artifactId>
</dependency>

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

Cannot run the macro... the macro may not be available in this workbook

Per Microsoft's KB, try allowing programmatic access to the Visual Basic project:

  1. Click the Microsoft Office Button, and then click Excel Options.
  2. Click Trust Center.
  3. Click Trust Center Settings.
  4. Click Macro Settings.
  5. Click to select the Trust access to the VBA project object model check box.
  6. Click OK to close the Excel Options dialog box.
  7. You may need to close and re-open excel.

Adding/removing items from a JavaScript object with jQuery

Adding an object in a json array

var arrList = [];
var arr = {};   
arr['worker_id'] = worker_id;
arr['worker_nm'] = worker_nm;
arrList.push(arr);

Removing an object from a json

It worker for me.

  arrList = $.grep(arrList, function (e) { 

        if(e.worker_id == worker_id) {
            return false;
        } else {
            return true;
        }
    });

It returns an array without that object.

Hope it helps.

How do I load the contents of a text file into a javascript variable?

here is how I did it in jquery:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});

Last element in .each() set

each passes into your function index and element. Check index against the length of the set and you're good to go:

var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
      thisVal = $(this).val();
      if(parseInt(thisVal) !== 0) {
          console.log('Valid Field: ' + thisVal);
          if (index === (length - 1)) {
              console.log('Last field, submit form here');
          }
      }
});

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915) and make sure you add other jar files present in lib and ooxml-lib folders.

Hope this helps!!!:)

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

Use 'class' or 'typename' for template parameters?

In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:

template <class IntegerType>
class smart_integer {
public: 
    typedef integer_traits<Integer> traits;
    IntegerType operator+=(IntegerType value){
        typedef typename traits::larger_integer_t larger_t;
        larger_t interm = larger_t(myValue) + larger_t(value); 
        if(interm > traits::max() || interm < traits::min())
            throw overflow();
        myValue = IntegerType(interm);
    }
}

larger_integer_t is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t is a type. class, on the otherhand, has no such overloaded meaning.

That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

Downloading and unzipping a .zip file without writing to disk

Adding on to the other answers using requests:

 # download from web

 import requests
 url = 'http://mlg.ucd.ie/files/datasets/bbc.zip'
 content = requests.get(url)

 # unzip the content
 from io import BytesIO
 from zipfile import ZipFile
 f = ZipFile(BytesIO(content.content))
 print(f.namelist())

 # outputs ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Use help(f) to get more functions details for e.g. extractall() which extracts the contents in zip file which later can be used with with open.

How to create a localhost server to run an AngularJS project

If you're running node.js http-server is super easy.

cd into your project folder and

npx http-server -o 

# or, install it separately so you don't need npx
npm install -g http-server
http-server -o 

-o is to open browser to the page. Run http-server --help to view other options such as changing the port number

Don't have node?

these other one-liners might be easier if you don't have node/npm installed.

For example python comes preinstalled on most systems, so John Doe's python servers below would be quicker.

MacOS comes installed with ruby, so this is another easy option if you're running a Mac: ruby -run -ehttpd . -p8000 and open your browser to http://localhost:8000.

How to add a ListView to a Column in Flutter?

I have SingleChildScrollView as a parent, and one Column Widget and then List View Widget as last child.

Adding these properties in List View Worked for me.

  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  scrollDirection: Axis.vertical,

How to reformat JSON in Notepad++?

You can view in Notepad++ no problem now (maybe older versions were bugged?)

for win64: You can find the latest plugin here: https://github.com/kapilratnani/JSON-Viewer/releases . The latest zip file contains a .dll file.

And then follow the github priject README instructions:

  1. Paste the file "NPPJSONViewer.dll" to Notepad++ plugin folder
  2. open a document containing a JSON string
  3. Select JSON fragment and navigate to plugins/JSON Viewer/show JSON Viewer or press "Ctrl+Alt+Shift+J"
  4. Voila!! if the JSON is valid, it will be shown in a Treeview

It should be the same process for win32 but I cannot personally verify it.

Load RSA public key from file

Below is the relevant information from the link which Zaki provided.

Generate a 2048-bit RSA private key

$ openssl genrsa -out private_key.pem 2048

Convert private Key to PKCS#8 format (so Java can read it)

$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt

Output public key portion in DER format (so Java can read it)

$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

Private key

import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;

public class PrivateKeyReader {

  public static PrivateKey get(String filename)
  throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    PKCS8EncodedKeySpec spec =
      new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
  }
}

Public key

import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;

public class PublicKeyReader {

  public static PublicKey get(String filename)
    throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
  }
}

Android 6.0 multiple permissions

I found this is in the runtime permissions example from Google's github.

 private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
        Manifest.permission.WRITE_CONTACTS};
private static final int REQUEST_CONTACTS = 1;
ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);

How to read a large file line by line?

The obvious answer wasn't there in all the responses.
PHP has a neat streaming delimiter parser available made for exactly that purpose.

$fp = fopen("/path/to/the/file", "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
  echo $line;
}
fclose($fp);

MySQL: Check if the user exists and drop it

I wrote this procedure inspired by Cherian's answer. The difference is that in my version the user name is an argument of the procedure ( and not hard coded ) . I'm also doing a much necessary FLUSH PRIVILEGES after dropping the user.

DROP PROCEDURE IF EXISTS DropUserIfExists;
DELIMITER $$
CREATE PROCEDURE DropUserIfExists(MyUserName VARCHAR(100))
BEGIN
  DECLARE foo BIGINT DEFAULT 0 ;
  SELECT COUNT(*)
  INTO foo
    FROM mysql.user
      WHERE User = MyUserName ;
   IF foo > 0 THEN
         SET @A = (SELECT Result FROM (SELECT GROUP_CONCAT("DROP USER"," ",MyUserName,"@'%'") AS Result) AS Q LIMIT 1);
         PREPARE STMT FROM @A;
         EXECUTE STMT;
         FLUSH PRIVILEGES;
   END IF;
END ;$$
DELIMITER ;

I also posted this code on the CodeReview website ( https://codereview.stackexchange.com/questions/15716/mysql-drop-user-if-exists )

What is an Android PendingIntent?

A Pending Intent is a token you give to some app to perform an action on your apps' behalf irrespective of whether your application process is alive or not.

I think the documentation is sufficiently detailed: Pending Intent docs.

Just think of use-cases for Pending Intents like (Broadcasting Intents, scheduling alarms) and the documentation will become clearer and meaningful.

How do I share a global variable between c files?

using extern <variable type> <variable name> in a header or another C file.

What is the difference between `git merge` and `git merge --no-ff`?

Graphic answer to this question

Here is a site with a clear explanation and graphical illustration of using git merge --no-ff:

difference between git merge --no-ff and git merge

Until I saw this, I was completely lost with git. Using --no-ff allows someone reviewing history to clearly see the branch you checked out to work on. (that link points to github's "network" visualization tool) And here is another great reference with illustrations. This reference complements the first one nicely with more of a focus on those less acquainted with git.


Basic info for newbs like me

If you are like me, and not a Git-guru, my answer here describes handling the deletion of files from git's tracking without deleting them from the local filesystem, which seems poorly documented but often occurrence. Another newb situation is getting current code, which still manages to elude me.


Example Workflow

I updated a package to my website and had to go back to my notes to see my workflow; I thought it useful to add an example to this answer.

My workflow of git commands:

git checkout -b contact-form
(do your work on "contact-form")
git status
git commit -am  "updated form in contact module"
git checkout master
git merge --no-ff contact-form
git branch -d contact-form
git push origin master

Below: actual usage, including explanations.
Note: the output below is snipped; git is quite verbose.

$ git status
# On branch master
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   ecc/Desktop.php
#       modified:   ecc/Mobile.php
#       deleted:    ecc/ecc-config.php
#       modified:   ecc/readme.txt
#       modified:   ecc/test.php
#       deleted:    passthru-adapter.igs
#       deleted:    shop/mickey/index.php
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       ecc/upgrade.php
#       ecc/webgility-config.php
#       ecc/webgility-config.php.bak
#       ecc/webgility-magento.php

Notice 3 things from above:
1) In the output you can see the changes from the ECC package's upgrade, including the addition of new files.
2) Also notice there are two files (not in the /ecc folder) I deleted independent of this change. Instead of confusing those file deletions with ecc, I'll make a different cleanup branch later to reflect those files' deletion.
3) I didn't follow my workflow! I forgot about git while I was trying to get ecc working again.

Below: rather than do the all-inclusive git commit -am "updated ecc package" I normally would, I only wanted to add the files in the /ecc folder. Those deleted files weren't specifically part of my git add, but because they already were tracked in git, I need to remove them from this branch's commit:

$ git checkout -b ecc
$ git add ecc/*
$ git reset HEAD passthru-adapter.igs
$ git reset HEAD shop/mickey/index.php
Unstaged changes after reset:
M       passthru-adapter.igs
M       shop/mickey/index.php

$ git commit -m "Webgility ecc desktop connector files; integrates with Quickbooks"

$ git checkout master
D       passthru-adapter.igs
D       shop/mickey/index.php
Switched to branch 'master'
$ git merge --no-ff ecc
$ git branch -d ecc
Deleted branch ecc (was 98269a2).
$ git push origin master
Counting objects: 22, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 59.00 KiB, done.
Total 14 (delta 10), reused 0 (delta 0)
To [email protected]:me/mywebsite.git
   8a0d9ec..333eff5  master -> master



Script for automating the above

Having used this process 10+ times in a day, I have taken to writing batch scripts to execute the commands, so I made an almost-proper git_update.sh <branch> <"commit message"> script for doing the above steps. Here is the Gist source for that script.

Instead of git commit -am I am selecting files from the "modified" list produced via git status and then pasting those in this script. This came about because I made dozens of edits but wanted varied branch names to help group the changes.

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

std::string length() and size() member functions

When using coding practice tools(LeetCode) it seems that size() is quicker than length() (although basically negligible)

How to label each equation in align environment?

You can label each line separately, in your case:

\begin{align}
  \lambda_i + \mu_i = 0 \label{eq:1}\\
  \mu_i \xi_i = 0 \label{eq:2}\\
  \lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0 \label{eq:3}
\end{align} 

Note that this only works for AMS environments that are designed for multiple equations (as opposed to multiline single equations).

Input text dialog Android

If you want some space at left and right of input view, you can add some padding like

private fun showAlertWithTextInputLayout(context: Context) {
    val textInputLayout = TextInputLayout(context)
    textInputLayout.setPadding(
        resources.getDimensionPixelOffset(R.dimen.dp_19), // if you look at android alert_dialog.xml, you will see the message textview have margin 14dp and padding 5dp. This is the reason why I use 19 here
        0,
        resources.getDimensionPixelOffset(R.dimen.dp_19),
        0
    )
    val input = EditText(context)
    textInputLayout.hint = "Email"
    textInputLayout.addView(input)

    val alert = AlertDialog.Builder(context)
        .setTitle("Reset Password")
        .setView(textInputLayout)
        .setMessage("Please enter your email address")
        .setPositiveButton("Submit") { dialog, _ ->
            // do some thing with input.text
            dialog.cancel()
        }
        .setNegativeButton("Cancel") { dialog, _ ->
            dialog.cancel()
        }.create()

    alert.show()
}

dimens.xml

<dimen name="dp_19">19dp</dimen>

Hope it help

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

If you are stuck with .Net 4.0 and the target site is using TLS 1.2, you need the following line instead. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

source: TLS 1.2 and .NET Support: How to Avoid Connection Errors

Set date input field's max date to today

You will need Javascript to do this:

HTML

<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>

JS

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
 if(dd<10){
        dd='0'+dd
    } 
    if(mm<10){
        mm='0'+mm
    } 

today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);

JSFiddle demo

SQLAlchemy: print the actual query

This code is based on brilliant existing answer from @bukzor. I just added custom render for datetime.datetime type into Oracle's TO_DATE().

Feel free to update code to suit your database:

import decimal
import datetime

def printquery(statement, bind=None):
    """
    print a query, with values filled in
    for debugging purposes *only*
    for security, you should always separate queries from their values
    please also note that this function is quite slow
    """
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        if bind is None:
            bind = statement.session.get_bind(
                    statement._mapper_zero_or_none()
            )
        statement = statement.statement
    elif bind is None:
        bind = statement.bind 

    dialect = bind.dialect
    compiler = statement._compiler(dialect)
    class LiteralCompiler(compiler.__class__):
        def visit_bindparam(
                self, bindparam, within_columns_clause=False, 
                literal_binds=False, **kwargs
        ):
            return super(LiteralCompiler, self).render_literal_bindparam(
                    bindparam, within_columns_clause=within_columns_clause,
                    literal_binds=literal_binds, **kwargs
            )
        def render_literal_value(self, value, type_):
            """Render the value of a bind parameter as a quoted literal.

            This is used for statement sections that do not accept bind paramters
            on the target driver/database.

            This should be implemented by subclasses using the quoting services
            of the DBAPI.

            """
            if isinstance(value, basestring):
                value = value.replace("'", "''")
                return "'%s'" % value
            elif value is None:
                return "NULL"
            elif isinstance(value, (float, int, long)):
                return repr(value)
            elif isinstance(value, decimal.Decimal):
                return str(value)
            elif isinstance(value, datetime.datetime):
                return "TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')" % value.strftime("%Y-%m-%d %H:%M:%S")

            else:
                raise NotImplementedError(
                            "Don't know how to literal-quote value %r" % value)            

    compiler = LiteralCompiler(dialect, statement)
    print compiler.process(statement)

Difference between return 1, return 0, return -1 and exit?

As explained here, in the context of main both return and exit do the same thing

Q: Why do we need to return or exit?

A: To indicate execution status.

In your example even if you didnt have return or exit statements the code would run fine (Assuming everything else is syntactically,etc-ally correct. Also, if (and it should be) main returns int you need that return 0 at the end).

But, after execution you don't have a way to find out if your code worked as expected. You can use the return code of the program (In *nix environments , using $?) which gives you the code (as set by exit or return) . Since you set these codes yourself you understand at which point the code reached before terminating.

You can write return 123 where 123 indicates success in the post execution checks.

Usually, in *nix environments 0 is taken as success and non-zero codes as failures.

Stock ticker symbol lookup API

Google Finance does let you retrieve up to 100 stock quotes at once using the following URL:

www.google.com/finance/info?infotype=infoquoteall&q=[ticker1],[ticker2],...,[tickern]

For example:

www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG

Someone has deciphered the available fields here:

http://qsb-mac.googlecode.com/svn/trunk/Vermilion/Modules/StockQuoter/StockQuoter.py

The current price ("l") is real-time and the delay is on par with Yahoo Finance. There are a few quirks you should be aware of. A handful of stocks require an exchange prefix. For example, if you query "BTIM", you'll get a "Bad Request" error but "AMEX:BTIM" works. A few stocks don't work even with the exchange prefix. For example, querying "FTWRD" and "NASDAQ:FTWRD" both generate "Bad Request" errors even though Google Finance does have information for this NASDAQ stock.

The "el" field, if present, tells you the current pre-market or after-hours price.

Import and insert sql.gz file into database with putty

Login into your server using a shell program like putty.

Type in the following command on the command line

zcat DB_File_Name.sql.gz | mysql -u username -p Target_DB_Name

where

DB_File_Name.sql.gz = full path of the sql.gz file to be imported

username = your mysql username

Target_DB_Name = database name where you want to import the database

When you hit enter in the command line, it will prompt for password. Enter your MySQL password.

You are done!

POST Content-Length exceeds the limit

In Some cases, you need to increase the maximum execution time.

max_execution_time=30

I made it

max_execution_time=600000

then I was happy.

How to convert array values to lowercase in PHP?

You don't say if your array is multi-dimensional. If it is, array_map will not work alone. You need a callback method. For multi-dimensional arrays, try array_change_key_case.

// You can pass array_change_key_case a multi-dimensional array,
// or call a method that returns one
$my_array = array_change_key_case(aMethodThatReturnsMultiDimArray(), CASE_UPPER);

How to decode JWT Token?

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(string token)
    {
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;
    }

Animated GIF in IE stopping

I encountered this problem when trying to show a loading gif while a form submit was processing. It had an added layer of fun in that the same onsubmit had to run a validator to make sure the form was correct. Like everyone else (on every IE/gif form post on the internet) I couldn't get the loading spinner to "spin" in IE (and, in my case, validate/submit the form). While looking through advice on http://www.west-wind.com I found a post by ev13wt that suggested the problem was "... that IE doesn't render the image as animated cause it was invisible when it was rendered." That made sense. His solution:

Leave blank where the gif would go and use JavaScript to set the source in the onsubmit function - document.getElementById('loadingGif').src = "path to gif file".

Here's how I implemented it:

<script type="text/javascript">
    function validateForm(form) {

        if (isNotEmptyid(form.A)) {
            if (isLen4(form.B)) {        
                if (isNotEmptydt(form.C)) {
                    if (isNumber(form.D)) {        
                        if (isLen6(form.E)){
                            if (isNotEmptynum(form.F)) {
                                if (isLen5(form.G)){
                                    document.getElementById('tabs').style.display = "none";                
                                    document.getElementById('dvloader').style.display = "block";                
                                    document.getElementById('loadingGif').src = "/images/ajax-loader.gif"; 
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
        return false;   
    }               
</script>

<form name="payo" action="process" method="post" onsubmit="return validateForm(this)">
    <!-- FORM INPUTS... -->
    <input type="submit" name="submit" value=" Authorize ">

    <div style="display:none" id="dvloader">  
        <img id="loadingGif" src="" alt="Animated Image that appears during processing of document." />
        Working... this process may take several minutes.
    </div>

</form>

This worked well for me in all browsers!

How to increase Java heap space for a tomcat app

if you are using Windows, it's very simple. Just go to System Environnement variables (right-clic Computer > Properties > Advanced System Parameters > Environnement Variables); create a new system variable with name = CATALINA_OPTS and value = -Xms512m -Xmx1024m. restart Tomcat and enjoy!

How does one convert a HashMap to a List in Java?

Assuming you have:

HashMap<Key, Value> map; // Assigned or populated somehow.

For a list of values:

List<Value> values = new ArrayList<Value>(map.values());

For a list of keys:

List<Key> keys = new ArrayList<Key>(map.keySet());

Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.

Repository Pattern Step by Step Explanation

This is a nice example: The Repository Pattern Example in C#

Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:

  • for reading, it creates the query satisfying the supplied criteria and returns the result set
  • for writing, it issues the commands necessary to make the underlying persistence engine (e.g. an SQL database) save the data

How to hide keyboard in swift on pressing return key?

The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:

// Called on 'Return' pressed. Return false to ignore.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}

Get values from an object in JavaScript

To access the properties of an object without knowing the names of those properties you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}

How do I update a Python package?

Use pipupgrade!

$ pip install pipupgrade
$ pipupgrade --latest --interactive

pipupgrade helps you upgrade your system, local or packages from a requirements.txt file! It also selectively upgrades packages that don't break change. Compatible with Python2.7+, Python3.4+ and pip9+, pip10+, pip18+.

enter image description here

NOTE: I'm the author of the tool.

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

I resorted to creating 2 style cascades using inline-block for input that pretty much override the field:

.input-sm {
    height: 2.1em;
    display: inline-block;
}

and a series of fixed sizes as opposed to %

.input-10 {
    width: 10em;
}

.input-32 {
    width: 32em;
}

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a similar issue but from reading this question I figured I could run on UI thread:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

Seems to do the trick for me.

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

The commercial solution, SpreadsheetGear for .NET will do it.

You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.

Disclaimer: I own SpreadsheetGear LLC

What is a Windows Handle?

A HANDLE in Win32 programming is a token that represents a resource that is managed by the Windows kernel. A handle can be to a window, a file, etc.

Handles are simply a way of identifying a particulate resource that you want to work with using the Win32 APIs.

So for instance, if you want to create a Window, and show it on the screen you could do the following:

// Create the window
HWND hwnd = CreateWindow(...); 
if (!hwnd)
   return; // hwnd not created

// Show the window.
ShowWindow(hwnd, SW_SHOW);

In the above example HWND means "a handle to a window".

If you are used to an object oriented language you can think of a HANDLE as an instance of a class with no methods who's state is only modifiable by other functions. In this case the ShowWindow function modifies the state of the Window HANDLE.

See Handles and Data Types for more information.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I generally install Apache + PHP + MySQL by-hand, not using any package like those you're talking about.

It's a bit more work, yes; but knowing how to install and configure your environment is great -- and useful.

The first time, you'll need maybe half a day or a day to configure those. But, at least, you'll know how to do so.

And the next times, things will be far more easy, and you'll need less time.

Else, you might want to take a look at Zend Server -- which is another package that bundles Apache + PHP + MySQL.

Or, as an alternative, don't use Windows.

If your production servers are running Linux, why not run Linux on your development machine?

And if you don't want to (or cannot) install Linux on your computer, use a Virtual Machine.

How do ports work with IPv6?

I'm pretty certain that ports only have a part in tcp and udp. So it's exactly the same even if you use a new IP protocol

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

How do I remove a comma off the end of a string?

This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:

if (substr($string, -1, 1) == ',')
{
  $string = substr($string, 0, -1);
}

If you want to remove all commas from the end of a line use the simpler:

$string = rtrim($string, ',');

The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:

$string = rtrim($string, ", \t\n");

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

Convert string (without any separator) to list

You mean that you want something like:

''.join(n for n in phone_str if n.isdigit())

This uses the fact that strings are iterable. They yield 1 character at a time when you iterate over them.


Regarding your efforts,

This one actually removes all of the digits from the string leaving you with only non-digits.

x = row.translate(None, string.digits)

This one splits the string on runs of whitespace, not after each character:

list = x.split()

How to remove an element from the flow?

There's display: none, but I think that might be a bit more than what you're looking for.

How to get the excel file name / path in VBA

If you need path only this is the most straightforward way:

PathOnly = ThisWorkbook.Path

Trying to merge 2 dataframes but get ValueError

@Arnon Rotem-Gal-Oz answer is right for the most part. But I would like to point out the difference between df['year']=df['year'].astype(int) and df.year.astype(int). df.year.astype(int) returns a view of the dataframe and doesn't not explicitly change the type, atleast in pandas 0.24.2. df['year']=df['year'].astype(int) explicitly change the type because it's an assignment. I would argue that this is the safest way to permanently change the dtype of a column.

Example:

df = pd.DataFrame({'Weed': ['green crack', 'northern lights', 'girl scout cookies'], 'Qty':[10,15,3]}) df.dtypes

Weed object, Qty int64

df['Qty'].astype(str) df.dtypes

Weed object, Qty int64

Even setting the inplace arg to True doesn't help at times. I don't know why this happens though. In most cases inplace=True equals an explicit assignment.

df['Qty'].astype(str, inplace = True) df.dtypes

Weed object, Qty int64

Now the assignment,

df['Qty'] = df['Qty'].astype(str) df.dtypes

Weed object, Qty object

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I was facing this issue for long time. Finally it was issue of ssh-add. Git ssh credentials were not taken into consideration.

Check following command might work for you:

ssh-add

Why can't I define a default constructor for a struct in .NET?

Here's my solution to the no default constructor dilemma. I know this is a late solution, but I think it's worth noting this is a solution.

public struct Point2D {
    public static Point2D NULL = new Point2D(-1,-1);
    private int[] Data;

    public int X {
        get {
            return this.Data[ 0 ];
        }
        set {
            try {
                this.Data[ 0 ] = value;
            } catch( Exception ) {
                this.Data = new int[ 2 ];
            } finally {
                this.Data[ 0 ] = value;
            }
        }
    }

    public int Z {
        get {
            return this.Data[ 1 ];
        }
        set {
            try {
                this.Data[ 1 ] = value;
            } catch( Exception ) {
                this.Data = new int[ 2 ];
            } finally {
                this.Data[ 1 ] = value;
            }
        }
    }

    public Point2D( int x , int z ) {
        this.Data = new int[ 2 ] { x , z };
    }

    public static Point2D operator +( Point2D A , Point2D B ) {
        return new Point2D( A.X + B.X , A.Z + B.Z );
    }

    public static Point2D operator -( Point2D A , Point2D B ) {
        return new Point2D( A.X - B.X , A.Z - B.Z );
    }

    public static Point2D operator *( Point2D A , int B ) {
        return new Point2D( B * A.X , B * A.Z );
    }

    public static Point2D operator *( int A , Point2D B ) {
        return new Point2D( A * B.Z , A * B.Z );
    }

    public override string ToString() {
        return string.Format( "({0},{1})" , this.X , this.Z );
    }
}

ignoring the fact I have a static struct called null, (Note: This is for all positive quadrant only), using get;set; in C#, you can have a try/catch/finally, for dealing with the errors where a particular data type is not initialized by the default constructor Point2D(). I guess this is elusive as a solution to some people on this answer. Thats mostly why i'm adding mine. Using the getter and setter functionality in C# will allow you to bypass this default constructor non-sense and put a try catch around what you dont have initialized. For me this works fine, for someone else you might want to add some if statements. So, In the case where you would want a Numerator/Denominator setup, this code might help. I'd just like to reiterate that this solution does not look nice, probably works even worse from an efficiency standpoint, but, for someone coming from an older version of C#, using array data types gives you this functionality. If you just want something that works, try this:

public struct Rational {
    private long[] Data;

    public long Numerator {
        get {
            try {
                return this.Data[ 0 ];
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                return this.Data[ 0 ];
            }
        }
        set {
            try {
                this.Data[ 0 ] = value;
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                this.Data[ 0 ] = value;
            }
        }
    }

    public long Denominator {
        get {
            try {
                return this.Data[ 1 ];
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                return this.Data[ 1 ];
            }
        }
        set {
            try {
                this.Data[ 1 ] = value;
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                this.Data[ 1 ] = value;
            }
        }
    }

    public Rational( long num , long denom ) {
        this.Data = new long[ 2 ] { num , denom };
        /* Todo: Find GCD etc. */
    }

    public Rational( long num ) {
        this.Data = new long[ 2 ] { num , 1 };
        this.Numerator = num;
        this.Denominator = 1;
    }
}

Page scroll when soft keyboard popped up

Ok, I have searched several hours now to find the problem, and I found it.

None of the changes like fillViewport="true" or android:windowSoftInputMode="adjustResize" helped me.

I use Android 4.4 and this is the big mistake:

android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

Somehow, the Fullscreen themes prevent the ScrollViews from scrolling when the SoftKeyboard is visible.

At the moment, I ended up using this instead:

android:theme="@android:style/Theme.Black.NoTitleBar

I don't know how to get rid of the top system bar with time and battery display, but at least I got the problem.

Hope this helps others who have the same problem.

EDIT: I got a little workaround for my case, so I posted it here:

I am not sure if this will work for you, but it will definitely help you in understanding, and clear some things up.

EDIT2: Here is another good topic that will help you to go in the right direction or even solve your problem.

The ResourceConfig instance does not contain any root resource classes

that issue is because jersey can't find a dependecy package for your rest service declarated

check your project package distribution and assert that is equals to your web.xml param value

How to convert int to float in python?

To convert an integer to a float in Python you can use the following:

float_version = float(int_version)

The reason you are getting 0 is that Python 2 returns an integer if the mathematical operation (here a division) is between two integers. So while the division of 144 by 314 is 0.45~~~, Python converts this to integer and returns just the 0 by eliminating all numbers after the decimal point.

Alternatively you can convert one of the numbers in any operation to a float since an operation between a float and an integer would return a float. In your case you could write float(144)/314 or 144/float(314). Another, less generic code, is to say 144.0/314. Here 144.0 is a float so it’s the same thing.

Android Studio: Can't start Git

The path for your git is invalid. Copy the path from File -> Settings -> Version Control -> Git and search that folder and you can see the path to your Git is not valid. Reset the path with correct location and test it. The error should be gone.