Programs & Examples On #Econnect

iPhone is not available. Please reconnect the device

Follow these steps:

  1. Check your iOS Version from (Settings ? General ? About ? Software Version) and get the device support file from the link below:

    https://github.com/iGhibli/iOS-DeviceSupport/tree/master/DeviceSupport

  2. Next, unzip the files and place them at the following location:

    Applications ? Xcode ? right click ? Show Package Contents ? Contents ? Developer ? Platforms ? iPhoneOS.platform ? DeviceSupport

  3. Restart Xcode

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I was hitting this error in one Spring Boot app, but not in another. Finally, I found the Spring Boot version in the one not working was 2.0.0.RELEASE and the one that was working was 2.0.1.RELEASE. That led to a difference in the MySQL Connector -- 5.1.45 vs. 5.1.46. I updated the Spring Boot version for the app that was throwing this error at startup and now it works.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

I have MYSQL on server and nodejs application on another server

Execute the following query in MYSQL Workbench

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password'

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

If you use JDK 1.8.0_201 or latest try it with older JDK.

I have same issue with JDK1.8.0_201, however it works with JDK1.8.0_101 without any code change.

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

I was having the same exception on the device Z3 Compact D5803 - 6.0.1

I went opened the .buckconfig file and changed the line:

target = Google Inc.:Google APIs:23

to

target = Google Inc.:Google APIs:24

Because i saw in SDK Manager that Android 6.X has api level 24.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Upgrade MySql driver to Connector/Python 8.0.17 or greater than 8.0.17, Those who are using greater than MySQL 5.5 version

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent). That wrapper component expects to have access to a Redux store. Normally that store is available as context.store, because at the top of your component hierarchy you'd have a <Provider store={myStore} />. However, you're rendering your connected component by itself, with no store, so it's throwing an error.

You've got a few options:

  • Create a store and render a <Provider> around your connected component
  • Create a store and directly pass it in as <MyConnectedComponent store={store} /> , as the connected component will also accept "store" as a prop
  • Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your mapStateToProps function, you can safely assume the connected version will work correctly.

You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.

edit:

After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = <SportsDatabase sportsWholeFramework="desktop" />; is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.

At this point, you have two new options:

  • Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
  • If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.

Overall, I would note that you might be trying to do too much in this one component and might want to consider breaking it into smaller pieces with less logic per component.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

Laravel 5 PDOException Could Not Find Driver

For me the problem was that I was running the migrate command not from inside the container where php was running. The extension was properly set there but not at my host machine.

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

I got that error message in code line containing SqlConnection.Open() running my .NET code as x64 application. Running as x86 causing no errors.

Solution was to deactivate the Force protocol encryption option for TCP/IP in %windir%\System32\cliconfg.exe

Force protocol encryption

android : Error converting byte to dex

After I upgraded to Android Studio 2.1, the next time I rebooted, I was asked to upgrade to JDK 1.8. After I upgraded to JDK 1.8, that's when my AS project had trouble compiling. I followed all of the suggestions in this page, but to no avail. Finally, I decided to check the version of JDK that my project was using, and to my surprise, it somehow was pointing to JDK 1.8!

Moral of the story: If compileSdkVersion<=23, double check that your project is using JDK1.7 as follows:

  • Right Mouse on top level module
  • Project STructure => JDK Location

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

How to provide a mysql database connection in single file in nodejs

You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:

every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

You could create db.js:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database : 'chat'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

Then in your app.js, you would simply require it.

var express = require('express');
var app = express();
var db = require('./db');

app.get('/save',function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    db.query('INSERT INTO messages SET ?', post, function(err, result) {
      if (err) throw err;
    });
});

server.listen(3000);

This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db thanks to how node require works :)

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case, everything was set up correctly, but my Docker infrastructure needed more RAM. I'm using Docker for Mac, where default RAM was around 1 GB, and as MySQL uses around 1.5Gb of RAM ( and probably was crashing ??? ), changing the Docker RAM utilization level to 3-4 Gb solved the issue.

How to restart ADB manually from Android Studio

When I had this problem, I wrote adb kill-server and adb restart-server in terminal, but the problem appeared again the next day. Then I updated GPU debugging tools in the Android SDK manager and restarted the computer, which worked for me.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

In my case I had to go to

File -> Settings -> Build, Execution, Deployment -> Gradle

and then I changed the Service directory path, which was pointing to a wrong location.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

As apc mentioned that error occurs "when a 32bit dll calls a 64bit dll or vice versa". The problem is that if you have build using AnyCPU and are running on a 64bit environment then the application will run as 64bit. If rebuilding explicitly for 32 and 64 bit is not an option then you could use a microsoft utility called corflags.exe which comes with the Windows SDK. Basically, you can modify a flag in the exe of the program you are executing to tell it to run as 32bit even if the environment is 64bit.

See here for information on using it

ORA-28040: No matching authentication protocol exception

I was using eclipse and after trying all the other answers it didn't work for me. In the end, what worked for me was moving the ojdb7.jar to top in the Build Path. This occurs when multiple jars have conflicting same classes.

  1. Select project in Project Explorer
  2. Right click on Project -> Build Path -> Configure Build Path
  3. Go to Order and Export tab and select ojdbc.jar
  4. Click button TOP to move it to top

How to disable SSL certificate checking with Spring RestTemplate?

In my case, with letsencrypt https, this was caused by using cert.pem instead of fullchain.pem as the certificate file on the requested server. See this thread for details.

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

Spring Boot JPA - configuring auto reconnect

I assume that boot is configuring the DataSource for you. In this case, and since you are using MySQL, you can add the following to your application.properties up to 1.3

spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1

As djxak noted in the comment, 1.4+ defines specific namespaces for the four connections pools Spring Boot supports: tomcat, hikari, dbcp, dbcp2 (dbcp is deprecated as of 1.5). You need to check which connection pool you are using and check if that feature is supported. The example above was for tomcat so you'd have to write it as follows in 1.4+:

spring.datasource.tomcat.testOnBorrow=true 
spring.datasource.tomcat.validationQuery=SELECT 1

Note that the use of autoReconnect is not recommended:

The use of this feature is not recommended, because it has side effects related to session state and data consistency when applications don't handle SQLExceptions properly, and is only designed to be used when you are unable to configure your application to handle SQLExceptions resulting from dead and stale connections properly.

System.Data.SqlClient.SqlException: Login failed for user

kinda dumb, but I had a weird character (é) in my password. After omitting it, I no longer got the error.

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
  ...
  at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:246)

The problem is that Tomcat can't find com.mysql.jdbc.Driver. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib directory).

Get SSID when WIFI is connected

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID(). Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.

Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."

ORA-01036: illegal variable name/number when running query through C#

I was having the same problem in an application that I was maintaining, among all the adjustments to prepare the environment, I also spent almost an hour banging my head with this error "ORA-01036: illegal variable name / number" until I found out that the application connection was pointed to an outdated database, so the application passed two more parameters to the outdated database procedure causing the error.

Mocking static methods with Mockito

You can do it with a little bit of refactoring:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return _getConnection(...some params...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //method to forward parameters, enabling mocking, extension, etc
    Connection _getConnection(...some params...) throws SQLException {
        return DriverManager.getConnection(...some params...);
    }
}

Then you can extend your class MySQLDatabaseConnectionFactory to return a mocked connection, do assertions on the parameters, etc.

The extended class can reside within the test case, if it's located in the same package (which I encourage you to do)

public class MockedConnectionFactory extends MySQLDatabaseConnectionFactory {

    Connection _getConnection(...some params...) throws SQLException {
        if (some param != something) throw new InvalidParameterException();

        //consider mocking some methods with when(yourMock.something()).thenReturn(value)
        return Mockito.mock(Connection.class);
    }
}

android studio 0.4.2: Gradle project sync failed error

I always remove the .gradle folder from %USERS% folder and start the studio again. When starting the IDE it downloads gradle again with all the dependencies again. Its work PERFECT.

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

The database must have a name (example DB1), try this one:

OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 

In case the TNS is not defined you can also try this one:

OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit"); 

nodejs mysql Error: Connection lost The server closed the connection

better solution is to use pool - ill handle this for you.

_x000D_
_x000D_
const pool = mysql.createPool({_x000D_
  host: 'localhost',_x000D_
  user: '--',_x000D_
  database: '---',_x000D_
  password: '----'_x000D_
});_x000D_
_x000D_
// ... later_x000D_
pool.query('select 1 + 1', (err, rows) => { /* */ });
_x000D_
_x000D_
_x000D_

https://github.com/sidorares/node-mysql2/issues/836

What are the differences between git remote prune, git prune, git fetch --prune, etc

In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.

If you guys see any issues with this please let me know and I'll fix it (etc. etc.)

Save it in a file called git-rm-ntb (call it whatever) on PATH and run:

git-rm-ntb <remote1:optional> <remote2:optional> ...

clean()
{
  REMOTES="$@";
  if [ -z "$REMOTES" ]; then
    REMOTES=$(git remote);
  fi
  REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
  RBRANCHES=()
  while read REMOTE; do
    CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
    RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
  done < <(echo "$REMOTES" )
  [[ $RBRANCHES ]] || exit
  LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
  for i in "${LBRANCHES[@]}"; do
    skip=
    for j in "${RBRANCHES[@]}"; do
      [[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
    done
    [[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
  done
}

clean $@

could not extract ResultSet in hibernate

I was using Spring Data JPA with PostgreSql and during UPDATE call it was showing errors-

  • 'could not extract ResultSet' and another one.
  • org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query. (Showing Transactional required.)

Actually, I was missing two required Annotations.

  • @Transactional and
  • @Modifying

With-

@Query(vlaue = " UPDATE DB.TABLE SET Col1 = ?1 WHERE id = ?2 ", nativeQuery = true)
void updateCol1(String value, long id);

Spring Data JPA - "No Property Found for Type" Exception

In my case I had a typo (camel case) in my method name. I named it to "findbyLastName" and faced this exception. After I changed it to "findByLastName" exception was gone.

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

How to query for Xml values and attributes from table in SQL Server?

I don't understand why some people are suggesting using cross apply or outer apply to convert the xml into a table of values. For me, that just brought back way too much data.

Here's my example of how you'd create an xml object, then turn it into a table.

(I've added spaces in my xml string, just to make it easier to read.)

DECLARE @str nvarchar(2000)

SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mike</firstName>'
SET @str = @str + '     <lastName>Gledhill</lastName>'
SET @str = @str + '     <age>31</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mark</firstName>'
SET @str = @str + '     <lastName>Stevens</lastName>'
SET @str = @str + '     <age>42</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Sarah</firstName>'
SET @str = @str + '     <lastName>Brown</lastName>'
SET @str = @str + '     <age>23</age>'
SET @str = @str + '  </user>'
SET @str = @str + '</users>'

DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 

--  Iterate through each of the "users\user" records in our XML
SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
    x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)

And here's the output:

enter image description here

Cannot overwrite model once compiled Mongoose

just export like this exports.User = mongoose.models.User || mongoose.model('User', userSchema);

Gradle error: could not execute build using gradle distribution

To correct this mistake very easily, If you read logs. The problem occurs because of the sudden shutdown of the IDEA. And the log files do not correctly write data. Just delete the file on the path

C:/Users/{UserName}/.Gradle/demon/{gradleVersion}/registry.bin.lock. 

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I have also receive the same IOException, but I find the Android system demo: "BluetoothChat" project is worked. I determined the problem is the UUID.

So i replace my UUID.fromString("00001001-0000-1000-8000-00805F9B34FB") to UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66") and it worked most scene,only sometimes need to restart the Bluetooth device;

Can't ping a local VM from the host

I know this is an old post, but I ran into this same issue with my VMs. Log into the VM and go to Control Panel > System and Security > Windows Firewall > Allowed Apps. Then check all of the boxes next to "File and Printer Sharing" to enable file sharing. This should allow you to ping the VM. The screenshot below is from a 2016 Windows Server but the same method will work on older ones.

enter image description here

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I had similar problem in SQL Workbench.

URL:

jdbc:oracle:thin:@111.111.111.111:1111:xe

doesn't work.

URL:

jdbc:oracle:thin:@111.111.111.111:1111:asdb

works.

This help me in my concrete situation. I afraid, that could exists many other reasons with different solutions.

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

actual error thrown Message=Unrecognized element 'providers' in web.config so from the web.config file remove the providers section

View contents of database file in Android Studio

Finally, Android Studio supports this functionality with database inspector tab. You can apply view/update/query operations easily. It's not in stable channel for now but you can try out with the Android Studio 4.1 Canary 5 and higher.

You can see what the database inspector looks like here

And you can download appropriate version here

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

If you are using tomcat then along with project directory you should also copy the database connector jar file to tomcat/lib. this worked for me

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

A "little" late to the party but the real answer to this - if you use Oracle.ManagedDataAccess ODP.NET provider, you should forget about things like network\admin, Oracle client, Oracle_Home, etc.

Here is what you need

  1. Download and install Oracle Developer Tools for VS or ODAC. Note - Dev tools will install ODAC for you. This will create relatively small installation under C:\Program Files (x86). With full dev tools, under 60Mb
  2. In your project you will install Nuget package with corresponding version of ODP.net (Oracle.ManagedDataAccess.dll) which you will reference
  3. At this point you have 2 options to connect.

    • a) In the connection string set datasource in the following format

      DataSource=ServerName:Port/SID . . . or DataSource=IP:Port/SID . . .

    • b) Create tnsnames.ora file (only it is going to be different from previous experiences). Have entry in it:

      AAA = (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ServerNameOrIP)(PORT = 1521))
      (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = SIDNAME)))

      And place this file into your bin folder, where your application is running from. Now you can connect using your connection name - DataSource=AAA . . . So, even though you have tnsnames.ora, with ODP.net managed it works a bit different - you create local TNS file. And now, it is easy to manage it.

To summarize - with managed, no need for heavy Oracle Client, Oracle_home or knowing depths of oracle installation folders. Everything can be done within your .net application structures.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

The DB_PATH was pointing to different database. Change it in database helper class and my code working.

private static String DB_PATH = "/data/data/com.example.abc";

Fit Image into PictureBox

Have a look at the sizemode property of the picturebox.

pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;

Download large file in python with requests

It's much easier if you use Response.raw and shutil.copyfileobj():

import requests
import shutil

def download_file(url):
    local_filename = url.split('/')[-1]
    with requests.get(url, stream=True) as r:
        with open(local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

    return local_filename

This streams the file to disk without using excessive memory, and the code is simple.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

On Windows make sure your Windows firewall is correctly configure / disabled. I had to disable the Windows firewall (because I didn't bother with configuring it) to get things to work even when I was testing with localhost.

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

The problem is mostly due to a MySQL service that is not running, so make sure it is. If it isn't, run this CMD with administrator privilege in order to start it:

sc start [Your MySQL Service name]

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

The EntityManager is closed

Symfony v4.1.6

Doctrine v2.9.0

Process inserting duplicates in a repository

  1. Get access a registry in your repo


    //begin of repo
    
    /** @var RegistryInterface */
    protected $registry;
    
    public function __construct(RegistryInterface $registry)
    {
        $this->registry = $registry;
        parent::__construct($registry, YourEntity::class);
    }

  1. Wrap risky code into transaction and reset manager in case of exception


    //in repo method
    $em = $this->getEntityManager();
    
    $em->beginTransaction();
    try {
        $em->persist($yourEntityThatCanBeDuplicate);
        $em->flush();
        $em->commit();
    
    } catch (\Throwable $e) {
        //Rollback all nested transactions
        while ($em->getConnection()->getTransactionNestingLevel() > 0) {
            $em->rollback();
        }
        
        //Reset the default em
        if (!$em->isOpen()) {
            $this->registry->resetManager();
        }
    }

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

team! For execute SQL-query from your Servlet you should add JDBC jar library in folder

WEB-INF/lib

After this you could call driver, example :

Class.forName("oracle.jdbc.OracleDriver");

Now Y can use connection to DB-server

==> 73!

Zookeeper connection error

I have just solved the problem. I am using centos 7. And the trouble-maker is firewall.Using "systemctl stop firewalld" to shut it all down in each server can simply solve the problem.Or you can use command like

firewall-cmd --zone=public --add-port=2181/udp --add-port=2181/tcp --permanent" to configure all three ports ,include 2181,2888,3888 in each server.And then "firewall-cmd --reload

Finally use

zkServer.sh restart

to restart your servers and problem solved.

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

Connecting to Oracle Database through C#?

Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

I encountered this error. The problem was that I had the wrong database name.

Pentaho Data Integration SQL connection

At the present time, there is a simple way to fix this problem:

  1. Go to Tools ? MarketPlace and search for "PDI MySQL Plugin"
  2. Install it ( this will automatically install the missing driver here: data-integration\plugins\databases\pdi-mysql-plugin\lib )
  3. Restart Pentaho
  4. Done.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

These two things don't match:

driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll database;create=true"

If you are using the EmbeddedDriver, your URL should not contain network syntax.

Conversely, if you are using network syntax, you need to use the ClientDriver.

http://db.apache.org/derby/docs/10.8/getstart/rgsquck35368.html

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

OracleCommand SQL Parameters Binding

Here is how I solved the same problem using the Oracle.DataAccess.Client Namespace.

using Oracle.DataAccess.Client;


string strConnection = ConfigurationManager.ConnectionStrings["oConnection"].ConnectionString;

dataConnection = new OracleConnectionStringBuilder(strConnection);

OracleConnection oConnection = new OracleConnection(dataConnection.ToString());

oConnection.Open();

OracleCommand tmpCommand = oConnection.CreateCommand();
tmpCommand.Parameters.Add("user", OracleDbType.Varchar2, txtUser.Text, ParameterDirection.Input);
tmpCommand.CommandText = "SELECT USER, PASS FROM TB_USERS WHERE USER = :1";

try
{
    OracleDataReader tmpReader = tmpCommand.ExecuteReader(CommandBehavior.SingleRow);
    
    if (tmpReader.HasRows)
    {
        // PT: IMPLEMENTE SEU CÓDIGO    
        // ES: IMPLEMENTAR EL CÓDIGO
        // EN: IMPLEMENT YOUR CODE
    }
}
catch(Exception e)
{
        // PT: IMPLEMENTE SEU CÓDIGO    
        // ES: IMPLEMENTAR EL CÓDIGO
        // EN: IMPLEMENT YOUR CODE
}

RabbitMQ / AMQP: single queue, multiple consumers for same message?

There is one interesting option in this scenario I haven`t found in answers here.

You can Nack messages with "requeue" feature in one consumer to process them in another. Generally speaking it is not a right way, but maybe it will be good enough for someone.

https://www.rabbitmq.com/nack.html

And beware of loops (when all concumers nack+requeue message)!

Most simple code to populate JTable from ResultSet

Class Row will handle one row from your database.

Complete implementation of UpdateTask responsible for filling up UI.

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTable;
import javax.swing.SwingWorker;

public class JTableUpdateTask extends SwingWorker<JTable, Row> {

    JTable      table       = null;

    ResultSet   resultSet   = null;

    public JTableUpdateTask(JTable table, ResultSet rs) {
        this.table = table;
        this.resultSet = rs;
    }

    @Override
    protected JTable doInBackground() throws Exception {
        List<Row> rows = new ArrayList<Row>();
        Object[] values = new Object[6];
        while (resultSet.next()) {
            values = new Object[6];
            values[0] = resultSet.getString("id");
            values[1] = resultSet.getString("student_name");
            values[2] = resultSet.getString("street");
            values[3] = resultSet.getString("city");
            values[4] = resultSet.getString("state");
            values[5] = resultSet.getString("zipcode");
            Row row = new Row(values);
            rows.add(row);
        }
        process(rows); 
        return this.table;
    }

    protected void process(List<Row> chunks) {
        ResultSetTableModel tableModel = (this.table.getModel() instanceof ResultSetTableModel ? (ResultSetTableModel) this.table.getModel() : null);
        if (tableModel == null) {
            try {
                tableModel = new ResultSetTableModel(this.resultSet.getMetaData(), chunks);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            this.table.setModel(tableModel);
        } else {
            tableModel.getRows().addAll(chunks);
        }
        tableModel.fireTableDataChanged();
    }
}

Table Model:

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

/**
 * Simple wrapper around Object[] representing a row from the ResultSet.
 */
class Row {
    private final Object[]  values;

    public Row(Object[] values) {
        this.values = values;
    }

    public int getSize() {
        return values.length;
    }

    public Object getValue(int i) {
        return values[i];
    }
}

// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
    private final ResultSetMetaData rsmd;

    private List<Row>               rows;

    public ResultSetTableModel(ResultSetMetaData rsmd, List<Row> rows) {
        this.rsmd = rsmd;
        if (rows != null) {
            this.rows = rows;
        } else {
            this.rows = new ArrayList<Row>();
        }

    }

    public int getRowCount() {
        return rows.size();
    }

    public int getColumnCount() {
        try {
            return rsmd.getColumnCount();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Object getValue(int row, int column) {
        return rows.get(row).getValue(column);
    }

    public String getColumnName(int col) {
        try {
            return rsmd.getColumnName(col + 1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "";
    }

    public Class<?> getColumnClass(int col) {
        String className = "";
        try {
            className = rsmd.getColumnClassName(col);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return className.getClass();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if(rowIndex > rows.size()){
            return null;
        }
        return rows.get(rowIndex).getValue(columnIndex);
    }

    public List<Row> getRows() {
        return this.rows;
    }

    public void setRows(List<Row> rows) {
        this.rows = rows;
    }
}

Main Application which builds UI and does the database connection

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;

public class MainApp {
    static Connection conn = null;
    static void init(final ResultSet rs) {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        final JTable table = new JTable();
        table.setPreferredSize(new Dimension(300,300));
        table.setMinimumSize(new Dimension(300,300));
        table.setMaximumSize(new Dimension(300,300));
        frame.add(table, BorderLayout.CENTER);
        JButton button = new JButton("Start Loading");
        button.setPreferredSize(new Dimension(30,30));
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTableUpdateTask jTableUpdateTask = new JTableUpdateTask(table, rs);
                jTableUpdateTask.execute();

            }
        });
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
            PreparedStatement pstmt = conn.prepareStatement("Select id, student_name, street, city, state,zipcode from student");
            ResultSet rs = pstmt.executeQuery();
            init(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ERROR 2006 (HY000): MySQL server has gone away

max_allowed_packet=64M

Adding this line into my.cnf file solves my problem.

This is useful when the columns have large values, which cause the issues, you can find the explanation here.

On Windows this file is located at: "C:\ProgramData\MySQL\MySQL Server 5.6"

On Linux (Ubuntu): /etc/mysql

How to clear PermGen space Error in tomcat

The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I’m in dev testing so I know I’m bound to run out sooner or later (primarily because Java’s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).

This should theoretically be less of an issue in production environments since you (hopefully) don’t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you’ll just need to mess around with stack and heap allocation. I think the standards are stuff like:

-XX:MaxPermSize=SIZE

I’ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

Stuff like that worked magic for me in the past. One thing tho, there’s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Common HTTPclient and proxy

Here is how to do that with the last version of HTTPClient (4.3.4)

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost("localhost", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet("/");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

Just check tsnnames.ora and listener.ora files. It should not have localhost as a server. change it to hostname.

Like in tnsnames.ora

LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

Replace localhost by hostname.

Inserting data into a MySQL table using VB.NET

After instantiating the connection, open it.

  SQLConnection = New MySqlConnection()
  SQLConnection.ConnectionString = connectionString
  SQLConnection.Open()

Also, avoid building SQL statements by just appending strings. It's better if you use parameters, that way you win on performance, your program is not prone to SQL injection attacks and your program is more stable. For example:

 str_carSql = "insert into members_car 
               (car_id, member_id, model, color, chassis_id, plate_number, code) 
               values 
               (@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"

And then you do this:

sqlCommand.Parameters.AddWithValue("@id",TextBox20.Text)
sqlCommand.Parameters.AddWithValue("@m_id",TextBox23.Text)
' And so on... 

Then you call:

sqlCommand.ExecuteNonQuery()

Setting Remote Webdriver to run tests in a remote computer using Java

  • First you need to create HubNode(Server) and start the HubNode(Server) from command Line/prompt using Java: -jar selenium-server-standalone-2.44.0.jar -role hub
  • Then bind the node/Client to this Hub using Hub machines IPAddress or Name with any port number >1024. For Node Machine for example: Java -jar selenium-server-standalone-2.44.0.jar -role webdriver -hub http://HubmachineIPAddress:4444/grid/register -port 5566

One more thing is that whenever we use Internet Explore or Google Chrome we need to set: System.setProperty("webdriver.ie.driver",path);

What's a clean way to stop mongod on Mac OS X?

Simple way is to get the process id of mongodb and kill it. Please note DO NOT USE kill -9 pid for this as it may cause damage to the database.

so, 1. get the pid of mongodb

$ pgrep mongo

you will get pid of mongo, Now

$ kill

You may use kill -15 as well

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I used SQL Server Profiler (available in SSMS => Tools menu) and saw there (when IIS attempted to connect to database) that my IIS user was for some reason NT AUTHORITY\IUSR, no matter of all steps recommended in answers in this question. So I added that user to SQL Server, and it worked...

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.

Connection Pooling

Hibernate itself admits that its connection pooling strategy is minimal

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I personally use C3P0. however there are other alternatives available including DBCP.
Check out

Below is a minimal configuration of C3P0 used in my application:

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property> 
<property name="c3p0.idle_test_period">100</property> <!-- seconds --> 
<property name="c3p0.max_size">100</property> 
<property name="c3p0.max_statements">0</property> 
<property name="c3p0.min_size">10</property> 
<property name="c3p0.timeout">1800</property> <!-- seconds --> 

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size

Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier. The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:

Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)

# c3p0.properties
c3p0.testConnectionOnCheckout=true

With this configuration each connection is tested before being used. It however might affect the performance of the site.

ORA-01008: not all variables bound. They are bound

You have two references to the :lot_priprc binding variable -- while it should require you to only set the variable's value once and bind it in both places, I've had problems where this didn't work and had to treat each copy as a different variable. A pain, but it worked.

How can I get the baseurl of site?

I'm using following code from Application_Start

String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);

java.lang.IllegalAccessError: tried to access method

In my case I was getting this error running my app in wildfly with the .ear deployed from eclipse. Because it was deployed from eclipse, the deployment folder did not contain an .ear file, but a folder representing it, and inside of it all the jars that would have been contained in the .ear file; like if the ear was unzipped.

So I had in on jar:

class MySuperClass {
  protected void mySuperMethod {}
}

And in another jar:

class MyExtendingClass extends MySuperClass {

  class MyChildrenClass {
    public void doSomething{
      mySuperMethod();
    }
  }
}

The solution for this was adding a new method to MyExtendingClass:

class MyExtendingClass extends MySuperClass {

  class MyChildrenClass {
    public void doSomething{
      mySuperMethod();
    }
  }

  @Override
  protected void mySuperMethod() {
    super.mySuperMethod();
  }
}

inject bean reference into a Quartz job in Spring?

The solution above is great but in my case the injection was not working. I needed to use autowireBeanProperties instead, probably due to the way my context is configured:

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        //beanFactory.autowireBean(job);
        beanFactory.autowireBeanProperties(job, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        return job;
    }
}

Solving a "communications link failure" with JDBC and MySQL

As the detailed answer above says, this error can be caused by many things.

I had this problem too. My setup was Mac OSX 10.8, using a Vagrant managed VirtualBox VM of Ubuntu 12.04, with MySQL 5.5.34.

I had correctly setup port forwarding in the Vagrant config file. I could telnet to the MySQL instance both from my Mac and from within the VM. So I knew the MySQL daemon was running and reachable. But when I tried to connect over JDBC, I got the "Communications link failure" error.

In my case, the problem was solved by editing the /etc/mysql/my.cnf file. Specifically, I commented out the "#bind-address=127.0.0.1" line.

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

Object cannot be cast from DBNull to other types

I suspect that the line

DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));

is causing the problem. Is it possible that the op_Id value is being set to null by the stored procedure?

To Guard against it use the Convert.IsDBNull method. For example:

if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, "op_Id"))
{
 DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
}
else 
{
 DataTO.Id = ...some default value or perform some error case management
}

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

For those finding this via Google;
I was getting this error because, as suggested by the error, I failed to close a SqlDataReader prior to creating another on the same SqlCommand, mistakenly assuming that it would be garbage collected when leaving the method it was created in.

I solved the issue by calling sqlDataReader.Close(); before creating the second reader.

database attached is read only

If you have tried all of this and still no luck, try the detach/attach again.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

I had the mysql jdbc library in both $CATALINA_HOME/lib and WEB-INF/lib, still i got this error . I needed Class.forName("com.mysql.jdbc.Driver"); to make it work.

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

Cannot create PoolableConnectionFactory

This specific issue may arise in localhost also. We cannot rule out this is because network issue or internet connectivity issue. This issue will come even though all the database connection properties are correct.

I have faced the same issue when i have used host name. Instead use ip address. It will get resolved.

Android "Only the original thread that created a view hierarchy can touch its views."

Solved : Just put this method in doInBackround Class... and pass the message

public void setProgressText(final String progressText){
        Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                // Any UI task, example
                progressDialog.setMessage(progressText);
            }
        };
        handler.sendEmptyMessage(1);

    }

Using Alert in Response.Write Function in ASP.NET

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

Git Bash is extremely slow on Windows 7 x64

You can significantly speed up Git on Windows by running three commands to set some config options:

git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256

Notes:

  • core.preloadindex does filesystem operations in parallel to hide latency (update: enabled by default in Git 2.1)

  • core.fscache fixes UAC issues so you don't need to run Git as administrator (update: enabled by default in Git for Windows 2.8)

  • gc.auto minimizes the number of files in .git/

Example: Communication between Activity and Service using Messaging

Everything is fine.Good example of activity/service communication using Messenger.

One comment : the method MyService.isRunning() is not required.. bindService() can be done any number of times. no harm in that.

If MyService is running in a different process then the static function MyService.isRunning() will always return false. So there is no need of this function.

How can I stop a running MySQL query?

mysql>show processlist;

mysql> kill "number from first col";

Http Basic Authentication in Java using HttpClient?

Here are a few points:

  • You could consider upgrading to HttpClient 4 (generally speaking, if you can, I don't think version 3 is still actively supported).

  • A 500 status code is a server error, so it might be useful to see what the server says (any clue in the response body you're printing?). Although it might be caused by your client, the server shouldn't fail this way (a 4xx error code would be more appropriate if the request is incorrect).

  • I think setDoAuthentication(true) is the default (not sure). What could be useful to try is pre-emptive authentication works better:

    client.getParams().setAuthenticationPreemptive(true);
    

Otherwise, the main difference between curl -d "" and what you're doing in Java is that, in addition to Content-Length: 0, curl also sends Content-Type: application/x-www-form-urlencoded. Note that in terms of design, you should probably send an entity with your POST request anyway.

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

If you are connecting to an old SQL Server:

Switch from System.Data.SqlClient.SqlConnection to System.Data.OleDb.OleDbConnection

Use an OleDb connection string:

<connectionStrings>
<add name="Northwind" connectionString="Provider=SQLOLEDB.1; Data Source=MyServer; Initial Catalog=Northwind;  Persist Security Info=True; User ID=abc; Password=xyz;" providerName="System.Data.OleDb" />
</connectionStrings>

Restful API service

There is another approach here which basically helps you to forget about the whole management of the requests. It is based on an async queue method and a callable/callback based response. The main advantage is that by using this method you'll be able to make the whole process (request, get and parse response, sabe to db) completely transparent for you. Once you get the response code the work is already done. After that you just need to make a call to your db and you are done. It helps as well with the problematic of what happens when your activity is not active. What will happen here is that you'll have all your data saved in your local database but the response won't be processed by your activity, that's the ideal way.

I wrote about a general approach here http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/

I'll be putting specific sample code in upcoming posts. Hope it helps, feel free to contact me for sharing the approach and solving potential doubts or issues.

How to detect online/offline event cross-browser?

well, you can try the javascript plugin which can monitor the browser connection in real time and notifies the user if internet or the browsers connection with the internet went down.

Wiremonkey Javascript plugin and the demo you can find here

http://ryvan-js.github.io/

How to set up default schema name in JPA configuration?

If you are using (org.springframework.jdbc.datasource.DriverManagerDataSource) in ApplicationContext.xml to specify Database details then use below simple property to specify the schema.

<property name="schema" value="schemaName" />

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

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

You can just controll it with a boolean, so you only call unbind if bind has been made

public void doBindService()
{
    if (!mIsBound)
    {
        bindService(new Intent(this, DMusic.class), Scon, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
}

public void doUnbindService()
{
    if (mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}

If you only want to unbind it if it has been connected

public ServiceConnection Scon = new ServiceConnection() {

    public void onServiceConnected(ComponentName name, IBinder binder)
    {
        mServ = ((DMusic.ServiceBinder) binder).getService();
        mIsBound = true;
    }

    public void onServiceDisconnected(ComponentName name)
    {
        mServ = null;
    }
};

How can I retrieve a table from stored procedure to a datatable?

Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:

var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);

(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)

Connection string with relative path to the database file

Relative path:

ConnectionString = "Data Source=|DataDirectory|\Database.sdf";

Modifying DataDirectory as executable's path:

string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);

How to handle invalid SSL certificates with Apache HttpClient?

Used the following along with DefaultTrustManager and it worked in httpclient like charm. Thanks a ton!! @Kevin and every other contributor

    SSLContext ctx = null;
    SSLConnectionSocketFactory sslsf = null;
    try {

        ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);

        sslsf = new SSLConnectionSocketFactory(
                ctx,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    } catch (Exception e) {
        e.printStackTrace();
    }

     CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();

Rmi connection refused with localhost

You need to have a rmiregistry running before attempting to connect (register) a RMI service with it.

The LocateRegistry.createRegistry(2020) method call creates and exports a registry on the specified port number.

See the documentation for LocateRegistry

Unable to make the session state request to the session state server

Not the best answer, but it's an option anyway:

Comment the given line in the web.config.

Best Practice to Use HttpClient in Multithreaded Environment

Definitely Method A because its pooled and thread safe.

If you are using httpclient 4.x, the connection manager is called ThreadSafeClientConnManager. See this link for further details (scroll down to "Pooling connection manager"). For example:

    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, registry);
    HttpClient client = new DefaultHttpClient(cm, params);

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Easiest Way!!!

  1. Right click on project and select "Manage NuGet Packages..."
  2. Search for Oracle.ManagedDataAccess. Install it.

If you are using Entity Framework and your Visual Studio Version is 2012 or higher,then

  1. Again search for Oracle.ManagedDataAccess.EntityFramework. Install it.
  2. Use below name spaces in your .cs file:
    using Oracle.ManagedDataAccess.Client;
    using Oracle.ManagedDataAccess.EntityFramework;

Its done. Now restart your visual studio and build your code.

What do these packages do?
After installing these packages no additional Oracle client software is required to be installed to connect to database.

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

I had similar issue, trying to load data from Excel spreadsheet; and was running on WinX64. So I went VS BI`s project properties: Configuration Properties \ Dbugging and Switch Run64BitRuntime from True to False. It worked.

The provider is not compatible with the version of Oracle client

Does the IIS/IWAM user have permissions on the Oracle directory? Can you connect to this data source using another app, such as Excel or Access?

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

end-of-file on communication channel:

One of the course of this error is due to database fail to write the log when its in the stage of opening;

Solution check the database if its running in ARCHIVELOG or NOARCHIVELOG

to check use

select log_mode from v$database;

if its on ARCHIVELOG try to change into NOARCHIVELOG

by using sqlplus

  • startup mount
  • alter database noarchivelog;
  • alter database open;

if it works for this

Then you can adjust your flashrecovery area its possibly that your flashrecovery area is full -> then after confirm that your flashrecovery area has the space you can alter your database into the ARCHIVELOG

Oracle: How to find out if there is a transaction pending?

The easiest and most reliable solution is to try and start a transaction and see it if succeeds. If some code already started a transaction but has not yet issued any DML, then the V$TRANSACTION view won't show anything.

In this example below, I handle the exception to raise a user-defined application error. To defer to an existing exception handler, just do a SET TRANSACTION and then immediately COMMIT to undo it.

DECLARE
    transaction_in_progress EXCEPTION;
    PRAGMA EXCEPTION_INIT(transaction_in_progress, -1453);
BEGIN
    SET TRANSACTION NAME 'CHECK_FOR_TRANSACTION_ALREADY_SET';
    COMMIT; -- end transaction
EXCEPTION
    WHEN transaction_in_progress THEN
        RAISE_APPLICATION_ERROR(-20000,'Transaction is already in progress');
END;
/

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

Why is access to the path denied?

I too faced the same problem when trying to do this after deployment at server:

dirPath = Server.MapPath(".") + "\\website\\" + strUserName;
if (!Directory.Exists(dirPath))
{
    DirectoryInfo DI = Directory.CreateDirectory(dirPath);
}
string filePath = Server.MapPath(".") + "\\Website\\default.aspx";
File.Copy(filePath, dirPath + "\\default.aspx", true);
File.SetAttributes(dirPath + "\\default.aspx", FileAttributes.Normal);

I granted permission in IIS to other group including administrator and my problem got solved.

"Cannot instantiate the type..."

You can use

Queue thequeue = new linkedlist();

or

Queue thequeue = new Priorityqueue();

Reason: Queue is an interface. So you can instantiate only its concrete subclass.

Proper way to initialize a C# dictionary with values?

With C# 6.0, you can create a dictionary in following way:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

It even works with custom types.

python error: no module named pylab

I solved the same problem by installing "matplotlib".

"Sub or Function not defined" when trying to run a VBA script in Outlook

I solved the problem by following the instructions on msdn.microsoft.com more closely. There, it is stated that one must create the new macro by selecting Developer -> Macros, typing a new macro name, and clicking "Create". Creating the macro in this way, I was able to run it (see message box below).

enter image description here

What is move semantics?

Move semantics is about transferring resources rather than copying them when nobody needs the source value anymore.

In C++03, objects are often copied, only to be destroyed or assigned-over before any code uses the value again. For example, when you return by value from a function—unless RVO kicks in—the value you're returning is copied to the caller's stack frame, and then it goes out of scope and is destroyed. This is just one of many examples: see pass-by-value when the source object is a temporary, algorithms like sort that just rearrange items, reallocation in vector when its capacity() is exceeded, etc.

When such copy/destroy pairs are expensive, it's typically because the object owns some heavyweight resource. For example, vector<string> may own a dynamically-allocated memory block containing an array of string objects, each with its own dynamic memory. Copying such an object is costly: you have to allocate new memory for each dynamically-allocated blocks in the source, and copy all the values across. Then you need deallocate all that memory you just copied. However, moving a large vector<string> means just copying a few pointers (that refer to the dynamic memory block) to the destination and zeroing them out in the source.

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

what does mysql_real_escape_string() really do?

The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

If you want the editor to work with git operations, setting the $EDITOR environment variable may not be enough, at least not in the case of Sublime - e.g. if you want to rebase, it will just say that the rebase was successful, but you won't have a chance to edit the file in any way, git will just close it straight away:

git rebase -i HEAD~
Successfully rebased and updated refs/heads/master.

If you want Sublime to work correctly with git, you should configure it using:

git config --global core.editor "sublime -n -w"

I came here looking for this and found the solution in this gist on github.

Word-wrap in an HTML table

A solution which work with Google Chrome and Firefox (not tested with Internet Explorer) is to set display: table-cell as a block element.

How to create RecyclerView with multiple view type?

if anyone is interested to see the super simple solution written in Kotlin, check the blogpost I just created. The example in the blogpost is based on creating Sectioned RecyclerView:

https://brona.blog/2020/06/sectioned-recyclerview-in-three-steps/

how to inherit Constructor from super class to sub class

Default constructors -- public constructors with out arguments (either declared or implied) -- are inherited by default. You can try the following code for an example of this:

public class CtorTest {
    public static void main(String[] args) {
        final Sub sub = new Sub();
        System.err.println("Finished.");
    }

    private static class Base {
        public Base() {
            System.err.println("In Base ctor");
        }
    }

    private static class Sub extends Base {
        public Sub() {
            System.err.println("In Sub ctor");
        }
    }
}

If you want to explicitly call a constructor from a super class, you need to do something like this:

public class Ctor2Test {
    public static void main(String[] args) {
        final Sub sub = new Sub();
        System.err.println("Finished.");
    }

    private static class Base {
        public Base() {
            System.err.println("In Base ctor");
        }

        public Base(final String toPrint) {
            System.err.println("In Base ctor.  To Print: " + toPrint);
        }
    }

    private static class Sub extends Base {
        public Sub() {
            super("Hello World!");
            System.err.println("In Sub ctor");
        }
    }
}

The only caveat is that the super() call must come as the first line of your constructor, else the compiler will get mad at you.

How can I check for IsPostBack in JavaScript?

Lots of options here.

For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.

The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:

<html>

<?php
if ($_POST['myVar']) {
    //postback
    echo '<script>var postingBack = true;</script>';
    //Do other processing
} else {
    echo '<script>var postingBack = false;</script>'
 } ?>
<script>
function myLoader() {
     if (postingBack == false) {
          //Do stuff
     }
 }

<body onLoad="myLoader():"> ...

How do I kill background processes / jobs when my shell script exits?

So script the loading of the script. Run a killall (or whatever is available on your OS) command that executes as soon as the script is finished.

How to find third or n?? maximum salary from salary table?

SELECT Salary,EmpName
FROM
(
SELECT Salary,EmpName,DENSE_RANK() OVER(ORDER BY Salary DESC) Rno from EMPLOYEE
) tbl
WHERE Rno=3

Check if a number has a decimal place/is a whole number

function isWholeNumber(num) {
  return num === Math.round(num);
}

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

Routing for custom ASP.NET MVC 404 Error page

I had the same problem, the thing you have to do is, instead of adding the customErrors attribute in the web.config file in your Views folder, you have to add it in the web.config file in your projects root folder

C# DataTable.Select() - How do I format the filter criteria to include null?

Try out Following:

DataRow rows = DataTable.Select("[Name]<>'n/a'")

For Null check in This:

DataRow rows =  DataTable.Select("[Name] <> 'n/a' OR [Name] is NULL" )

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

Set HTML element's style property in javascript

You can set the style attribute of any element... the trick is that in IE you have to do it differently. (bug 245)

//Standards base browsers
elem.setAttribute('style', styleString);

//Non Standards based IE browser
elem.style.setAttribute('cssText', styleString);

Note that in IE8, in Standards Mode, the first way does work.

List vs tuple, when to use each?

Must it be mutable? Use a list. Must it not be mutable? Use a tuple.

Otherwise, it's a question of choice.

For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.

Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.

Using ORDER BY and GROUP BY together

If you really don't care about which timestamp you'll get and your v_id is always the same for a given m_i you can do the following:

select m_id, v_id, max(timestamp) from table
group by m_id, v_id
order by timestamp desc

Now, if the v_id changes for a given m_id then you should do the following

select t1.* from table t1
left join table t2 on t1.m_id = t2.m_id and t1.timestamp < t2.timestamp
where t2.timestamp is null
order by t1.timestamp desc

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

Mean per group in a data.frame

This type of operation is exactly what aggregate was designed for:

d <- read.table(text=
'Name     Month  Rate1     Rate2
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32', header=TRUE)

aggregate(d[, 3:4], list(d$Name), mean)

  Group.1    Rate1    Rate2
1    Aira 16.33333 47.00000
2     Ben 31.33333 50.33333
3     Cat 44.66667 54.00000

Here we aggregate columns 3 and 4 of data.frame d, grouping by d$Name, and applying the mean function.


Or, using a formula interface:

aggregate(. ~ Name, d[-2], mean)

java.math.BigInteger cannot be cast to java.lang.Long

I'm lacking context, but this is working just fine:

List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...

How to get query parameters from URL in Angular 5?

When you have an empty route object, it's mainly due to the fact that you are not using a router-outlet in your app.component.html.

Without this, you won't be able to get a meaningful route object with non empty subObjects, particularly params & queryParams.

Try to add <router-outlet><router-outlet>just before calling your <app-main-component></app-main-component>

Before that, make sure you have your query param ready in app-routing > which export the class Route used by App component :

param: '/param/:dynamicParam', path: MyMainComponent

Last thing of course, to get your param, I personnaly use this.route.snapshot.params.dynamicParam where dynamicParam is the name used in your app-routing component :)

How to change workspace and build record Root Directory on Jenkins?

I figured it out. In order to save your Jenkins data on other drive you'll need to do the following:

Workspace Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\workspace
Build Record Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\builds

Change Directory

Image Greyscale with CSS & re-color on mouse-over?

You can use a sprite which has both version—the colored and the monochrome—stored into it.

Display a float with two decimal places in Python

If you want to get a floating point value with two decimal places limited at the time of calling input,

Check this out ~

a = eval(format(float(input()), '.2f'))   # if u feed 3.1415 for 'a'.
print(a)                                  # output 3.14 will be printed.

Twitter Bootstrap: div in container with 100% height

Set the class .fill to height: 100%

.fill { 
    min-height: 100%;
    height: 100%;
}

JSFiddle

(I put a red background for #map so you can see it takes up 100% height)

"Failed to install the following Android SDK packages as some licences have not been accepted" error

To add to the answers, you can also change to the sdkmanager directory and in a sub shell and accept the licenses there

(
    cd /home/user/android-sdk-linux/tools/bin
    yes | ./sdkmanager --licenses
)

ReactJS and images in public folder

We know React is SPA. Everything is rendered from the root component by expanding to appropriate HTML from JSX.

So it does not matter where you want to use the images. Best practice is to use an absolute path (with reference to public). Do not worry about relative paths.

In your case, this should work everywhere:

"./images/logofooter.png"

Checking length of dictionary object

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.

I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

Edit #1: Why can't you just do this?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The length is already set.

How can I get a uitableViewCell by indexPath?

[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]

will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)

ADD: Here is an alternate syntax that achieves the same thing without the cast.

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];

Differences between ConstraintLayout and RelativeLayout

In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1 Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate: 123ms

Last preformDraw time - OnCreate time: 311.3ms

Constraint Layout

OnCreate: 120.3ms

Last preformDraw time - OnCreate time: 310ms

Besides that, I've checked performance test from this article , here the code and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?

As always: It depends

I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it. For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.

installation app blocked by play protect

the only solution worked for me was using java keytool and generating a .keystore file the command line and then use that .keystore file to sign my app

you can find the java keytool at this directory C:\Program Files\Java\jre7\bin

open a command window and switch to that directory and enter a command like this

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Keytool prompts you to provide passwords for the keystore, your name , company etc . note that at the last prompt you need to enter yes.

It then generates the keystore as a file called my-release-key.keystore in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use later, to refer to this keystore when signing your application.

For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html

jQuery select box validation

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here

Pseudo-terminal will not be allocated because stdin is not a terminal

Also with option -T from manual

Disable pseudo-tty allocation

Ignore outliers in ggplot2 boxplot

Ipaper::geom_boxplot2 is just what you want.

# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)

enter image description here

versionCode vs versionName in Android Manifest

I'm going to give you my interpretation of the only documentation I can find on the subject.

"for example to check an upgrade or downgrade relationship." <- You can downgrade an app.

"you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior" <- The number really should increase, but you can still downgrade an app.

android:versionCode — An integer value that represents the version of the application code, relative to other versions. The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative. Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.

Gerrit error when Change-Id in commit messages are missing

It is because Gerrit is configured to require Change-Id in the commit messages.

http://gerrit.googlecode.com/svn-history/r6114/documentation/2.1.7/error-missing-changeid.html

You have to change the messages of every commit that you are pushing to include the change id ( using git filter-branch ) and only then push.

How to implement drop down list in flutter?

When I ran into this issue of wanting a less generic DropdownStringButton, I just created it:

dropdown_string_button.dart

import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage: 
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton<String> {
  DropdownStringButton({
    Key key, @required List<String> items, value, hint, disabledHint,
    @required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
    isExpanded = false, }) : 
    assert(items == null || value == null || items.where((String item) => item == value).length == 1),
        super(
          key: key,
          items: items.map((String item) {
            return DropdownMenuItem<String>(child: Text(item), value: item);
          }).toList(),
        value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
        elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
        isExpanded: isExpanded,
        );
    }

how to get session id of socket.io client in Client

On socket.io >=1.0, after the connect event has triggered:

var socket = io('localhost');
var id = socket.io.engine.id

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

this worked for me

// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.LoginPath = new PathString("/auth/login");
            options.AccessDeniedPath = new PathString("/auth/denied");
        });

How to create the most compact mapping n ? isprime(n) up to a limit N?

We can use java streams to implement this in O(sqrt(n)); Consider that noneMatch is a shortCircuiting method that stops the operation when finds it unnecessary for determining the result:

Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n == 2 ? "Prime" : IntStream.rangeClosed(2, ((int)(Math.sqrt(n)) + 1)).noneMatch(a -> n % a == 0) ? "Prime" : "Not Prime");

jquery multiple checkboxes array

You can use $.map() (or even the .map() function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number

var arr = $.map($('input:checkbox:checked'), function(e,i) {
    return +e.value;
});

console.log(arr);

Here's an example

Class name does not name a type in C++

Aren't you missing the #include "B.h" in A.h?

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

implement time delay in c

For delays as large as one minute, sleep() is a nice choice.

If someday, you want to pause on delays smaller than one second, you may want to consider poll() with a timeout.

Both are POSIX.

Download file through an ajax call php

A very simple solution using jQuery:

on the client side:

$('.act_download_statement').click(function(e){
    e.preventDefault();
    form = $('#my_form');
    form.submit();
});

and on the server side, make sure you send back the correct Content-Type header, so the browser will know its an attachment and the download will begin.

SQL Error: ORA-01861: literal does not match format string 01861

The format you use for the date doesn't match to Oracle's default date format.

A default installation of Oracle Database sets the DEFAULT DATE FORMAT to dd-MMM-yyyy.

Either use the function TO_DATE(dateStr, formatStr) or simply use dd-MMM-yyyy date format model.

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

Yes, adding your own Custom Observable Collection would be fair enough. Don't forget to raise appropriate events regardless whether it is used by UI for the moment or not ;) You will have to raise property change notification for "Item[]" property (required by WPF side and bound controls) as well as NotifyCollectionChangedEventArgs with a set of items added (your range). I've did such things (as well as sorting support and some other stuff) and had no problems with both Presentation and Code Behind layers.

How do you share code between projects/solutions in Visual Studio?

You would simply create a separate Class Library project to contain the common code. It need not be part of any solution that uses it. Reference the class library from any project that needs it.

The only trick at all is that you will need to use a file reference to reference the project, since it will not be part of the solutions that refer to it. This means that the actual output assembly will have to be placed in a location that can be accessed by anyone building a project that references it. This can be done by placing the assembly on a share, for instance.

Insert current date into a date column using T-SQL?

To insert a new row into a given table (tblTable) :

INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :

UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...

 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

POSIX 7 quotes

POSIX 7 specifies both at http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html:

CLOCK_REALTIME:

This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.

CLOCK_MONOTONIC (optional feature):

For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime().

clock_settime() gives an important hint: POSIX systems are able to arbitrarily change CLOCK_REALITME with it, so don't rely on it flowing neither continuously nor forward. NTP could be implemented using clock_settime(), and could only affect CLOCK_REALITME.

The Linux kernel implementation seems to take boot time as the epoch for CLOCK_MONOTONIC: Starting point for CLOCK_MONOTONIC

SQL Server Group By Month

Now your query is explicitly looking at only payments for year = 2010, however, I think you meant to have your Jan/Feb/Mar actually represent 2009. If so, you'll need to adjust this a bit for that case. Don't keep requerying the sum values for every column, just the condition of the date difference in months. Put the rest in the WHERE clause.

SELECT 
      SUM( case when DateDiff(m, PaymentDate, @start) = 0 
           then Amount else 0 end ) AS "Apr",
      SUM( case when DateDiff(m, PaymentDate, @start) = 1 
           then Amount else 0 end ) AS "May",
      SUM( case when DateDiff(m, PaymentDate, @start) = 2 
           then Amount else 0 end ) AS "June",
      SUM( case when DateDiff(m, PaymentDate, @start) = 3 
           then Amount else 0 end ) AS "July",
      SUM( case when DateDiff(m, PaymentDate, @start) = 4 
           then Amount else 0 end ) AS "Aug",
      SUM( case when DateDiff(m, PaymentDate, @start) = 5 
           then Amount else 0 end ) AS "Sep",
      SUM( case when DateDiff(m, PaymentDate, @start) = 6 
           then Amount else 0 end ) AS "Oct",
      SUM( case when DateDiff(m, PaymentDate, @start) = 7 
           then Amount else 0 end ) AS "Nov",
      SUM( case when DateDiff(m, PaymentDate, @start) = 8 
           then Amount else 0 end ) AS "Dec",
      SUM( case when DateDiff(m, PaymentDate, @start) = 9 
           then Amount else 0 end ) AS "Jan",
      SUM( case when DateDiff(m, PaymentDate, @start) = 10 
           then Amount else 0 end ) AS "Feb",
      SUM( case when DateDiff(m, PaymentDate, @start) = 11 
           then Amount else 0 end ) AS "Mar"
   FROM 
      Payments I
         JOIN Live L
            on I.LiveID = L.Record_Key
   WHERE 
          Year = 2010 
      AND UserID = 100

Convert Long into Integer

If you care to check for overflows and have Guava handy, there is Ints.checkedCast():

int theInt = Ints.checkedCast(theLong);

The implementation is dead simple, and throws IllegalArgumentException on overflow:

public static int checkedCast(long value) {
  int result = (int) value;
  checkArgument(result == value, "Out of range: %s", value);
  return result;
}

How to solve a pair of nonlinear equations using Python?

Try this one, I assure you that it will work perfectly.

    import scipy.optimize as opt
    from numpy import exp
    import timeit

    st1 = timeit.default_timer()

    def f(variables) :
        (x,y) = variables

        first_eq = x + y**2 -4
        second_eq = exp(x) + x*y - 3
        return [first_eq, second_eq]

    solution = opt.fsolve(f, (0.1,1) )
    print(solution)


    st2 = timeit.default_timer()
    print("RUN TIME : {0}".format(st2-st1))

->

[ 0.62034452  1.83838393]
RUN TIME : 0.0009331008900937708

FYI. as mentioned above, you can also use 'Broyden's approximation' by replacing 'fsolve' with 'broyden1'. It works. I did it.

I don't know exactly how Broyden's approximation works, but it took 0.02 s.

And I recommend you do not use Sympy's functions <- convenient indeed, but in terms of speed, it's quite slow. You will see.

Uses for the '&quot;' entity in HTML

In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.

When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.

Referring to your example, the reason why every occurrence of " is represented by &quot; could be because using that approach, you can safely use such "special" characters in both attributes and values.

Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.

Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:

public class HtmlAndXmlWriter
{
    private string Escape(string badString)
    {
        return badString.Replace("&", "&amp;").Replace("\"", "&quot;").Replace("'", "&apos;").Replace(">", "&gt;").Replace("<", "&lt;");

    }

    public string GetHtmlFromOutObject(Object obj)
    {
        return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";    

    }

}

It's really very common to see such approaches taken to generate HTML.

Find object by id in an array of JavaScript objects

While there are many correct answers here, many of them do not address the fact that this is an unnecessarily expensive operation if done more than once. In an extreme case this could be the cause of real performance problems.

In the real world, if you are processing a lot of items and performance is a concern it's much faster to initially build a lookup:

var items = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var lookup = items.reduce((o,i)=>o[i.id]=o,{});

you can then get at items in fixed time like this :

var bar = o[id];

You might also consider using a Map instead of an object as the lookup: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

In Python, what is the difference between ".append()" and "+= []"?

The performance tests here are not correct:

  1. You shouldn't run the profile only once.
  2. If comparing append vs. += [] number of times you should declare append as a local function.
  3. time results are different on different python versions: 64 and 32 bit

e.g.

timeit.Timer('for i in xrange(100): app(i)', 's = [] ; app = s.append').timeit()

good tests can be found here: http://markandclick.com/1/post/2012/01/python-list-append-vs.html

SCRIPT5: Access is denied in IE9 on xmlhttprequest

Open the Internet Explorer Developer Tool, Tools -> F12 developer tools. (I think you can also press F12 to get it)

Change the Document Mode to Standards. (The page should be automatically refresh, if you change the Document Mode)

Problem should be fixed. Enjoy

Laravel 5 Application Key

Just as another option if you want to print only the key (doesn't write the .env file) you can use:

php artisan key:generate --show

Android WebView style background-color:transparent ignored on android 2.2

I had the same issue with 2.2 and also in 2.3. I solved the problem by giving the alpa value in html not in android. I tried many things and what I found out is setBackgroundColor(); color doesnt work with alpha value. webView.setBackgroundColor(Color.argb(128, 0, 0, 0)); will not work.

so here is my solution, worked for me.

      String webData = StringHelper.addSlashes("<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
      "content=\"text/html; charset=utf-8\"> </head><body><div style=\"background-color: rgba(10,10,10,0.5); " +
      "padding: 20px; height: 260px; border-radius: 8px;\"> $$$ Content Goes Here ! $$$ </div> </body></html>");

And in Java,

    webView = (WebView) findViewById(R.id.webview);
    webView.setBackgroundColor(0);
    webView.loadData(webData, "text/html", "UTF-8");

And here is the Output screenshot below.enter image description here

Shall we always use [unowned self] inside closure in Swift

Update 11/2016

I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.

Original answer

The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.

The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.

swift weak vs unowned

Scenarios

You can have two possible scenarios:

  1. The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self] used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.

  2. The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate] you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.

Actual Usage

So, which will/should you actually use most of the times?

Quoting Joe Groff from twitter:

Unowned is faster and allows for immutability and nonoptionality.

If you don't need weak, don't use it.

You'll find more about unowned* inner workings here.

* Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

i have used following line of code & it works fine Thanks.... @Mithun Sasidharan **

SELECT DATE_FORMAT(column_name, '%d/%m/%Y') FROM tablename

**

How do I create dynamic variable names inside a loop?

Try this

window['marker'+i] = "some stuff"; 

How to link an image and target a new window

If you use script to navigate to the page, use the open method with the target _blank to open a new window / tab:

<img src="..." alt="..." onclick="window.open('anotherpage.html', '_blank');" />

However, if you want search engines to find the page, you should just wrap the image in a regular link instead.

How to push objects in AngularJS between ngRepeat arrays

You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

What is AF_INET, and why do I need it?

You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.

As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:

  1. A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.

  2. A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. Used to communicate between processes over the Internet.

AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.

This thread about the differences between AF_INET and PF_INET might also be useful.

What is the difference between json.load() and json.loads() functions

Yes, s stands for string. The json.loads function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!

Possible cases for Javascript error: "Expected identifier, string or number"

Typescript for Windows issue

This works in IE, chrome, FF

export const OTP_CLOSE = { 'outcomeCode': 'OTP_CLOSE' };

This works in chrome, FF, Does not work in IE 11

export const OTP_CLOSE = { outcomeCode: 'OTP_CLOSE' };

I guess it somehow related to Windows reserved wordsenter image description here

How to switch back to 'master' with git?

According to the Git Cheatsheet you have to create the branch first

git branch [branchName]

and then

git checkout [branchName]

Add an element to an array in Swift

To add to the solutions suggesting append, it's useful to know that this is an amortised constant time operation in many cases:

Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

I'm looking for a cons like operator for Swift. It should return a new immutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!

What is the correct way to represent null XML elements?

The documentation in the w3 link

http://www.w3.org/TR/REC-xml/#sec-starttags

says that this are the recomended forms.

<test></test>
<test/>

The attribute mentioned in the other answer is validation mechanism and not a representation of state. Please refer to the http://www.w3.org/TR/xmlschema-1/#xsi_nil

XML Schema: Structures introduces a mechanism for signaling that an element should be accepted as ·valid· when it has no content despite a content type which does not require or even necessarily allow empty content. An element may be ·valid· without content if it has the attribute xsi:nil with the value true. An element so labeled must be empty, but can carry attributes if permitted by the corresponding complex type.

To clarify this answer: Content

  <Book>
    <!--Invalid construct since the element attribute xsi:nil="true" signal that the element must be empty-->
    <BuildAttributes HardCover="true" Glued="true" xsi:nil="true">
      <anotherAttribute name="Color">Blue</anotherAttribute>
    </BuildAttributes>
    <Index></Index>
    <pages>
      <page pageNumber="1">Content</page>            
    </pages>
    <!--Missing ISBN number could be confusing and misguiding since its not present-->
  </Book>
</Books>

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

A more up to date answer:

allprojects {
    repositories {
        google() // add this
    }
}

And don't forget to update gradle to 4.1+ (in gradle-wrapper.properties):

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

source: https://developer.android.com/studio/build/dependencies.html#google-maven

Timeout jQuery effects

I just figured it out below:

$(".notice")
   .fadeIn( function() 
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });

I will keep the post for other users!

What is the difference between HTML tags and elements?

This visualization can help us to find out difference between concept of element and tag (each indent means contain):

- element

        - content:

            - text 

            - other elements 

            - or empty

        - and its markup

            - tags (start or end tag)

                - element name

                - angle brackets < >

                - or attributes (just for start tag)

                - or slash / 

How link to any local file with markdown syntax?

This is a old question, but to me it still doesn't seem to have a complete answer to the OP's question. The chosen answer about security being the possible issue is actually often not the problem when using the Firefox 'Markdown Viewer' plug-in in my experience. Also, the OP seems to be using MS-Windows, so there is the added issue of specifying different drives.

So, here is a little more complete yet simple answer for the 'Markdown Viewer' plug-in on Windows (and other Markdown renderers I've seen): just enter the local path as you would normally, and if it is an absolute path make sure to start it with a slash. So:

[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)

That last one was probably what the OP was looking for given their example. Note this can also be used to display directories rather than files.

Though late, I hope this helps!

Error: Failed to lookup view in Express

In my case, I solved it with the following:

app.set('views', `${__dirname}/views`);
app.use(express.static(`${__dirname}/public`));

I needed to start node app.min.js from /dist folder.

My folder structure was:

Start app from /dist

How do I setup the InternetExplorerDriver so it works

Another way to resolve this problem is:

Let's assume:

path_to_driver_directory = C:\Work\drivers\

driver = IEDriverServer.exe

When getting messsage about path you can always add path_to_driver_directory containing driver to the PATH environment variable. Check: http://java.com/en/download/help/path.xml

Then simply check in cmd window if driver is available - just run cmd in any location and type name of driver.

If everything works fine then you get:

C:\Users\A>IEDriverServer.exe
Started InternetExplorerDriver server (32-bit)
2.28.0.0
Listening on port 5555

Thats it.

Facebook Graph API, how to get users email?

Just add these code block on status return, and start passing a query string object {}. For JavaScript devs

After initializing your sdk.

step 1: // get login status

$(document).ready(function($) {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
        console.log(response);
    });
  });

This will check on document load and get your login status check if users has been logged in.

Then the function checkLoginState is called, and response is pass to statusChangeCallback

function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

Step 2: Let you get the response data from the status

function statusChangeCallback(response) {
    // body...
    if(response.status === 'connected'){
      // setElements(true);
      let userId = response.authResponse.userID;
      // console.log(userId);
      console.log('login');
      getUserInfo(userId);

    }else{
      // setElements(false);
      console.log('not logged in !');
    }
  }

This also has the userid which is being set to variable, then a getUserInfo func is called to fetch user information using the Graph-api.

function getUserInfo(userId) {
    // body...
    FB.api(
      '/'+userId+'/?fields=id,name,email',
      'GET',
      {},
      function(response) {
        // Insert your code here
        // console.log(response);
        let email = response.email;
        loginViaEmail(email);
      }
    );
  }

After passing the userid as an argument, the function then fetch all information relating to that userid. Note: in my case i was looking for the email, as to allowed me run a function that can logged user via email only.

// login via email

function loginViaEmail(email) {
    // body...
    let token = '{{ csrf_token() }}';

    let data = {
      _token:token,
      email:email
    }

    $.ajax({
      url: '/login/via/email',    
      type: 'POST',
      dataType: 'json',
      data: data,
      success: function(data){
        console.log(data);
        if(data.status == 'success'){
          window.location.href = '/dashboard';
        }

        if(data.status == 'info'){
          window.location.href = '/create-account'; 
        }
      },
      error: function(data){
        console.log('Error logging in via email !');
        // alert('Fail to send login request !');
      }
    });
  }

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

As programmers we want the quickest, most fool-proof way to get our tools in order so we can start hacking. Here are how I got it to work in MacOS 10.13.1 (High Sierra):

  • Option 1: Go to System Preferences | Keyboard | Shortcut | Services. Under Files and Folders section, enable New Terminal at Folder and/or New Terminal Tab at Folder and assign a shortcut key to it. Keyboard shortcut config

  • Option 2: If you want the shortcut key to work anywhere, create a new Service using Automator, then go to the Keyboard Shortcut to assign a shortcut key to it. Known limitation: not work from the desktop

enter image description here

Notes:

  • If the shortcut doesn't work, it might be in conflict with another key binding (and the OS wouldn't warn you), try something else, e.g. if ??T doesn't work, try ??T.
  • Don't spell-correct MacOS, that's not necessary.

Detect element content changes with jQuery

Try the livequery plugin. That seems to work for something similar I am doing.

http://docs.jquery.com/Plugins/livequery

How can one run multiple versions of PHP 5.x on a development LAMP server?

Rasmus Lerdorf, who created PHP, is maintaining an active Vagrant solution that seems to solve your needs. It allows for quickly switching between PHP versions, currently supporting more than 20 different versions. It comes out of the box with an nginx server, but can easily be switched to apache2 with a preconfigured setting. It also supports MySQL out of the box.

This way you will have access to all versions of PHP, deployable on two of the main web servers, in a nice vagrant box, maintained by the big man behind PHP.

For more information I would like to refer to the talk given by mr. Lerdorf at https://youtu.be/6XnysJAyThs?t=2864

The github repository containing the Vagrant solution is found at https://github.com/rlerdorf/php7dev

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

How to make circular background using css?

Keep it simple:

.circle
  {
    border-radius: 50%;
    width: 200px;
    height: 200px; 
  }

Width and height can be anything, as long as they're equal

Alternative to the HTML Bold tag

You can code like below..

<html>
 <head>
 <style>
 p.boldstats{
 font-weight: bold
  }
  </style>
 </head>

  <body>
  <p class="boldstats"> The bold finder </p>
  </body>
</html>

TortoiseGit save user authentication / credentials

If you're going to downvote this answer

I wrote this a few months prior to the inclusion of git-credential in TortoiseGit. Given the number of large security holes found in the last few years and how much I've learned about network security, I would HIGHLY recommend you use a unique (minimum 2048-bit RSA) SSH key for every server you connect to.

The below syntax is still available, though there are far better tools available today like git-credential that the accepted answer tells you how to use. Do that instead.


Try changing the remote URL to https://[email protected]/username/repo.git where username is your github username and repo is the name of your repository.

If you also want to store your password (not recommended), the URL would look like this: https://username:[email protected]/username/repo.git.

There's also another way to store the password from this github help article: https://help.github.com/articles/set-up-git#password-caching

How to remove \xa0 from string in Python?

Generic version with the regular expression (It will remove all the control characters):

import re
def remove_control_chart(s):
    return re.sub(r'\\x..', '', s)

Jquery Ajax, return success/error from mvc.net controller

When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

return StatusCode(500, "My error");

Or

return StatusCode((int)HttpStatusCode.InternalServerError, "My error");

Or

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });

Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

you can have ajax call like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
       success: function (response)  {
            console.log("Custom message : " + response.responseText);
        }, //Is Called when Status Code is 200[OK] or other Http success code
        error: function (jqXHR, textStatus, errorThrown)  {
            console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
        }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
        })

Additionally you can handle different HTTP errors from jQuery side like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
        statusCode: {
            500: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            501: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            }
        })

statusCode: is useful when you want to call different functions for different status codes that you return from server.

You can see list of different Http Status codes here:Wikipedia

Additional resources:

  1. Returning Server-Side Errors from AJAX Calls
  2. Returning a JsonResult within the Error function of JQuery Ajax
  3. Handling Ajax errors with jQuery

How to prevent multiple definitions in C?

If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.

Good luck with it

How to clear exisiting dropdownlist items when its content changes?

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:

Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()

ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub

and it worked just fine

How do I exclude Weekend days in a SQL Server query?

When dealing with day-of-week calculations, it's important to take account of the current DATEFIRST settings. This query will always correctly exclude weekend days, using @@DATEFIRST to account for any possible setting for the first day of the week.

SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + @@DATEFIRST) % 7) NOT IN (0, 1)

Reading a string with spaces with sscanf

You want the %c conversion specifier, which just reads a sequence of characters without special handling for whitespace.

Note that you need to fill the buffer with zeroes first, because the %c specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):

memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

For individual element the code below could be used:

private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
for (int second = 0;; second++) {
            if (second >= 60){
                fail("timeout");
            }
            try {
                if (isElementPresent(By.id("someid"))){
                    break;
                }
                }
            catch (Exception e) {

            }
            Thread.sleep(1000);
        }

Javascript : get <img> src and set as variable?

How about this for instance :

var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');

Find nginx version?

Try running command 'whereis nginx'. It will give you the correct path of the nginx installation, in my case nginx is installed in '/usr/local/sbin', so I need to check if this path exists in output of command 'echo $PATH'. If you don't find the path in the output of this command, then you can add this.

Suppose the output of my 'echo $PATH' command is this:

  ~$ echo $PATH
/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin

Then I can append the path '/usr/local/sbin' in $PATH by following command:

~$ echo 'export PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin"' >> $HOME/.bashrc

Please check your nginx installation path may differ from mine, but the steps for adding them are same.

After updating Entity Framework model, Visual Studio does not see changes

Right click the .tt file and select "Run Custom Tool", that should update it: see image

click command in selenium webdriver does not work

There's nothing wrong with either version of your code. Whatever is causing this, that's not it.

Have you triple checked your locator? Your element definitely has name=submit not id=submit?

Textarea that can do syntax highlighting on the fly?

You can Highlight text in a <textarea>, using a <div> carefully placed behind it.

check out Highlight Text Inside a Textarea.

Define an alias in fish shell

This is how I define a new function foo, run it, and save it persistently.

sthorne@pearl~> function foo
                    echo 'foo was here'
                end
sthorne@pearl~> foo
foo was here
sthorne@pearl~> funcsave foo

Compare and contrast REST and SOAP web services?

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

By way of illustration here are few calls and their appropriate home with commentary.

getUser(User);

This is a rest operation as you are accessing a resource (data).

switchCategory(User, OldCategory, NewCategory)

REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.

Check whether a string matches a regex in JS

You can use match() as well:

if (str.match(/^([a-z0-9]{5,})$/)) {
    alert("match!");
}

But test() seems to be faster as you can read here.

Important difference between match() and test():

match() works only with strings, but test() works also with integers.

12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345);  // true
/^([a-z0-9]{5,})$/.test(null);   // false

// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true

How do you create a static class in C++?

You can also create a free function in a namespace:

In BitParser.h

namespace BitParser
{
    bool getBitAt(int buffer, int bitIndex);
}

In BitParser.cpp

namespace BitParser
{
    bool getBitAt(int buffer, int bitIndex)
    {
        //get the bit :)
    }
}

In general this would be the preferred way to write the code. When there's no need for an object don't use a class.

What is the difference between require_relative and require in Ruby?

Summary

Use require for installed gems

Use require_relative for local files

require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement


require

Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.

require_relative

This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

require_relative '../../../filename'

(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

How can I convert an integer to a hexadecimal string in C?

The following code takes an integer and makes a string out of it in hex format:

int  num = 32424;
char hex[5];

sprintf(hex, "%x", num);
puts(hex);

gives

7ea8

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

you may check this equation i think it will help

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

Angular ngClass and click event for toggling class

This should work for you.

In .html:

<div class="my_class" (click)="clickEvent()"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

In .ts:

status: boolean = false;
clickEvent(){
    this.status = !this.status;       
}

"Submit is not a function" error in JavaScript

In fact, the solution is very easy...

Original:

    <form action="product.php" method="get" name="frmProduct" id="frmProduct"
enctype="multipart/form-data">
    <input onclick="submitAction()" id="submit_value" type="button" 
    name="submit_value" value="">
</form>
<script type="text/javascript">
    function submitAction()
    {
        document.frmProduct.submit();
    }
</script>

Solution:

    <form action="product.php" method="get" name="frmProduct" id="frmProduct" 
enctype="multipart/form-data">
</form>

<!-- Place the button here -->
<input onclick="submitAction()" id="submit_value" type="button" 
    name="submit_value" value="">

<script type="text/javascript">
    function submitAction()
    {
        document.frmProduct.submit();
    }
</script>

How to replace a hash key with another key

If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:

h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }

The k[1, k.length - 1] bit grabs all of k except the first character. If you want a copy, then:

new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]

Or

new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }

You could also use sub if you don't like the k[] notation for extracting a substring:

h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }

And, if only some of the keys have the underscore prefix:

h.keys.each do |k|
  if(k[0,1] == '_')
    h[k[1, k.length - 1]] = h[k]
    h.delete(k)
  end
end

Similar modifications can be done to all the other variants above but these two:

Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }

should be okay with keys that don't have underscore prefixes without extra modifications.

TSQL How do you output PRINT in a user defined function?

No, sorry. User-defined functions in SQL Server are really limited, because of a requirement that they be deterministic. No way round it, as far as I know.

Have you tried debugging the SQL code with Visual Studio?

'react-scripts' is not recognized as an internal or external command

Try:

rm -rf node_modules && npm install

Wiping node_modules first, often tends to fix a lot of weird, package related issues like that in Node.

What can be the reasons of connection refused errors?

From the standpoint of a Checkpoint firewall, you will see a message from the firewall if you actually choose Reject as an Action thereby exposing to a propective attacker the presence of a firewall in front of the server. The firewall will silently drop all connections that doesn't match the policy. Connection refused almost always comes from the server

How to check if a registry value exists using C#?

Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.

For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

Import an existing git project into GitLab?

rake gitlab:import:repos might be a more suitable method for mass importing:

  • copy the bare repository under repos_path (/home/git/repositories/group/repo.git). Directory name must end in .git and be under a group or user namespace.
  • run bundle exec rake gitlab:import:repos

The owner will the first admin, and a group will get created if not already existent.

See also: How to import an existing bare git repository into Gitlab?

Difference between abstract class and interface in Python

Python doesn't really have either concept.

It uses duck typing, which removed the need for interfaces (at least for the computer :-))

Python <= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract.

Python >= 2.6: Abstract base classes do exist (http://docs.python.org/library/abc.html). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

How to use graphics.h in codeblocks?

AFAIK, in the epic DOS era there is a header file named graphics.h shipped with Borland Turbo C++ suite. If it is true, then you are out of luck because we're now in Windows era.

How to make use of SQL (Oracle) to count the size of a string?

You can use LENGTH() for CHAR / VARCHAR2 and DBMS_LOB.GETLENGTH() for CLOB. Both functions will count actual characters (not bytes).

See the linked documentation if you do need bytes.

How to pass multiple parameters in a querystring

~mypage.aspx?strID=x&strName=y&strDate=z

Unable to open debugger port in IntelliJ IDEA

All the other solutions unfortunately did not work. This is what worked for me . I simply changed the debugger port to some other port number.

Intelij-> preferences->Build, execution, deployment ->Debugger-> Built in server->port(change value )

enter image description here

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

How can I get LINQ to return the object which has the max value for a given property?

In LINQ you can solve it the following way:

Item itemMax = (from i in items
     let maxId = items.Max(m => m.ID)
     where i.ID == maxId
     select i).FirstOrDefault();

How do I disable TextBox using JavaScript?

Form elements can be accessed via the form's DOM element by name, not by "id" value. Give your form elements names if you want to access them like that, or else access them directly by "id" value:

document.getElementById("color").disabled = true;

edit — oh also, as pointed out by others, it's just "text", not "TextBox", for the "type" attribute.

You might want to invest a little time in reading some front-end development tutorials.

String is immutable. What exactly is the meaning?

I think the following code clears the difference:

String A = new String("Venugopal");
String B = A;

A = A +"mitul";

System.out.println("A is " + A);
System.out.println("B is " + B);

StringBuffer SA = new StringBuffer("Venugopal");
StringBuffer SB = SA;

SA = SA.append("mitul");

System.out.println("SA is " + SA);
System.out.println("SB is " + SB);

How to combine GROUP BY, ORDER BY and HAVING

Steps for Using Group by,Having By and Order by...

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.

How do I generate random number for each row in a TSQL Select?

It's as easy as:

DECLARE @rv FLOAT;
SELECT @rv = rand();

And this will put a random number between 0-99 into a table:

CREATE TABLE R
(
    Number int
)

DECLARE @rv FLOAT;
SELECT @rv = rand();

INSERT INTO dbo.R
(Number)
    values((@rv * 100));

SELECT * FROM R

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

I solved the same problem by changing this from false to true. in the end I went into the database and changed my bit field to allow null, and then refreshed my xsd, and refreshed my wsdl and reference.cs and now all is well.

this.columnAttachPDFToEmailFlag.AllowDBNull = true;

Make first letter of a string upper case (with maximum performance)

I found something here http://www.dotnetperls.com/uppercase-first-letter :

static string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
    return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}

maybe this helps!!

Makefile to compile multiple C programs?

all: program1 program2

program1:
    gcc -Wall -ansi -pedantic -o prog1 program1.c

program2:
    gcc -Wall -ansi -pedantic -o prog2 program2.c

I rather the ansi and pedantic, a better control for your program. It wont let you compile while you still have warnings !!

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

SSH configuration: override the default username

Create a file called config inside ~/.ssh. Inside the file you can add:

Host *
    User buck

Or add

Host example
    HostName example.net
    User buck

The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net; ssh example will be enough.

Open PDF in new browser full window

<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>

The above link will open the PDF in full screen mode, that's the best you can achieve.

cartesian product in pandas

As an alternative, one can rely on the cartesian product provided by itertools: itertools.product, which avoids creating a temporary key or modifying the index:

import numpy as np 
import pandas as pd 
import itertools

def cartesian(df1, df2):
    rows = itertools.product(df1.iterrows(), df2.iterrows())

    df = pd.DataFrame(left.append(right) for (_, left), (_, right) in rows)
    return df.reset_index(drop=True)

Quick test:

In [46]: a = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])

In [47]: b = pd.DataFrame(np.random.rand(5, 3), columns=["d", "e", "f"])    

In [48]: cartesian(a,b)
Out[48]:
           a         b         c         d         e         f
0   0.436480  0.068491  0.260292  0.991311  0.064167  0.715142
1   0.436480  0.068491  0.260292  0.101777  0.840464  0.760616
2   0.436480  0.068491  0.260292  0.655391  0.289537  0.391893
3   0.436480  0.068491  0.260292  0.383729  0.061811  0.773627
4   0.436480  0.068491  0.260292  0.575711  0.995151  0.804567
5   0.469578  0.052932  0.633394  0.991311  0.064167  0.715142
6   0.469578  0.052932  0.633394  0.101777  0.840464  0.760616
7   0.469578  0.052932  0.633394  0.655391  0.289537  0.391893
8   0.469578  0.052932  0.633394  0.383729  0.061811  0.773627
9   0.469578  0.052932  0.633394  0.575711  0.995151  0.804567
10  0.466813  0.224062  0.218994  0.991311  0.064167  0.715142
11  0.466813  0.224062  0.218994  0.101777  0.840464  0.760616
12  0.466813  0.224062  0.218994  0.655391  0.289537  0.391893
13  0.466813  0.224062  0.218994  0.383729  0.061811  0.773627
14  0.466813  0.224062  0.218994  0.575711  0.995151  0.804567
15  0.831365  0.273890  0.130410  0.991311  0.064167  0.715142
16  0.831365  0.273890  0.130410  0.101777  0.840464  0.760616
17  0.831365  0.273890  0.130410  0.655391  0.289537  0.391893
18  0.831365  0.273890  0.130410  0.383729  0.061811  0.773627
19  0.831365  0.273890  0.130410  0.575711  0.995151  0.804567
20  0.447640  0.848283  0.627224  0.991311  0.064167  0.715142
21  0.447640  0.848283  0.627224  0.101777  0.840464  0.760616
22  0.447640  0.848283  0.627224  0.655391  0.289537  0.391893
23  0.447640  0.848283  0.627224  0.383729  0.061811  0.773627
24  0.447640  0.848283  0.627224  0.575711  0.995151  0.804567

How to handle the new window in Selenium WebDriver using Java?

I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

For me, ASP.NET 5 is not yet required, I removed update, and then reinstalled ASP.NET 4.5. It's a bit tricky:

  1. Removed from control panel "Microsoft ASP.NET 5 RC1 Update1". After that, you will no longer open ASP.NET MVC projects
  2. Then I changed the installation of "Microsoft Visual Studio Professional 2015", clicked "Modify", and selected "Microsoft Web Developer Tools"

No longer follow the notification of update in Visual Studio 2015!!!

Equivalent to AssemblyInfo in dotnet core/csproj

Those settings has moved into the .csproj file.

By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package tab.

Project properties, tab Package

Once saved those values can be found in MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <Version>1.2.3.4</Version>
    <Authors>Author 1</Authors>
    <Company>Company XYZ</Company>
    <Product>Product 2</Product>
    <PackageId>MyApp</PackageId>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
    <FileVersion>3.0.0.0</FileVersion>
    <NeutralLanguage>en</NeutralLanguage>
    <Description>Description here</Description>
    <Copyright>Copyright</Copyright>
    <PackageLicenseUrl>License URL</PackageLicenseUrl>
    <PackageProjectUrl>Project URL</PackageProjectUrl>
    <PackageIconUrl>Icon URL</PackageIconUrl>
    <RepositoryUrl>Repo URL</RepositoryUrl>
    <RepositoryType>Repo type</RepositoryType>
    <PackageTags>Tags</PackageTags>
    <PackageReleaseNotes>Release</PackageReleaseNotes>
  </PropertyGroup>

In the file explorer properties information tab, FileVersion is shown as "File Version" and Version is shown as "Product version"

Uncaught TypeError: Cannot read property 'appendChild' of null

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src="script.js" defer></script>

How to use OKHTTP to make a post request?

  1. Add the following to the build.gradle

compile 'com.squareup.okhttp3:okhttp:3.7.0'

  1. Create a new thread, in the new thread add the following code.
OkHttpClient client = new OkHttpClient();
MediaType MIMEType= MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create (MIMEType,"{}");
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

How do I detect when someone shakes an iPhone?

Add Following methods in ViewController.m file, its working properly

    -(BOOL) canBecomeFirstResponder
    {
         /* Here, We want our view (not viewcontroller) as first responder 
         to receive shake event message  */

         return YES;
    }

    -(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
            if(event.subtype==UIEventSubtypeMotionShake)
            {
                    // Code at shake event

                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Motion" message:@"Phone Vibrate"delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                    [alert show];
                    [alert release];

                    [self.view setBackgroundColor:[UIColor redColor]];
             }
    }
    - (void)viewDidAppear:(BOOL)animated
    {
             [super viewDidAppear:animated];
             [self becomeFirstResponder];  // View as first responder 
     }

How to clear a textbox using javascript

just get element using

   function name()
   {  
   document.getElementById('elementid').value = "";
   }

you can call this function on onfocus event of textbox and clear the value

Group array items using object

Start by creating a mapping of group names to values. Then transform into your desired format.

_x000D_
_x000D_
var myArray = [_x000D_
    {group: "one", color: "red"},_x000D_
    {group: "two", color: "blue"},_x000D_
    {group: "one", color: "green"},_x000D_
    {group: "one", color: "black"}_x000D_
];_x000D_
_x000D_
var group_to_values = myArray.reduce(function (obj, item) {_x000D_
    obj[item.group] = obj[item.group] || [];_x000D_
    obj[item.group].push(item.color);_x000D_
    return obj;_x000D_
}, {});_x000D_
_x000D_
var groups = Object.keys(group_to_values).map(function (key) {_x000D_
    return {group: key, color: group_to_values[key]};_x000D_
});_x000D_
_x000D_
var pre = document.createElement("pre");_x000D_
pre.innerHTML = "groups:\n\n" + JSON.stringify(groups, null, 4);_x000D_
document.body.appendChild(pre);
_x000D_
_x000D_
_x000D_

Using Array instance methods such as reduce and map gives you powerful higher-level constructs that can save you a lot of the pain of looping manually.

Android Completely transparent Status Bar?

All one need is to go into MainActivity.java


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

        Window g = getWindow();
        g.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        setContentView(R.layout.activity_main);

    }

Android widget: How to change the text of a button

//text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" text button" />

// color text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/color text"/>

// background button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/ background button"/>

// text size button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:textSize="text size"/>

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

How can I add or update a query string parameter?

Based on the answer @ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:

function updateQueryString(key, value, options) {
    if (!options) options = {};

    var url = options.url || location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;

    hash = url.split('#');
    url = hash[0];
    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            url = url.replace(re, '$1' + key + "=" + value + '$2$3');
        } else {
            url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
        }
    } else if (typeof value !== 'undefined' && value !== null) {
        var separator = url.indexOf('?') !== -1 ? '&' : '?';
        url = url + separator + key + '=' + value;
    }

    if ((typeof options.hash === 'undefined' || options.hash) &&
        typeof hash[1] !== 'undefined' && hash[1] !== null)
        url += '#' + hash[1];
    return url;
}

Call it like this:

updateQueryString('foo', 'bar', {
    url: 'http://my.example.com#hash',
    hash: false
});

Results in:

http://my.example.com?foo=bar

How can I add new item to the String array?

You can't. A Java array has a fixed length. If you need a resizable array, use a java.util.ArrayList<String>.

BTW, your code is invalid: you don't initialize the array before using it.

Why and when to use angular.copy? (Deep Copy)

I would say angular.copy(source); in your situation is unnecessary if later on you do not use is it without a destination angular.copy(source, [destination]);.

If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

https://docs.angularjs.org/api/ng/function/angular.copy

How to describe "object" arguments in jsdoc?

There's a new @config tag for these cases. They link to the preceding @param.

/** My function does X and Y.
    @params {object} parameters An object containing the parameters
    @config {integer} setting1 A required setting.
    @config {string} [setting2] An optional setting.
    @params {MyClass~FuncCallback} callback The callback function
*/
function(parameters, callback) {
    // ...
};

/**
 * This callback is displayed as part of the MyClass class.
 * @callback MyClass~FuncCallback
 * @param {number} responseCode
 * @param {string} responseMessage
 */

Java: How can I compile an entire directory structure of code ?

You'd have to use something like Ant to do this hierarchically:

http://ant.apache.org/manual/Tasks/javac.html

You'll need to create a build script with a target called compile containing the following:

<javac sourcepath="" srcdir="${src}"
         destdir="${build}" >
    <include name="**/*.java"/>
</javac>

Then you''ll be able to compile all files by running:

 ant compile

Alternatively, import your project into Eclipse and it will automatically compile all the source files for that project.

MySQL with Node.js

You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb.

-- create this file at: db/mdb/setup/create.database.sql
CREATE DATABASE IF NOT EXISTS sqlermysql
const conf = {
  "univ": {
    "db": {
      "mdb": {
        "host": "localhost",
        "username":"admin",
        "password": "mysqlpassword"
      }
    }
  },
  "db": {
    "dialects": {
      "mdb": "sqler-mdb"
    },
    "connections": [
      {
        "id": "mdb",
        "name": "mdb",
        "dir": "db/mdb",
        "service": "MySQL",
        "dialect": "mdb",
        "pool": {},
        "driverOptions": {
          "connection": {
            "multipleStatements": true
          }
        }
      }
    ]
  }
};

// create/initialize manager
const manager = new Manager(conf);
await manager.init();

// .sql file path is path to db function
const result = await manager.db.mdb.setup.create.database();

console.log('Result:', result);

// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
  await manager.close();
  console.log('Manager has been closed');
});

Make elasticsearch only return certain fields?

Here is another solution, now using a match expression

Source filtering allows to control how the _source field is returned with every hit.

Tested with Elastiscsearch version 5.5

The keyword includes defines the specifics fields.

GET /my_indice/my_indice_type/_search
{
  "_source": {
    "includes": [
      "my_especific_field"
    ]
  },
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "_id": "%my_id_here_without_percent%"
          }
        }
      ]
    }
  }
}

Javascript foreach loop on associative array object

If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

_x000D_
_x000D_
const h = {_x000D_
  a: 1,_x000D_
  b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
_x000D_
_x000D_

in this example, forEach uses Destructuring assignment of an array.

Download and install an ipa from self hosted url on iOS

More simply you can utilize DropBox for this. The steps basically remain the same. You can do the following-:

1) upload your .ipa to dropBox, Share the link for this .ipa

2) Paste the shared link for .ipa in your manifest.plist file , Upload manifest file in DropBox again share the link for this .plist file

3)paste the link for this Plist in your index.html file with a suitable tag.

Share this index.html file with anybody who can tap on the URL and download. or you can directly hit the URL instead.

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

Move existing, uncommitted work to a new branch in Git

3 Steps to Commit your changes

Suppose you have created a new branch on GitHub with the name feature-branch.

enter image description here

FETCH

    git pull --all         Pull all remote branches
    git branch -a          List all branches now

Checkout and switch to the feature-branch directory. You can simply copy the branch name from the output of branch -a command above

git checkout -b feature-branch

VALIDATE

Next use the git branch command to see the current branch. It will show feature-branch with * In front of it

git branch         

COMMIT

git add .   add all files
git commit -m "Rafactore code or use your message"

Take update and the push changes on the origin server

 git pull origin feature-branch
 git push origin feature-branch

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

In Python try until no error

Here is one that hard fails after 4 attempts, and waits 2 seconds between attempts. Change as you wish to get what you want form this one:

from time import sleep

for x in range(0, 4):  # try 4 times
    try:
        # msg.send()
        # put your logic here
        str_error = None
    except Exception as str_error:
        pass

    if str_error:
        sleep(2)  # wait for 2 seconds before trying to fetch the data again
    else:
        break

Here is an example with backoff:

from time import sleep

sleep_time = 2
num_retries = 4
for x in range(0, num_retries):  
    try:
        # put your logic here
        str_error = None
    except Exception as str_error:
        pass

    if str_error:
        sleep(sleep_time)  # wait before trying to fetch the data again
        sleep_time *= 2  # Implement your backoff algorithm here i.e. exponential backoff
    else:
        break

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors.

MySQL: selecting rows where a column is null

There's also a <=> operator:

SELECT pid FROM planets WHERE userid <=> NULL

Would work. The nice thing is that <=> can also be used with non-NULL values:

SELECT NULL <=> NULL yields 1.

SELECT 42 <=> 42 yields 1 as well.

See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

Getting the first and last day of a month, using a given DateTime object

Here you can add one month for the first day of current month than delete 1 day from that day.

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

How do I sort a Set to a List in Java?

List myList = new ArrayList(collection);
Collections.sort(myList);

… should do the trick however. Add flavour with Generics where applicable.

Python function attributes - uses and abuses

I use them sparingly, but they can be pretty convenient:

def log(msg):
   log.logfile.write(msg)

Now I can use log throughout my module, and redirect output simply by setting log.logfile. There are lots and lots of other ways to accomplish that, but this one's lightweight and dirt simple. And while it smelled funny the first time I did it, I've come to believe that it smells better than having a global logfile variable.

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

Convert nullable bool? to bool

This answer is for the use case when you simply want to test the bool? in a condition. It can also be used to get a normal bool. It is an alternative I personnaly find easier to read than the coalescing operator ??.

If you want to test a condition, you can use this

bool? nullableBool = someFunction();
if(nullableBool == true)
{
    //Do stuff
}

The above if will be true only if the bool? is true.

You can also use this to assign a regular bool from a bool?

bool? nullableBool = someFunction();
bool regularBool = nullableBool == true;

witch is the same as

bool? nullableBool = someFunction();
bool regularBool = nullableBool ?? false;

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

Including another class in SCSS

Looks like @mixin and @include are not needed for a simple case like this.

One can just do:

.myclass {
  font-weight: bold;
  font-size: 90px;
}

.myotherclass {
  @extend .myclass;
  color: #000000;
}

CKEditor instance already exists

I chose to rename all instances instead of destroy/replace - since sometimes the AJAX loaded instance doesn't really replace the one on the core of the page... keeps more in RAM, but less conflict this way.

    if (CKEDITOR && CKEDITOR.instances) {
        for (var oldName in CKEDITOR.instances) {
            var newName = "ajax"+oldName;
            CKEDITOR.instances[newName] = CKEDITOR.instances[oldName];
            CKEDITOR.instances[newName].name = newName;
            delete CKEDITOR.instances[oldName];
        }
    }

How do I set up Visual Studio Code to compile C++ code?

If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json like below:

{
    "version": "0.1.0",
    "command": "sh",
    "isShellCommand": true,
    "args": ["-c"],
    "showOutput": "always",
    "suppressTaskName": true,
    "options": {
        "cwd": "${workspaceRoot}/build"
    },
    "tasks": [
        {
            "taskName": "cmake",
            "args": ["cmake ."]
        },
        {
            "taskName": "make",
            "args" : ["make"],
            "isBuildCommand": true,
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": "absolute",
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

This assumes that there is a folder build in the root of the workspace with a CMake configuration.

There's also a CMake integration extension that adds a "CMake build" command to VScode.

PS! The problemMatcher is setup for clang-builds. To use GCC I believe you need to change fileLocation to relative, but I haven't tested this.

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument size= in geom_line().

#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

enter image description here

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

How to `wget` a list of URLs in a text file?

Quick man wget gives me the following:

[..]

-i file

--input-file=file

Read URLs from a local or external file. If - is specified as file, URLs are read from the standard input. (Use ./- to read from a file literally named -.)

If this function is used, no URLs need be present on the command line. If there are URLs both on the command line and in an input file, those on the command lines will be the first ones to be retrieved. If --force-html is not specified, then file should consist of a series of URLs, one per line.

[..]

So: wget -i text_file.txt

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I like the Aptana Browser Preview windo for this.

You can get it from their update site: http://download.aptana.org/tools/studio/plugin/update/studio/

After you install the Aptana plugin, open an Aptana project and there should be an option under help to install aptana features. under other you will find a Firefox/XUL browser. There may be a more direct way to install the XUL plugin, but the above procedure works.

VBA code to set date format for a specific column as "yyyy-mm-dd"

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

How do you count the lines of code in a Visual Studio solution?

An open source line counter for VS2005, 2003 and 2002 is available here:

http://www.wndtabs.com/

There is also discussion of creating a line counting VS addin, complete with code on Codeproject, here

http://www.codeproject.com/KB/macros/LineCounterAddin.aspx

Also Slick Edit Gadgets have a nice line-counter, here:

http://www.slickedit.com/products/slickedit

and Microsoft Visual Studio Team System 2008 includes a good line counter.

Just remember though:

Measuring programming progress by lines of code is like measuring aircraft building progress by weight. Bill Gates

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

how can I debug a jar at runtime?

With IntelliJ IDEA you can create a Jar Application runtime configuration, select the JAR, the sources, the JRE to run the Jar with and start debugging. Here is the documentation.

Integer division: How do you produce a double?

Just add "D".

int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D

Is Android using NTP to sync time?

I know about Android ICS that it uses a custom service called: NetworkTimeUpdateService. This service also implements a NTP time synchronization via the NtpTrustedTime singleton.

In NtpTrustedTime the default NTP server is requested from the Android system string source:

final Resources res = context.getResources();

final String defaultServer = res.getString(
                                com.android.internal.R.string.config_ntpServer);

If the automatic time sync option in the system settings is checked and no NITZ time service is available then the time will be synchronized with the NTP server from com.android.internal.R.string.config_ntpServer.

To get the value of com.android.internal.R.string.config_ntpServer you can use the following method:

    final Resources res = this.getResources();
    final int id = Resources.getSystem().getIdentifier(
                       "config_ntpServer", "string","android");
    final String defaultServer = res.getString(id);

How to upgrade pip3?

If you try to run

sudo -H pip3 install --upgrade pip3 

you will get the following error:

WARNING: You are using pip version 19.2.3, however version 21.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

but if you upgrade using the suggested command:

pip install --upgrade pip

then, the legacy pip will be upgraded, so what I did is the following:

which pip3

and I located my pip3 installation (just in case the following command wouldn't upgrade the legacy pip. Then i changed to that directory and upgraded pip3 using the following commands: (your directory could be different)

cd /Library/Frameworks/Python.framework/Versions/3.8/bin
sudo -H pip3 install --upgrade pip

after this:

pip --version

will still show the legacy version, while

pip3 --version

will show pip 21.0.1

rand() returns the same number each time the program is run

You need to change the seed.

int main() {

    srand(time(NULL));
    cout << (rand() % 101);
    return 0;
}

the srand seeding thing is true also for a c language code.


See also: http://xkcd.com/221/