Programs & Examples On #Bho

A Browser Helper Object (BHO) is a DLL module designed as a plugin for Microsoft's Internet Explorer web browser (as well as Windows Explorer) to provide added functionality.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

After upgrading from 4.6.1 framework to 4.7.2 we started getting this error:

"The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'." and ultimately the solution was to add the "netstandard" assembly reference mentioned above:

<compilation debug="true" targetFramework="4.7.1" >
    <assemblies>
      <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
            PublicKeyToken=cc7b13ffcd2ddd51"/>
    </assemblies>
  </compilation>

How to use log4net in Asp.net core 2.0

I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.

When using "CreateRepository" there appears to be a difference between .net framework and .net standard.

Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config

GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);

Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config". It wasn't loading the previous known configuration. Once I added the configuration to the configurator it still didn't log, while not complaining about it either.

To get it working under .Net Standard with similar behavior as before, this is what I did.

var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");

I didn't want to create a configuration file for every repo, so this works. Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.

Unable to create migrations after upgrading to ASP.NET Core 2.0

I had same problem. Just changed the ap.jason to application.jason and it fixed the issue

No Network Security Config specified, using platform default - Android Log

I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.

android:usesCleartextTraffic="true"

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

In your PHP code you have set the incorrect port, this is what the code should be

<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

The port in your code is set to 3360 when it should be 3306, however as this is the default port, you don't need to specify.

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

4.6.1-2 in VS2017 users may experience the unwanted replacement of their version of System.Net.Http by the one VS2017 or Msbuild 15 wants to use.

We deleted this version here:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.Net.Http.dll

and here:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.Net.Http.dll

Then the project builds with the version we have referenced via NuGet.

How to specify the port an ASP.NET Core application is hosted on?

On .Net Core 3.1 just follow Microsoft Doc that it is pretty simple: kestrel-aspnetcore-3.1

To summarize:

  1. Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs:

    // using Microsoft.Extensions.DependencyInjection;
    
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                services.Configure<KestrelServerOptions>(
                    context.Configuration.GetSection("Kestrel"));
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    
  2. Add the below basic config to appsettings.json file (more config options on Microsoft article):

    "Kestrel": {
        "EndPoints": {
            "Http": {
                "Url": "http://0.0.0.0:5002"
            }
        }
    }
    
  3. Open CMD or Console on your project Publish/Debug/Release binaries folder and run:

    dotnet YourProject.dll
    
  4. Enjoy exploring your site/api at your http://localhost:5002

The target principal name is incorrect. Cannot generate SSPI context

I had this problem when accessing the web application. It might be due to i have changed a windows password recently.

This issue got resolved when i have updated the password for the app pool where i have hosted the web application.

How to get 'System.Web.Http, Version=5.2.3.0?

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Then in the project Add Reference -> Browse. Push the browse button and go to the C:\Users\UserName\Documents\Visual Studio 2015\Projects\ProjectName\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45 and add the needed .dll file

Git push error pre-receive hook declined

GitLab by default marks master branch as protected (See part Protecting your code in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:

Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.

via https://gitlab.com/gitlab-com/support-forum/issues/40

For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users

Oracle listener not running and won't start

I solved it by updating listener.ora file inside oracle directory oraclexe\app\oracle\product\11.2.0\server\network\ADMIN.

Why did it happen to me was because I changed my system name but inside listener.ora there was old name for HOST.

This might be one of the reasons... for those who still face such issue might think of this possibility as well.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

The following works perfectly:-

if(isset($_POST['signup'])){
$username=mysqli_real_escape_string($connect,$_POST['username']);
$email=mysqli_real_escape_string($connect,$_POST['email']);
$pass1=mysqli_real_escape_string($connect,$_POST['pass1']);
$pass2=mysqli_real_escape_string($connect,$_POST['pass2']);

Now, the $connect is my variable containing my connection to the database. You only left out the connection variable. Include it and it shall work perfectly.

The listener supports no services

Check local_listener definition in your spfile or pfile. In my case, the problem was with pfile, I had moved the pfile from a similar environment and it had LISTENER_sid as LISTENER and not just LISTENER.

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I just had same issue when I installed the oracle 11g and then creating the database.

I don't even know that the listener has to create manually. Hence, I open Net Configuration Assistant and manually create the listener.

And I can connect the database that I created locally through sql developer.

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;

or maybe

shutdown abort;

or maybe

lsnrctl stop

lsnrctl start

Couldn't load memtrack module Logcat Error

I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

This happened to me on VS2013(Update 5)/ASP.NET 4.5, under project type "Web Application" that includes MVC and Web API 2. Error happened right after creating the project and before adding any code. Adding the following configuration fix it for me. After resolving "System.Web.Helpers" issue two more similar errors surfaced for "System.Web.Mvc" and "System.Web.WebPages".

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>

How to Get the HTTP Post data in C#?

Try this

string[] keys = Request.Form.AllKeys;
var value = "";
for (int i= 0; i < keys.Length; i++) 
{
   // here you get the name eg test[0].quantity
   // keys[i];
   // to get the value you use
   value = Request.Form[keys[i]];
}

Using intents to pass data between activities

Pass the data from Activity-1 to AndroidTabRes.. as below:

At sending activity...

Intent intent = new Intent(current.this, AndroidTabRestaurantDescSearchListView.class);
intent.putExtra("keyName","value");
startActivity(intent);

At AndroidTabRes.. activity...

  String data = getIntent().getExtras().getString("keyName");

Thus you can have data at receiving activity from sending activity...

And in your AndroidTabRestaurantDescSearchListView class, do this:

String value= getIntent().getStringExtra("keyName");

Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);

Then in your RatingDescriptionSearchActivity class, do this:

 String data= getIntent().getStringExtra("keyName");

Update MySQL using HTML Form and PHP

Update query may have some issues

$query = "UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ";
echo $query;

Please make sure that, your variable not having values with qoutes ( ' ), May be the query is breaking somewhere.

echo the query and try to execute in phpmyadmin itself. Then you can find the issues.

PDO with INSERT INTO through prepared statements

Thanks to Novocaine88's answer to use a try catch loop I have successfully received an error message when I caused one.

    <?php
    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    try {
        $statement = $link->prepare("INERT INTO testtable(name, lastname, age)
            VALUES(?,?,?)");

        $statement->execute(array("Bob","Desaunois",18));
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    ?>

In the following code instead of INSERT INTO it says INERT.

this is the error I got.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunoi' at line 1

When I "fix" the issue, it works as it should. Thanks alot everyone!

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Writing html form data to a txt file without the use of a webserver

Something like this?

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">Please type in this box. When you 

click the Download button, the contents of this box will be downloaded to 

your machine at the location you specify. Pretty nifty. </textarea>
  <input type="submit" value="Download">
</form>
</body>
</html>

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Try this, instead of selecting your websete's Application Pool to DefaultAppPool, select ASP.NET v4.0

Select your website in IIS => Basic Settings => Application Pool => Select ASP.NET v4.0

and you will be good to go. Hope it helps :)

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

If this is the code you have, then you will get an error because, you are reassigning $row while in the loop, so you would never be able to iterate over the results. Replace

$rows = $rows['Name'];

with

$name = $rows['Name']'

So your code would look like

WHILE ($rows = mysql_fetch_array($query)):

   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment'];

Also I am assuming that the column names in the table users are Name, Address, Email etc. and not name,address, email. Remember that every variable name/field nameh is case sensitive.

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

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

After installing Microsoft.Web.Infrastructure through Nuget-Package Manager

PM> Install-Package Microsoft.Web.Infrastructure

Copy the Microsoft.Web.Infrastructure.dll manually from the Nuget-Package folder on your web application and then paste it in your bin folder of your web application deployed on the web server.

packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll

It worked for me.

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

Tomcat is not deploying my web project from Eclipse

I fixed this issue, this way:

  1. Stop the Server
  2. Remove the previous Deploy that You did
  3. Clean it
  4. Deploy it again

How to use PDO to fetch results array in PHP?

$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10"); 

How to avoid using Select in Excel VBA

Working with the .Parent feature, this example shows how setting only one myRng reference enables dynamic access to the entire environment without any .Select, .Activate, .Activecell, .ActiveWorkbook, .ActiveSheet and so on. (There isn't any generic .Child feature.)

Sub ShowParents()
    Dim myRng As Range
    Set myRng = ActiveCell
    Debug.Print myRng.Address                    ' An address of the selected cell
    Debug.Print myRng.Parent.name                ' The name of sheet, where MyRng is in
    Debug.Print myRng.Parent.Parent.name         ' The name of workbook, where MyRng is in
    Debug.Print myRng.Parent.Parent.Parent.name  ' The name of application, where MyRng is in

    ' You may use this feature to set reference to these objects
    Dim mySh  As Worksheet
    Dim myWbk As Workbook
    Dim myApp As Application

    Set mySh = myRng.Parent
    Set myWbk = myRng.Parent.Parent
    Set myApp = myRng.Parent.Parent.Parent
    Debug.Print mySh.name, mySh.Cells(10, 1).Value
    Debug.Print myWbk.name, myWbk.Sheets.Count
    Debug.Print myApp.name, myApp.Workbooks.Count

    ' You may use dynamically addressing
    With myRng
        .Copy

        ' Pastes in D1 on sheet 2 in the same workbook, where the copied cell is
        .Parent.Parent.Sheets(2).Range("D1").PasteSpecial xlValues

        ' Or myWbk.Sheets(2).Range("D1").PasteSpecial xlValues

        ' We may dynamically call active application too
        .Parent.Parent.Parent.CutCopyMode = False

        ' Or myApp.CutCopyMode = False
    End With
End Sub

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

java.lang.RuntimeException: Unable to start activity ComponentInfo

I had the same issue, I cleaned and rebuilt the project and it worked.

How can I set the focus (and display the keyboard) on my EditText programmatically

I finally figured out a solution and create a Kotlin class for it

object KeyboardUtils {

    fun showKeyboard(editText: EditText) {
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideKeyboard(editText: EditText) {
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

}

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

If you are doing some FragmentTransaction in onActivityResult what you can do you can set some boolean value inside onActivityResult then in onResume you can do your FragmentTransaction on the basis of the boolean value. Please refer the code below.

@Override
protected void onResume() {
    super.onResume;
    if(isSwitchFragment){
        isSwitchFragment=false;
        bottomNavigationView.getTabAt(POS_FEED).select();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == FilterActivity.FILTER_REQUEST_EVENT && data != null) {
        isSwitchFragment=true;
    }
}

Getting RSA private key from PEM BASE64 Encoded private key file

As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec needs to understand it. If you don't want to convert the key using openssl pkcs8 or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:

static final Base64.Decoder DECODER = Base64.getMimeDecoder();

private static byte[] buildPKCS8Key(File privateKey) throws IOException {
  final String s = new String(Files.readAllBytes(privateKey.toPath()));
  if (s.contains("--BEGIN PRIVATE KEY--")) {
    return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
  }
  if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
    throw new RuntimeException("Invalid cert format: "+ s);
  }

  final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
  final byte[] result = new byte[innerKey.length + 26];
  System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
  System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
  System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
  System.arraycopy(innerKey, 0, result, 26, innerKey.length);
  return result;
}

Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

After wasting so much time i got to know that there was mistake in my syntax to connect with DB. I was using colon ":" instead of slash "/".

(1) if you use sid below is the syntax to get connection:

**"jdbc:oracle:thin:@{hostname}:{port}:{SID}"**

(2) if you use service name, below is the syntax to get connection:

"**jdbc:oracle:thin:@//{hostname}:{port}/{servicename}**"

ListView inside ScrollView is not scrolling on Android

For ListView inside ScrollView use NestedScrollView it can handle this functionality very easily:

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="5dip"/>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data

Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from

data = data.decode(encoding)

to

data = data.decode("ISO-8859-1")

solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.

jquery - is not a function error

I solved it by renaming my function.

Changed

function editForm(value)

to

function editTheForm(value)

Works perfectly.

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

How to redirect to another page using PHP

You can conditionally redirect to some page within a php file....

if (/*Condition to redirect*/){
  //You need to redirect
  header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
  exit();
 }
else{
  // do some
}

mysql server port number

If your MySQL server runs on default settings, you don't need to specify that.

Default MySQL port is 3306.

[updated to show mysql_error() usage]

$conn = mysql_connect($dbhost, $dbuser, $dbpass)
    or die('Error connecting to mysql: '.mysql_error());

php: Get html source code with cURL

Try the following:

$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.


EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).

what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.

//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch); 

Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();.

Python base64 data decode

import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)

worked for me. At the risk of pasting an offensively-long result, I got:

>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'

What problem are you having, specifically?

How to read XML using XPath in Java

Getting started example:

xml file:

<inventory>
    <book year="2000">
        <title>Snow Crash</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553380958</isbn>
        <price>14.95</price>
    </book>

    <book year="2005">
        <title>Burning Tower</title>
        <author>Larry Niven</author>
        <author>Jerry Pournelle</author>
        <publisher>Pocket</publisher>
        <isbn>0743416910</isbn>
        <price>5.99</price>
    </book>

    <book year="1995">
        <title>Zodiac</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553573862</isbn>
        <price>7.50</price>
    </book>

    <!-- more books... -->

</inventory>

Java code:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


try {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("c:\\tmp\\my.xml"));

    // normalize text representation
    doc.getDocumentElement().normalize();
    System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

    NodeList listOfBooks = doc.getElementsByTagName("book");
    int totalBooks = listOfBooks.getLength();
    System.out.println("Total no of books : " + totalBooks);

    for(int i=0; i<listOfBooks.getLength() ; i++) {

        Node firstBookNode = listOfBooks.item(i);
        if(firstBookNode.getNodeType() == Node.ELEMENT_NODE) {

            Element firstElement = (Element)firstBookNode;                              
            System.out.println("Year :"+firstElement.getAttribute("year"));

            //-------
            NodeList firstNameList = firstElement.getElementsByTagName("title");
            Element firstNameElement = (Element)firstNameList.item(0);

            NodeList textFNList = firstNameElement.getChildNodes();
            System.out.println("title : " + ((Node)textFNList.item(0)).getNodeValue().trim());
        }
    }//end of for loop with s var
} catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
} catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
} catch (Throwable t) {
    t.printStackTrace ();
}                

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
finish();

I hope that will be helpful if someone looks for this problem workaround again.

Android: How to detect double-tap?

This is a solution that wait if there is a second clic before executing any action

  int init = 0;
  myView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            if (init == 0) {
                init++;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {



                        if (init == 1) {
                            Log.d("hereGoes", "actionOne");
                        } else {
                            Log.d("hereGoes", "actionTwo");
                        }


                        init = 0;
                    }
                }, 250);
            } else {
                init++;
            }

        }
    });

Connecting to remote MySQL server using PHP

I just solved this kind of a problem. What I've learned is:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

you should be able to now connect mysql server form your client server php script.

Test if string is URL encoded in PHP

I think there's no foolproof way to do it. For example, consider the following:

$t = "A+B";

Is that an URL encoded "A B" or does it need to be encoded to "A%2BB"?

MySQL - force not to use cache for testing speed of query

Any reference to current date/time will disable the query cache for that selection:

SELECT *,NOW() FROM TABLE

See "Prerequisites and Notes for MySQL Query Cache Use" @ http://dev.mysql.com/tech-resources/articles/mysql-query-cache.html

What exactly should be set in PYTHONPATH?

Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:

% python3 -c "import sys;print(sys.path)"
['', 
'/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

where the first path '' denotes the current dir., the 2nd path is via

%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite 

which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.

As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:

% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)

Note that if you start a Python script, the CWD will be the script's directory. For example:

username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:

username@bud:~/Documents/DjangoTutorial% python3 
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', 
'/home/username/Documents']
>>> from Python import Fibonacci as fibo

or via

% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['', 
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo

How to use radio buttons in ReactJS?

Any changes to the rendering should be change via the state or props (react doc).

So here I register the event of the input, and then change the state, which will then trigger the render to show on the footer.

var SearchResult = React.createClass({
  getInitialState: function () {
    return {
      site: '',
      address: ''
    };
  },
  onSiteChanged: function (e) {
    this.setState({
      site: e.currentTarget.value
      });
  },

  onAddressChanged: function (e) {
    this.setState({
      address: e.currentTarget.value
      });
  },

  render: function(){
       var resultRows = this.props.data.map(function(result){
           return (
               <tbody>
                    <tr>
                        <td><input type="radio" name="site_name" 
                                   value={result.SITE_NAME} 
                                   checked={this.state.site === result.SITE_NAME} 
                                   onChange={this.onSiteChanged} />{result.SITE_NAME}</td>
                        <td><input type="radio" name="address" 
                                   value={result.ADDRESS}  
                                   checked={this.state.address === result.ADDRESS} 
                                   onChange={this.onAddressChanged} />{result.ADDRESS}</td>
                    </tr>
               </tbody>
           );
       }, this);
       return (
           <table className="table">
               <thead>
                   <tr>
                       <th>Name</th>
                       <th>Address</th>
                   </tr>
               </thead>
                {resultRows}
               <tfoot>
                   <tr>
                       <td>chosen site name {this.state.site} </td>
                       <td>chosen address {this.state.address} </td>
                   </tr>
               </tfoot>
           </table>
       );
  }
});

jsbin

JAVA_HOME is set to an invalid directory:

Try the following:

  • Remove \bin from JAVA_HOME path.
  • Open new command line window.
  • Run your command as an administrator.

T-SQL and the WHERE LIKE %Parameter% clause

you may try this one, used CONCAT

WHERE LastName LIKE Concat('%',@LastName,'%')

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Execute PHP scripts within Node.js web server

Node.js only supports JavaScript. Here is a tutorial on how to have PHP running with Node.js on the side.

http://blog.mixu.net/2011/01/04/nginx-php-fpm-and-node-js-install-on-centos-5-5/

Differences between SP initiated SSO and IDP initiated SSO

IDP Initiated SSO

From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html

In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.

Processing Steps:

  1. A user has logged on to the IdP.
  2. The user requests access to a protected SP resource. The user is not logged on to the SP site.
  3. Optionally, the IdP retrieves attributes from the user data store.
  4. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP.

SP Initiated SSO

From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST

In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.

Processing Steps:

  1. The user requests access to a protected SP resource. The request is redirected to the federation server to handle authentication.
  2. The federation server sends an HTML form back to the browser with a SAML request for authentication from the IdP. The HTML form is automatically posted to the IdP’s SSO service.
  3. If the user is not already logged on to the IdP site or if re-authentication is required, the IdP asks for credentials (e.g., ID and password) and the user logs on.
  4. Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)

  5. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.

  6. (Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Import SQL file by command line in Windows 7

mysql : < (for import) > (for export)

in windows, you want to take backup or import the sql file, then goto cmd prompt type the address were the mysql is installed eg:C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> after this

C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> mysql -u UserName -p Password DatabaseName < FileName.sql (import)

C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> mysql -u UserName -p Password DatabaseName > FileName.sql (export)

Oracle copy data to another table

If you want to create table with data . First create the table :

create table new_table as ( select * from old_table); 

and then insert

insert into new_table ( select * from old_table);

If you want to create table without data . You can use :

create table new_table as ( select * from old_table where 1=0);

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
    {
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
    
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
    
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
    
        //check for double squares
        if (oW == oH && dW == dH)
        {
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            original.Dispose();
            return square;
        }
    
        //check original image is square
        if (oW == oH)
        {
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            original.Dispose();
            return square;
        }
    
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
        {
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            original.Dispose();
            return resized;
        }
        else
        {
            if (oW > dW) //image is wider than bounding box
            {
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
            else
            {
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
        }
    }
    

Why does Eclipse Java Package Explorer show question mark on some classes?

It sounds like you're using Subclipse; is that correct? If so, there's a great list of decorators and their descriptions at this answer by Tim Stone.

Here's the relevant snippet for your case:

Unversioned File - A file not under version control. These are typically new files that you have not committed to the repository yet.
Synchronized File - A file with no local changes.

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Where do I find old versions of Android NDK?

Simply replacing .bin with .tar.bz2 is not enough, for NDK releases older than 10b. For example, https://dl.google.com/android/ndk/android-ndk-r10b-linux-x86_64.tar.bz2 is not a valid link.

Turned out that the correct link for 10b was: https://dl.google.com/android/ndk/android-ndk32-r10b-linux-x86_64.tar.bz2 (note the additional '32'). However, this doesn't seem to apply to e.g. 10a, as this link doesn't work: https://dl.google.com/android/ndk/android-ndk32-r10a-linux-x86_64.tar.bz2 .

Bottom line: use http://web.archive.org until Google fixes this, if ever...

How to use C++ in Go

You can't quite yet from what I read in the FAQ:

Do Go programs link with C/C++ programs?

There are two Go compiler implementations, gc (the 6g program and friends) and gccgo. Gc uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. Gccgo is a GCC front-end that can, with care, be linked with GCC-compiled C or C++ programs.

The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.

Global approach

Configure Git line endings handling on Linux or OS X:

git config --global core.autocrlf input

Configure Git line endings handling on Windows:

git config --global core.autocrlf true

Per-repo approach:

In the root of your repo, create a .gitattributes file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings where line-ending-settings is one of the following:

  • text
  • binary (files that Git should not modify line endings for - as this can cause some image types such as PNGs not to render in a browser)

The text value can be configured further to instruct Git on how to handle line endings for matching files:

  • text - Changes line endings to OS native line endings.
  • text eol=crlf - Converts line endings to CRLF on checkout.
  • text eol=lf - Converts line endings to LF on checkout.
  • text=auto - Sensible default that leaves line handle up to Git's discretion.

Here is the content of a sample .gitattributes file:

# Set the default behavior for all files.
* text=auto

# Normalized and converts to 
# native line endings on checkout.
*.c text
*.h text

# Convert to CRLF line endings on checkout.
*.sln text eol=crlf

# Convert to LF line endings on checkout.
*.sh text eol=lf

# Binary files.
*.png binary
*.jpg binary

More on how to refresh your repo after changing line endings settings here. Tldr:

backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.

git add . -u

git commit -m "Saving files before refreshing line endings"

Remove the index and force Git to rescan the working directory.

rm .git/index

Rewrite the Git index to pick up all the new line endings.

git reset

Show the rewritten, normalized files.

In some cases, this is all that needs to be done. Others may need to complete the following additional steps:

git status

Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.

git add -u

It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."

Rewrite the .gitattributes file.

git add .gitattributes

Commit the changes to your repository.

git commit -m "Normalize all the line endings"

Foreign keys in mongo?

How to design table like this in mongodb?

First, to clarify some naming conventions. MongoDB uses collections instead of tables.

I think there are no foreign keys!

Take the following model:

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: [
    { course: 'bio101', mark: 85 },
    { course: 'chem101', mark: 89 }
  ]
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.

In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.

How can I solve this task?

To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.

Correct use of flush() in JPA/Hibernate

Actually, em.flush(), do more than just sends the cached SQL commands. It tries to synchronize the persistence context to the underlying database. It can cause a lot of time consumption on your processes if your cache contains collections to be synchronized.

Caution on using it.

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...

Location Services not working in iOS 8

        // ** Don't forget to add NSLocationWhenInUseUsageDescription in MyApp-Info.plist and give it a string

        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];


    // Location Manager Delegate Methods    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        NSLog(@"%@", [locations lastObject]);

}

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Change <select>'s option and trigger events with JavaScript

You can fire the event manually after changing the selected option on the onclick event doing: document.getElementById("sel").onchange();

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

Deleting all files from bin and then rebuilding the solution worked for me.

Change x axes scale in matplotlib

I find the simple solution

pylab.ticklabel_format(axis='y',style='sci',scilimits=(1,4))

Is there 'byte' data type in C++?

There's also byte_lite, compatible with C++98, C++11 and later.

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

What is <=> (the 'Spaceship' Operator) in PHP 7?

The <=> ("Spaceship") operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater

The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.

   //Comparing Integers

    echo 1 <=> 1; //output  0
    echo 3 <=> 4; //output -1
    echo 4 <=> 3; //output  1

    //String Comparison

    echo "x" <=> "x"; //output  0
    echo "x" <=> "y"; //output -1
    echo "y" <=> "x"; //output  1

Error Message : Cannot find or open the PDB file

  1. Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.

  2. Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .

  3. You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"

What USB driver should we use for the Nexus 5?

Everything else here failed for me initially (it kept coming up as an MTP device no matter how many times I uninstalled and restarted).

However, by going and enabling USB debugging, it worked. Just do this:

  1. Uninstall the Nexus 5 driver
  2. Disconnect from the computer
  3. Enable developer options, see How to Enable Developer Options on the Nexus 5 & KitKat.
  4. Enable USB debugging: Go to Settings -> Developer Options -> USB Debugging
  5. Reconnect
  6. It will probably fail to install all drivers. Go update the drivers as described in other answers.

How to get row number in dataframe in Pandas?

df.index[df.LastName == 'Smith']

Or

df.query('LastName == "Smith"').index

Will return all row indices where LastName is Smith

Int64Index([1], dtype='int64')

Using Mockito with multiple calls to the same method with the same arguments

You can even chain doReturn() method invocations like this

doReturn(null).doReturn(anotherInstance).when(mock).method();

cute isn't it :)

Extract the filename from a path

Just to complete the answer above that use .Net.

In this code the path is stored in the %1 argument (which is written in the registry under quote that are escaped: \"%1\" ). To retrieve it, we need the $arg (inbuilt arg). Don't forget the quote around $FilePath.

# Get the File path:  
$FilePath = $args
Write-Host "FilePath: " $FilePath

# Get the complete file name:
$file_name_complete = [System.IO.Path]::GetFileName("$FilePath")
Write-Host "fileNameFull :" $file_name_complete

# Get File Name Without Extension:
$fileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension("$FilePath")
Write-Host "fileNameOnly :" $fileNameOnly

# Get the Extension:
$fileExtensionOnly = [System.IO.Path]::GetExtension("$FilePath")
Write-Host "fileExtensionOnly :" $fileExtensionOnly

Get the Year/Month/Day from a datetime in php?

Use DateTime with DateTime::format()

$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');

Simplest way to download and unzip files in Node.js cross-platform?

yauzl is a robust library for unzipping. Design principles:

  • Follow the spec. Don't scan for local file headers. Read the central directory for file metadata.
  • Don't block the JavaScript thread. Use and provide async APIs.
  • Keep memory usage under control. Don't attempt to buffer entire files in RAM at once.
  • Never crash (if used properly). Don't let malformed zip files bring down client applications who are trying to catch errors.
  • Catch unsafe filenames entries. A zip file entry throws an error if its file name starts with "/" or /[A-Za-z]:// or if it contains ".." path segments or "\" (per the spec).

Currently has 97% test coverage.

How to delete from multiple tables in MySQL?

Since this appears to be a simple parent/child relationship between pets and pets_activities, you would be better off creating your foreign key constraint with a deleting cascade.

That way, when a pets row is deleted, the pets_activities rows associated with it are automatically deleted as well.

Then your query becomes a simple:

delete from `pets`
    where `order` > :order
      and `pet_id` = :pet_id

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Insert Data Into Temp Table with Query

This is possible. Try this way:

Create Global Temporary Table 
BossaDoSamba 
On Commit Preserve Rows 
As 
select ArtistName, sum(Songs) As NumberOfSongs 
 from Spotfy 
    where ArtistName = 'BossaDoSamba'
 group by ArtistName;

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How to get a list of user accounts using the command line in MySQL?

to avoid repetitions of users when they connect from different origin:

select distinct User from mysql.user;

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

javascript regular expression to check for IP addresses

A short RegEx: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$

Example

_x000D_
_x000D_
const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value) ? true : false);_x000D_
_x000D_
_x000D_
// valid_x000D_
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));_x000D_
console.log("isValidIp('110.234.52.124' ? ", isValidIp('110.234.52.124'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));_x000D_
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));_x000D_
_x000D_
// Invalid_x000D_
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));_x000D_
console.log("isValidIp('255') ? ", isValidIp('255'));_x000D_
console.log("isValidIp('y.y.y.y' ? ", isValidIp('y.y.y.y'));_x000D_
console.log(" isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));_x000D_
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));_x000D_
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));_x000D_
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
_x000D_
_x000D_
_x000D_

Make XAMPP / Apache serve file outside of htdocs folder

Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:


Virtual Hosts

  1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.
  2. Un-comment ~line 19 (NameVirtualHost *:80).
  3. Add your virtual host (~line 36):

    <VirtualHost *:80>
        DocumentRoot C:\Projects\transitCalculator\trunk
        ServerName transitcalculator.localhost
        <Directory C:\Projects\transitCalculator\trunk>
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>
    
  4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts).

  5. Add

    127.0.0.1 transitcalculator.localhost #transitCalculator
    

    to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).

  6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).
  7. Restart Apache.

Now you can access that directory by browsing to http://transitcalculator.localhost/.


Make an Alias

  1. Starting ~line 200 of your http.conf file, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.

  2. Find the <IfModule alias_module></IfModule> section (~line 300) and add

    Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
    

    (or whatever is relevant to your desires) below the Alias comment block, inside the module tags.


Change your document root

  1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).

  2. Edit ~line 203 to match your new location (in this case C:/Projects).


Notes:

  • You have to use forward slashes "/" instead of back slashes "\".
  • Don't include the trailing "/" at the end.
  • restart your server.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

Convert String to Calendar Object in Java

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

If don't like to add time picker, we can use just javascript for time part.

  var dateObj=new Date();
  var date = $.datepicker.formatDate('dd M yy', dateObj);
  var time  = dateObj.getHours()+":"+dateObj.getMinutes()+":"+dateObj.getSeconds(); 

  console.log(date," ",time);

Cross Browser Flash Detection in Javascript

View the source at http://whatsmy.browsersize.com (lines 14-120).

Here is the abstracted cross browser code on jsbin for flash detection only, works on: FF/IE/Safari/Opera/Chrome.

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

you may need to try

pip install --upgrade setuptools

you may also need to install Visual Studio 2015, and remember to choose to install Visual C++ 14.0 https://visualstudio.microsoft.com/visual-cpp-build-tools/

How to set child process' environment variable in Makefile

As MadScientist pointed out, you can export individual variables with:

export MY_VAR = foo  # Available for all targets

Or export variables for a specific target (target-specific variables):

my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz

my-target: dependency_1 dependency_2
  echo do something

You can also specify the .EXPORT_ALL_VARIABLES target to—you guessed it!—EXPORT ALL THE THINGS!!!:

.EXPORT_ALL_VARIABLES:

MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz

test:
  @echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3

see .EXPORT_ALL_VARIABLES

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

ios Upload Image and Text using HTTP POST

I can show you an example of uploading a .txt file to a server with NSMutableURLRequest and NSURLSessionUploadTask with help of a php script.

-(void)uploadFileToServer : (NSString *) filePath
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
[request setHTTPMethod:@"POST"]; 
[request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];

NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                      {
                                          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                          if (error || [httpResponse statusCode]!=202)
                                          {

                                              //Error
                                          }
                                          else
                                          {
                                             //Success
                                          }
                                          [defaultSession invalidateAndCancel];
                                      }];
[uploadTask resume];
}

php Script

<?php 
$request_body = @file_get_contents('php://input');
foreach (getallheaders() as $name => $value) 
{
    if ($FileName=="FileName") 
    {
        $header=$value;
        break;
    }
}   
$uploadedDir = "directory/";
@mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);  
?>       

Show constraints on tables command

The main problem with the validated answer is you'll have to parse the output to get the informations. Here is a query allowing you to get them in a more usable manner :

SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
    cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
    cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
    cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
    cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
    cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
    links.TABLE_NAME, links.COLUMN_NAME,
    cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.TABLE_NAME=cols.TABLE_NAME
    AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
    AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
    AND cols.TABLE_NAME="table"

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

What is the "double tilde" (~~) operator in JavaScript?

That ~~ is a double NOT bitwise operator.

It is used as a faster substitute for Math.floor() for positive numbers. It does not return the same result as Math.floor() for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).

How to downgrade to older version of Gradle

Got to

gradle-wrapper.properties

Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)

distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

Check if argparse optional argument is set or not

As @Honza notes is None is a good test. It's the default default, and the user can't give you a string that duplicates it.

You can specify another default='mydefaultvalue, and test for that. But what if the user specifies that string? Does that count as setting or not?

You can also specify default=argparse.SUPPRESS. Then if the user does not use the argument, it will not appear in the args namespace. But testing that might be more complicated:

args.foo # raises an AttributeError
hasattr(args, 'foo')  # returns False
getattr(args, 'foo', 'other') # returns 'other'

Internally the parser keeps a list of seen_actions, and uses it for 'required' and 'mutually_exclusive' testing. But it isn't available to you out side of parse_args.

How to echo print statements while executing a sql script

Just to make your script more readable, maybe use this proc:

DELIMITER ;;

DROP PROCEDURE IF EXISTS printf;
CREATE PROCEDURE printf(thetext TEXT)
BEGIN

  select thetext as ``;

 END;

;;

DELIMITER ;

Now you can just do:

call printf('Counting products that have missing short description');

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

Check service dependencies if they are disabled.

Set those dependencies to Automatic, Start them and it should work.

C# switch on type

Update: This got fixed in C# 7.0 with pattern matching

switch (MyObj)
    case Type1 t1: 
    case Type2 t2:
    case Type3 t3:

Old answer:

It is a hole in C#'s game, no silver bullet yet.

You should google on the 'visitor pattern' but it might be a little heavy for you but still something you should know about.

Here's another take on the matter using Linq: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx

Otherwise something along these lines could help

// nasty..
switch(MyObj.GetType.ToString()){
  case "Type1": etc
}

// clumsy...
if myObj  is Type1 then
if myObj is Type2 then

etc.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

pyyaml should also be mentioned here. It is both human readable and can serialize any python object.
pyyaml is hosted here:
https://bitbucket.org/xi/pyyaml

SVG drop shadow using css3

Easiest way I've found is with feDropShadow.

<filter id="shadow" x="0" y="0" width="200%" height="200%">
  <feDropShadow dx="40" dy="40" stdDeviation="35" flood-color="#ff0000" flood-opacity="1" />
</filter>

On the element:

<path d="..." filter="url(#shadow)"/>

How to commit to remote git repository

Have you tried git push? gitref.org has a nice section dealing with remote repositories.

You can also get help from the command line using the --help option. For example:

% git push --help
GIT-PUSH(1)                             Git Manual                             GIT-PUSH(1)



NAME
       git-push - Update remote refs along with associated objects

SYNOPSIS
       git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
                  [--repo=<repository>] [-f | --force] [-v | --verbose] [-u | --set-upstream]
                  [<repository> [<refspec>...]]
...

Checking if float is an integer

stdlib float modf (float x, float *ipart) splits into two parts, check if return value (fractional part) == 0.

Reading Properties file in Java

if your config.properties is not in src/main/resource directory and it is in root directory of the project then you need to do somethinglike below :-

Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

How to specify font attributes for all elements on an html web page?

If you want to set styles of all elements in body you should use next code^

  body{
    color: green;
    }

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet big_honking_mainframe_box.com 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

Duplicate Entire MySQL Database

For me the following lines of code did the trick

mysqldump --quote-names -q -u username1 --password='password1' originalDB | mysql -u username2 --password='password2' duplicateDB

CSS 100% height with padding/margin

According the w3c spec height refers to the height of the viewable area e.g. on a 1280x1024 pixel resolution monitor 100% height = 1024 pixels.

min-height refers to the total height of the page including content so on a page where the content is bigger than 1024px min-height:100% will stretch to include all of the content.

The other problem then is that padding and border are added to the height and width in most modern browsers except ie6(ie6 is actually quite logical but does not conform to the spec). This is called the box model. So if you specify

min-height: 100%;
padding: 5px; 

It will actually give you 100% + 5px + 5px for the height. To get around this you need a wrapper container.

<style>
    .FullHeight { 
       height: auto !important; /* ie 6 will ignore this */
       height: 100%;            /* ie 6 will use this instead of min-height */
       min-height: 100%;        /* ie 6 will ignore this */
    }

    .Padded {
       padding: 5px;
    }
</style>

<div class="FullHeight">
   <div class="Padded">
      Hello i am padded.
   </div
</div>

MongoDb query condition on comparing 2 fields

In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:

import pymongo
from random import randrange

docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]

coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)

Using aggregate:

%timeit -n1 -r1 list(coll.aggregate([
    {
        '$project': {
            'diff': {'$subtract': ['$Grade1', '$Grade2']},
            'Grade1': 1,
            'Grade2': 1
        }
    },
    {
        '$match': {'diff': {'$gt': 0}}
    }
]))

1 loop, best of 1: 192 ms per loop

Using find and $where:

%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))

1 loop, best of 1: 4.54 s per loop

Read lines from a file into a Bash array

One alternate way if file contains strings without spaces with 1string each line:

fileItemString=$(cat  filename |tr "\n" " ")

fileItemArray=($fileItemString)

Check:

Print whole Array:

${fileItemArray[*]}

Length=${#fileItemArray[@]}

How to create empty constructor for data class in Kotlin Android

the modern answer for this should be using Kotlin's no-arg compiler plugin which creates a non argument construct code for classic apies more about here

simply you have to add the plugin class path in build.gradle project level

    dependencies {
    ....

    classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"

    ....
    }

then configure your annotation to generate the no-arg constructor

apply plugin: "kotlin-noarg"

noArg {
      annotation("your.path.to.annotaion.NoArg")
      invokeInitializers = true
}

then define your annotation file NoArg.kt

 @Target(AnnotationTarget.CLASS)
 @Retention(AnnotationRetention.SOURCE)
 annotation class NoArg

finally in any data class you can simply use your own annotation

@NoArg
data class SomeClass( val datafield:Type , ...   )

I used to create my own no-arg constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .

What is the difference between __str__ and __repr__?

__repr__: representation of python object usually eval will convert it back to that object

__str__: is whatever you think is that object in text form

e.g.

>>> s="""w'o"w"""
>>> repr(s)
'\'w\\\'o"w\''
>>> str(s)
'w\'o"w'
>>> eval(str(s))==s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    w'o"w
       ^
SyntaxError: EOL while scanning single-quoted string
>>> eval(repr(s))==s
True

How to check variable type at runtime in Go language

quux00's answer only tells about comparing basic types.

If you need to compare types you defined, you shouldn't use reflect.TypeOf(xxx). Instead, use reflect.TypeOf(xxx).Kind().

There are two categories of types:

  • direct types (the types you defined directly)
  • basic types (int, float64, struct, ...)

Here is a full example:

type MyFloat float64
type Vertex struct {
    X, Y float64
}

type EmptyInterface interface {}

type Abser interface {
    Abs() float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func (f MyFloat) Abs() float64 {
    return math.Abs(float64(f))
}

var ia, ib Abser
ia = Vertex{1, 2}
ib = MyFloat(1)
fmt.Println(reflect.TypeOf(ia))
fmt.Println(reflect.TypeOf(ia).Kind())
fmt.Println(reflect.TypeOf(ib))
fmt.Println(reflect.TypeOf(ib).Kind())

if reflect.TypeOf(ia) != reflect.TypeOf(ib) {
    fmt.Println("Not equal typeOf")
}
if reflect.TypeOf(ia).Kind() != reflect.TypeOf(ib).Kind() {
    fmt.Println("Not equal kind")
}

ib = Vertex{3, 4}
if reflect.TypeOf(ia) == reflect.TypeOf(ib) {
    fmt.Println("Equal typeOf")
}
if reflect.TypeOf(ia).Kind() == reflect.TypeOf(ib).Kind() {
    fmt.Println("Equal kind")
}

The output would be:

main.Vertex
struct
main.MyFloat
float64
Not equal typeOf
Not equal kind
Equal typeOf
Equal kind

As you can see, reflect.TypeOf(xxx) returns the direct types which you might want to use, while reflect.TypeOf(xxx).Kind() returns the basic types.


Here's the conclusion. If you need to compare with basic types, use reflect.TypeOf(xxx).Kind(); and if you need to compare with self-defined types, use reflect.TypeOf(xxx).

if reflect.TypeOf(ia) == reflect.TypeOf(Vertex{}) {
    fmt.Println("self-defined")
} else if reflect.TypeOf(ia).Kind() == reflect.Float64 {
    fmt.Println("basic types")
}

Set default format of datetimepicker as dd-MM-yyyy

Ensure that control Format property is properly set to use a custom format:

DateTimePicker1.Format = DateTimePickerFormat.Custom

Then this is how you can set your desired format:

DateTimePicker1.CustomFormat = "dd-MM-yyyy"

What is the best way to implement nested dictionaries?

I have a similar thing going. I have a lot of cases where I do:

thedict = {}
for item in ('foo', 'bar', 'baz'):
  mydict = thedict.get(item, {})
  mydict = get_value_for(item)
  thedict[item] = mydict

But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of

value = mydict.get('foo', {}).get('bar', {}).get('baz', 0)

So instead, I made:

def dictgetter(thedict, default, *args):
  totalargs = len(args)
  for i,arg in enumerate(args):
    if i+1 == totalargs:
      thedict = thedict.get(arg, default)
    else:
      thedict = thedict.get(arg, {})
  return thedict

Which has the same effect if you do:

value = dictgetter(mydict, 0, 'foo', 'bar', 'baz')

Better? I think so.

How to properly make a http web GET request

Another way is using 'HttpClient' like this:

using System;
using System.Net;
using System.Net.Http;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Making API Call...");
            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
            {
                client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
                HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
                response.EnsureSuccessStatusCode();
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Result: " + result);
            }
            Console.ReadLine();
        }
    }
}

Check HttpClient vs HttpWebRequest from stackoverflow and this from other.

Update June 22, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
   client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
   HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
   response.EnsureSuccessStatusCode();
   string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);           
 }

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

Batch: Remove file extension

In case the file your variable holds doesn't actually exist the FOR approach won't work. One trick you could use, if you know the length of the extension, is taking a substring:

%var:~0,-4%

the -4 means that the last 4 digits (presumably .ext) will be truncated.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Check to find the root cause by reading logs in the tomcat installation log folder if all the above answers failed.Read the catalina.out file to find out the exact cause. It might be database credentials error or class definition not found.

TSQL Pivot without aggregate function

Try this:

SELECT CUSTOMER_ID, MAX(FIRSTNAME) AS FIRSTNAME, MAX(LASTNAME) AS LASTNAME ...

FROM
(

SELECT CUSTOMER_ID, 
       CASE WHEN DBCOLUMNNAME='FirstName' then DATA ELSE NULL END AS FIRSTNAME,
       CASE WHEN DBCOLUMNNAME='LastName' then DATA ELSE NULL END AS LASTNAME,
        ... and so on ...
GROUP BY CUSTOMER_ID

) TEMP

GROUP BY CUSTOMER_ID

Add CSS or JavaScript files to layout head from views or partial views

Layout:

<html>
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
        @if (IsSectionDefined("AddToHead"))
        {
            @RenderSection("AddToHead", required: false)
        }

        @RenderSection("AddToHeadAnotherWay", required: false)
    </head>

View:

@model ProjectsExt.Models.DirectoryObject

@section AddToHead{
    <link href="@Url.Content("~/Content/Upload.css")" rel="stylesheet" type="text/css" />
}

Only mkdir if it does not exist

if [ ! -d directory ]; then
  mkdir directory
fi

or

mkdir -p directory

-p ensures creation if directory does not exist

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case, the error was triggered by duplicating an import of a component in the module.

Invalid default value for 'create_date' timestamp field

Change this:

`create_date` TIMESTAMP NOT NULL DEFAULT  '0000-00-00 00:00:00',
`update_date` TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP  ,

To the following:

`create_date` TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP ,
`update_date` TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,

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

Use timer.scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:

  • task - task to be scheduled.
  • delay - delay in milliseconds before task is to be executed.
  • period - time in milliseconds between successive task executions.

Throws:

  • IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
  • IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Update values from one column in same table to another in SQL Server

UPDATE a
SET a.column1 = b.column2
FROM myTable a 
INNER JOIN myTable b
on a.myID = b.myID

in order for both "a" and "b" to work, both aliases must be defined

MySQL, Concatenate two columns

You can use php built in CONCAT() for this.

SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;

change filed name as your requirement

then the result is

enter image description here

and if you want to concat same filed using other field which same then

SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1 

then this is output enter image description here

Run javascript script (.js file) in mongodb including another file inside js

To call external file you can use :

load ("path\file")

Exemple: if your file.js file is on your "Documents" file (on windows OS), you can type:

load ("C:\users\user_name\Documents\file.js")

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

MySQL error: key specification without a key length

You should define which leading portion of a TEXT column you want to index.

InnoDB has a limitation of 768 bytes per index key and you won't be able to create an index longer than that.

This will work fine:

CREATE TABLE t_length (
      mydata TEXT NOT NULL,
      KEY ix_length_mydata (mydata(255)))
    ENGINE=InnoDB;

Note that the maximum value of the key size depends on the column charset. It's 767 characters for a single-byte charset like LATIN1 and only 255 characters for UTF8 (MySQL only uses BMP which requires at most 3 bytes per character)

If you need your whole column to be the PRIMARY KEY, calculate SHA1 or MD5 hash and use it as a PRIMARY KEY.

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

Can I make 'git diff' only the line numbers AND changed file names?

The cleanest output, i.e. file names/paths only, comes with

git diff-tree --no-commit-id --name-only -r

HTH

What's the best way of scraping data from a website?

You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.

Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.

Tools

Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.

You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.

Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.

Language

PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.

A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.

Javascript-heavy sites

In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.

There are two approaches to this problem:

The low level approach:

You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.

The embedded browser approach:

Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.

If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.

You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.

Which approach is best?

That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.

The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.

Rate Limiting/Bot behaviour

You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.

Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.

You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.

Testing

Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.

There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.

The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.

You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.

Legal Issues

The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.

The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.

It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.

Who am I to write this giant wall of text anyway?

I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.

I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)

I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.

I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.

Failed to connect to camera service

since this question was asked 4 years back..and i didn't realised that unless mentioned by the Questioner..when there were no Run time permissions support.

but hoping it useful for the users who still caught in this situation.. Have a look at Run Time Permissions ,for me it solved the problem when i added Run time permissions to grant camera access. Alternatively you can grant permissions to the app manually by going to your mobile settings=>Apps=>(select your app)=>Permissions section in the appeared window and enable/disable desired permissions. hope this will work.

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

Notepad++ Setting for Disabling Auto-open Previous Files

I read the answers. Then I noticed for me that the check box was already unchecked, but it still always reloaded the files. This is the Settings->Preferences->MISC->"Remember current session for next launch" check box on version 6.3.2. The following got rid of the problem:

1. Check the check box.
2. Exit the program.
3. Start the program again.
4. Uncheck the checkbox.

MySQL SELECT last few days?

SELECT DATEDIFF(NOW(),pickup_date) AS noofday 
FROM cir_order 
WHERE DATEDIFF(NOW(),pickup_date)>2;

or

SELECT * 
FROM cir_order 
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )

How to insert programmatically a new line in an Excel cell in C#?

Actually, it is really simple.

You may edit an xml version of excel. Edit a cell to give it new line between your text, then save it. Later you may open the file in editor, then you will see a new line is represented by &#10;

Have a try....

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need

now.MONTH now.HOUR

etc.

git still shows files as modified after adding to .gitignore

Using git rm --cached *file* is not working fine for me (I'm aware this question is 8 years old, but it still shows at the top of the search for this topic), it does remove the file from the index, but it also deletes the file from the remote.

I have no idea why that is. All I wanted was keeping my local config isolated (otherwise I had to comment the localhost base url before every commit), not delete the remote equivalent to config.

Reading some more I found what seems to be the proper way to do this, and the only way that did what I needed, although it does require more attention, especially during merges.

Anyway, all it requires is git update-index --assume-unchanged *path/to/file*.

As far as I understand, this is the most notable thing to keep in mind:

Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

Convert SQL Server result set into string

Use the COALESCE function:

DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = COALESCE(@StudentID + ',', '') + StudentID
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

Unzip files (7-zip) via cmd command

In Windows 10 I had to run the batch file as an administrator.

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE_FORMAT(startTime, "%Y-%m-%d") = '2010-04-29'"

OR

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'

export html table to csv

Used the answer above, but altered it for my needs.

I used the following function and imported to my REACT file where I needed to download the csv file.

I had a span tag within my th elements. Added comments to what most functions/methods do.

import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';


export function tableToCSV(){
  let tableHeaders = Array.from(document.querySelectorAll('th'))
    .map(item => {
      // title = splits elem tags on '\n',
      // then filter out blank "" that appears in array.
      // ex ["Timestamp", "[Full time]", ""]
      let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
      return title
    }).join(",")

  const rows = Array.from(document.querySelectorAll('tr'))
  .reduce((arr, currRow) => {
    // if tr tag contains th tag.
    // if null return array.
    if (currRow.querySelector('th')) return arr

    // concats individual cells into csv format row.
    const cells = Array.from(currRow.querySelectorAll('td'))
      .map(item => item.innerText)
      .join(',')
    return arr.concat([cells])
  }, [])

return tableHeaders + '\n' + rows.join('\n')
}

export function downloadCSV(csv){
  const csvFile = new Blob([csv], { type: 'text/csv' })
  const downloadLink =  document.createElement('a')
  // sets the name for the download file
  downloadLink.download = `CSV-${currentDateUSWritten()}.csv`
  // sets the url to the window URL created from csv file above
  downloadLink.href = window.URL.createObjectURL(csvFile)
  // creates link, but does not display it.
  downloadLink.style.display = 'none'
  // add link to body so click function below works
  document.body.appendChild(downloadLink)

  downloadLink.click()
}

When user click export to csv it trigger the following function in react.

  handleExport = (e) => {
    e.preventDefault();
    const csv = tableToCSV()
    return downloadCSV(csv)
  }

Example html table elems.

  <table id="datatable">
        <tbody>
          <tr id="tableHeader" className="t-header">
            <th>Timestamp
              <span className="block">full time</span></th>
            <th>current rate
              <span className="block">alt view</span>
            </th>
            <th>Battery Voltage
              <span className="block">current voltage
              </span>
            </th>
            <th>Temperature 1
              <span className="block">[C]</span>
            </th>
            <th>Temperature 2
              <span className="block">[C]</span>
            </th>
            <th>Time & Date </th>
          </tr>

        </tbody>
        <tbody>
          {this.renderData()}
        </tbody>
      </table>
    </div>

How to initialise a string from NSData in Swift

This is the implemented code needed:

in Swift 3.0:

var dataString = String(data: fooData, encoding: String.Encoding.utf8)

or just

var dataString = String(data: fooData, encoding: .utf8)

Older swift version:

in Swift 2.0:

import Foundation

var dataString = String(data: fooData, encoding: NSUTF8StringEncoding)

in Swift 1.0:

var dataString = NSString(data: fooData, encoding:NSUTF8StringEncoding)

Generate Java classes from .XSD files...?

The well-known JAXB

There is a maven plugin that could do this for you at any build phase you want.

You could do this stuff in both ways: xsd <-> Java

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

Check if datetime instance falls in between other two datetime objects

Write yourself a Helper function:

public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
    return dt >= start && dt <= end;
}

Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));

Javascript change color of text and background to input value

Depending on which event you actually want to use (textbox change, or button click), you can try this:

HTML:

<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>

JS:

function changeBackground(obj) {
    document.getElementById("coltext").style.color = obj.value;
}

DEMO: http://jsfiddle.net/6pLUh/

One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange allows you to change the color based on the input.

How to set HttpResponse timeout for Android in Java

For those saying that the answer of @kuester2000 does not work, please be aware that HTTP requests, first try to find the host IP with a DNS request and then makes the actual HTTP request to the server, so you may also need to set a timeout for the DNS request.

If your code worked without the timeout for the DNS request it's because you are able to reach a DNS server or you are hitting the Android DNS cache. By the way you can clear this cache by restarting the device.

This code extends the original answer to include a manual DNS lookup with a custom timeout:

//Our objective
String sURL = "http://www.google.com/";
int DNSTimeout = 1000;
int HTTPTimeout = 2000;

//Get the IP of the Host
URL url= null;
try {
     url = ResolveHostIP(sURL,DNSTimeout);
} catch (MalformedURLException e) {
    Log.d("INFO",e.getMessage());
}

if(url==null){
    //the DNS lookup timed out or failed.
}

//Build the request parameters
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTPTimeout);
HttpConnectionParams.setSoTimeout(params, HTTPTimeout);

DefaultHttpClient client = new DefaultHttpClient(params);

HttpResponse httpResponse;
String text;
try {
    //Execute the request (here it blocks the execution until finished or a timeout)
    httpResponse = client.execute(new HttpGet(url.toString()));
} catch (IOException e) {
    //If you hit this probably the connection timed out
    Log.d("INFO",e.getMessage());
}

//If you get here everything went OK so check response code, body or whatever

Used method:

//Run the DNS lookup manually to be able to time it out.
public static URL ResolveHostIP (String sURL, int timeout) throws MalformedURLException {
    URL url= new URL(sURL);
    //Resolve the host IP on a new thread
    DNSResolver dnsRes = new DNSResolver(url.getHost());
    Thread t = new Thread(dnsRes);
    t.start();
    //Join the thread for some time
    try {
        t.join(timeout);
    } catch (InterruptedException e) {
        Log.d("DEBUG", "DNS lookup interrupted");
        return null;
    }

    //get the IP of the host
    InetAddress inetAddr = dnsRes.get();
    if(inetAddr==null) {
        Log.d("DEBUG", "DNS timed out.");
        return null;
    }

    //rebuild the URL with the IP and return it
    Log.d("DEBUG", "DNS solved.");
    return new URL(url.getProtocol(),inetAddr.getHostAddress(),url.getPort(),url.getFile());
}   

This class is from this blog post. Go and check the remarks if you will use it.

public static class DNSResolver implements Runnable {
    private String domain;
    private InetAddress inetAddr;

    public DNSResolver(String domain) {
        this.domain = domain;
    }

    public void run() {
        try {
            InetAddress addr = InetAddress.getByName(domain);
            set(addr);
        } catch (UnknownHostException e) {
        }
    }

    public synchronized void set(InetAddress inetAddr) {
        this.inetAddr = inetAddr;
    }
    public synchronized InetAddress get() {
        return inetAddr;
    }
}

Laravel Eloquent inner join with multiple conditions

This is not politically correct but works

   ->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

Understanding PIVOT function in T-SQL

These are the very basic pivot example kindly go through that.

SQL SERVER – PIVOT and UNPIVOT Table Examples

Example from above link for the product table:

SELECT PRODUCT, FRED, KATE
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
 PIVOT (SUM(QTY) FOR CUST IN (FRED, KATE)) AS pvt
ORDER BY PRODUCT

renders:

 PRODUCT FRED  KATE
 --------------------
 BEER     24    12
 MILK      3     1
 SODA   NULL     6
 VEG    NULL     5

Similar examples can be found in the blog post Pivot tables in SQL Server. A simple sample

How to change the font size on a matplotlib plot

Here is a totally different approach that works surprisingly well to change the font sizes:

Change the figure size!

I usually use code like this:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example from above code: enter image description here

How do I compile a .cpp file on Linux?

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

2D character array initialization in C

I think what you originally meant to do was to make an array only of characters, not of pointers:

char options[2][100];

options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0';  /* NUL termination of C string */

/* A standard C library function which copies strings. */
strcpy(options[1], "test2");

The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.

Split comma-separated input box values into array in jquery, and loop through it

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

Play sound on button click android

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    MediaPlayer mp;
    Button one;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mp = MediaPlayer.create(this, R.raw.soho);
        one = (Button)this.findViewById(R.id.button1);

        one.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mp.start();
            }
        });
    }
}

Select2 doesn't work when embedded in a bootstrap modal

If you have a problem with the iPad keyboard which hide the bootstrap modal while clicking on the select2 input, you can resolve this by adding the following rule after the initialization of the select2 input :

if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
   var styleEl = document.createElement('style'), styleSheet;
   document.head.appendChild(styleEl);
   styleSheet = styleEl.sheet;
   styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
   document.body.scrollTop = 0; // Only for Safari
}

Taken from https://github.com/angular-ui/bootstrap/issues/1812#issuecomment-135119475

EDIT: If your options are not shown properly, you need to use the dropdownParent attribute when initializing select2 :

$(".select2").select2({
    dropdownParent: $("#YOURMODALID")
});

Good luck (:

How to pass a single object[] to a params object[]

new[] { (object) 0, (object) null, (object) false }

List of All Folders and Sub-folders

You can use find

find . -type d > output.txt

or tree

tree -d > output.txt

tree, If not installed on your system.

If you are using ubuntu

sudo apt-get install tree

If you are using mac os.

brew install tree

The point of test %eax %eax

You are right, that test "and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test instruction is used (and exist).

JE jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF flag is set. And as it is one of the flags that is set by test, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.

For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.

Using --add-host or extra_hosts with docker-compose

Basic docker-compose.yml with extra hosts:

version: '3'
services:
api:
    build: .
    ports:
        - "5003:5003"
    extra_hosts:
        - "your-host.name.com:162.242.195.82" #host and ip
        - "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
        

The content in the /etc/hosts file in the created container:

162.242.195.82  your-host.name.com
50.31.209.229   your-host--1.name.com your-host--2.name.com

You can check the /etc/hosts file with the following commands:

$ docker-compose -f path/to/file/docker-compose.yml run api bash  # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts

Output Django queryset as JSON

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Or another approach with Django's built-in serializers:

from django.core import serializers
from django.http import HttpResponse

def some_view(request):
    qs = SomeModel.objects.all()
    qs_json = serializers.serialize('json', qs)
    return HttpResponse(qs_json, content_type='application/json')

In this case result is slightly different (without indent by default):

[
    {
        "model": "some_app.some_model",
        "pk": 1,
        "fields": {
            "name": "Elon",
            "age": 48,
            ...
        }
    },
    ...
]

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

Laravel 5 – Remove Public from URL

Let's say you placed all the other files and directories in a folder named 'locale'.

enter image description here

Just go to index.php and find these two lines:

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

and change them to this:

require __DIR__.'/locale/bootstrap/autoload.php';

$app = require_once __DIR__.'/locale/bootstrap/app.php';

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

On Windows also check whether the file is not encrypted using EFS. I had the same problem untill I decrypted the file manualy.

Select all from table with Laravel and Eloquent

using DB facade you can perform SQL queries

 public function index()
{
    return DB::table('table_name')->get();
}

"Invalid JSON primitive" in Ajax processing

On the Server, to Serialize/Deserialize json to custom objects:

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

Python Request Post with param data

Set data to this:

data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}

C# Get a control's position on a form

private Point FindLocation(Control ctrl)
{
    if (ctrl.Parent is Form)
        return ctrl.Location;
    else
    {
        Point p = FindLocation(ctrl.Parent);
        p.X += ctrl.Location.X;
        p.Y += ctrl.Location.Y;
        return p;
    }
}

Detecting when Iframe content has loaded (Cross browser)

For those using React, detecting a same-origin iframe load event is as simple as setting onLoad event listener on iframe element.

<iframe src={'path-to-iframe-source'} onLoad={this.loadListener} frameBorder={0} />

firestore: PERMISSION_DENIED: Missing or insufficient permissions

make sure your DB is not empty nor your query is for collection whom not exist

Extracting an attribute value with beautifulsoup

For me:

<input id="color" value="Blue"/>

This can be fetched by below snippet.

page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(color['value'])

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

How to make Python script run as service?

first import os module in your app than with use from getpid function get pid's app and save in a file.for example :

import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()

and create a bash file in /etc/init.d path: /etc/init.d/servername

PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in 
        start)
                echo "starting"
                $(python $PATHAPP)
        ;;
        stop)
                echo "stoping"
                PID=$(cat $PIDAPP)
                kill $PID
        ;;

esac

now , u can start and stop ur app with down command:

service servername stop service servername start

or

/etc/init.d/servername stop /etc/init.d/servername start

Copy all the lines to clipboard

Use:

:%y+

to yank all lines.

Explanation:

  • % to refer the next command to work on all the lines
  • y to yank those lines
  • + to copy to the system clipboard

NB: In Windows, + and * are equivalent see this answer.

How do I view executed queries within SQL Server Management Studio?

If you want to see queries that are already executed there is no supported default way to do this. There are some workarounds you can try but don’t expect to find all.

You won’t be able to see SELECT statements for sure but there is a way to see other DML and DDL commands by reading transaction log (assuming database is in full recovery mode).

You can do this using DBCC LOG or fn_dblog commands or third party log reader like ApexSQL Log (note that tool comes with a price)

Now, if you plan on auditing statements that are going to be executed in the future then you can use SQL Profiler to catch everything.

Undoing a 'git push'

git revert is less dangerous than some of the approaches suggested here:

prompt> git revert 35f6af6f77f116ef922e3d75bc80a4a466f92650
[master 71738a9] Revert "Issue #482 - Fixed bug."
 4 files changed, 30 insertions(+), 42 deletions(-)
prompt> git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
prompt>

Replace 35f6af6f77f116ef922e3d75bc80a4a466f92650 with your own commit.

How to use OUTPUT parameter in Stored Procedure

SqlCommand yourCommand = new SqlCommand();
yourCommand.Connection = yourSqlConn;
yourCommand.Parameters.Add("@yourParam");
yourCommand.Parameters["@yourParam"].Direction = ParameterDirection.Output;

// execute your query successfully

int yourResult = yourCommand.Parameters["@yourParam"].Value;

simple way to display data in a .txt file on a webpage?

I find that if I try things that others say do not work, it's how I learn the most.

<p>&nbsp;</p>
<p>README.txt</p>
<p>&nbsp;</p>
<div id="list">
  <p><iframe src="README.txt" frameborder="0" height="400"
      width="95%"></iframe></p>
</div>

This worked for me. I used the yellow background-color that I set in the stylesheet.

#list  p {
    font: arial;
    font-size: 14px;
    background-color: yellow ;
}

Margin on child element moves parent element

I had this problem too but preferred to prevent negative margins hacks, so I put a

<div class="supercontainer"></div>

around it all which has paddings instead of margins. Of course this means more divitis but it's probably the cleanest way to do get this done properly.

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

Change the content of a div based on selection from dropdown menu

The accepted answer has a couple of shortcomings:

  • Don't target IDs in your JavaScript code. Use classes and data attributes to avoid repeating your code.
  • It is good practice to hide with CSS on load rather than with JavaScript—to support non-JavaScript users, and prevent a show-hide flicker on load.

Considering the above, your options could even have different values, but toggle the same class:

<select class="div-toggle" data-target=".my-info-1">
  <option value="orange" data-show=".citrus">Orange</option>
  <option value="lemon" data-show=".citrus">Lemon</option>
  <option value="apple" data-show=".pome">Apple</option>
  <option value="pear" data-show=".pome">Pear</option>
</select>

<div class="my-info-1">
  <div class="citrus hide">Citrus is...</div>
  <div class="pome hide">A pome is...</div>
</div>

jQuery:

$(document).on('change', '.div-toggle', function() {
  var target = $(this).data('target');
  var show = $("option:selected", this).data('show');
  $(target).children().addClass('hide');
  $(show).removeClass('hide');
});
$(document).ready(function(){
    $('.div-toggle').trigger('change');
});

CSS:

.hide {
  display: none;
}

Here's a JSFiddle to see it in action.

mySQL :: insert into table, data from another table?

INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)  
SELECT campaign_id, from_number, received_msg, date_received
  FROM `received_txts`
 WHERE `campaign_id` = '8'

Move SQL data from one table to another

Try this

INSERT INTO TABLE2 (Cols...) SELECT Cols... FROM TABLE1 WHERE Criteria

Then

DELETE FROM TABLE1 WHERE Criteria

Substring with reverse index

here is my custom function

function reverse_substring(str,from,to){
  var temp="";
  var i=0;
  var pos = 0;
  var append;      
  for(i=str.length-1;i>=0;i--){
    //alert("inside loop " + str[i]);
    if(pos == from){
         append=true;
    }

    if(pos == to){
         append=false;
         break;
    }
    if(append){
         temp = str[i] + temp;
    }
    pos++;
  }
  alert("bottom loop " + temp);
}

var str = "bala_123";
reverse_substring(str,0,3);

This function works for reverse index.

Redirecting output to $null in PowerShell, but ensuring the variable remains set

I'd prefer this way to redirect standard output (native PowerShell)...

($foo = someFunction) | out-null

But this works too:

($foo = someFunction) > $null

To redirect just standard error after defining $foo with result of "someFunction", do

($foo = someFunction) 2> $null

This is effectively the same as mentioned above.

Or to redirect any standard error messages from "someFunction" and then defining $foo with the result:

$foo = (someFunction 2> $null)

To redirect both you have a few options:

2>&1>$null
2>&1 | out-null

Print series of prime numbers in python

n = int(input())
is_prime = lambda n: all( n%i != 0 for i in range(2, int(n**.5)+1) )
def Prime_series(n):
    for i in range(2,n):
        if is_prime(i) == True:
            print(i,end = " ")
        else:
            pass
Prime_series(n)

Here is a simplified answer using lambda function.

How to calculate distance from Wifi router using Signal Strength?

FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them.

FSPL (dB) = 20log10(d) + 20log10(f) + K

d = distance
f = frequency
K= constant that depends on the units used for d and f
If d is measured in kilometers, f in MHz, the formula is:

FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44

From the Fade Margin equation, Free Space Path Loss can be computed with the following equation.

Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin

With the above two Free Space Path Loss equations, we can find out the Distance in km.

Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20

The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant.

FSPLr=17.32*v(d/4f)

d = distance [km]
f = frequency [GHz]
r = radius [m]

Source : http://www.tp-link.com/en/support/calculator/

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

In C++, use the const_cast as like below

char* str = const_cast<char*>("Test string");

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

jQuery $(document).ready and UpdatePanels?

I would use one of the following approaches:

  1. Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.

  2. Use the livequery plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

If you're using npm >=1.0, you can use npm link <global-package> to create a local link to a package already installed globally. (Caveat: The OS must support symlinks.)

However, this doesn't come without its problems.

npm link is a development tool. It's awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.

As an alternative, you can install the packages locally as well as globally.

For additional information, see

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to convert xml into array in php?

easy!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Making a <button> that's a link in HTML

A little bit easier and it looks exactly like the button in the form. Just use the input and wrap the anchor tag around it.

<a href="#"><input type="button" value="Button Text"></a>

How to get just the responsive grid from Bootstrap 3?

Go to http://getbootstrap.com/customize/ and toggle just what you want from the BS3 framework and then click "Compile and Download" and you'll get the CSS and JS that you chose.

Bootstrap Customizer

Open up the CSS and remove all but the grid. They include some normalize stuff too. And you'll need to adjust all the styles on your site to box-sizing: border-box - http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.

For example:

NSArray *array = @[@"a", @"b", @"c"];

int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!

if (i == NSNotFound) {
    // thought we'd get here, but we don't
    NSLog(@"it's not here");
}
else {
    // this is what actually happens
    NSLog(@"it's here: %d", i);

    // **** crash horribly ****
    NSLog(@"the object is %@", array[i]);
}

IntelliJ does not show project folders

  1. You don't have to quit Intellij completely to make this work. Simply close the project that you have open. (You can open any another project to avoid closing it completely)

  2. Go to the directory where you have your project installed and delete the ".idea" folder.

  3. Reopen the Project.

That should fix it. It worked for me in May 2018.

How to get Tensorflow tensor dimensions (shape) as int values?

2.0 Compatible Answer: In Tensorflow 2.x (2.1), you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:

Method 1 (using tf.shape):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape)   # [2,3]

Method 2 (using tf.get_shape()):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape)   # [2,3]

Spring Boot - Handle to Hibernate SessionFactory

Great work Andreas. I created a bean version so the SessionFactory could be autowired.

import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

....

@Autowired
private EntityManagerFactory entityManagerFactory;

@Bean
public SessionFactory getSessionFactory() {
    if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
        throw new NullPointerException("factory is not a hibernate factory");
    }
    return entityManagerFactory.unwrap(SessionFactory.class);
}

VBA Count cells in column containing specified value

Do you mean you want to use a formula in VBA? Something like:

Dim iVal As Integer
iVal = Application.WorksheetFunction.COUNTIF(Range("A1:A10"),"Green")

should work.

Does C# have extension properties?

For the moment it is still not supported out of the box by Roslyn compiler ...

Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.

But it will ...

There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.

However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.

Moreover you can use a workaround

As specified in this article, you can use the TypeDescriptor capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
string Data(this MyClass instance) as an alias for extension method
string GetData(this MyClass instance) as it stores data into the class.

I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.

And feel free to contribute as the software of tomorrow will come from the community.

Update: August 2016

As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:

Extension properties: we had a (brilliant!) intern implement them over the summer as an experiment, along with other kinds of extension members. We remain interested in this, but it’s a big change and we need to feel confident that it’s worth it.

It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.

Update: May 2017

The extension members has been closed as duplicate of extension everything issue which is closed too. The main discussion was in fact about Type extensibility in a broad sense. The feature is now tracked here as a proposal and has been removed from 7.0 milestone.

Update: August, 2017 - C# 8.0 proposed feature

While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:

public interface IEmployee 
{
    public decimal Salary { get; set; }
}

public class Employee
{
    public decimal Salary { get; set; }
}

public extension MyPersonExtension extends Person : IEmployee
{
    private static readonly ConditionalWeakTable<Person, Employee> _employees = 
        new ConditionalWeakTable<Person, Employee>();


    public decimal Salary
    {
        get 
        {
            // `this` is the instance of Person
            return _employees.GetOrCreate(this).Salary; 
        }
        set 
        {
            Employee employee = null;
            if (!_employees.TryGetValue(this, out employee)
            {
                employee = _employees.GetOrCreate(this);
            }
            employee.Salary = value;
        }
    }
}

IEmployee person = new Person();
var salary = person.Salary;

Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...). For this, you can still use the TypeDescriptor/ConditionalWeakTable technique described earlier and with the property extension, hides it under a nice property.

Syntax is still subject to change as implies this issue. For example, extends could be replaced by for which some may feel more natural and less java related.

Update December 2018 - Roles, Extensions and static interface members

Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:

Roles allow interfaces to be implemented on specific values of a given type. Extensions allow interfaces to be implemented on all values of a given type, within a specific region of code.

It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:

public extension ULongEnumerable of ulong
{
    public IEnumerator<byte> GetEnumerator()
    {
        for (int i = sizeof(ulong); i > 0; i--)
        {
            yield return unchecked((byte)(this >> (i-1)*8));
        }
    }
}

then you would be able to do this:

foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
    WriteLine($"{e.Current:X}");
}

And for a static interface:

public interface IMonoid<T> where T : IMonoid<T>
{
    static T operator +(T t1, T t2);
    static T Zero { get; }
}

Add an extension property on int and treat the int as IMonoid<int>:

public extension IntMonoid of int : IMonoid<int>
{
    public static int Zero => 0;
}

How to add external library in IntelliJ IDEA?

Easier procedure on latest versions:

  • Copy jar to libs directory in the app (you can create the directory it if not there)
  • Refresh project so libs show up in the structure (right click on project top level, refresh/synchronize)
  • Expand libs and right click on the jar
  • Select "Add as Library"

Done

Split / Explode a column of dictionaries into separate columns with pandas

I've concatenated those steps in a method, you have to pass only the dataframe and the column which contains the dict to expand:

def expand_dataframe(dw: pd.DataFrame, column_to_expand: str) -> pd.DataFrame:
    """
    dw: DataFrame with some column which contain a dict to expand
        in columns
    column_to_expand: String with column name of dw
    """
    import pandas as pd

    def convert_to_dict(sequence: str) -> Dict:
        import json
        s = sequence
        json_acceptable_string = s.replace("'", "\"")
        d = json.loads(json_acceptable_string)
        return d    

    expanded_dataframe = pd.concat([dw.drop([column_to_expand], axis=1),
                                    dw[column_to_expand]
                                    .apply(convert_to_dict)
                                    .apply(pd.Series)],
                                    axis=1)
    return expanded_dataframe

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

This is due a conflict of versions, to solve it, just force an update of your support-annotations version, adding this line on your module: app gradle

implementation ('com.android.support:support-annotations:27.1.1')

Hope this solves your issue ;)

Edit

Almost forgot, you can declare a single extra property (https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties) for the version, go to your project (or your top) gradle file, and declare your support, or just for this example, annotation version var

ext.annotation_version = "27.1.1"

Then in your module gradle replace it with:

implementation ("com.android.support:support-annotations:$annotation_version")

This is very similar to the @emadabel solution, which is a good alternative for doing it, but without the block, or the rootproject prefix.

Iterating through all the cells in Excel VBA or VSTO 2005

There are several methods to accomplish this, each of which has advantages and disadvantages; First and foremost, you're going to need to have an instance of a Worksheet object, Application.ActiveSheet works if you just want the one the user is looking at.

The Worksheet object has three properties that can be used to access cell data (Cells, Rows, Columns) and a method that can be used to obtain a block of cell data, (get_Range).

Ranges can be resized and such, but you may need to use the properties mentioned above to find out where the boundaries of your data are. The advantage to a Range becomes apparent when you are working with large amounts of data because VSTO add-ins are hosted outside the boundaries of the Excel application itself, so all calls to Excel have to be passed through a layer with overhead; obtaining a Range allows you to get/set all of the data you want in one call which can have huge performance benefits, but it requires you to use explicit details rather than iterating through each entry.

This MSDN forum post shows a VB.Net developer asking a question about getting the results of a Range as an array

C# Regex for Guid

For C# .Net to find and replace any guid looking string from the given text,

Use this RegEx:

[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?

Example C# code:

var result = Regex.Replace(
      source, 
      @"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?", 
      @"${ __UUID}", 
      RegexOptions.IgnoreCase
);

Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.

"aa761232bd4211cfaacd00aa0057b243" 
"AA761232-BD42-11CF-AACD-00AA0057B243" 
"{AA761232-BD42-11CF-AACD-00AA0057B243}" 
"(AA761232-BD42-11CF-AACD-00AA0057B243)" 

Email & Phone Validation in Swift

The following code works in xcode 6.3 beta

func isValidEmail(testStr:String) -> Bool {

   let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
   let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
   let result = range != nil ? true : false
   return result

}

how to use it:

Ex.

if isValidEmail(email.text) == false{
//your code here
}

Regular expression for exact match of a string

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

MSVCP140.dll missing

Your friend's PC is missing the runtime support DLLs for your program:

Matplotlib figure facecolor (background color)

It's because savefig overrides the facecolor for the background of the figure.

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)

Hope that helps!

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

In my case checking the check-box

"Copy project into workspace"

did the trick.

HashSet vs. List performance

Just thought I'd chime in with some benchmarks for different scenarios to illustrate the previous answers:

  1. A few (12 - 20) small strings (length between 5 and 10 characters)
  2. Many (~10K) small strings
  3. A few long strings (length between 200 and 1000 characters)
  4. Many (~5K) long strings
  5. A few integers
  6. Many (~10K) integers

And for each scenario, looking up values which appear:

  1. In the beginning of the list ("start", index 0)
  2. Near the beginning of the list ("early", index 1)
  3. In the middle of the list ("middle", index count/2)
  4. Near the end of the list ("late", index count-2)
  5. At the end of the list ("end", index count-1)

Before each scenario I generated randomly sized lists of random strings, and then fed each list to a hashset. Each scenario ran 10,000 times, essentially:

(test pseudocode)

stopwatch.start
for X times
    exists = list.Contains(lookup);
stopwatch.stop

stopwatch.start
for X times
    exists = hashset.Contains(lookup);
stopwatch.stop

Sample Output

Tested on Windows 7, 12GB Ram, 64 bit, Xeon 2.8GHz

---------- Testing few small strings ------------
Sample items: (16 total)
vgnwaloqf diwfpxbv tdcdc grfch icsjwk
...

Benchmarks:
1: hashset: late -- 100.00 % -- [Elapsed: 0.0018398 sec]
2: hashset: middle -- 104.19 % -- [Elapsed: 0.0019169 sec]
3: hashset: end -- 108.21 % -- [Elapsed: 0.0019908 sec]
4: list: early -- 144.62 % -- [Elapsed: 0.0026607 sec]
5: hashset: start -- 174.32 % -- [Elapsed: 0.0032071 sec]
6: list: middle -- 187.72 % -- [Elapsed: 0.0034536 sec]
7: list: late -- 192.66 % -- [Elapsed: 0.0035446 sec]
8: list: end -- 215.42 % -- [Elapsed: 0.0039633 sec]
9: hashset: early -- 217.95 % -- [Elapsed: 0.0040098 sec]
10: list: start -- 576.55 % -- [Elapsed: 0.0106073 sec]


---------- Testing many small strings ------------
Sample items: (10346 total)
dmnowa yshtrxorj vthjk okrxegip vwpoltck
...

Benchmarks:
1: hashset: end -- 100.00 % -- [Elapsed: 0.0017443 sec]
2: hashset: late -- 102.91 % -- [Elapsed: 0.0017951 sec]
3: hashset: middle -- 106.23 % -- [Elapsed: 0.0018529 sec]
4: list: early -- 107.49 % -- [Elapsed: 0.0018749 sec]
5: list: start -- 126.23 % -- [Elapsed: 0.0022018 sec]
6: hashset: early -- 134.11 % -- [Elapsed: 0.0023393 sec]
7: hashset: start -- 372.09 % -- [Elapsed: 0.0064903 sec]
8: list: middle -- 48,593.79 % -- [Elapsed: 0.8476214 sec]
9: list: end -- 99,020.73 % -- [Elapsed: 1.7272186 sec]
10: list: late -- 99,089.36 % -- [Elapsed: 1.7284155 sec]


---------- Testing few long strings ------------
Sample items: (19 total)
hidfymjyjtffcjmlcaoivbylakmqgoiowbgxpyhnrreodxyleehkhsofjqenyrrtlphbcnvdrbqdvji...
...

Benchmarks:
1: list: early -- 100.00 % -- [Elapsed: 0.0018266 sec]
2: list: start -- 115.76 % -- [Elapsed: 0.0021144 sec]
3: list: middle -- 143.44 % -- [Elapsed: 0.0026201 sec]
4: list: late -- 190.05 % -- [Elapsed: 0.0034715 sec]
5: list: end -- 193.78 % -- [Elapsed: 0.0035395 sec]
6: hashset: early -- 215.00 % -- [Elapsed: 0.0039271 sec]
7: hashset: end -- 248.47 % -- [Elapsed: 0.0045386 sec]
8: hashset: start -- 298.04 % -- [Elapsed: 0.005444 sec]
9: hashset: middle -- 325.63 % -- [Elapsed: 0.005948 sec]
10: hashset: late -- 431.62 % -- [Elapsed: 0.0078839 sec]


---------- Testing many long strings ------------
Sample items: (5000 total)
yrpjccgxjbketcpmnvyqvghhlnjblhgimybdygumtijtrwaromwrajlsjhxoselbucqualmhbmwnvnpnm
...

Benchmarks:
1: list: early -- 100.00 % -- [Elapsed: 0.0016211 sec]
2: list: start -- 132.73 % -- [Elapsed: 0.0021517 sec]
3: hashset: start -- 231.26 % -- [Elapsed: 0.003749 sec]
4: hashset: end -- 368.74 % -- [Elapsed: 0.0059776 sec]
5: hashset: middle -- 385.50 % -- [Elapsed: 0.0062493 sec]
6: hashset: late -- 406.23 % -- [Elapsed: 0.0065854 sec]
7: hashset: early -- 421.34 % -- [Elapsed: 0.0068304 sec]
8: list: middle -- 18,619.12 % -- [Elapsed: 0.3018345 sec]
9: list: end -- 40,942.82 % -- [Elapsed: 0.663724 sec]
10: list: late -- 41,188.19 % -- [Elapsed: 0.6677017 sec]


---------- Testing few ints ------------
Sample items: (16 total)
7266092 60668895 159021363 216428460 28007724
...

Benchmarks:
1: hashset: early -- 100.00 % -- [Elapsed: 0.0016211 sec]
2: hashset: end -- 100.45 % -- [Elapsed: 0.0016284 sec]
3: list: early -- 101.83 % -- [Elapsed: 0.0016507 sec]
4: hashset: late -- 108.95 % -- [Elapsed: 0.0017662 sec]
5: hashset: middle -- 112.29 % -- [Elapsed: 0.0018204 sec]
6: hashset: start -- 120.33 % -- [Elapsed: 0.0019506 sec]
7: list: late -- 134.45 % -- [Elapsed: 0.0021795 sec]
8: list: start -- 136.43 % -- [Elapsed: 0.0022117 sec]
9: list: end -- 169.77 % -- [Elapsed: 0.0027522 sec]
10: list: middle -- 237.94 % -- [Elapsed: 0.0038573 sec]


---------- Testing many ints ------------
Sample items: (10357 total)
370826556 569127161 101235820 792075135 270823009
...

Benchmarks:
1: list: early -- 100.00 % -- [Elapsed: 0.0015132 sec]
2: hashset: end -- 101.79 % -- [Elapsed: 0.0015403 sec]
3: hashset: early -- 102.08 % -- [Elapsed: 0.0015446 sec]
4: hashset: middle -- 103.21 % -- [Elapsed: 0.0015618 sec]
5: hashset: late -- 104.26 % -- [Elapsed: 0.0015776 sec]
6: list: start -- 126.78 % -- [Elapsed: 0.0019184 sec]
7: hashset: start -- 130.91 % -- [Elapsed: 0.0019809 sec]
8: list: middle -- 16,497.89 % -- [Elapsed: 0.2496461 sec]
9: list: end -- 32,715.52 % -- [Elapsed: 0.4950512 sec]
10: list: late -- 33,698.87 % -- [Elapsed: 0.5099313 sec]

Iterator invalidation rules

Here is a nice summary table from cppreference.com:

enter image description here

Here, insertion refers to any method which adds one or more elements to the container and erasure refers to any method which removes one or more elements from the container.

Relative URLs in WordPress

There is an easy way

Instead of /pagename/ use index.php/pagename/ or if you don't use permalinks do the following :

Post

index.php?p=123

Page

index.php?page_id=42

Category

index.php?cat=7

More information here : http://codex.wordpress.org/Linking_Posts_Pages_and_Categories

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

Kotlin Answer

We have to use UI Thread for the job with true way. We can use UI Thread in Kotlin:

runOnUiThread(Runnable {
   //TODO: Your job is here..!
})

@canerkaseler

Regular expression to find URLs within a string

Wrote one up myself:

let regex = /([\w+]+\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#\.]?[\w-]+)*\/?/gm

It works on ALL of the following domains:

https://www.facebook.com
https://app-1.number123.com
http://facebook.com
ftp://facebook.com
http://localhost:3000
localhost:3000/
unitedkingdomurl.co.uk
this.is.a.url.com/its/still=going?wow
shop.facebook.org
app.number123.com
app1.number123.com
app-1.numbEr123.com
app.dashes-dash.com
www.facebook.com
facebook.com
fb.com/hello_123
fb.com/hel-lo
fb.com/hello/goodbye
fb.com/hello/goodbye?okay
fb.com/hello/goodbye?okay=alright
Hello www.google.com World http://yahoo.com
https://www.google.com.tr/admin/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
https://google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
http://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
ftp://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
www.google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
www.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
drive.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
https://www.example.pl
http://www.example.com
www.example.pl
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
shop.facebook.org/derf.html

You can see how it performs here on regex101 and adjust as needed

How to switch activity without animation in Android?

create your own style overriding android:Theme

<style name="noAnimationStyle" parent="android:Theme">
    <item name="android:windowAnimationStyle">@null</item>
</style>

Then use it in manifest like this:

<activity android:name=".MainActivity"
    android:theme="@style/noAnimationStyle">
</activity>

Laravel Eloquent ORM Transactions

If you don't like anonymous functions:

try {
    DB::connection()->pdo->beginTransaction();
    // database queries here
    DB::connection()->pdo->commit();
} catch (\PDOException $e) {
    // Woopsy
    DB::connection()->pdo->rollBack();
}

Update: For laravel 4, the pdo object isn't public anymore so:

try {
    DB::beginTransaction();
    // database queries here
    DB::commit();
} catch (\PDOException $e) {
    // Woopsy
    DB::rollBack();
}

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Simplified version for Oracle. If you don't want to create OracleParameter

var sql = "Update [User] SET FirstName = :p0 WHERE Id = :p1";
context.Database.ExecuteSqlCommand(sql, firstName, id);

Session 'app' error while installing APK

I was facing similar kind of problem.There is image of error attached.Error is highlighted in red. Turning off the Instant run removed error for Android Studio 2.3 and 3.1.4.

Error, after running the app Turning off the Instant run

How to get selected path and name of the file opened with file dialog?

Sub GetFilePath()

Set myFile = Application.FileDialog(msoFileDialogOpen)

With myFile

.Title = "Choose File"

.AllowMultiSelect = False

If .Show <> -1 Then

Exit Sub

End If

FileSelected = Replace(.SelectedItems(1), .InitialFileName, "")

End With

ActiveSheet.Range("A1") = FileSelected

End Sub

How can I see an the output of my C programs using Dev-C++?

Use #include conio.h

Then add getch(); before return 0;

Switch case in C# - a constant value is expected

There is this trick which was shared with me (don't ask for details - won't be able to provide them, but it works for me):

switch (variable_1)
{
    case var value when value == variable_2: // that's the trick
        DoSomething();
        break;
    default:
        DoSomethingElse();
        break;
}