Programs & Examples On #Tsr

Android Material and appcompat Manifest merger failed

In my case, this is working perfectly.. I have added below two line codes inside manifest file

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

Credit goes to this answer.

Manifest file Example

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

How can I mock the JavaScript window object using Jest?

In my component I need access to window.location.search. This is what I did in the Jest test:

Object.defineProperty(global, "window", {
  value: {
    location: {
      search: "test"
    }
  }
});

In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:

function mockWindow(search, pathname) {
  Object.defineProperty(global, "window", {
    value: {
      location: {
        search,
        pathname
      }
    },
    writable: true
  });
}

And reset after each test:

afterEach(() => {
  delete global.window.location;
});

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

I was facing same issue and got the error while uploading apk to Google play. I used ads in my app, and I was not even mentioned READ_PHONE_STATE permission in my manifest file. but yet I got this error. Then I change dependencies for ads in build.gradle file. and then it solved my issue. They solved this issue in 12.0.1.

compile 'com.google.android.gms:play-services-ads:12.0.1'

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Used to face the same problem. The reason was in incorrect context passing to AlertDialog.Builder(here). use like AlertDialog.Builder(Homeactivity.this)

How do I access Configuration in any class in ASP.NET Core?

There is also an option to make configuration static in startup.cs so that what you can access it anywhere with ease, static variables are convenient huh!

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

internal static IConfiguration Configuration { get; private set; }

This makes configuration accessible anywhere using Startup.Configuration.GetSection... What can go wrong?

Listing files in a specific "folder" of a AWS S3 bucket

While everybody say that there are no directories and files in s3, but only objects (and buckets), which is absolutely true, I would suggest to take advantage of CommonPrefixes, described in this answer. So, you can do following to get list of "folders" (commonPrefixes) and "files" (objectSummaries):

ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket.getName()).withPrefix(prefix).withDelimiter(DELIMITER);
ListObjectsV2Result listing = s3Client.listObjectsV2(req);
for (String commonPrefix : listing.getCommonPrefixes()) {
        System.out.println(commonPrefix);
}
for (S3ObjectSummary summary: listing.getObjectSummaries()) {
    System.out.println(summary.getKey());
}

In your case, for objectSummaries (files) it should return (in case of correct prefix):
users/user-id/contacts/contact-id/file1.txt
users/user-id/contacts/contact-id/file2.txt

for commonPrefixes:
users/user-id/contacts/contact-id/

Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html

Firebase cloud messaging notification not received by device

You have placed your service outside the application tag. Change bottom to this.

<service
    android:name=".NotificationGenie">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

</application>

How to remove title bar from the android activity?

Try this:

this.getSupportActionBar().hide();

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

    try
    {
        this.getSupportActionBar().hide();
    }
    catch (NullPointerException e){}

    setContentView(R.layout.activity_main);
}

ActivityCompat.requestPermissions not showing dialog box

This just happened to me. It turned out I was requesting ALL permissions, when I needed to filter to just DANGEROUS permissions, and it suddenly started working.

fun requestPermissions() {
    val missingDangerPermissions = PERMISSIONS
            .filter { ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED }
            .filter { this.getPackageManager().getPermissionInfo(it, PackageManager.GET_META_DATA).protectionLevel == PermissionInfo.PROTECTION_DANGEROUS } // THIS FILTER HERE!

    if (missingDangerPermissions.isNotEmpty()) {
        Log.i(TAG, "Requesting dangerous permission to $missingDangerPermissions.")
        ActivityCompat.requestPermissions(this,
                missingDangerPermissions.toTypedArray(),
                REQUEST_CODE_REQUIRED_PERMISSIONS);
        return
    } else {
        Log.i(TAG, "We had all the permissions we needed (yay!)")
    }
}

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

From here:

Root Cause: Maximum connection has been exceeded on your SQL Server Instance.

How to fix it...!

  1. F8 or Object Explorer
  2. Right click on Instance --> Click Properties...
  3. Select "Connections" on "Select a page" area at left
  4. Chenge the value to 0 (Zero) for "Maximum number of concurrent connections(0 = Unlimited)"
  5. Restart the SQL Server Instance once.

Apart from that also ensure that below are enabled:

  • Shared Memory protocol is enabled
  • Named Pipes protocol is enabled
  • TCP/IP is enabled

IIS Manager in Windows 10

@user1664035 & @Attila Mika's suggestion worked. You have to navigate to Control Panel -> Programs And Features -> Turn Windows Features On or Off. And refer to the screenshot. You should check IIS Management console.

Screenshot

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Make sure you import the @Test annotation from the correct library:

import org.junit.jupiter.api.Test

not

import org.junit.Test

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

After some modifications in my Web.config CORS suddenly stopped working in my Web API 2 project (at least for OPTIONS request during the preflight). It seems that you need to have the section mentioned below in your Web.config or otherwise the (global) EnableCorsAttribute will not work on OPTIONS requests. Note that this is the exact same section Visual Studio will add in a new Web API 2 project.

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="OPTIONSVerbHandler"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
  </handlers>
</system.webServer>

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Reason for this error is that PHP does not have a list of trusted certificate authorities.

PHP 5.6 and later try to load the CAs trusted by the system automatically. Issues with that can be fixed. See http://php.net/manual/en/migration56.openssl.php for more information.

PHP 5.5 and earlier are really hard to setup correctly since you manually have to specify the CA bundle in each request context, a thing you do not want to sprinkle around your code. So I decided for my code that for PHP versions < 5.6, SSL verification simply gets disabled:

$req = new HTTP_Request2($url);
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
    //correct ssl validation on php 5.5 is a pain, so disable
    $req->setConfig('ssl_verify_host', false);
    $req->setConfig('ssl_verify_peer', false);
}

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.

Bootstrap trying to load map file. How to disable it? Do I need to do it?

.map files allow a browser to download a full version of the minified JS. It is really for debugging purposes.

In effect, the .map missing isn't a problem. You only know it is missing, as the browser has had its Developer tools opened, detected a minified file and is just informing you that the JS debugging won't be as good as it could be.

This is why libraries like jQuery have the full, the minified and the map file too.

See this article for a full explanation of .map files:

Disable password authentication for SSH

Here's a script to do this automatically

# Only allow key based logins
sed -n 'H;${x;s/\#PasswordAuthentication yes/PasswordAuthentication no/;p;}' /etc/ssh/sshd_config > tmp_sshd_config
cat tmp_sshd_config > /etc/ssh/sshd_config
rm tmp_sshd_config

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

I was having the same difficulty loading my VB 6 project. Here is a sample error message: "Class MSComctlLib.ProgressBar of control prgExecution was not a loaded control class."

This problem was solved by some Microsoft Magic as follows: I opened the Project Components window in my broken project. I clicked on Browse and found the file MsComctl.ocx. I clicked on OK. VB 6 then got stuck (the application non responsive). After some time, I ended the VB 6 application using the task manager.

Then, magically, when I opened up my VB 6 project to show my programming friend what a POS this project was, all the controls were back, linked as expected. Somehow, something was registered or fixed.

How to set an iframe src attribute from a variable in AngularJS

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

In the controller:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

In the Template:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:

SQLSVCACCOUNT:                 NT AUTHORITY\SYSTEM

According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

Angular JS POST request not sending JSON data

you can use your method by this way

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/apiControllerName/methodName',
    method: 'POST',
    params: {application:app, from:d1, to:d2},
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    //timeout: 1,
    //cache: false,
    //transformRequest: false,
    //transformResponse: false
}).then(function (results) {
    return results;
}).catch(function (e) {

});

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.

Allow anonymous authentication for a single folder in web.config?

Use <location> configuration tag, and <allow users="?"/> to allow anonymous only or <allow users="*"/> for all:

<configuration>
   <location path="Path/To/Public/Folder">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

assignment operator overloading in c++

The second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c; resolve as expected. I can't think of any cases where I would want to return a copy from assignment.

One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...

Edit:

Here's some basic calls:

SimpleCircle x; // default constructor
SimpleCircle y(x); // copy constructor
x = y; // assignment operator

Now say we had the first version of your assignment operator:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this; // calls copy constructor SimpleCircle(*this)
     itsRadius = rhs.getRadius(); // copy member
     return *this; // calls copy constructor
}

It calls the copy constructor and passes a reference to this in order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this; // return reference to this (no copy)
    itsRadius = rhs.getRadius(); // copy member
    return *this; // return reference to this (no copy)
}

How to enable ASP classic in IIS7.5

  • Go to control panel
  • click program features
  • turn windows on and off
  • go to internet services
  • under world wide web services check the asp.net and others

Click ok and your web sites will load properly.

What is w3wp.exe?

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.

ASP.NET strange compilation error

The answers provided are not the solution. The .NET 6# stuff is pretty different from what we used to. A lot has changed, from having to deal with portable libraries to Visual Studio 2015 installing an old compiler (it cost me four hours cracking my head).

The long story short: Stack Overflow question How do I use C# 6 with a Web Site project type?

You need to install the C# .NET compiler (now runs as a service bla bla bla). and you need to run updates on NuGet to get the latest everything (before trying anything else).

The compiler must be installed on the project your solution runs from (so your website or your main project your application starts from (if you have multiple projects)).

Once you install that then sort out your web.config referencing any portable libraries, and delete both the bin and obj folder (to avoid works on my computer nightmare), It should just run. But be patient; what happens on your machine may vary as much as the answers above. Most of the answers above hide other problems. It may work for a while, then boom: compiler error. I had a few pages working, then some pages started failing because of some packages that have started using portable libraries.

There is already an open DataReader associated with this Command which must be closed first

Most likely this issue happens because of "lazy loading" feature of Entity Framework. Usually, unless explicitly required during initial fetch, all joined data (anything that stored in other database tables) is fetched only when required. In many cases that is a good thing, since it prevents from fetching unnecessary data and thus improve query performance (no joins) and saves bandwidth.

In the situation described in the question, initial fetch is performed, and during "select" phase missing lazy loading data is requested, additional queries are issued and then EF is complaining about "open DataReader".

Workaround proposed in the accepted answer will allow execution of these queries, and indeed the whole request will succeed.

However, if you will examine requests sent to the database, you will notice multiple requests - additional request for each missing (lazy loaded) data. This might be a performance killer.

A better approach is to tell to EF to preload all needed lazy loaded data during the initial query. This can be done using "Include" statement:

using System.Data.Entity;

query = query.Include(a => a.LazyLoadedProperty);

This way, all needed joins will be performed and all needed data will be returned as a single query. The issue described in the question will be solved.

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

android listview item height

The height of list view items are adjusted based on its contents. In first image, no content. so height is very minimum. In second image, height is increased based on the size of the text. Because, you specified android:layout_height="wrap_content".

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\ C:\HostingSpaces\dbname_jun14_2010_new.bak'

The error is quite self-explanatory. The file C:\program files\...\Backup \c:\Hosting...\ is incorrectly formatted. This is quite obvious if you inspect the file name. Perhaps ommit the extra space in your backup statement?

BACKUP DATABASE go4sharepoint_1384_8481 
TO DISK='C:\HostingSpaces\dbname_jun14_2010_new.bak' with FORMAT

Note there is no space between ' and C:

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

Passing parameters to JavaScript files

No, you cant really do this by adding variables to the querystring portion of the JS file URL. If its writing the portion of code to parse the string that bothers you, perhaps another way would be to json encode your variables and put them in something like the rel attribute of the tag? I don't know how valid this is in terms of HTML validation, if thats something you're very worried about. Then you just need to find the rel attribute of the script and then json_decode that.

eg

<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>

How to retrieve the last autoincremented ID from a SQLite table?

With SQL Server you'd SELECT SCOPE_IDENTITY() to get the last identity value for the current process.

With SQlite, it looks like for an autoincrement you would do

SELECT last_insert_rowid()

immediately after your insert.

http://www.mail-archive.com/[email protected]/msg09429.html

In answer to your comment to get this value you would want to use SQL or OleDb code like:

using (SqlConnection conn = new SqlConnection(connString))
{
    string sql = "SELECT last_insert_rowid()";
    SqlCommand cmd = new SqlCommand(sql, conn);
    conn.Open();
    int lastID = (Int32) cmd.ExecuteScalar();
}

How do I make a file:// hyperlink that works in both IE and Firefox?

Paste following link to directly under link button click event, otherwise use javascript to call code behind function

Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs) 
    System.Diagnostics.Process.Start(FilePath)
End Sub

How to connect to local instance of SQL Server 2008 Express

var.connectionstring = "server=localhost; database=dbname; integrated security=yes"

or

var.connectionstring = "server=localhost; database=dbname; login=yourlogin; pwd=yourpass"

Find position of a node using xpath

Try:

count(a/b[.='tsr']/preceding-sibling::*)+1.

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Invalidating JSON Web Tokens

Kafka message queue and local black lists

I thought about using a messaging system like kafka. Let me explain:

You could have one micro service (let call it userMgmtMs service) for example which is responsible for the login and logout and to produce the JWT token. This token then gets passed to the client.

Now the client can use this token to call different micro services (lets call it pricesMs), within pricesMs there will be NO database check to the users table from which the initial token creation was triggered. This database has only to exist in userMgmtMs. Also the JWT token should include the permissions / roles so that the pricesMs do not need to lookup anything from the DB to allow spring security to work.

Instead of going to the DB in the pricesMs the JwtRequestFilter could provide a UserDetails object created by the data provided in the JWT token (without the password obviously).

So, how to logout or invalidate a token? Since we do not wanna call the database of userMgmtMs with every request for priecesMs (which would introduce quite a lot of unwanted dependencies) a solution could be to use this token blacklist.

Instead of keeping this blacklist central and haveing a dependency on one table from all microservices, I propose to use a kafka message queue.

The userMgmtMs is still responsible for the logout and once this is done it puts it into its own blacklist (a table NOT shared among microservices). In addition it sends a kafka event with the content of this token to a internal kafka service where all other microservices are subscribed to.

Once the other microservices receive the kafka event they will put it as well in their internal blacklist.

Even if some microservices are down at the time of logout they will eventually go up again and will receive the message at a later state.

Since kafka is developed so that clients have their own reference which messages they did read it is ensured that no client, down or up will miss any of this invalid tokens.

The only issue again what I can think of is that the kafka messaging service will again introduce a single point of failure. But it is kind of reversed because if we have one global table where all invalid JWT tokens are saved and this db or micro service is down nothing works. With the kafka approach + client side deletion of JWT tokens for a normal user logout a downtime of kafka would in most cases not even be noticeable. Since the black lists are distributed among all microservies as an internal copy.

In the off case that you need to invalidate a user which was hacked and kafka is down this is where the problems start. In this case changing the secret as a last resort could help. Or just make sure kafka is up before doing so.

Disclaimer: I did not implement this solution yet but somehow I feel that most of the proposed solution negate the idea of the JWT tokens with having a central database lookup. So I was thinking about another solution.

Please let me know what you think, does it make sense or is there an obvious reason why it cant?

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

After countless hours of frustration I managed to get all working:

odbcinst.ini:

[FreeTDS]
Description = FreeTDS Driver v0.91
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
fileusage=1
dontdlclose=1
UsageCount=1

odbc.ini:

[test]
Driver = FreeTDS
Description = My Test Server
Trace = No
#TraceFile = /tmp/sql.log
ServerName = mssql
#Port = 1433
instance = SQLEXPRESS
Database = usedbname
TDS_Version = 4.2

FreeTDS.conf:

[mssql]
host = hostnameOrIP
instance = SQLEXPRESS
#Port = 1433
tds version = 4.2

First test connection (mssql is a section name from freetds.conf):

tsql -S mssql -U username -P password

You must see some settings but no errors and only a 1> prompt. Use quit to exit.

Then let's test DSN/FreeTDS (test is a section name from odbc.ini; -v means verbose):

isql -v test username password -v

You must see message Connected!

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

What is the (function() { } )() construct in JavaScript?

This is the self-invoking anonymous function. It is executed while it is defined. Which means this function is defined and invokes itself immediate after the definition.

And the explanation of the syntax is: The function within the first () parenthesis is the function which has no name and by the next (); parenthesis you can understand that it is called at the time it is defined. And you can pass any argument in this second () parenthesis which will be grabbed in the function which is in the first parenthesis. See this example:

(function(obj){
    // Do something with this obj
})(object);

Here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature.

libpng warning: iCCP: known incorrect sRGB profile

Use pngcrush to remove the incorrect sRGB profile from the png file:

pngcrush -ow -rem allb -reduce file.png
  • -ow will overwrite the input file
  • -rem allb will remove all ancillary chunks except tRNS and gAMA
  • -reduce does lossless color-type or bit-depth reduction

In the console output you should see Removed the sRGB chunk, and possibly more messages about chunk removals. You will end up with a smaller, optimized PNG file. As the command will overwrite the original file, make sure to create a backup or use version control.

How can I get form data with JavaScript/jQuery?

Use $('form').serializeArray(), which returns an array:

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

Other option is $('form').serialize(), which returns a string:

"foo=1&bar=xxx&this=hi"

Take a look at this jsfiddle demo

Is there any good dynamic SQL builder library in Java?

You can use the following library:

https://github.com/pnowy/NativeCriteria

The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).

You can find the examples on github page, the library is available at Maven central of course.

NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));

What is the most efficient way to get first and last line of a text file?

Here's a modified version of SilentGhost's answer that will do what you want.

with open(fname, 'rb') as fh:
    first = next(fh)
    offs = -100
    while True:
        fh.seek(offs, 2)
        lines = fh.readlines()
        if len(lines)>1:
            last = lines[-1]
            break
        offs *= 2
    print first
    print last

No need for an upper bound for line length here.

How to resolve javax.mail.AuthenticationFailedException issue?

When you are trying to sign in to your Google Account from your new device or application you have to unlock the CAPTCHA. To unlock the CAPTCHA go to https://www.google.com/accounts/DisplayUnlockCaptcha and then enter image description here

And also make sure to allow less secure apps on enter image description here

How to convert LINQ query result to List?

What you can do is select everything into a new instance of Course, and afterwards convert them to a List.

var qry = from a in obj.tbCourses
                     select new Course() {
                         Course.Property = a.Property
                         ...
                     };

qry.toList<Course>();

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

How do I make an HTTP request in Swift?

KISS answer:

URLSession.shared.dataTask(with: URL(string: "https://google.com")!) {(data, response, error) in
    print(String(data: data!, encoding: .utf8))
}.resume()

Calling one Activity from another in Android

I have implemented this way and it works.It is much easier than all that is reported.

We have two activities : one is the main and another is the secondary.

In secondary activity, which is where we want to end the main activity , define the following variable:

public static Activity ACTIVIDAD;

And then the following method:

public static void enlaceActividadPrincipal(Activity actividad) 
{
    tuActividad.ACTIVIDAD=actividad;
}

Then, in your main activity from the onCreate method , you make the call:

    actividadSecundaria.enlaceActividadPrincipal(this);

Now, you're in control. Now, from your secondary activity, you can complete the main activity. Finish calling the function, like this:

ACTIVIDAD.finish();

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Using Case/Switch and GetType to determine the object

I'm faced with the same problem and came across this post. Is this what's meant by the IDictionary approach:

Dictionary<Type, int> typeDict = new Dictionary<Type, int>
{
    {typeof(int),0},
    {typeof(string),1},
    {typeof(MyClass),2}
};

void Foo(object o)
{
    switch (typeDict[o.GetType()])
    {
        case 0:
            Print("I'm a number.");
            break;
        case 1:
            Print("I'm a text.");
            break;
        case 2:
            Print("I'm classy.");
            break;
        default:
            break;
    }
}

If so, I can't say I'm a fan of reconciling the numbers in the dictionary with the case statements.

This would be ideal but the dictionary reference kills it:

void FantasyFoo(object o)
{
    switch (typeDict[o.GetType()])
    {
        case typeDict[typeof(int)]:
            Print("I'm a number.");
            break;
        case typeDict[typeof(string)]:
            Print("I'm a text.");
            break;
        case typeDict[typeof(MyClass)]:
            Print("I'm classy.");
            break;
        default:
            break;
    }
}

Is there another implementation I've overlooked?

How to transfer paid android apps from one google account to another google account

You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.

There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).

Add multiple items to already initialized arraylist in java

I believe the answer above is incorrect, the proper way to initialize with multiple values would be this...

int[] otherList ={1,2,3,4,5};

so the full answer with the proper initialization would look like this

int[] otherList ={1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

Jquery DatePicker Set default date

For today's Date

$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});

Show or hide element in React

I was able to use css property "hidden". Don't know about possible drawbacks.

export default function App() {
    const [hidden, setHidden] = useState(false);
    return (
      <div>
        <button onClick={() => setHidden(!hidden)}>HIDE</button>
        <div hidden={hidden}>hidden component</div>
      </div>
    );
  }

How to get the Google Map based on Latitude on Longitude?

Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests

How to change Screen buffer size in Windows Command Prompt from batch script

I created the following utility to set the console size and scroll buffers.

I compiled it using DEV C++ (http://www.bloodshed.net/devcpp.html).

An executable is included in https://sourceforge.net/projects/wa2l-wintools/.

#include <iostream>
#include <windows.h> 

using namespace std;


// SetWindow(Width,Height,WidthBuffer,HeightBuffer) -- set console size and buffer dimensions
//
void SetWindow(int Width, int Height, int WidthBuffer, int HeightBuffer) { 
    _COORD coord; 
    coord.X = WidthBuffer; 
    coord.Y = HeightBuffer; 

    _SMALL_RECT Rect; 
    Rect.Top = 0; 
    Rect.Left = 0; 
    Rect.Bottom = Height - 1; 
    Rect.Right = Width - 1; 

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);      // Get Handle 
    SetConsoleScreenBufferSize(Handle, coord);            // Set Buffer Size 
    SetConsoleWindowInfo(Handle, TRUE, &Rect);            // Set Window Size 
}  // SetWindow



// main(Width,Height,WidthBuffer,HeightBuffer) -- main
//
int main(int argc, char *argv[]) {     
    int width = 80;
    int height = 25;
    int wbuffer = width + 200;
    int hbuffer = height + 1000;

    if ( argc == 5 ){
        width = atoi(argv[1]);
        height = atoi(argv[2]);
        wbuffer = atoi(argv[3]);
        hbuffer = atoi(argv[4]);
    } else if ( argc > 1 ) {
        cout << "Usage: " << argv[0] << " [ width height bufferwidth bufferheight ]" << endl << endl;
        cout << "  Where" << endl;
        cout << "    width            console width" << endl;
        cout << "    height           console height" << endl;
        cout << "    bufferwidth      scroll buffer width" << endl;
        cout << "    bufferheight     scroll buffer height" << endl;
        return 4;
    }    

    SetWindow(width,height,wbuffer,hbuffer);
    return 0;
} 

How to set the width of a RaisedButton in Flutter?

This worked for me. The Container provides the height and FractionallySizedBox provides the width for the RaisedButton.

Container(
  height: 50.0, //Provides height for the RaisedButton
  child: FractionallySizedBox(
    widthFactor: 0.7, ////Provides 70% width for the RaisedButton
    child: RaisedButton(
      onPressed: () {},
    ),
  ),
),

Date object to Calendar [Java]

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

However, another approach is to not use Date at all. You could use an approach like this:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

Upload a file to Amazon S3 with NodeJS

I found the following to be a working solution::

npm install aws-sdk


Once you've installed the aws-sdk , use the following code replacing values with your where needed.

var AWS = require('aws-sdk');
var fs =  require('fs');

var s3 = new AWS.S3();

// Bucket names must be unique across all S3 users

var myBucket = 'njera';

var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file                
fs.readFile('demo.jpg', function (err, data) {
  if (err) { throw err; }



     params = {Bucket: myBucket, Key: myKey, Body: data };

     s3.putObject(params, function(err, data) {

         if (err) {

             console.log(err)

         } else {

             console.log("Successfully uploaded data to myBucket/myKey");

         }

      });

});

I found the complete tutorial on the subject here in case you're looking for references ::


How to upload files (text/image/video) in amazon s3 using node.js

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

All of the answers here use the Class.forName("my.vandor.Driver"); line to load the driver.

As an (better) alternative you can use the DriverManager helper class which provides you with a handful of methods to handle your JDBC driver/s.

You might want to

  1. Use DriverManager.registerDriver(driverObject); to register your driver to it's list of drivers

Registers the given driver with the DriverManager. A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager. If the driver is currently registered, no action is taken

  1. Use DriverManager.deregisterDriver(driverObject); to remove it.

Removes the specified driver from the DriverManager's list of registered drivers.

Example:

Driver driver = new oracle.jdbc.OracleDriver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
// ... 
// and when you don't need anything else from the driver
DriverManager.deregisterDriver(driver);

or better yet, use a DataSource

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Other type of format :

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Java - What does "\n" mean?

\n

That means a new line is printed.

As a side note there is no need to write that extra line . There is an built in inbuilt function there.

 println()  //prints the content in new line

Learn more from docs

Copying a HashMap in Java

Since this question is still unanswered and I had a similar problem, I will try to answer this. The problem (as others already mentioned) is that you just copy references to the same object and thus a modify on the copy will also modify the origin object. So what you have to to is to copy the object (your map value) itself. The far easiest way to do so is to make all your objects implementing the serializeable interface. Then serialize and deserialize your map to get a real copy. You can do this by yourself or use the apache commons SerializationUtils#clone() which you can find here: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html But be aware this is the simplest approach but it is an expensive task to serialize and deserialize a lot of objects.

How to use C++ in Go

Seems that currently SWIG is best solution for this:

http://www.swig.org/Doc2.0/Go.html

It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.

Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".

Cannot use Server.MapPath

bool IsExist = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
if (!IsExist)
    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/UploadedFiles/"));

StreamWriter textWriter = File.CreateText(Path.Combine(HttpContext.Current.Server.MapPath("/UploadedFiles/") + "FileName.csv"));
var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);
csvWriter.WriteRecords(classVM);

CURRENT_DATE/CURDATE() not working as default DATE value

Currently from MySQL 8 you can set the following to a DATE column:

In MySQL Workbench, in the Default field next to the column, write: (curdate())

If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.

Value of type 'T' cannot be converted to

I know similar code that the OP posted in this question from generic parsers. From a performance perspective, you should use Unsafe.As<TFrom, TResult>(ref TFrom source), which can be found in the System.Runtime.CompilerServices.Unsafe NuGet package. It avoids boxing for value types in these scenarios. I also think that Unsafe.As results in less machine code produced by the JIT than casting twice (using (TResult) (object) actualString), but I haven't checked that out.

public TResult ParseSomething<TResult>(ParseContext context)
{
    if (typeof(TResult) == typeof(string))
    {
        var token = context.ParseNextToken();
        string parsedString = token.ParseToDotnetString();
        return Unsafe.As<string, TResult>(ref parsedString);
    }
    else if (typeof(TResult) == typeof(int))
    {
        var token = context.ParseNextToken();
        int parsedInt32 = token.ParseToDotnetInt32();
        // This will not box which might be critical to performance
        return Unsafe.As<int, TResult>(ref parsedInt32); 
    }
    // other cases omitted for brevity's sake
}

Unsafe.As will be replaced by the JIT with efficient machine code instructions, as you can see in the official CoreFX repo:

Source Code of Unsafe.As

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Use collections.Counter:

>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})

Counters are basically a subclass of dict, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.

Compare one String with multiple values in one expression

For those who came here for exact equality checks (not ignoring case), I find that

if (Arrays.asList(str1, str2, str3).contains(strToCheck)) {
    ...
}

is one of, if the most concise solution, and is available on Java 7.

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Javascript How to define multiple variables on a single line?

Using Javascript's es6 or node, you can do the following:

var [a,b,c,d] = [0,1,2,3]

And if you want to easily print multiple variables in a single line, just do this:

console.log(a, b, c, d)

0 1 2 3

This is similar to @alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.

Note that this uses Javascript's array destructuring assignment

In C++ check if std::vector<string> contains a certain value

  1. If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.

     std::set<std::string> s;
     s.insert("abc");
     s.insert("xyz");
     if (s.find("abc") != s.end()) { ...
    
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

Java 8 Stream and operation on arrays

Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.

Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

Two-way SSL clarification

In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.

Warning: date_format() expects parameter 1 to be DateTime

This may help

$formattedweddingdate =date('d-m-Y',strtotime($weddingdate));

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

append multiple values for one key in a dictionary

It's easier if you get these values into a list of tuples. To do this, you can use list slicing and the zip function.

data_in = [2010,2,2009,4,1989,8,2009,7]
data_pairs = zip(data_in[::2],data_in[1::2])

Zip takes an arbitrary number of lists, in this case the even and odd entries of data_in, and puts them together into a tuple.

Now we can use the setdefault method.

data_dict = {}
for x in data_pairs:
    data_dict.setdefault(x[0],[]).append(x[1])

setdefault takes a key and a default value, and returns either associated value, or if there is no current value, the default value. In this case, we will either get an empty or populated list, which we then append the current value to.

Firebase (FCM) how to get token

The team behind Firebase Android SDK change API a little bit. I've implemented "Token to Server" logic like this:

In my instance of FirebaseMessagingService:

public class FirebaseCloudMessagingService extends FirebaseMessagingService {

    ...

    @Override
    public void onNewToken(String token) {
        // sending token to server here
    }

    ...

}

Keep in mind that token is per device, and it can be updated by Firebase regardless of your login logic. So, if you have Login and Logout functionality, you have to consider extra cases:

  1. When a new user logs in, you need to bind token to the new user (send it to the server). Because token might be updated during the session of old user and server doesn't know token of the new user.
  2. When the user logs out, you need to unbind token. Because user should not receive notifications/messages anymore.

Using new API, you can get token like this:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            // send it to server
        }
    });

Good luck!

How to add a JAR in NetBeans

Right click 'libraries' in the project list, then click add.

How do I read a text file of about 2 GB?

Try Glogg. the fast, smart log explorer.

I have opened log file of size around 2 GB, and the search is also very fast.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

The memory allocation for PHP can be adjusted permanently, or temporarily.

Permanently

You can permanently change the PHP memory allocation two ways.

If you have access to your php.ini file, you can edit the value for memory_limit to your desire value.

If you do not have access to your php.ini file (and your webhost allows it), you can override the memory allocation through your .htaccess file. Add php_value memory_limit 128M (or whatever your desired allocation is).

Temporary

You can adjust the memory allocation on the fly from within a PHP file. You simply have the code ini_set('memory_limit', '128M'); (or whatever your desired allocation is). You can remove the memory limit (although machine or instance limits may still apply) by setting the value to "-1".

How to add font-awesome to Angular 2 + CLI project

After some experimentation I managed to get the following working:

  1. Install with npm:

    npm install font-awesome --save
    
  2. add to angular-cli-build.js file:

    vendorNpmFiles : [
        font-awesome/**/*.+(css|css.map|otf|eot|svg|ttf|woff|woff2)',
    ]
    
  3. add to index.html

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
    

The key was to include the font file types in the angular-cli-build.js file

.+(css|css.map|otf|eot|svg|ttf|woff|woff2)

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

Notepad++ change text color?

A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors

Android: Is it possible to display video thumbnails?

Android 1.5 and 1.6 do not offer this thumbnails, but 2.0 does, as seen on the official release notes:

Media

  • MediaScanner now generates thumbnails for all images when they are inserted into MediaStore.
  • New Thumbnail API for retrieving image and video thumbnails on demand.

How can I compile and run c# program without using visual studio?

If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\

(Please do not edit, leave as a single line)

... The line above broken up for readability

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\

What is ADT? (Abstract Data Type)

Abstract data type are like user defined data type on which we can perform functions without knowing what is there inside the datatype and how the operations are performed on them . As the information is not exposed its abstracted. eg. List,Array, Stack, Queue. On Stack we can perform functions like Push, Pop but we are not sure how its being implemented behind the curtains.

Append value to empty vector in R?

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

Here are several ways to append values to a vector. All of them are discouraged.

Appending to a vector in a loop

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Pre-allocate the vector before looping

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use the quotemeta function:

$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";

print "wee" if ($text_to_search =~ /$search_string/);

toBe(true) vs toBeTruthy() vs toBeTrue()

Disclamer: This is just a wild guess

I know everybody loves an easy-to-read list:

  • toBe(<value>) - The returned value is the same as <value>
  • toBeTrue() - Checks if the returned value is true
  • toBeTruthy() - Check if the value, when cast to a boolean, will be a truthy value

    Truthy values are all values that aren't 0, '' (empty string), false, null, NaN, undefined or [] (empty array)*.

    * Notice that when you run !![], it returns true, but when you run [] == false it also returns true. It depends on how it is implemented. In other words: (!![]) === ([] == false)


On your example, toBe(true) and toBeTrue() will yield the same results.

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

I had this problem and then I ran "apache_start.bat" the error in german told me there was a problem with line 51 in httpd-ssl.conf which is

SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5

What I did was comment lines 163 (ssl module) and 522 (httpd-ssl.conf include) in httpd.conf; I don't need ssl for development, so that solved it for me.

How to make the corners of a button round?

Create file myButton.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorButton"/>
    <corners android:radius="10dp"/>
</shape>

add to your button

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/myButton"/>

How to get text with Selenium WebDriver in Python

Python

element.text

Java

element.getText()

C#

element.Text

Ruby

element.text

Can't find how to use HttpContent

For JSON Post:

var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Non-JSON:

var stringContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("field1", "value1"),
    new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/

Storing Form Data as a Session Variable

Yes this is possible. kizzie is correct with the session_start(); having to go first.

another observation I made is that you need to filter your form data using:

strip_tags($value);

and/or

stripslashes($value);

Is there a "standard" format for command line/shell help text?

yes, you're on the right track.

yes, square brackets are the usual indicator for optional items.

Typically, as you have sketched out, there is a commandline summary at the top, followed by details, ideally with samples for each option. (Your example shows lines in between each option description, but I assume that is an editing issue, and that your real program outputs indented option listings with no blank lines in between. This would be the standard to follow in any case.)

A newer trend, (maybe there is a POSIX specification that addresses this?), is the elimination of the man page system for documentation, and including all information that would be in a manpage as part of the program --help output. This extra will include longer descriptions, concepts explained, usage samples, known limitations and bugs, how to report a bug, and possibly a 'see also' section for related commands.

I hope this helps.

Which TensorFlow and CUDA version combinations are compatible?

You can use this configuration for cuda 10.0 (10.1 does not work as of 3/18), this runs for me:

  • tensorflow>=1.12.0
  • tensorflow_gpu>=1.4

Install version tensorflow gpu:

pip install tensorflow-gpu==1.4.0

Where can I find my Facebook application id and secret key?

I had a hard time finding where it is so here the image depicting it in 2019.  the location of app secret and app id in 2019.

What is in your .vimrc?

I use the following to keep all the temporary and backup files in one place:

set backup
set backupdir=~/.vim/backup
set directory=~/.vim/tmp

Saves cluttering working directories all over the place.

You will have to create these directories first, vim will not create them for you.

Compare objects in Angular

Assuming that the order is the same in both objects, just stringify them both and compare!

JSON.stringify(obj1) == JSON.stringify(obj2);

iPhone keyboard, Done button and resignFirstResponder

In Xcode 5.1

Enable Done Button

  • In Attributes Inspector for the UITextField in Storyboard find the field "Return Key" and select "Done"

Hide Keyboard when Done is pressed

  • In Storyboard make your ViewController the delegate for the UITextField
  • Add this method to your ViewController

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    

How do I combine a background-image and CSS3 gradient on the same element?

If you have strange errors with downloading background images use W3C Link checker: https://validator.w3.org/checklink

Here are modern mixins that I use (credits: PSA: don't use gradient generators):

.buttonAkc
{
    .gradientBackground(@imageName: 'accept.png');
    background-repeat: no-repeat !important;
    background-position: center right, top left !important;
}

.buttonAkc:hover
{
    .gradientBackgroundHover('accept.png');
}

.gradientBackground(@startColor: #fdfdfd, @endColor: #d9d9db, @imageName)
{
    background-color: mix(@startColor, @endColor, 60%); // fallback
    background-image: url("@{img-folder}/@{imageName}?v=@{version}"); // fallback
    background: url("@{img-folder}/@{imageName}?v=@{version}") no-repeat scroll right center, -webkit-linear-gradient(top, @startColor 0%, @endColor 100%) no-repeat scroll left top; // Chrome 10-25, Safari 5.1-6
    background: url("@{img-folder}/@{imageName}?v=@{version}") no-repeat scroll right center, linear-gradient(to bottom, @startColor 0%, @endColor 100%) no-repeat scroll left top;
}

.gradientBackgroundHover(@imageName)
{
    .gradientBackground(#fdfdfd, #b5b6b9, @imageName);
}

Are SSL certificates bound to the servers ip address?

Most SSL certificates are bound to the hostname of the machine and not the ip address.

You might get a better answer if you ask this question on serverfault.com

How to enable authentication on MongoDB through Docker?

you can use env variables to setup username and password for mongo

MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD

using simple docker command

docker run -e MONGO_INITDB_ROOT_USERNAME=my-user MONGO_INITDB_ROOT_PASSWORD=my-password mongo

using docker-compose

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: my-user
      MONGO_INITDB_ROOT_PASSWORD: my-password

and the last option is to manually access the container and set the user and password inside the mongo docker container

docker exec -it mongo-container bash

now you can use mongo shell command to configure everything that you want

Get an element by index in jQuery

You can use jQuery's .eq() method to get the element with a certain index.

$('ul li').eq(index).css({'background-color':'#343434'});

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

Bootstrap control with multiple "data-toggle"

Since Bootstrap forces you to initialize tooltips only through Javascript, I changed data-toggle="tooltip" (since it's useless then) to class="bootstrap-tooltip" and used this Javascript to initialize my tooltips:

$('.bootstrap-tooltip').tooltip();

And so I was free to use the data-toggle attribute for something else (e.g. data-toggle="button").

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

How do I vertically align text in a paragraph?

Below styles will vertically center it for you.

p.event_desc {
 font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
 line-height: 14px;
 height: 35px;
 display: table-cell;
 vertical-align: middle;
 margin: 0px;
}

What is DOM Event delegation?

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How to create duplicate table with new name in SQL Server 2008

SELECT * 
INTO target
FROM  source
WHERE 1 = 2

How to convert Django Model object to dict with its fields and values?

I found a neat solution to get to result:

Suppose you have an model object o:

Just call:

type(o).objects.filter(pk=o.pk).values().first()

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

WebAPI to Return XML

If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

public HttpResponseMessage Authenticate()
{
  //process the request 
  .........

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
  { 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 
  };
}

This is the quickest way to always return XML from Web API.

How to get the list of all printers in computer

You can also use the LocalPrintServer class. See: System.Printing.LocalPrintServer

    public List<string>  InstalledPrinters
    {
        get
        {
            return (from PrintQueue printer in new LocalPrintServer().GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local,
                EnumeratedPrintQueueTypes.Connections }).ToList()
                    select printer.Name).ToList(); 
        } 
    }

As stated in the docs: Classes within the System.Printing namespace are not supported for use within a Windows service or ASP.NET application or service.

How to loop through file names returned by find?

find <path> -xdev -type f -name *.txt -exec ls -l {} \;

This will list the files and give details about attributes.

How to remove element from array in forEach loop?

You could also use indexOf instead to do this

var i = review.indexOf('\u2022 \u2022 \u2022');
if (i !== -1) review.splice(i,1);

putting datepicker() on dynamically created elements - JQuery/JQueryUI

Make sure your element with the .date-picker class does NOT already have a hasDatepicker class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker(); will fail! Instead you need to do...

$myDatepicker.removeClass('hasDatepicker').datepicker();

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Here is your relief for the problem :

I have a problem of running different versions of STS this morning, the application crash with the similar way as the question did.

Excerpt of my log file.

A fatal error has been detected by the Java Runtime Environment:
#a
#  SIGSEGV (0xb) at pc=0x00007f459db082a1, pid=4577, tid=139939015632640
#
# JRE version: 6.0_30-b12
# Java VM: Java HotSpot(TM) 64-Bit Server VM 
(20.5-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libsoup-2.4.so.1+0x6c2a1]  short+0x11

note that exception occured at # C [libsoup-2.4.so.1+0x6c2a1] short+0x11

Okay then little below the line:

R9 =0x00007f461829e550: <offset 0xa85550> in /usr/share/java/jdk1.6.0_30/jre/lib/amd64/server/libjvm.so at 0x00007f4617819000
R10=0x00007f461750f7c0 is pointing into the stack for thread: 0x00007f4610008000
R11=0x00007f459db08290: soup_session_feature_detach+0 in /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1 at 0x00007f459da9c000
R12=0x0000000000000000 is an unknown value
R13=0x000000074404c840 is an oop
{method} 

This line tells you where the actual bug or crash is to investigate more on this crash issue please use below links to see more, but let's continue the crash investigation and how I resolved it and the novelty of this bug :)

links are :

a fATAL ERROR JAVA THIS ONE IS GREAT LOTS OF USER!

a fATAL ERROR JAVA 2

Okay, after that here's what I found out to casue this case and why it happens as general advise.

  1. Most of the time, check that if you have installed, updated recently on Ubunu and Windows there are libraries like libsoup in linux which were the casuse of my crash.

  2. Check also for a new hardware problem and try to investigate the Logfile which STS or Java generated and also syslog in linux by

    tail - f /var/lib/messages or some other file
    

Then by carfully looking at those files the one you have the crash log for ... you can really solve the issue as follows:

sudo unlink /usr/lib/i386-linux-gnu/libsoup-2.4.so.1

or

sudo unlink /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1

Done !! Cheers!!

Java Program to test if a character is uppercase/lowercase/number/vowel

You don't need a for loop in your code.

Here is how you can re implement your method

  • If input is between 'A' and 'Z' its uppercase
  • If input is between 'a' and 'z' its lowercase
  • If input is one of 'a,e,i,o,u,A,E,I,O,U' its Vowel
  • Else Consonant

Edit:

Here is hint for you to proceed, Following code snippet gives int values for chars

System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');

Output

a=97
z=122
A=65
Z=90

Here is how you can check if a number x exists between two numbers say a and b

// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b ) 

During comparisons chars can be treated as numbers

If you can combine these hints, you should be able to find what you want ;)

Java method to sum any number of ints

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

CSS: image link, change on hover

 <a href="http://twitter.com/me" class="twitterbird" title="Twitter link"></a>

use a class for the link itself and forget the div

.twitterbird {
 margin-bottom: 10px;
 width: 160px;
 height:160px;
 display:block;
 background:transparent url('twitterbird.png') center top no-repeat;
}

.twitterbird:hover {
   background-image: url('twitterbird_hover.png');
}

Get index of a key/value pair in a C# dictionary based on the value

You can use LINQ to help you with this.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "hi");
dict.Add(2, "NotHi");
dict.Add(3, "Bah");

var item = (from d in dict
            where d.Value == "hi"
            select d.Key).FirstOrDefault();

Console.WriteLine(item); //Prints 1

jQuery selector for id starts with specific text

Add a common class to all the div. For example add foo to all the divs.

$('.foo').each(function () {
   $(this).dialog({
    autoOpen: false,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "explode",
      duration: 1000
    }
  });
});

How can I output the value of an enum class in C++11

Following worked for me in C++11:

template <typename Enum>
constexpr typename std::enable_if<std::is_enum<Enum>::value,
                                  typename std::underlying_type<Enum>::type>::type
to_integral(Enum const& value) {
    return static_cast<typename std::underlying_type<Enum>::type>(value);
}

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

Why are only final variables accessible in anonymous class?

private void f(Button b, final int a[]) {

    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            a[0] = a[0] * 5;

        }
    });
}

Differences between Ant and Maven

I can take a person that has never seen Ant - its build.xmls are reasonably well-written - and they can understand what is going on. I can take that same person and show them a Maven POM and they will not have any idea what is going on.

In an engineering organization that is huge, people write about Ant files becoming large and unmanageable. I've written those types and clean Ant scripts. It's really understanding upfront what you need to do going forward and designing a set of templates that can respond to change and scale over a 3+ year period.

Unless you have a simple project, learning the Maven conventions and the Maven way about getting things done is quite a bit of work.

At the end of the day you cannot consider project startup with Ant or Maven a factor: it's really the total cost of ownership. What it takes for the organization to maintain and extend its build system over a few years is one of the main factors that must be considered.

The most important aspects of a build system are dependency management and flexibility in expressing the build recipe. It must be somewhat intuitive when done well.

Rails ActiveRecord date between

Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])

Virtualbox shared folder permissions

After adding the user to the vboxsf group, you might need to completely log out of the gnome/xfce/??? session, because someone long ago decided that group affiliation should be cached at first login to the window system.

Or go old school:

% newgrp vboxsf

in any shell you want to use to access the folder. Luckily, newgrp looks up the group list for itself and doesn't used the cached values. You'll still need to log out and back in to access the folder from something other than a shell.

How to load Spring Application Context

I am using in the way and it is working for me.

public static void main(String[] args) {
    new CarpoolDBAppTest();

}

public CarpoolDBAppTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Student stud = (Student) context.getBean("yourBeanId");
}

Here Student is my classm you will get the class matching yourBeanId.

Now work on that object with whatever operation you want to do.

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

Writing your own square root function

There is an algorithm that I studied in school that you can use to compute exact square roots (or of arbitrarily large precision if the root is an irrational number). It is definitely slower than Newton's algorithms but it is exact. Lets say you want to compute the square root of 531.3025

First thing is you divide your number starting from the decimal point into groups of 2 digits:
{5}{31}.{30}{25}
Then:
1) Find the closest square root for first group that is smaller or equal to the actual square root of first group: sqrt({5}) >= 2. This square root is the first digit of your final answer. Lets denote the digits we have already found of our final square root as B. So at the moment B = 2.
2) Next compute the difference between {5} and B^2: 5 - 4 = 1.
3) For all subsequent 2 digit groups do the following:
Multiply the remainder by 100, then add it to the second group: 100 + 31 = 131.
Find X - next digit of your root, such that 131 >=((B*20) + X)*X. X = 3. 43 * 3 = 129 < 131. Now B = 23. Also because you have no more 2-digit groups to the left of decimal points, you have found all integer digits of your final root.
4)Repeat the same for {30} and {25}. So you have:
{30} : 131 - 129 = 2. 2 * 100 + 30 = 230 >= (23*2*10 + X) * X -> X = 0 -> B = 23.0
{25} : 230 - 0 = 230. 230 * 100 + 25 = 23025. 23025 >= (230 * 2 * 10 + X) * X -> X = 5 -> B = 23.05
Final result = 23.05.
The algorithm looks complicated this way but it is much simpler if you do it on paper using the same notation you use for "long division" you have studied in school, except that you don't do division but instead compute the square root.

Decimal values in SQL for dividing results

CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)

How to remove blank lines from a Unix file

grep . file

grep looks at your file line-by-line; the dot . matches anything except a newline character. The output from grep is therefore all the lines that consist of something other than a single newline.

How to get Android crash logs?

The way to do this is to implement the Thread.UncaughtExceptionHandler interface and pass it to Thread.setDefaultUncaughtExceptionHandler() at the beginning of your Activity's onCreate(). Here is the implementation class TopExceptionHandler.

public class TopExceptionHandler implements Thread.UncaughtExceptionHandler {
    private Thread.UncaughtExceptionHandler defaultUEH;
    private Activity app = null;

    public TopExceptionHandler(Activity app) {
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        this.app = app;
    }

    public void uncaughtException(Thread t, Throwable e) {
        StackTraceElement[] arr = e.getStackTrace();
        String report = e.toString()+"\n\n";
        report += "--------- Stack trace ---------\n\n";
        for (int i=0; i<arr.length; i++) {
            report += "    "+arr[i].toString()+"\n";
        }
        report += "-------------------------------\n\n";

        // If the exception was thrown in a background thread inside
        // AsyncTask, then the actual exception can be found with getCause

        report += "--------- Cause ---------\n\n";
        Throwable cause = e.getCause();
        if(cause != null) {
            report += cause.toString() + "\n\n";
            arr = cause.getStackTrace();
            for (int i=0; i<arr.length; i++) {
                report += "    "+arr[i].toString()+"\n";
            }
        }
        report += "-------------------------------\n\n";

        try {
            FileOutputStream trace = app.openFileOutput("stack.trace", 
                                                        Context.MODE_PRIVATE);
            trace.write(report.getBytes());
            trace.close();
        } catch(IOException ioe) {
        // ...
        }

        defaultUEH.uncaughtException(t, e);
    }
}

Note We let the Android framework's defaultUEH to handle it.

At the top of your Activity register an instance of above class like this:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));
...

This handler saves the trace in a file. When ReaderScope restarts next time, it detects the file and prompts the user if he/she wants to email it to the developer.

To Email the Stack Trace, execute following code to pack it in an email.

try {
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(ReaderScopeActivity.this.openFileInput("stack.trace")));
    while((line = reader.readLine()) != null) {
        trace += line+"\n";
    }
} catch(FileNotFoundException fnfe) {
    // ...
} catch(IOException ioe) {
    // ...
}

Intent sendIntent = new Intent(Intent.ACTION_SEND);
String subject = "Error report";
String body = "Mail this to [email protected]: " + "\n" + trace + "\n";

sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"});
sendIntent.putExtra(Intent.EXTRA_TEXT, body);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
sendIntent.setType("message/rfc822");

ReaderScopeActivity.this.startActivity(Intent.createChooser(sendIntent, "Title:"));

ReaderScopeActivity.this.deleteFile("stack.trace");

Or you can also use ACRA Error Reporting System.Just Include the ACRA.jar in your project libs and use the below code snippet before your launcher activity class declaration

@ReportsCrashes(formKey = "", mailTo = "[email protected];[email protected]", mode = ReportingInteractionMode.SILENT) 

or You can try this from console:-

adb logcat -b crash 

Call jQuery Ajax Request Each X Minutes

You can use the built-in javascript setInterval.

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

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

setInterval(ajax_call, interval);

or if you are the more terse type ...

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

Is there an equivalent of lsusb for OS X

In mac osx , you can use the following command:

system_profiler SPUSBDataType

What's the most efficient way to check if a record exists in Oracle?

select decode(count(*), 0, 'N', 'Y') rec_exists 
      from sales 
      where sales_type = 'Accessories'; 

Convert a JSON String to a HashMap

Imagine u have a list of email like below. not constrained to any programming language,

emailsList = ["[email protected]","[email protected]","[email protected]"]

Now following is JAVA code - for converting json to map

JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

Swap x and y axis without manually swapping values

In Numbers, click on the chart. Then in the BOTTOM LEFT corner there is the the option to either 'Plot Rows as Series'or 'Plot Columns as series'

Convert string to int if string is a number

To put it on one line:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)

How do I UPDATE from a SELECT in SQL Server?

I'd modify Robin's excellent answer to the following:

UPDATE Table
SET Table.col1 = other_table.col1,
 Table.col2 = other_table.col2
FROM
    Table
INNER JOIN other_table ON Table.id = other_table.id
WHERE
    Table.col1 != other_table.col1
OR Table.col2 != other_table.col2
OR (
    other_table.col1 IS NOT NULL
    AND Table.col1 IS NULL
)
OR (
    other_table.col2 IS NOT NULL
    AND Table.col2 IS NULL
)

Without a WHERE clause, you'll affect even rows that don't need to be affected, which could (possibly) cause index recalculation or fire triggers that really shouldn't have been fired.

Reversing a String with Recursion in Java

Run the code below - it prints:

Step 0: ello / H
Step 1: llo / e
Step 2: lo / l
Step 3: o / l
Step 3 returns: ol
Step 2 returns: oll
Step 1 returns: olle
Step 0 returns: olleH

Code:

public class Test {

    private static int i = 0;

    public static void main(String args[]) {
        reverse("Hello");
    }

    public static String reverse(String str) {
        int localI = i++;
        if ((null == str) || (str.length()  <= 1)) {
            return str;
        }
        System.out.println("Step " + localI + ": " + str.substring(1) + " / " + str.charAt(0));
        String reversed = reverse(str.substring(1)) + str.charAt(0);

        System.out.println("Step " + localI + " returns: " + reversed);
        return reversed;
    }
}

How do I toggle an element's class in pure JavaScript?

If you want to toggle a class to an element using native solution, you could try this suggestion. I have tasted it in different cases, with or without other classes onto the element, and I think it works pretty much:

(function(objSelector, objClass){
   document.querySelectorAll(objSelector).forEach(function(o){
      o.addEventListener('click', function(e){
        var $this = e.target,
            klass = $this.className,
            findClass = new RegExp('\\b\\s*' + objClass + '\\S*\\s?', 'g');

        if( !findClass.test( $this.className ) )
            if( klass ) 
                $this.className = klass + ' ' + objClass;
            else 
                $this.setAttribute('class', objClass);
        else 
        {
            klass = klass.replace( findClass, '' );
            if(klass) $this.className = klass;
            else $this.removeAttribute('class');
        }
    });
  });
})('.yourElemetnSelector', 'yourClass');

Git commit date

If you like to have the timestamp without the timezone but local timezone do

git log -1 --format=%cd --date=local

Which gives this depending on your location

Mon Sep 28 12:07:37 2015

Assign value from successful promise resolve to external variable

You could provide your function with the object and its attribute. Next, do what you need to do inside the function. Finally, assign the value returned in the promise to the right place in your object. Here's an example:

let myFunction = function (vm, feed) {
    getFeed().then( data => {
        vm[feed] = data
    })
} 

myFunction(vm, "feed")

You can also write a self-invoking function if you want.

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

Create a function that addresses all the whitespace possibilites and enable only those that seem appropriate:

SELECT dbo.ShowWhiteSpace(myfield) from mytable

Uncomment only those whitespace cases you want to test for:


CREATE FUNCTION dbo.ShowWhiteSpace (@str varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
     DECLARE @ShowWhiteSpace varchar(8000);
     SET @ShowWhiteSpace = @str
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(32), '[?]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(13), '[CR]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(10), '[LF]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(9),  '[TAB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(1),  '[SOH]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(2),  '[STX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(3),  '[ETX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(4),  '[EOT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(5),  '[ENQ]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(6),  '[ACK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(7),  '[BEL]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(8),  '[BS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(11), '[VT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(12), '[FF]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(14), '[SO]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(15), '[SI]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(16), '[DLE]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(17), '[DC1]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(18), '[DC2]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(19), '[DC3]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(20), '[DC4]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(21), '[NAK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(22), '[SYN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(23), '[ETB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(24), '[CAN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(25), '[EM]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(26), '[SUB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(27), '[ESC]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(28), '[FS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(29), '[GS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(30), '[RS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(31), '[US]')
     RETURN(@ShowWhiteSpace)
END

Java Regex Capturing Groups

This is totally OK.

  1. The first group (m.group(0)) always captures the whole area that is covered by your regular expression. In this case, it's the whole string.
  2. Regular expressions are greedy by default, meaning that the first group captures as much as possible without violating the regex. The (.*)(\\d+) (the first part of your regex) covers the ...QT300 int the first group and the 0 in the second.
  3. You can quickly fix this by making the first group non-greedy: change (.*) to (.*?).

For more info on greedy vs. lazy, check this site.

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

Extract and delete all .gz in a directory- Linux

for foo in *.gz
do
  tar xf "$foo"
  rm "$foo"
done

iterating and filtering two lists using java 8

See below, would welcome anyones feedback on the below code.

not common between two arrays:

List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());

Common between two arrays:

List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());

Manually type in a value in a "Select" / Drop-down HTML list?

Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.

http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx

But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

Avoid synchronized(this) in Java?

I'll cover each point separately.

  1. Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)

    I'm more worried about accidentally. What it amounts to is that this use of this is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like Collections.synchronizedMap (see the javadoc).

  2. All synchronized methods within the same class use the exact same lock, which reduces throughput

    This is overly simplistic thinking; just getting rid of synchronized(this) won't solve the problem. Proper synchronization for throughput will take more thought.

  3. You are (unnecessarily) exposing too much information

    This is a variant of #1. Use of synchronized(this) is part of your interface. If you don't want/need this exposed, don't do it.

Convert array values from string to int?

If you have a multi-dimensional array, none of the previously mentioned solutions will work. Here is my solution:

public function arrayValuesToInt(&$array){
  if(is_array($array)){
    foreach($array as &$arrayPiece){
      arrayValuesToInt($arrayPiece);
    }
  }else{
    $array = intval($array);
  }
}

Then, just do this:

arrayValuesToInt($multiDimentionalArray);

This will make an array like this:

[["1","2"]["3","4"]]

look like this:

[[1,2][3,4]]

This will work with any level of depth.

Alternatively, you can use array_walk_recursive() for a shorter answer:

array_walk_recursive($array, function(&$value){
    $value = intval($value);
});

ReactNative: how to center text?

You can use two approaches for this...

  1. To make text align center horizontally, apply this Property (textAlign:"center"). Now to make the text align vertically, first check direction of flex. If flexDirection is column apply property (justifyContent:"center") and if flexDirection is row is row apply property (alignItems : "center") .

  2. To Make text align center apply same property (textAlign:"center"). Now to make it align vertically make the hieght of the <Text> </Text> equal to view and then apply property (textAlignVertical: "center")...

Most Probably it will Work...

How to start MySQL with --skip-grant-tables?

After trying lots of things, this is what worked for me:

sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword'; 

So first we use sudo to log in mysql as root without needing a password. Then we just update root's password.

After that, I restarted mysqld:

sudo service mysql restart

And the newpassword logged root in!

In Flask, What is request.args and how is it used?

@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...

... the request.args is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question

And how many parameters request.args.get() takes.

It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).

Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.

How to iterate over the files of a certain directory, in Java?

If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

intellij idea - Error: java: invalid source release 1.9

Select the project, then File > ProjectStructure > ProjectSettings > Modules -> sources You probably have the Language Level set at 9:

screenshot

Just change it to 8 (or whatever you need) and you're set to go.

Also, check the same Language Level settings mentioned above, under Project Settings > Project

enter image description here

what does mysql_real_escape_string() really do?

Best explained here.

http://www.w3schools.com/php/func_mysql_real_escape_string.asp

http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

It generally it helps to avoid SQL injection, for example consider the following code:

<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

and a hacker can send a query like:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

How to encode the filename parameter of Content-Disposition header in HTTP?

I tested the following code in all major browsers, including older Explorers (via the compatibility mode), and it works well everywhere:

$filename = $_GET['file']; //this string from $_GET is already decoded
if (strstr($_SERVER['HTTP_USER_AGENT'],"MSIE"))
  $filename = rawurlencode($filename);
header('Content-Disposition: attachment; filename="'.$filename.'"');

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

I had the same issue. It happened after windows start up error, it seems some files got corrupted due to this. I did import the DB again from the saved script and it works fine.

How to create an array containing 1...N

Based on high voted answer and its high voted comment.

const range = (from, to) => [...Array(to + 1).keys()].slice(from);

// usage
let test = [];
test = range(5, 10);
console.log(test); // output: [ 5, 6, 7, 8, 9, 10 ]

JPA: unidirectional many-to-one and cascading delete

Use this way to delete only one side

    @ManyToOne(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
//  @JoinColumn(name = "qid")
    @JoinColumn(name = "qid", referencedColumnName = "qid", foreignKey = @ForeignKey(name = "qid"), nullable = false)
    // @JsonIgnore
    @JsonBackReference
    private QueueGroup queueGroup;

when I run mockito test occurs WrongTypeOfReturnValue Exception

I recently encountered this issue while mocking a function in a Kotlin data class. For some unknown reason one of my test runs ended up in a frozen state. When I ran the tests again some of my tests that had previously passed started to fail with the WrongTypeOfReturnValue exception.

I ensured I was using org.mockito:mockito-inline to avoid the issues with final classes (mentioned by Arvidaa), but the problem remained. What solved it for me was to kill the process and restart Android Studio. This terminated my frozen test run and the following test runs passed without issues.

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

PHP code is not being executed, instead code shows on the page

Make sure the script contains

<?php

before the code that should be executed. There should be no space between <? and php in this.

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

A rather separable way of doing this is to use

import tensorflow as tf
from keras import backend as K

num_cores = 4

if GPU:
    num_GPU = 1
    num_CPU = 1
if CPU:
    num_CPU = 1
    num_GPU = 0

config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
                        inter_op_parallelism_threads=num_cores, 
                        allow_soft_placement=True,
                        device_count = {'CPU' : num_CPU,
                                        'GPU' : num_GPU}
                       )

session = tf.Session(config=config)
K.set_session(session)

Here, with booleans GPU and CPU, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU and num_CPU define this value. num_cores then sets the number of CPU cores available for usage via intra_op_parallelism_threads and inter_op_parallelism_threads.

The intra_op_parallelism_threads variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).

allow_soft_placement allows for operations to be run on the CPU if any of the following criterion are met:

  1. there is no GPU implementation for the operation

  2. there are no GPU devices known or registered

  3. there is a need to co-locate with other inputs from the CPU

All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.

Note: This requires tensorflow-gpu and cuda/cudnn to be installed because the option is given to use a GPU.

Refs:

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

Primary key or Unique index?

As long as you do not allow NULL for a value, they should be handled the same, but the value NULL is handled differently on databases(AFAIK MS-SQL do not allow more than one(1) NULL value, mySQL and Oracle allow this, if a column is UNIQUE) So you must define this column NOT NULL UNIQUE INDEX

How to create a zip archive with PowerShell?

Here a complete command line example to launch from cmd.exe or from ssh or what you want !

powershell.exe -nologo -noprofile -command "&{ Add-Type -A 'System.IO.Compression.FileSystem' [System.IO.Compression.ZipFile]::CreateFromDirectory('c:/path/to/source/folder/', 'c:/path/to/output/file.zip');}"

Regards

How to make ConstraintLayout work with percentage values?

With the ConstraintLayout v1.1.2, the dimension should be set to 0dp and then set the layout_constraintWidth_percent or layout_constraintHeight_percent attributes to a value between 0 and 1 like :

<!-- 50% width centered Button -->
<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintWidth_percent=".5" />

(You don't need to set app:layout_constraintWidth_default="percent" or app:layout_constraintHeight_default="percent" with ConstraintLayout 1.1.2 and following versions)

Changing ImageView source

get ID of ImageView as

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

then Use

imgFp.setImageResource(R.drawable.fpscan);

to set source image programatically instead from XML.

Alter user defined type in SQL Server

The solutions provided here can only be applied if the user defined types are used in table definitions only, and if the UDT columns are not indexed.

Some developers also have SP's and functions using UDT parameters, which is not covered either. (see comments on Robin's link and in the Connect entry)

The Connect entry from 2007 has finally been closed after 3 years:

Thank you for submitting this suggestion, but given its priority relative to the many other items in our queue, it is unlikely that we will actually complete it. As such, we are closing this suggestion as “won’t fix”.

I tried to solve a similiar problem ALTERing XML SCHEMA COLLECTIONS, and the steps seem to mostly apply to ALTER TYPE, too:

To drop a UDT, the following steps are necessary:

  • If a table column references the UDT, it has to be converted to the underlying type
  • If the table column has a default constraint, drop the default constraint
  • If a procedure or function has UDT parameters, the procedure or function has to be dropped
  • If there is an index on a UDT column, the index has to be dropped
  • If the index is a primary key, all foreign keys have to be dropped
  • If there are computed columns based on a UDT column, the computed columns have to be dropped
  • If there are indexes on these computed columns, the indexes have to be dropped
  • If there are schema-bound views, functions, or procedures based on tables containing UDT columns, these objects have to be dropped

convert iso date to milliseconds in javascript

Yes, you can do this in a single line

let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673

Set Jackson Timezone for Date deserialization

For anyone struggling with this problem in the now (Feb 2020), the following Medium post was crucial to overcoming it for us.

https://medium.com/@ttulka/spring-http-message-converters-customizing-770814eb2b55

In our case, the app uses @EnableWebMvc and would break if removed so, the section on 'The Life without Spring Boot' was critical. Here's what ended up solving this for us. It allows us to still consume and produce JSON and XML as well as format our datetime during serialization to suit the app's needs.

@Configuration
@ComponentScan("com.company.branch")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(0, new MappingJackson2XmlHttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .defaultUseWrapper(false)
                        .createXmlMapper(true)
                        .simpleDateFormat("yyyy-mm-dd'T'HH:mm:ss'Z'")
                        .build()
        ));
    converters.add(1, new MappingJackson2HttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .build()
        ));
    }
}

Detect encoding and make everything UTF-8

I know this is an older question, but I figure a useful answer never hurts. I was having issues with my encoding between a desktop application, SQLite, and GET/POST variables. Some would be in UTF-8, some would be in ASCII, and basically everything would get screwed up when foreign characters got involved.

Here is my solution. It scrubs your GET/POST/REQUEST (I omitted cookies, but you could add them if desired) on each page load before processing. It works well in a header. PHP will throw warnings if it can't detect the source encoding automatically, so these warnings are suppressed with @'s.

//Convert everything in our vars to UTF-8 for playing nice with the database...
//Use some auto detection here to help us not double-encode...
//Suppress possible warnings with @'s for when encoding cannot be detected
try
{
    $process = array(&$_GET, &$_POST, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = $v;
                $process[] = &$process[$key][@mb_convert_encoding($k,'UTF-8','auto')];
            } else {
                $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = @mb_convert_encoding($v,'UTF-8','auto');
            }
        }
    }
    unset($process);
}
catch(Exception $ex){}

How to create a bash script to check the SSH connection?

To connect to a server with multiple interfaces

ssh -o ConnectTimeout=1 -q [email protected];[ $? = 1 ] || ssh -o ConnectTimeout=1 -q [email protected]

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.

If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.

Maven : error in opening zip file when running maven

This error can occur when your connection gets interrupted during your dependencies are being downloaded. Delete the relevant repository folder and run following command again to download a fresh copy of corrupted file.

mvn clean install 

Comparing two NumPy arrays for equality, element-wise

If you want to check if two arrays have the same shape AND elements you should use np.array_equal as it is the method recommended in the documentation.

Performance-wise don't expect that any equality check will beat another, as there is not much room to optimize comparing two elements. Just for the sake, i still did some tests.

import numpy as np
import timeit

A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))

timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761

So pretty much equal, no need to talk about the speed.

The (A==B).all() behaves pretty much as the following code snippet:

x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True

Creating a very simple linked list

Dmytro did a good job, but here is a more concise version.

class Program
{
    static void Main(string[] args)
    {
        LinkedList linkedList = new LinkedList(1);

        linkedList.Add(2);
        linkedList.Add(3);
        linkedList.Add(4);

        linkedList.AddFirst(0);

        linkedList.Print();            
    }
}

public class Node
{
    public Node(Node next, Object value)
    {
        this.next = next;
        this.value = value;
    }

    public Node next;
    public Object value;
}

public class LinkedList
{
    public Node head;

    public LinkedList(Object initial)
    {
        head = new Node(null, initial);
    }

    public void AddFirst(Object value)
    {
        head = new Node(head, value);            
    }

    public void Add(Object value)
    {
        Node current = head;

        while (current.next != null)
        {
            current = current.next;
        }

        current.next = new Node(null, value);
    }

    public void Print()
    {
        Node current = head;

        while (current != null)
        {
            Console.WriteLine(current.value);
            current = current.next;
        }
    }
}

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

Count frequency of words in a list and sort by frequency

You can use

from collections import Counter

It supports Python 2.7,read more information here

1.

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

use dict

>>>d={1:'one', 2:'one', 3:'two'}
>>>c = Counter(d.values())
[('one', 2), ('two', 1)]

But, You have to read the file first, and converted to dict.

2. it's the python docs example,use re and Counter

# Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

Multiple distinct pages in one HTML file

have all the pages in distinct div areas

<div style="" id="page1">
First Page Contents
</div>

<div style="display:none" id="page2">
Second Page Contents
</div>

then use a js script to workout what you are viewing (like within an hashtag style) to navigate. Either that, or ajax to get the response from a specific file (like /pages/page1.html)

var $prehashval = "";
function loop()
{
    if (location.hash.slice(1)!=$prehashval)
        hashChanged();

    $prehashval = location.hash.slice(1);
    setTimeout("loop()", 100);
}
function hashChanged()
{
    var $output;
    switch (location.hash.slice(1))
    {
        case "page1":
            document.getElementById('page1').style.display = "";
            document.getElementById('page2').style.display = "none";
            break;
        case "page2":
            document.getElementById('page1').style.display = "none";
            document.getElementById('page2').style.display = "";
            break;
        default:
            $output = location.hash.slice(1);
    }
}
loop();

What is a good alternative to using an image map generator?

Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.

This btw is Search Engine Optimised as well :)

Source code follows:

_x000D_
_x000D_
.image-map {
  background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  width: 272px;
  height: 92px;
  display: block;
  position: relative;
  margin-top:10px;
  float: left;
}

.image-map > a.map {
  position: absolute;
  display: block;
  border: 1px solid green;
}
_x000D_
<div class="image-map">
    <a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
    <a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
    <a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
_x000D_
_x000D_

EDIT:

After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.

Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)

However I guess the target audience for this question does not agree with me.

You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.

How to know Hive and Hadoop versions from command prompt?

You can not get hive version from command line.

You can checkout hadoop version as mentioned by Dave.

Also if you are using cloudera distribution, then look directly at the libs:

ls /usr/lib/hive/lib/ and check for hive library

hive-hwi-0.7.1-cdh3u3.jar

You can also check the compatible versions here:

http://www.cloudera.com/content/cloudera/en/documentation/cdh5/v5-1-x/CDH-Version-and-Packaging-Information/CDH-Version-and-Packaging-Information.html

How to round the minute of a datetime object

A straightforward approach:

def round_time(dt, round_to_seconds=60):
    """Round a datetime object to any number of seconds
    dt: datetime.datetime object
    round_to_seconds: closest number of seconds for rounding, Default 1 minute.
    """
    rounded_epoch = round(dt.timestamp() / round_to_seconds) * round_to_seconds
    rounded_dt = datetime.datetime.fromtimestamp(rounded_epoch).astimezone(dt.tzinfo)
    return rounded_dt

find all unchecked checkbox in jquery

$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if (this.name != "chkAll") { 
      a = this.name + "|off"; 
   } 
   return a; 
}).get().join();

This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

Pretty printing XML with javascript

Or just print out the special HTML characters?

Ex: <xmlstuff>&#10; &#09;<node />&#10;</xmlstuff>   


&#09;   Horizontal tab  
&#10;   Line feed

Force unmount of NFS-mounted directory

Your NFS server disappeared.

Ideally your best bet is if the NFS server comes back.

If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.

If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.

Finally, I'd guess you need to reboot.

Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.

Why am I getting "void value not ignored as it ought to be"?

srand doesn't return anything so you can't initialize a with its return value because, well, because it doesn't return a value. Did you mean to call rand as well?

How do you open a file in C++?

You need to use an ifstream if you just want to read (use an ofstream to write, or an fstream for both).

To open a file in text mode, do the following:

ifstream in("filename.ext", ios_base::in); // the in flag is optional

To open a file in binary mode, you just need to add the "binary" flag.

ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 

Use the ifstream.read() function to read a block of characters (in binary or text mode). Use the getline() function (it's global) to read an entire line.

How to install the current version of Go in Ubuntu Precise

i installed from source. there is a step-by-step tutorial here: http://golang.org/doc/install/source

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

How to get a view table query (code) in SQL Server 2008 Management Studio

right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"

TypeError: unhashable type: 'dict'

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Check this out :

http://jsfiddle.net/PTbGc/

Your issue seems to have been fixed.


What shows up for me (under Chrome and Mac OS X)

1. one
2. two
  2.1. two.one
  2.2. two.two
  2.3. two.three
3. three
  3.1 three.one
  3.2 three.two
    3.2.1 three.two.one
    3.2.2 three.two.two
4. four

How I did it


Instead of :

<li>Item 1</li>
<li>Item 2</li>
   <ol>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
   </ol>

Do :

<li>Item 1</li>
<li>Item 2
   <ol>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
   </ol>
</li>

Mocking member variables of a class using Mockito

If you can't change the member variable, then the other way around this is to use powerMockit and call

Second second = mock(Second.class)
when(second.doSecond()).thenReturn("Stubbed Second");
whenNew(Second.class).withAnyArguments.thenReturn(second);

Now the problem is that ANY call to new Second will return the same mocked instance. But in your simple case this will work.

For loop in multidimensional javascript array

var cubes = [["string", "string"], ["string", "string"]];

for(var i = 0; i < cubes.length; i++) {
    for(var j = 0; j < cubes[i].length; j++) {
        console.log(cubes[i][j]);
    }
}

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins> in <pluginManagement> tested with Eclipse Indigo SR1, maven 2.2.1

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How to access model hasMany Relation with where condition?

Just in case anyone else encounters the same problems.

Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().

You can easily find out investigating the Laravel source:

// Illuminate\Database\Eloquent\Model.php
...
/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

This also explains why my code worked, whenever I loaded the data using the load() method before.

Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.

Convert Current date to integer

I've solved this as is shown below:

    long year = calendar.get(Calendar.YEAR);
    long month = calendar.get(Calendar.MONTH) + 1;
    long day = calendar.get(Calendar.DAY_OF_MONTH);
    long calcDate = year * 100 + month;
    calcDate = calcDate * 100 + day;
    System.out.println("int: " + calcDate);

Trigger insert old values- values that was updated

In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx

Resize HTML5 canvas to fit window

Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.

A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:

#containingDiv { 
  overflow: hidden;
}
#myCanvas {
  position: absolute; 
  top: 0px;
  left: 0px;
} 

The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.

Undefined symbols for architecture armv7

I use to face that issue when the module (file .m) is not in the target that I am working with.

C# Collection was modified; enumeration operation may not execute

As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:

foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....

    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

What may not be obvious from the code above is where the Enumerator comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach loop gets expanded to by the compiler. The generated code will look something like:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator() returns) you will see:

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.

What is the difference between a 'closure' and a 'lambda'?

It depends on whether a function uses external variable or not to perform operation.

External variables - variables defined outside the scope of a function.

  • Lambda expressions are stateless because It depends on parameters, internal variables or constants to perform operations.

    Function<Integer,Integer> lambda = t -> {
        int n = 2
        return t * n 
    }
    
  • Closures hold state because it uses external variables (i.e. variable defined outside the scope of the function body) along with parameters and constants to perform operations.

    int n = 2
    
    Function<Integer,Integer> closure = t -> {
        return t * n 
    }
    

When Java creates closure, it keeps the variable n with the function so it can be referenced when passed to other functions or used anywhere.

Woocommerce, get current product id

2017 Update - since WooCommerce 3:

global $product;
$id = $product->get_id();

Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.

How to scroll to top of the page in AngularJS?

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

What's the best way to detect a 'touch screen' device using JavaScript?

I like this one:

function isTouchDevice(){
    return typeof window.ontouchstart !== 'undefined';
}

alert(isTouchDevice());

Regex match entire words only

To match any whole word you would use the pattern (\w+)

Assuming you are using PCRE or something similar:

enter image description here

Above screenshot taken from this live example: http://regex101.com/r/cU5lC2

Matching any whole word on the commandline with (\w+)

I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match

Start phpsh, put some content into a variable, match on word.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1, $content2 and $content3 with the (\w)+ pattern.

$content1 and $content2 contain at least one word, $content3 does not.

Match a number of literal words on the commandline with (dart|fart)

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

variables gun1 and gun2 contain the string dart or fart. gun4 does not. However it may be a problem that looking for word fart matches farty. To fix this, enforce word boundaries in regex.

Match literal words on the commandline with word boundaries.

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

So it's the same as the previous example except that the word fart with a \b word boundary does not exist in the content: farty.

How to handle a single quote in Oracle SQL

Use two single-quotes

SQL> SELECT 'D''COSTA' name FROM DUAL;

NAME
-------
D'COSTA

Alternatively, use the new (10g+) quoting method:

SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;

NAME
-------
D'COSTA

What is the most accurate way to retrieve a user's correct IP address in PHP?

The biggest question is for what purpose?

Your code is nearly as comprehensive as it could be - but I see that if you spot what looks like a proxy added header, you use that INSTEAD of the CLIENT_IP, however if you want this information for audit purposes then be warned - its very easy to fake.

Certainly you should never use IP addresses for any sort of authentication - even these can be spoofed.

You could get a better measurement of the client ip address by pushing out a flash or java applet which connects back to the server via a non-http port (which would therefore reveal transparent proxies or cases where the proxy-injected headers are false - but bear in mind that, where the client can ONLY connect via a web proxy or the outgoing port is blocked, there will be no connection from the applet.

How do you add an SDK to Android Studio?

You can change from the "build.gradle" file the line:

compileSdkVersion 18

to the sdk that you want to be used.

Vue.js dynamic images not working

I got this working by following code

  getImgUrl(pet) {
    var images = require.context('../assets/', false, /\.png$/)
    return images('./' + pet + ".png")
  }

and in HTML:

<div class="col-lg-2" v-for="pic in pics">
   <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

But not sure why my earlier approach did not work.

How to download a file from a website in C#

Use WebClient.DownloadFile:

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}

Retrieving the output of subprocess.call()

I recently just figured out how to do this, and here's some example code from a current project of mine:

#Getting the random picture.
#First find all pictures:
import shlex, subprocess
cmd = 'find ../Pictures/ -regex ".*\(JPG\|NEF\|jpg\)" '
#cmd = raw_input("shell:")
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
#Another way to get output
#output = subprocess.Popen(args,stdout = subprocess.PIPE).stdout
ber = raw_input("search complete, display results?")
print output
#... and on to the selection process ...

You now have the output of the command stored in the variable "output". "stdout = subprocess.PIPE" tells the class to create a file object named 'stdout' from within Popen. The communicate() method, from what I can tell, just acts as a convenient way to return a tuple of the output and the errors from the process you've run. Also, the process is run when instantiating Popen.

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?