Programs & Examples On #Packet sniffers

A software or a piece of computer hardware that can intercept and log traffic passing over a digital network or part of a network

iPhone and WireShark

This worked for me:

  1. Connect your iOS device by USB

  2. $ rvictl -s UDID where UDID is the UDID of your device (located in XCode under Devices, shortcut to with ??2)

  3. $ sudo launchctl list com.apple.rpmuxd

  4. $ sudo tcpdump -n -t -i rvi0 -q tcp or $ sudo tcpdump -i rvi0 -n

If victl is not working install Xcode and the developer tools.

For more info see Remote Virtual Interface and for the original tutorial here's the Use Your Loaf blog post

Wireshark localhost traffic capture

For some reason, none of previous answers worked in my case, so I'll post something that did the trick. There is a little jewel called RawCap that can capture localhost traffic on Windows. Advantages:

  • only 17 kB!
  • no external libraries needed
  • extremely simple to use (just start it, choose the loopback interface and destination file and that's all)

After the traffic has been captured, you can open it and examine in Wireshark normally. The only disadvantage that I found is that you cannot set filters, i.e. you have to capture all localhost traffic which can be heavy. There is also one bug regarding Windows XP SP 3.

Few more advices:

Detect click inside/outside of element with single event handler

In JavaScript (via jQuery):

_x000D_
_x000D_
$(function() {_x000D_
  $("body").click(function(e) {_x000D_
    if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {_x000D_
      alert("Inside div");_x000D_
    } else {_x000D_
      alert("Outside div");_x000D_
    }_x000D_
  });_x000D_
})
_x000D_
#myDiv {_x000D_
  background: #ff0000;_x000D_
  width: 25vw;_x000D_
  height: 25vh;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"></div>
_x000D_
_x000D_
_x000D_

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

How to import a bak file into SQL Server Express

There is a step by step explanation (with pictures) available @ Restore DataBase

  1. Click Start, select All Programs, click Microsoft SQL Server 2008 and select SQL Server Management Studio.
    This will bring up the Connect to Server dialog box.
    Ensure that the Server name YourServerName and that Authentication is set to Windows Authentication.
    Click Connect.

  2. On the right, right-click Databases and select Restore Database.
    This will bring up the Restore Database window.

  3. On the Restore Database screen, select the From Device radio button and click the "..." box.
    This will bring up the Specify Backup screen.

  4. On the Specify Backup screen, click Add.
    This will bring up the Locate Backup File.

  5. Select the DBBackup folder and chose your BackUp File(s).

  6. On the Restore Database screen, under Select the backup sets to restore: place a check in the Restore box, next to your data and in the drop-down next to To database: select DbName.

  7. You're done.

Daemon Threads Explanation

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

Node.js heap out of memory

The following environment variable can be used:

NODE_OPTIONS= --max-old-space-size=8192 .

Another note: console.log() also consumes memory in the terminal.

just tried to comment the console.log() on terminal. because that will also take memory.

Using iFrames In ASP.NET

How about:

<asp:HtmlIframe ID="yourIframe" runat="server" />

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

How and where to use ::ng-deep?

USAGE

::ng-deep, >>> and /deep/ disable view encapsulation for specific CSS rules, in other words, it gives you access to DOM elements, which are not in your component's HTML. For example, if you're using Angular Material (or any other third-party library like this), some generated elements are outside of your component's area (such as dialog) and you can't access those elements directly or using a regular CSS way. If you want to change the styles of those elements, you can use one of those three things, for example:

::ng-deep .mat-dialog {
  /* styles here */
}

For now Angular team recommends making "deep" manipulations only with EMULATED view encapsulation.

DEPRECATION

"deep" manipulations are actually deprecated too, BUT it stills working for now, because Angular does pre-processing support (don't rush to refuse ::ng-deep today, take a look at deprecation practices first).

Anyway, before following this way, I recommend you to take a look at disabling view encapsulation approach (which is not ideal too, it allows your styles to leak into other components), but in some cases, it's a better way. If you decided to disable view encapsulation, it's strongly recommended to use specific classes to avoid CSS rules intersection, and finally, avoid a mess in your stylesheets. It's really easy to disable right in the component's .ts file:

@Component({
  selector: '',
  template: '',
  styles: [''],
  encapsulation: ViewEncapsulation.None  // Use to disable CSS Encapsulation for this component
})

You can find more info about the view encapsulation in this article.

symfony2 twig path with parameter url creation

Make sure your routing.yml file has 'id' specified in it. In other words, it should look like:

_category:
    path: /category/{id}

Escape double quotes in a string

No.

Either use verbatim string literals as you have, or escape the " using backslash.

string test = "He said to me, \"Hello World\" . How are you?";

The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.

Java OCR implementation

I recommend trying the Java OCR project on sourceforge.net. I originally developed it, and I have a blog posting on it.

Since I put it up on sourceforge, its functionality been expanded and improved quite a bit through the great work of a volunteer researcher/developer.

Give it a try, and if you don't like it, you can always improve it!

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

How to print a groupby object

you cannot see the groupBy data directly by print statement but you can see by iterating over the group using for loop try this code to see the group by data

group = df.groupby('A') #group variable contains groupby data
for A,A_df in group: # A is your column and A_df is group of one kind at a time
  print(A)
  print(A_df)

you will get an output after trying this as a groupby result

I hope it helps

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

The parameter of exit should qualify if the execution of the program went good or bad. It's a sort of heredity from older programming languages where it's useful to know if something went wrong and what went wrong.

Exit code is

  • 0 when execution went fine;
  • 1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.

If I'm correct exit codes used to be just positive numbers (I mean in UNIX) and according to range:

  • 1-127 are user defined codes (so generated by calling exit(n))
  • 128-255 are codes generated by termination due to different unix signals like SIGSEGV or SIGTERM

But I don't think you should care while coding on Java, it's just a bit of information. It's useful if you plan to make your programs interact with standard tools.

jQuery Datepicker with text input that doesn't allow user input

Here is your answer which is way to solve.You do not want to use jquery when you restricted the user input in textbox control.

<input type="text" id="my_txtbox" readonly />  <!--HTML5-->

<input type="text" id="my_txtbox" readonly="true"/>

Center HTML Input Text Field Placeholder

input{
   text-align:center;
}

is all you need.

Working example in FF6. This method doesn't seem to be cross-browser compatible.

Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".

How to set border on jPanel?

An empty border is transparent. You need to specify a Line Border or some other visible border when you set the border in order to see it.

Based on Edit to question:

The painting does not honor the border. Add this line of code to your test and you will see the border:

    jboard.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
    jboard.add(new JButton("Test"));  //Add this line
    frame.add(jboard);

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Ahah! Cade is on the money.

An artifact in TOAD prints \r\n as two placeholder 'blob' characters, but prints a single \r also as two placeholders. The 1st step toward a solution is to use ..

REPLACE( col_name, CHR(13) || CHR(10) )

.. but I opted for the slightly more robust ..

REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )

.. which catches offending characters in any order. My many thanks to Cade.

M.

access key and value of object using *ngFor

Here is the simple solution

You can use typescript iterators for this

import {Component} from 'angular2/core';
declare var Symbol;
@Component({
    selector: 'my-app',
    template:`<div>
    <h4>Iterating an Object using Typescript Symbol</h4><br>
Object is : <p>{{obj | json}}</p>
</div>
============================<br>
Iterated object params are:
<div *ngFor="#o of obj">
{{o}}
</div>

`
})
export class AppComponent {
  public obj: any = {
    "type1": ["A1", "A2", "A3","A4"],
    "type2": ["B1"],
    "type3": ["C1"],
    "type4": ["D1","D2"]
  };

  constructor() {
    this.obj[Symbol.iterator] =  () => {
          let i =0;

          return {
            next: () => {
              i++;
              return {
                  done: i > 4?true:false,
                  value: this.obj['type'+i]
              }
            }
          }
    };
  }
}

http://plnkr.co/edit/GpmX8g?p=info

Java - get index of key in HashMap?

You can't - a set is unordered, so there's no index provided. You'll have to declare an int, as you say. Just remember that the next time you call keySet() you won't necessarily get the results in the same order.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

You need the Apache Commons Codec library 1.4 or above in your classpath. This library contains Base64 implementation.

How to get a list of programs running with nohup

You can also just use the top command and your user ID will indicate the jobs running and the their times.

$ top

(this will show all running jobs)

$ top -U [user ID]

(This will show jobs that are specific for the user ID)

Password masking console application

This masks the password with a red square, then reverts back to the original colours once the password has been entered.

It doesn't stop the user from using copy/paste to get the password, but if it's more just about stopping someone looking over your shoulder, this is a good quick solution.

Console.Write("Password ");
ConsoleColor origBG = Console.BackgroundColor; // Store original values
ConsoleColor origFG = Console.ForegroundColor;

Console.BackgroundColor = ConsoleColor.Red; // Set the block colour (could be anything)
Console.ForegroundColor = ConsoleColor.Red;

string Password = Console.ReadLine(); // read the password

Console.BackgroundColor= origBG; // revert back to original
Console.ForegroundColor= origFG;

How to display a list of images in a ListView in Android?

Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.

In main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

  <TextView
      android:id="@+id/textview"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />

 <ListView
     android:id="@+id/listview"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

create listview_layout.xml and paste this code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

   <ImageView
      android:id="@+id/flag"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:contentDescription="@string/hello"
      android:paddingTop="10dp"
      android:paddingRight="10dp"
      android:paddingBottom="10dp" />

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

     <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/cur"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10dp"
        android:text="TextView2" />
   </LinearLayout>

In your Activity

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class SimpleListImageActivity extends Activity {

    // Array of strings storing country names
    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    // Array of integers points to images stored in /res/drawable-hdpi/

   //here you have to give image name which you already pasted it in /res/drawable-hdpi/

     int[] flags = new int[]{
        R.drawable.image1,
        R.drawable.image2,   
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7,
        R.drawable.image8,
        R.drawable.image9,
        R.drawable.image10,
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
        "Indian Rupee",
        "Pakistani Rupee",
        "Sri Lankan Rupee",
        "Renminbi",
        "Bangladeshi Taka",
        "Nepalese Rupee",
        "Afghani",
        "North Korean Won",
        "South Korean Won",
        "Japanese Yen"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
            HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur","Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt","cur" };

        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt,R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = ( ListView ) findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
    }
}

This is the full code.you can make changes to your need... Comments are welcome

SQL changing a value to upper or lower case

You can use LOWER function and UPPER function. Like

SELECT LOWER('THIS IS TEST STRING')

Result:

this is test string

And

SELECT UPPER('this is test string')

result:

THIS IS TEST STRING

How do I analyze a .hprof file?

You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.

You need Java 6+ to fully use Visual VM.

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "os"
)

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

What SOAP client libraries exist for Python, and where is the documentation for them?

Im using SOAPpy with Python 2.5.3 in a production setting.

I had to manually edit a couple of files in SOAPpy (something about header code being in the wrong place) but other than that it worked and continues to do so very reliably.

What is the purpose of the vshost.exe file?

The vshost.exe file is the executable run by Visual Studio (Visual Studio host executable). This is the executable that links to Visual Studio and improves debugging.

When you're distributing your application to others, you do not use the vshost.exe or .pdb (debug database) files.

How to pass password automatically for rsync SSH command?

You can avoid the password prompt on rsync command by setting the environment variable RSYNC_PASSWORD to the password you want to use or using the --password-file option.

json_decode() expects parameter 1 to be string, array given

  • Make an object

    $obj = json_decode(json_encode($need_to_json));

  • Show data from this $obj

    $obj->{'needed'};

Reference

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

How can I get the error message for the mail() function?

Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php and checkErrorEmail.php and uploaded them to your server. Then load index.php with your browser.

Index.php

<?php
    include('checkErrorEmail.php');
    include('dereporting.php');
    $temp;
    echo 'hi '.$temp;
?>

checkErrorEmail.php

<?php
  // Destinations
  define("ADMIN_EMAIL", "[email protected]");
  //define("LOG_FILE", "/my/home/errors.log");

  // Destination types
  define("DEST_EMAIL", "1");
  //define("DEST_LOGFILE", "3");

  /* Examples */

  // Send an e-mail to the administrator
  //error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  //error_log("Error", DEST_LOGFILE, LOG_FILE);

  /**
    * my_error_handler($errno, $errstr, $errfile, $errline)
    *
    * Author(s): thanosb, ddonahue
    * Date: May 11, 2008
    * 
    * custom error handler
    *
    * Parameters:
    *  $errno:   Error level
    *  $errstr:  Error message
    *  $errfile: File in which the error was raised
    *  $errline: Line at which the error occurred
    */

  function my_error_handler($errno, $errstr, $errfile, $errline)
  {  
  echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
      if($errno)
      {
              error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
      }
    /*switch ($errno) {
      case E_USER_ERROR:
        // Send an e-mail to the administrator
        error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

        // Write the error to our log file
        //error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_WARNING:
        // Write the error to our log file
        //error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_NOTICE:
        // Write the error to our log file
       // error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      default:
        // Write the error to our log file
        //error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;
    }*/

    // Don't execute PHP's internal error handler
    return TRUE;
  }


  // Use set_error_handler() to tell PHP to use our method
  $old_error_handler = set_error_handler("my_error_handler");


?>

Extract the filename from a path

You can try this:

[System.IO.FileInfo]$path = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
# Returns name and extension
$path.Name
# Returns just name
$path.BaseName

HQL Hibernate INNER JOIN

Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team, of type int, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

Then, the following query will work flawlessly:

select e from Employee e inner join e.team

Which will load all the employees, except those that aren't associated to any team.

The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss, id_profession).

It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.

How to run .sql file in Oracle SQL developer tool to import database?

As others recommend, you can use Oracle SQL Developer. You can point to the location of the script to run it, as described. A slightly simpler method, though, is to just use drag-and-drop:

  • Click and drag your .sql file over to Oracle SQL Developer
  • The contents will appear in a "SQL Worksheet"
  • Click "Run Script" button, or hit F5, to run

enter image description here

Throwing exceptions from constructors

It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:

class A
{
public:
  A () {
    throw int ();
  }
};

A a;     // Implementation defined behaviour if exception is thrown (15.3/13)

int main ()
{
  try
  {
    // Exception for 'a' not caught here.
  }
  catch (int)
  {
  }
}

How to save select query results within temporary table?

You can also do the following:

CREATE TABLE #TEMPTABLE
(
    Column1 type1,
    Column2 type2,
    Column3 type3
)

INSERT INTO #TEMPTABLE
SELECT ...

SELECT *
FROM #TEMPTABLE ...

DROP TABLE #TEMPTABLE

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Have you tried @Lazy loading the datasource? Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your DataSource (until the JNDI vars have been setup).

N.B. I haven't had a chance to test this code yet!

@Lazy
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    //bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

You may also need to add the @Lazy annotation wherever the DataSource is being used. e.g.

@Lazy
@Autowired
private DataSource dataSource;

How do I sleep for a millisecond in Perl?

From the Perldoc page on sleep:

For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().

Actually, it provides usleep() (which sleeps in microseconds) and nanosleep() (which sleeps in nanoseconds). You may want usleep(), which should let you deal with easier numbers. 1 millisecond sleep (using each):

use strict;
use warnings;

use Time::HiRes qw(usleep nanosleep);

# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);

If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select() function:

# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

Align <div> elements side by side

Beware float: left

…there are many ways to align elements side-by-side.

Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {
  background: mediumpurple;
  padding: 1rem;
}
.child {
  border: 1px solid indigo;
  padding: 1rem;
}

float:left

Using the float solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)

html

<div class='parent'>
  <div class='child float-left-child'>A</div>
  <div class='child float-left-child'>B</div>
</div>

css

.float-left-child {
  float: left;
}

display:inline-block

html

<div class='parent'>
  <div class='child inline-block-child'>A</div>
  <div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

Note: the space between these two child elements can be removed, by removing the space between the div tags:

display:inline-block (no space)

html

<div class='parent'>
  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

display:flex

html

<div class='parent flex-parent'>
  <div class='child flex-child'>A</div>
  <div class='child flex-child'>B</div>
</div>

css

.flex-parent {
  display: flex;
}
.flex-child {
  flex: 1;
}

display:inline-flex

html

<div class='parent inline-flex-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.inline-flex-parent {
  display: inline-flex;
}

display:grid

html

<div class='parent grid-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.grid-parent {
  display: grid;
  grid-template-columns: 1fr 1fr
}

Maven 3 warnings about build.plugins.plugin.version

Maven 3 is more restrictive with the POM-Structure. You have to set versions of Plugins for instance.

With maven 3.1 these warnings may break you build. There are more changes between maven2 and maven3: https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes

Can't access Tomcat using IP address

If you are trying to access your web app which is running on apache tomcat server, it might be working perfect while you are trying to use it on http://localhost:8080/ , it will not work same if you are trying to access it on your mobile device browser for ex. chrome using http://192.168.x.x:8080/ so if you want to access via ip address on your remote/mobile device , do following settings

  1. Open server.xml file.
  2. Change

    <Connector connectionTimeout="20000" port="8080"protocol="HTTP/1.1" redirectPort="8443"/>
    

to.

    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" address="0.0.0.0" />
  1. Save the file
  2. Stop and restart the server
  3. Now access on your mobile device using ip address http://192.168.1.X:8080/

You are good to go.

How do I prevent site scraping?

I have done a lot of web scraping and summarized some techniques to stop web scrapers on my blog based on what I find annoying.

It is a tradeoff between your users and scrapers. If you limit IP's, use CAPTCHA's, require login, etc, you make like difficult for the scrapers. But this may also drive away your genuine users.

After MySQL install via Brew, I get the error - The server quit without updating PID file

The key takeaway is to check the .err file, by default on Mac OSX it's in /usr/local/var/mysql.

That log filed revealed to me that I had to delete the following files:

ibdata1
ib_logfile0
ib_logfile1

Running MySQL with mysql.start worked successfully after that. Note that deleting those files will likely causes data loss.

Listening for variable changes in JavaScript

Yes, this is now completely possible!

I know this is an old thread but now this effect is possible using accessors (getters and setters): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters

You can define an object like this, in which aInternal represents the field a:

x = {
  aInternal: 10,
  aListener: function(val) {},
  set a(val) {
    this.aInternal = val;
    this.aListener(val);
  },
  get a() {
    return this.aInternal;
  },
  registerListener: function(listener) {
    this.aListener = listener;
  }
}

Then you can register a listener using the following:

x.registerListener(function(val) {
  alert("Someone changed the value of x.a to " + val);
});

So whenever anything changes the value of x.a, the listener function will be fired. Running the following line will bring the alert popup:

x.a = 42;

See an example here: https://jsfiddle.net/5o1wf1bn/1/

You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

How can I simulate a click to an anchor tag?

well, you can very quickly test the click dispatch via jQuery like so

$('#link-id').click();

If you're still having problem with click respecting the target, you can always do this

$('#link-id').click( function( event, anchor )
{
  window.open( anchor.href, anchor.target, '' );
  event.preventDefault();
  return false;
});

Type converting slices of interfaces

Convert interface{} into any type.

Syntax:

result := interface.(datatype)

Example:

var employee interface{} = []string{"Jhon", "Arya"}
result := employee.([]string)   //result type is []string.

Python: Passing variables between functions

passing variable from one function as argument to other functions can be done like this

define functions like this

def function1():
global a
a=input("Enter any number\t")

def function2(argument):
print ("this is the entered number - ",argument)

call the functions like this

function1()
function2(a)

VBA copy cells value and format

This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype

It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.

Pass request headers in a jQuery AJAX GET call

_x000D_
_x000D_
$.ajax({_x000D_
            url: URL,_x000D_
            type: 'GET',_x000D_
            dataType: 'json',_x000D_
            headers: {_x000D_
                'header1': 'value1',_x000D_
                'header2': 'value2'_x000D_
            },_x000D_
            contentType: 'application/json; charset=utf-8',_x000D_
            success: function (result) {_x000D_
               // CallBack(result);_x000D_
            },_x000D_
            error: function (error) {_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

Are iframes considered 'bad practice'?

It's 'bad practice' to use them without understanding their drawbacks. Adzm's post sums them up very well.

On the flipside, gmail makes heavy use of iFrames in the background for some of it's cooler features (like the automatic file upload). If you're aware of the limitations of iFrames I don't believe you should feel any compunction about using them.

input type="submit" Vs button tag are they interchangeable?

If you are talking about <input type=button>, it won't automatically submit the form

if you are talking about the <button> tag, that's newer and doesn't automatically submit in all browsers.

Bottom line, if you want the form to submit on click in all browsers, use <input type="submit">

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

Just in case if this helps anybody.

Python version: 3.7.7 platform: Ubuntu 18.04.4 LTS

This came with default python version 3.6.9, however I had installed my own 3.7.7 version python on it (installed building it from source)

tkinter was not working even when the help('module') shows tkinter in the list.

The following steps worked for me:

  1. sudo apt-get install tk-dev.

rebuild the python: 1. Navigate to your python folder and run the checks:

cd Python-3.7.7
sudo ./configure --enable-optimizations
  1. Build using make command: sudo make -j 8 --- here 8 are the number of processors, check yours using nproc command.
  2. Installing using:

    sudo make altinstall
    

Don't use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.

  1. Check tkinter now
    python3.7 -m tkinter
    

A windows box will pop up, your tkinter is ready now.

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

Complete list of reasons why a css file might not be working

I'm using Wordpress and the stylesheet was set to enqueue to the footer

wp_enqueue_style(
        'editor-css',
        $stylesheet_directory_uri . '/assets/css/editor.css',
        ['wp-edit-blocks'],
        null,
        true   // $in_footer
    );
}

This resulted in a media="1" attribute getting added to the <link> tag and resulted in the stylesheet being loaded but not applied.

Changed the parameter to false and its working now

Converting a char to uppercase

I think you are trying to capitalize first and last character of each word in a sentence with space as delimiter.

Can be done through StringBuffer:

public static String toFirstLastCharUpperAll(String string){
    StringBuffer sb=new StringBuffer(string);
        for(int i=0;i<sb.length();i++)
            if(i==0 || sb.charAt(i-1)==' ' //for first character of string/each word
                || i==sb.length()-1 || sb.charAt(i+1)==' ') //for last character of string/each word
                sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
     return sb.toString();
}

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

Bootstrap 3 Horizontal and Vertical Divider

I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)

Fiddle: https://jsfiddle.net/tqmfpwhv/1/


css based on OP information, media query at end is for med & lg view.

.vr-all {
    padding:0px;
    border-right:1px solid #CC0000;
}
.vr-xs {
    padding:0px;
}
.vr-md {
    padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
    border-color: #CC0000;
    border-style: solid;
    border-bottom: 1px;
    margin:0px;
    padding:0px;
}
/* for medium and up */
@media(min-width:992px){
    .vr-xs {
        border-right:1px solid #CC0000;
    }
    }

html adjustments to OP provided code. Red border and Img links for example.

<div class="container">
  <div class="row">
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
            <h5>Rich Media Ad Production</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
            <h5>Web Design & Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
            <h5>Mobile Apps Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
            <h5>Creative Design</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for for all viewports -->
        <div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
            <h5>Web Analytics</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
            <h5>Search Engine Marketing</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
            <h5>Mobile Apps Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
            <h5>Quality Assurance</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>


    </div>
</div>

How do I add a newline to a windows-forms TextBox?

Try using Environment.NewLine:

Gets the newline string defined for this environment.

Something like this ought to work:

textBox.AppendText("your new text" & Environment.NewLine)

gradlew: Permission Denied

Try below command:

chmod +x gradlew && ./gradlew compileDebug --stacktrace

UIButton Image + Text IOS

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.image = [UIImage imageNamed:@"your image name here"];
button.titleLabel.text = @"your text here";

but following code will show label above and image in background

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.background.image = [UIImage imageNamed:@"your image name here"];
button.titleLabel.text = @"your text here";

There is no need to use label and button in same control because UIButton has UILabel and UIimageview properties.

DataRow: Select cell value by a given column name

Which version of .NET are you using? Since .NET 3.5, there's an assembly System.Data.DataSetExtensions, which contains various useful extensions for dataTables, dataRows and the like.

You can try using

row.Field<type>("fieldName");

if that doesn't work, you can do this:

DataTable table = new DataTable();
var myColumn = table.Columns.Cast<DataColumn>().SingleOrDefault(col => col.ColumnName == "myColumnName");
if (myColumn != null)
{
    // just some roww
    var tableRow = table.AsEnumerable().First();
    var myData = tableRow.Field<string>(myColumn);
    // or if above does not work
    myData = tableRow.Field<string>(table.Columns.IndexOf(myColumn));
}

Reading *.wav files in Python

u can also use simple import wavio library u also need have some basic knowledge of the sound.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

force browsers to get latest js and css files in asp.net application

The main problem with doing it this way is mainly that you will need to remember to update your version number in your code every time you make any change to your css or js files.

A possibly better way to do it is to set a guaranteed unique parameter with each of your css or js files, like so:

<script src="scripts/myjavascript.js?_=<%=DateTime.Now.Ticks%>" type="text/javascript"></script>
<link href="styles/mystyle.css?_=<%=DateTime.Now.Ticks%>" rel="stylesheet" type="text/css" />

This forces the files to be requested from the server every single time, which also means that your site will not be as performant upon page load, since those files will never be cached, and will use unneeded bandwidth each time.

Essentially, if you can remember to update the version number every time a change is made, you can get away with how you're doing it.

EnterKey to press button in VBA Userform

Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default property of the button to True (you can set this in the properties window, open by hitting F4)

That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel property of a button to True would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)


Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896

How to uncheck checkbox using jQuery Uniform library

you need to call $.uniform.update() if you update element using javascript as mentioned in the documentation.

Convert hex string to int in Python

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

>>> 0xffff

65535

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

Right Click Microsoft BI -> Click Run as Administrator -> either open your existing SSRS report or create your new SSRS report and then deploy your report after that complied you will be received one web URL for to view your report. Copy that URL and paste to web browser(Run as Administrator) and you will get your report view. You could use Internet Explorer, which would be essential for web service

If it is wrong means,Please forgive me since i did like this so that i just written.

How do I run a program with commandline arguments using GDB within a Bash script?

In addition to the answer of Hugo Ideler. When using arguments having themself prefix like -- or -, I was not sure to conflict with gdb one.

It seems gdb takes all after args option as arguments for the program.

At first I wanted to be sure, I ran gdb with quotes around your args, it is removed at launch.

This works too, but optional:

gdb --args executablename "--arg1" "--arg2" "--arg3"

This doesn't work :

gdb --args executablename "--arg1" "--arg2" "--arg3" -tui

In that case, -tui is used as my program parameter not as gdb one.

When to use @QueryParam vs @PathParam

This is what I do.

If there is a scenario to retrieve a record based on id, for example you need to get the details of the employee whose id is 15, then you can have resource with @PathParam.

GET /employee/{id}

If there is a scenario where you need to get the details of all employees but only 10 at a time, you may use query param

GET /employee?start=1&size=10

This says that starting employee id 1 get ten records.

To summarize, use @PathParam for retrieval based on id. User @QueryParam for filter or if you have any fixed list of options that user can pass.

How do I put a clear button inside my HTML text input box like the iPhone does?

You can't actually put it inside the text box unfortunately, only make it look like its inside it, which unfortunately means some css is needed :P

Theory is wrap the input in a div, take all the borders and backgrounds off the input, then style the div up to look like the box. Then, drop in your button after the input box in the code and the jobs a good'un.

Once you've got it to work anyway ;)

How to replace all dots in a string using JavaScript

mystring.replace(new RegExp('.', "g"), ' ');

How to kill all processes with a given partial name?

Also you can use killall -r my_pattern. -r Interpret process name pattern as an extended regular expression.

killall -r my_pattern

How to completely remove a dialog on close

You can do use

$(dialogElement).empty();    
$(dialogElement).remove();

Assign keyboard shortcut to run procedure

For assigning a keyboard key to button on the sheet you can use this code, just copy this code to the sheet which contain the button.

Here Return specifies the key and get_detail is the procedure name.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.OnKey "{RETURN}", "get_detail"

End Sub

Now within this sheet whenever you press Enter button the assigned macro will be called.

What is $@ in Bash?

Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters

Special Parameters

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Cast IList to List

If you have an IList containing interfaces, you can cast it like this:

List to IList

List<Foo> Foos = new List<Foo>(); 
IList<IFoo> IFoos = Foos.ToList<IFoo>();

IList to List

IList<IFoo> IFoos = new List<IFoo>();
List<Foo> Foos = new List<Foo>(IFoos.Select(x => (Foo)x));

This assumes Foo has IFoo interfaced.

Android Linear Layout - How to Keep Element At Bottom Of View?

try this

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewProfileName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

Change select box option background color

Simply change bg color

select { background: #6ac17a; color:#fff; }

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

Add 10 seconds to a Date

Just for the performance maniacs among us.

getTime

var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);

5,196,949 Ops/sec, fastest


setSeconds

var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);

2,936,604 Ops/sec, 43% slower


moment.js

var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');

22,549 Ops/sec, 100% slower


So maybe its the least human readable (not that bad) but the fastest way of going :)

jspref online tests

Setting background-image using jQuery CSS property

The problem I was having, is that I kept adding a semi-colon ; at the end of the url() value, which prevented the code from working.

? NOT WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');

? WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');

Notice the omitted semi-colon ; at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.

How to select date without time in SQL

If you want to return a date type as just a date use

CONVERT(date, SYSDATETIME())

or

SELECT CONVERT(date,SYSDATETIME()) 

or

DECLARE @DateOnly Datetime
SET @DateOnly=CONVERT(date,SYSDATETIME())

How to include a PHP variable inside a MySQL statement

The text inside $type is substituted directly into the insert string, therefore MySQL gets this:

... VALUES(testing, 'john', 'whatever')

Notice that there are no quotes around testing, you need to put these in like so:

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");

I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:

Mac OS X and multiple Java versions

I followed steps in below link - https://medium.com/@euedofia/fix-default-java-version-on-maven-on-mac-os-x-156cf5930078 and it worked for me.

cd /usr/local/Cellar/maven/3.5.4/bin/
nano mvn
--Update JAVA_HOME -> "${JAVA_HOME:-$(/usr/libexec/java_home)}"
mvn -version

How can I create persistent cookies in ASP.NET?

Although the accepted answer is correct, it does not state why the original code failed to work.

Bad code from your question:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.

Corrected code:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);

How can I display a pdf document into a Webview?

You can use Google PDF Viewer to read your pdf online:

WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); 
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

How to specify a min but no max decimal using the range data annotation attribute?

You can use custom validation:

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public int IntValue { get; set; }

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public decimal DecValue { get; set; }

Validation methods type:

public class ValidationMethods
{
    public static ValidationResult ValidateGreaterOrEqualToZero(decimal value, ValidationContext context)
    {
        bool isValid = true;

        if (value < decimal.Zero)
        {
            isValid = false;
        }

        if (isValid)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult(
                string.Format("The field {0} must be greater than or equal to 0.", context.MemberName),
                new List<string>() { context.MemberName });
        }
    }
}

How can I list all foreign keys referencing a given table in SQL Server?

Mysql server has information_schema.REFERENTIAL_CONSTRAINTS table FYI, you can filter it by table name or referenced table name.

How do I compare two DateTime objects in PHP 5.2.8?

If you want to compare dates and not time, you could use this:

$d1->format("Y-m-d") == $d2->format("Y-m-d")

How to change the timeout on a .NET WebClient object

As Sohnee says, using System.Net.HttpWebRequest and set the Timeout property instead of using System.Net.WebClient.

You can't however set an infinite timeout value (it's not supported and attempting to do so will throw an ArgumentOutOfRangeException).

I'd recommend first performing a HEAD HTTP request and examining the Content-Length header value returned to determine the number of bytes in the file you're downloading and then setting the timeout value accordingly for subsequent GET request or simply specifying a very long timeout value that you would never expect to exceed.

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

How to convert the background to transparent?

For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif....

How do I edit SSIS package files?

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

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

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

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

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

changing textbox border colour using javascript

I'm agree with Vicente Plata you should try using jQuery IMHO is the best javascript library. You can create a class in your CSS file and just do the following with jquery:

$('#fName').addClass('name_of_the_class'); 

and that's all, and of course you won't be worried about incompatibility of the browsers, that's jquery's team problem :D LOL

SQL - Select first 10 rows only?

In MySQL:

SELECT * FROM `table` LIMIT 0, 10

Check if number is decimal

i use this:

function is_decimal ($price){
  $value= trim($price); // trim space keys
  $value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
  $value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
  $value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12

  return $value;
}

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

CSS grid wrapping

Use either auto-fill or auto-fit as the first argument of the repeat() notation.

<auto-repeat> variant of the repeat() notation:

repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )

auto-fill

When auto-fill is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

The grid will repeat as many tracks as possible without overflowing its container.

Using auto-fill as the repetition number of the repeat() notation

In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.

The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.


auto-fit

The auto-fit keyword behaves the same as auto-fill, except that after grid item placement any empty repeated tracks are collapsed.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0.

A collapsed track is treated as having a fixed track sizing function of 0px.

Using auto-fit as the repetition number of the repeat() notation

Unlike the auto-fill image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.


auto-fill vs auto-fit

The difference between the two is noticeable when the minmax() function is used.

Use minmax(186px, 1fr) to range the items from 186px to a fraction of the leftover space in the grid container.

When using auto-fill, the items will grow once there is no space to place empty tracks.

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

When using auto-fit, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px.

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_


Playground:

CodePen

Inspecting auto-fill tracks

auto-fill


Inspecting auto-fit tracks

auto-fit

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

MySQL select query with multiple conditions

You have conditions that are mutually exclusive - if meta_key is 'first_name', it can't also be 'yearofpassing'. Most likely you need your AND's to be OR's:

$result = mysql_query("SELECT user_id FROM wp_usermeta 
WHERE (meta_key = 'first_name' AND meta_value = '$us_name') 
OR (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') 
OR (meta_key = 'u_city' AND meta_value = '$us_reg') 
OR (meta_key = 'us_course' AND meta_value = '$us_course')")

Disable PHP in directory (including all sub-directories) with .htaccess

None of those answers are working for me (either generating a 500 error or doing nothing). That is probably due to the fact that I'm working on a hosted server where I can't have access to Apache configuration.

But this worked for me :

RewriteRule ^.*\.php$ - [F,L]

This line will generate a 403 Forbidden error for any URL that ends with .php and ends up in this subdirectory.

@Oussama lead me to the right direction here, thanks to him.

CSV in Python adding an extra carriage return, on Windows

You have to add attribute newline="\n" to open function like this:

with open('file.csv','w',newline="\n") as out:
    csv_out = csv.writer(out, delimiter =';')

Find files with size in Unix

Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.

Example

find . -size +10000k -printf "%h/%f,%s\n"

Output

./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116

How to prompt for user input and read command-line arguments

As of Python 3.2 2.7, there is now argparse for processing command line arguments.

Could not complete the operation due to error 80020101. IE

I dont know why but it worked for me. If you have comments like

//Comment

Then it gives this error. To fix this do

/*Comment*/

Doesn't make sense but it worked for me.

Convert UTC/GMT time to local time

In answer to Dana's suggestion:

The code sample now looks like:

string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);

The original date was 20/08/08; the kind was UTC.

Both "convertedDate" and "dt" are the same:

21/08/08 10:00:26; the kind was local

Makefile ifeq logical or

ifeq ($(GCC_MINOR), 4)
    CFLAGS += -fno-strict-overflow
endif
ifeq ($(GCC_MINOR), 5)
    CFLAGS += -fno-strict-overflow
endif

Another you can consider using in this case is:

GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -c "^gcc version (4.[2-9]|[5-9])")

# -Wstrict-overflow: http://www.airs.com/blog/archives/120
ifeq ($(GCC42_OR_LATER),1)
  CFLAGS += -Wstrict-overflow
endif

I actually use the same in my code because I don't want to maintain a separate config or Configure.

But you have to use a portable, non-anemic make, like GNU make (gmake), and not Posix's make.

And it does not address the issue of logical AND and OR.

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

Submitting the value of a disabled input field

you can also use the Readonly attribute: the input is not gonna be grayed but it won't be editable

<input type="text" name="lat" value="22.2222" readonly="readonly" />

How to hide code from cells in ipython notebook visualized with nbviewer?

Many times, we need to hide some parts of codes while writing a long code.

Example: - Just on clicking "Code show/hide", we can hide 3 lines of codes.

enter image description here

So here is the function that you need to define for partially hiding few part of codes and then call it whenever you want to hide some code:

from IPython.display import HTML

def hide_toggle(for_next=False):
    this_cell = """$('div.cell.code_cell.rendered.selected')""" ; next_cell = this_cell + '.next()';
    toggle_text = 'Code show/hide'  # text shown on toggle link
    target_cell = this_cell ;  js_hide_current = '' 

    if for_next:
        target_cell = next_cell; toggle_text += ' next cell';
        js_hide_current = this_cell + '.find("div.input").hide();'
    js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))

    html = """<script>
            function {f_name}() {{{cell_selector}.find('div.input').toggle(); }}
            {js_hide_current}
        </script>
        <a href="javascript:{f_name}()">{toggle_text}</a>
    """.format(f_name=js_f_name,cell_selector=target_cell,js_hide_current=js_hide_current, toggle_text=toggle_text )
    return HTML(html)

Once we are ready with function definition, our next task is very easy. Just we need to call the function to hide/show the code.

print("Function for hiding the cell")
hide_toggle()

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

Open terminal here in Mac OS finder

If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items. I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):


on main(filelist)
    tell application "Finder"
        try
            activate
            set frontWin to folder of front window as string
            set frontWinPath to (get POSIX path of frontWin)
            tell application "Terminal"
                activate
                do script with command "cd \"" & frontWinPath & "\""
            end tell
        on error error_message
            beep
            display dialog error_message buttons ¬
                {"OK"} default button 1
        end try
    end tell
end main

Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.

How to use global variables in React Native?

You can use the global keyword to solve this.

Assume that you want to declare a variable called isFromManageUserAccount as a global variable you can use the following code.

global.isFromManageUserAccount=false;

After declaring like this you can use this variable anywhere in the application.

"python" not recognized as a command

emphasis: Remember to always RESTART the CMD WINDOW after setting the PATH environmental variable for it to take effect!

how to set ul/li bullet point color?

Apply the color to the li and set the span (or other child element) color to whatever color the text should be.

ul
{
    list-style-type: square;
}

ul > li
{
    color: green;
}

ul > li > span
{
    color: black;
}

JSFiddle

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

Most efficient way to increment a Map value in Java

Another way would be creating a mutable integer:

class MutableInt {
  int value = 0;
  public void inc () { ++value; }
  public int get () { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt> ();
MutableInt value = map.get (key);
if (value == null) {
  value = new MutableInt ();
  map.put (key, value);
} else {
  value.inc ();
}

of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.

2 column div layout: right column with fixed width, left fluid

Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like

div#left {

width: 600px;
float: left;
}

div#right {

width: 240px;
float: right;

}

div.clear {

clear:both;

}

place a the clear div under left and right container.

How to stop mongo DB in one command

My special case is:

previously start mongod by:

sudo -u mongod mongod -f /etc/mongod.conf

now, want to stop mongod.

and refer official doc Stop mongod Processes, has tried:

(1) shutdownServer but failed:

> use admin
switched to db admin
> db.shutdownServer()
2019-03-06T14:13:15.334+0800 E QUERY    [thread1] Error: shutdownServer failed: {
        "ok" : 0,
        "errmsg" : "shutdown must run from localhost when running db without auth",
        "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.shutdownServer@src/mongo/shell/db.js:302:1
@(shell):1:1

(2) --shutdown still failed:

# mongod --shutdown
There doesn't seem to be a server running with dbpath: /data/db

(3) previous start command adding --shutdown:

sudo -u mongod mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213
failed to kill process: errno:1 Operation not permitted

(4) use service to stop:

service mongod stop

and

service mongod status

show expected Active: inactive (dead) but mongod actually still running, for can see process from ps:

# ps -edaf | grep mongo | grep -v grep
root     30213     1  0 Feb04 ?        03:33:22 mongod --port PORT --dbpath=/var/lib/mongo

and finally, really stop mongod by:

# sudo mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213

until now, root cause: still unknown ...

hope above solution is useful for your.

Creating a segue programmatically

First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:

1). Define all your views with class file and also storyboard id in identity inspector.

2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller

3). In your first class, import the "secondClass.h"

#import "ViewController.h
#import "secondController.h"

4). Add this command in the IBAction that has to perform the segue

secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.navigationController pushViewController:next animated:YES];

5). @"second" is secondview controller class, storyboard id.

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

How to handle ListView click in Android

Use setOnItemClickListener() api in your activity. Following is the sample.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

@Override
public void onItemClick(AdapterView<> parent, View view, int position, long id)
{
     // your code here.
}

});

How to use relative paths without including the context root name?

This is a derivative of @Ralph suggestion that I've been using. Add the c:url to the top of your JSP.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/" var="root" />

Then just reference the root variable in your page:

<link rel="stylesheet" href="${root}templates/style/main.css">

How to call a php script/function on a html button click

Just try this:

<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){

            $.ajax({
                type: 'POST',
                url: 'script.php',
                success: function(data) {
                    alert(data);
                    $("p").text(data);

                }
            });
   });
});
</script>

In script.php

<?php 
  echo "You win";
 ?>

Googlemaps API Key for Localhost

It didn't work for me when I used

http://localhost{port}/
http://localhost:{port}/something-else/here

However, removing the http did the trick for me. I just added localhost:8000 without prefixing it with the http.

How do I style a <select> dropdown with only CSS?

I had this exact problem, except I couldn't use images and was not limited by browser support. This should be «on spec» and with luck start working everywhere eventually.

It uses layered rotated background layers to «cut out» a dropdown arrow, as pseudo-elements wouldn't work for the select element.

Edit: In this updated version I am using CSS variables and a tiny theming system.

_x000D_
_x000D_
:root {_x000D_
  --radius: 2px;_x000D_
  --baseFg: dimgray;_x000D_
  --baseBg: white;_x000D_
  --accentFg: #006fc2;_x000D_
  --accentBg: #bae1ff;_x000D_
}_x000D_
_x000D_
.theme-pink {_x000D_
  --radius: 2em;_x000D_
  --baseFg: #c70062;_x000D_
  --baseBg: #ffe3f1;_x000D_
  --accentFg: #c70062;_x000D_
  --accentBg: #ffaad4;_x000D_
}_x000D_
_x000D_
.theme-construction {_x000D_
  --radius: 0;_x000D_
  --baseFg: white;_x000D_
  --baseBg: black;_x000D_
  --accentFg: black;_x000D_
  --accentBg: orange;_x000D_
}_x000D_
_x000D_
select {_x000D_
  font: 400 12px/1.3 sans-serif;_x000D_
  -webkit-appearance: none;_x000D_
  appearance: none;_x000D_
  color: var(--baseFg);_x000D_
  border: 1px solid var(--baseFg);_x000D_
  line-height: 1;_x000D_
  outline: 0;_x000D_
  padding: 0.65em 2.5em 0.55em 0.75em;_x000D_
  border-radius: var(--radius);_x000D_
  background-color: var(--baseBg);_x000D_
  background-image: linear-gradient(var(--baseFg), var(--baseFg)),_x000D_
    linear-gradient(-135deg, transparent 50%, var(--accentBg) 50%),_x000D_
    linear-gradient(-225deg, transparent 50%, var(--accentBg) 50%),_x000D_
    linear-gradient(var(--accentBg) 42%, var(--accentFg) 42%);_x000D_
  background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;_x000D_
  background-size: 1px 100%, 20px 22px, 20px 22px, 20px 100%;_x000D_
  background-position: right 20px center, right bottom, right bottom, right bottom;   _x000D_
}_x000D_
_x000D_
select:hover {_x000D_
  background-image: linear-gradient(var(--accentFg), var(--accentFg)),_x000D_
    linear-gradient(-135deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(-225deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(var(--accentFg) 42%, var(--accentBg) 42%);_x000D_
}_x000D_
_x000D_
select:active {_x000D_
  background-image: linear-gradient(var(--accentFg), var(--accentFg)),_x000D_
    linear-gradient(-135deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(-225deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(var(--accentFg) 42%, var(--accentBg) 42%);_x000D_
  color: var(--accentBg);_x000D_
  border-color: var(--accentFg);_x000D_
  background-color: var(--accentFg);_x000D_
}
_x000D_
<select>_x000D_
  <option>So many options</option>_x000D_
  <option>...</option>_x000D_
</select>_x000D_
_x000D_
<select class="theme-pink">_x000D_
  <option>So many options</option>_x000D_
  <option>...</option>_x000D_
</select>_x000D_
_x000D_
<select class="theme-construction">_x000D_
  <option>So many options</option>_x000D_
  <option>...</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

What are best practices for multi-language database design?

I find this type of approach works for me:

Product     ProductDetail        Country
=========   ==================   =========
ProductId   ProductDetailId      CountryId
- etc -     ProductId            CountryName
            CountryId            Language
            ProductName          - etc -
            ProductDescription
            - etc -

The ProductDetail table holds all the translations (for product name, description etc..) in the languages you want to support. Depending on your app's requirements, you may wish to break the Country table down to use regional languages too.

How can I dynamically set the position of view in Android?

One thing to keep in mind with positioning is that each view has an index relative to its parent view. So if you have a linear layout with three subviews, the subviews will each have an index: 0, 1, 2 in the above case.

This allows you to add a view to the last position (or the end) in a parent view by doing something like this:

int childCount = parent.getChildCount();
parentView.addView(newView, childCount);

Alternatively you could replace a view using something like the following:

int childIndex = parentView.indexOfChild(childView);
childView.setVisibility(View.GONE);

parentView.addView(newView, childIndex);

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

Why does 2 mod 4 = 2?

Modulo is the remainder, expressed as an integer, of a mathematical division expression.

So, lets say you have a pixel on a screen at position 90 where the screen is 100 pixels wide and add 20, it will wrap around to position 10. Why...because 90 + 20 = 110 therefore 110 % 100 = 10.

For me to understand it I consider the modulo is the integer representation of fractional number. Furthermore if you do the expression backwards and process the remainder as a fractional number and then added to the divisor it will give you your original answer.

Examples:

    100
(A) ---  =  14 mod 2
     7

    123
(B) ---  =  8 mod 3
     15

     3
(C) ---  =  0 mod 3
     4

Reversed engineered to:

                        2      14(7)    2       98    2     100
 (A) 14 mod 2  =  14 + ---  =  ----- + ---  =  --- + ---  = ---
                        7        7      7       7     7      7

                      3      8(15)    3      120    3      123
 (B) 8 mod 3  =  8 + ---  =  ----- + ---  =  --- + ---  =  ---
                      15       15     15      15    15      15

                      3       3
 (B) 0 mod 3  =  0 + ---  =  ---
                      4       4

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

My problem turned out to be blank spaces in the txt file that I was using to feed the WMI Powershell script.

How to convert color code into media.brush?

For simplicity you could create an extension:-

    public static SolidColorBrush ToSolidColorBrush(this string hex_code)
    {
        return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
    }

And then to use:-

 SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

How to represent a fix number of repeats in regular expression?

^\w{14}$ in Perl and any Perl-style regex.

If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.

AngularJS resource promise

You could also do:

Regions.query({}, function(response) {
    $scope.regions = response;
    // Do stuff that depends on $scope.regions here
});

How to install pkg config in windows?

for w64-based computers you have to install mingw64. If pkg-config.exe is missing then, you can refer to http://ftp.acc.umu.se/pub/gnome/binaries/win64/dependencies/

Unzip and copy/merge pkg-config.exe into your C:\mingw-w64 installation, eg. into on my pc into C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin

CSS hide scroll bar, but have element scrollable

if you use sass, you can try this

&::-webkit-scrollbar { 

}

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

python how to pad numpy array with zeros

In case you need to add a fence of 1s to an array:

>>> mat = np.zeros((4,4), np.int32)
>>> mat
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
>>> mat[0,:] = mat[:,0] = mat[:,-1] =  mat[-1,:] = 1
>>> mat
array([[1, 1, 1, 1],
       [1, 0, 0, 1],
       [1, 0, 0, 1],
       [1, 1, 1, 1]])

Where are $_SESSION variables stored?

The location of the $_SESSION variable storage is determined by PHP's session.save_path configuration. Usually this is /tmp on a Linux/Unix system. Use the phpinfo() function to view your particular settings if not 100% sure by creating a file with this content in the DocumentRoot of your domain:

<?php
    phpinfo();
?>

Here is the link to the PHP documentation on this configuration setting:

http://php.net/manual/en/session.configuration.php#ini.session.save-path

How do I rotate a picture in WinForms

I have modified the function of Mr.net_prog which gets only the picture box and rotate the image in it.

    public static void RotateImage(PictureBox picBox)
    {

        Image img = picBox.Image;
        var bmp = new Bitmap(img);

        using (Graphics gfx = Graphics.FromImage(bmp))
        {
            gfx.Clear(Color.White);
            gfx.DrawImage(img, 0, 0, img.Width, img.Height);
        }

        bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
        picBox.Image = bmp;
    }

How can I show an image using the ImageView component in javafx and fxml?

It's recommended to put the image to the resources, than you can use it like this:

imageView = new ImageView("/gui.img/img.jpg");

Why XML-Serializable class need a parameterless constructor

First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?

I think there is a workaround to make constructor private.

How can I make Bootstrap columns all the same height?

I tried alot of the suggestions made in this thread and on other pages but no solution worked 100% in every browsers.

So I experimented quite some time and came up with this. A complete solution for Bootstrap Equal Height columns with the help of flexbox with only 1 class. This works in all major browsers IE10+.

CSS:

.row.equal-cols {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.row.equal-cols:before,
.row.equal-cols:after {
  display: block;
}

.row.equal-cols > [class*='col-'] {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
}

.row.equal-cols > [class*='col-'] > * {
  -webkit-flex: 1 1 auto;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto; 
}

HTML:

<div class="container">
  <div class="row equal-cols">
    <div class="col-sm-4">
      <div class="content"></div>
    </div>
    <div class="col-sm-4">
      <div class="content"></div>
    </div>
    <div class="col-sm-4">
      <div class="content"></div>
    </div>
  </div>
</div>

To support even more versions of IE you can, for example, use https://github.com/liabru/jquery-match-height and target all child columns of .equal-cols. Like this:

// Create a check for IE9 (or any other specific browser).
if(IE9) {
  $(".row.equal-cols > [class*='col-']").matchHeight();
}

Without this polyfill the columns will behave as usual Bootstrap columns so which is a quite good fallback.

converting date time to 24 hour format

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateFormatExample {

public static void main(String args[]) {

    // This is how to get today's date in Java
    Date today = new Date();

    //If you print Date, you will get un formatted output
    System.out.println("Today is : " + today);

    //formatting date in Java using SimpleDateFormat
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
    String date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yyyy format : " + date);

    //Another Example of formatting Date in Java using SimpleDateFormat
    DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd/MM/yy pattern : " + date);

    //formatting Date with time information
    DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yy:HH:mm:SS : " + date);

    //SimpleDateFormat example - Date with timezone information
    DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);

} 

}

Output:

Today is : Fri Nov 02 16:11:27 IST 2012

Today in dd-MM-yyyy format : 02-11-2012

Today in dd/MM/yy pattern : 02/11/12

Today in dd-MM-yy:HH:mm:SS : 02-11-12:16:11:316

Today in dd-MM-yy:HH:mm:SSZ : 02-11-12:16:11:316 +0530

Switch statement with returns -- code correctness

Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.

Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.

One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.

How to deserialize a list using GSON or another JSON library in Java?

Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

List<Video> = new ArrayList<>(Arrays.asList(videoArray));

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

Trust Store vs Key Store - creating with keytool

keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.

How to create a new text file using Python

f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2shush
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
# File closed automatically

Ruby max integer

FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))

PyCharm error: 'No Module' when trying to import own module (python script)

This can be caused when Python interpreter can't find your code. You have to mention explicitly to Python to find your code in this location.

To do so:

  • Go to your python console
  • Add sys.path.extend(['your module location']) to Python console.

In your case:

  • Go to your python console,
  • On the start, write the following code:

    import sys
    sys.path.extend([my module URI location])
    
  • Once you have written this statement you can run following command:

    from mymodule import functions
    

MySQL join with where clause

You need to put it in the join clause, not the where:

SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON 
    user_category_subscriptions.category_id = categories.category_id
    and user_category_subscriptions.user_id =1

See, with an inner join, putting a clause in the join or the where is equivalent. However, with an outer join, they are vastly different.

As a join condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1 first, and takes the subset of user_category_subscriptions with a user_id of 1 to join to all of the rows in categories. This will give you all of the rows in categories, while only the categories that this particular user has subscribed to will have any information in the user_category_subscriptions columns. Of course, all other categories will be populated with null in the user_category_subscriptions columns.

Conversely, a where clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id doesn't equal 1. You're left with an inefficient way to get an inner join.

Hopefully this helps!

How to add column to numpy array

It can be done like this:

import numpy as np

# create a random matrix:
A = np.random.normal(size=(5,2))

# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))

In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.

Parsing a JSON string in Ruby

As of Ruby v1.9.3 you don't need to install any Gems in order to parse JSON, simply use require 'json':

require 'json'

json = JSON.parse '{"foo":"bar", "ping":"pong"}'
puts json['foo'] # prints "bar"

See JSON at Ruby-Doc.

C# Form.Close vs Form.Dispose

As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.

Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.

In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.

Where does Oracle SQL Developer store connections?

If you have previously installed SQL Developer then it will store the connection details in the 'connection.xml' which will be located in below mentioned path.

C:\Users\Username\AppData\Roaming\SQL Developer\system3.1.07.42\o.jdeveloper.db.connection.11.1.1.4.37.59.48

Once you get that 'connection.xml' try to import it into SQLDeveloper by right clicking to CONNECTIONS.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

Another solution is to mix valueChangeListener, ajax and process:

<p:selectManyCheckbox id="employees" value="#{employees}" columns="1" layout="grid" valueChangeListener="#{mybean.fireSelection}"   >
    <f:selectItems var="employee" value="#{employeesSI}" />
    <p:ajax event="valueChange" immediate="true" process="@this"/>
</p:selectManyCheckbox>

Method in mybean is just :

public void fireSelection(ValueChangeEvent event) {
    log.debug("New: "+event.getNewValue()+", Old: "+event.getOldValue());
}

Like this, valueChangeEvent is very light !

PS: Works fine with PrimeFaces 5.0

sass --watch with automatic minify?

There are some different way to do that

sass --watch --style=compressed main.scss main.css

or

sass --watch a.scss:a.css --style compressed

or

By Using visual studio code extension live sass compiler

see more

How to submit http form using C#

Response.Write("<script> try {this.submit();} catch(e){} </script>");

Firebase Storage How to store and Retrieve images

I ended up storing the images in base64 format myself. I translate them from their base64 value when called back from firebase.

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

Bootstrap 3: Offset isn't working?

There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.

To get the result I believe you are looking for try this:

<div class="container">
    <div class="row">
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
    </div>
  </div>

Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.

Hope this helps.

Getting GET "?" variable in laravel

In laravel 5.3

I want to show the get param in my view

Step 1 : my route

Route::get('my_route/{myvalue}', 'myController@myfunction');

Step 2 : Write a function inside your controller

public function myfunction($myvalue)
{
    return view('get')->with('myvalue', $myvalue);
}

Now you're returning the parameter that you passed to the view

Step 3 : Showing it in my View

Inside my view you i can simply echo it by using

{{ $myvalue }}

So If you have this in your url

http://127.0.0.1/yourproject/refral/[email protected]

Then it will print [email protected] in you view file

hope this helps someone.

How to place Text and an Image next to each other in HTML?

img {
    float:left;
}
h3 {
    float:right;
}

jsFiddle example

Note that you will probably want to use the style clear:both on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.

How do I rewrite URLs in a proxy response in NGINX

We should first read the documentation on proxy_pass carefully and fully.

The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /. Absense of trailing slash means hat URI is absent.

Proxy_pass with URI:

location /some_dir/ {
    proxy_pass http://some_server/;
}

With the above, there's the following proxy:

http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/          some_subdir/some_file

Basically, /some_dir/ gets replaced by / to change the request path from /some_dir/some_subdir/some_file to /some_subdir/some_file.

Proxy_pass without URI:

location /some_dir/ {
    proxy_pass http://some_server;
}

With the second (no trailing slash): the proxy goes like this:

http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file

Basically, the full original request path gets passed on without changes.


So, in your case, it seems you should just drop the trailing slash to get what you want.


Caveat

Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:

location /some_dir/ {
  rewrite    /some_dir/(.*) /$1 break;
  proxy_pass $upstream_server;
}

There are other cases where rewrite wouldn't work, that's why reading documentation is a must.


Edit

Reading your question again, it seems I may have missed that you just want to edit the html output.

For that, you can use the sub_filter directive. Something like ...

location /admin/ {
    proxy_pass http://localhost:8080/;
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

Basically, the string you want to replace and the replacement string

React won't load local images

src={"/images/resto.png"}

Using of src attribute in this way means, your image will be loaded from the absolute path "/images/resto.png" for your site. Images directory should be located at the root of your site. Example: http://www.example.com/images/resto.png

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How to remove anaconda from windows completely?

In the folder where you installed Anaconda (Example: C:\Users\username\Anaconda3) there should be an executable called Uninstall-Anaconda.exe. Double click on this file to start uninstall Anaconda.

That should do the trick as well.

How to convert local time string to UTC?

Thanks @rofly, the full conversion from string to string is as follows:

time.strftime("%Y-%m-%d %H:%M:%S", 
              time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", 
                                                    "%Y-%m-%d %H:%M:%S"))))

My summary of the time/calendar functions:

time.strptime
string --> tuple (no timezone applied, so matches string)

time.mktime
local time tuple --> seconds since epoch (always local time)

time.gmtime
seconds since epoch --> tuple in UTC

and

calendar.timegm
tuple in UTC --> seconds since epoch

time.localtime
seconds since epoch --> tuple in local timezone

What do I use on linux to make a python program executable

Just put this in the first line of your script :

#!/usr/bin/env python

Make the file executable with

chmod +x myfile.py

Execute with

./myfile.py

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

TLDR:

hostname=XXX
port=443
trust_cert_file_location=`curl-config --ca`

sudo bash -c "echo -n | openssl s_client -showcerts -connect $hostname:$port -servername $hostname \
    2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'  \
    >> $trust_cert_file_location"

Long answer

The basic reason is that your computer doesn't trust the certificate authority that signed the certificate used on the Gitlab server. This doesn't mean the certificate is suspicious, but it could be self-signed or signed by an institution/company that isn't in the list of your OS's list of CAs. What you have to do to circumvent the problem on your computer is telling it to trust that certificate - if you don't have any reason to be suspicious about it.

You need to check the web certificate used for your gitLab server, and add it to your </git_installation_folder>/bin/curl-ca-bundle.crt.

To check if at least the clone works without checking said certificate, you can set:

export GIT_SSL_NO_VERIFY=1
#or
git config --global http.sslverify false

But that would be for testing only, as illustrated in "SSL works with browser, wget, and curl, but fails with git", or in this blog post.

Check your GitLab settings, a in issue 4272.


To get that certificate (that you would need to add to your curl-ca-bundle.crt file), type a:

echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpsGitlabPort \
  2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

(with 'yourserver.com' being your GitLab server name, and YourHttpsGitlabPort is the https port, usually 443)

To check the CA (Certificate Authority issuer), type a:

echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpsGilabPort \
  2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' \
  | openssl x509 -noout -text | grep "CA Issuers" | head -1

Note: Valeriy Katkov suggests in the comments to add -servername option to the openssl command, otherwise the command isn't showed certificate for www.github.com in Valeriy's case.

openssl s_client -showcerts -servername www.github.com -connect www.github.com:443

Findekano adds in the comments:

to identify the location of curl-ca-bundle.crt, you could use the command

curl-config --ca

Also, see my more recent answer "github: server certificate verification failed": you might have to renistall those certificates:

sudo apt-get install --reinstall ca-certificates
sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates
git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt

How do I check if a string contains a specific word?

While most of these answers will tell you if a substring appears in your string, that's usually not what you want if you're looking for a particular word, and not a substring.

What's the difference? Substrings can appear within other words:

  • The "are" at the beginning of "area"
  • The "are" at the end of "hare"
  • The "are" in the middle of "fares"

One way to mitigate this would be to use a regular expression coupled with word boundaries (\b):

function containsWord($str, $word)
{
    return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}

This method doesn't have the same false positives noted above, but it does have some edge cases of its own. Word boundaries match on non-word characters (\W), which are going to be anything that isn't a-z, A-Z, 0-9, or _. That means digits and underscores are going to be counted as word characters and scenarios like this will fail:

  • The "are" in "What _are_ you thinking?"
  • The "are" in "lol u dunno wut those are4?"

If you want anything more accurate than this, you'll have to start doing English language syntax parsing, and that's a pretty big can of worms (and assumes proper use of syntax, anyway, which isn't always a given).

Sort array of objects by object fields

You can use usort like this

If you want to sort by number:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

Or Abc char:

function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

See more: https://www.php.net/manual/en/function.usort.php

How to pipe list of files returned by find command to cat to view all the files

Here is my shot for general use:

grep YOURSTRING `find .`

It will print the file name

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.

 document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});

Without this snippet, the app container stayed in the up-scrolled position until page refresh.

List an Array of Strings in alphabetical order

Here is code that works:

import java.util.Arrays;
import java.util.Collections;

public class Test
{
    public static void main(String[] args)
    {
        orderedGuests1(new String[] { "c", "a", "b" });
        orderedGuests2(new String[] { "c", "a", "b" });
    }

    public static void orderedGuests1(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }

    public static void orderedGuests2(String[] hotel)
    {
        Collections.sort(Arrays.asList(hotel));
        System.out.println(Arrays.toString(hotel));
    }

}

How to set up devices for VS Code for a Flutter emulator

The following steps were done:

  1. installed genymotion
  2. configured a device and ran it
  3. in the vscode lower right corner the device shows

How to deselect a selected UITableView cell?

Please check with the delegate method whether it is correct or not. For example;

-(void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

for

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

How can I view the Git history in Visual Studio Code?

You won't need a plugin to see commit history with Visual Studio Code 1.42 or more.

Timeline view

In this milestone, we've made progress on the new Timeline view, and have an early preview to share.
This is a unified view for visualizing time-series events (e.g. commits, saves, test runs, etc.) for a resource (file, folder, etc.).

To enable the Timeline view, you must be using the Insiders Edition (VSCode 1.44 March 2020) and then add the following setting:

"timeline.showView": true

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/timeline.png

spring PropertyPlaceholderConfigurer and context:property-placeholder

Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>

Somehow "classpath:xxx" is not picking the file.

How to get to Model or Viewbag Variables in a Script Tag

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);

Order by descending date - month, day and year

Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date if SQL Server 2008).

Storing dates as mm/dd/yyyy strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.

Simple logical operators in Bash

What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.

  • (…) parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
    • With a leading dollar sign, $(…) is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).
  • { … } braces are like parentheses in that they group commands, but they only influence parsing, not grouping. The program x=2; { x=4; }; echo $x prints 4, whereas x=2; (x=4); echo $x prints 2. (Also braces require spaces around them and a semicolon before closing, whereas parentheses don't. That's just a syntax quirk.)
    • With a leading dollar sign, ${VAR} is a parameter expansion, expanding to the value of a variable, with possible extra transformations.
  • ((…)) double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals.
    • The same syntax is used in arithmetic expressions $((…)), which expand to the integer value of the expression.
  • [[ … ]] double brackets surround conditional expressions. Conditional expressions are mostly built on operators such as -n $variable to test if a variable is empty and -e $file to test if a file exists. There are also string equality operators: "$string1" == "$string2" (beware that the right-hand side is a pattern, e.g. [[ $foo == a* ]] tests if $foo starts with a while [[ $foo == "a*" ]] tests if $foo is exactly a*), and the familiar !, && and || operators for negation, conjunction and disjunction as well as parentheses for grouping. Note that you need a space around each operator (e.g. [[ "$x" == "$y" ]], not [[ "$x"=="$y" ]]), and a space or a character like ; both inside and outside the brackets (e.g. [[ -n $foo ]], not [[-n $foo]]).
  • [ … ] single brackets are an alternate form of conditional expressions with more quirks (but older and more portable). Don't write any for now; start worrying about them when you find scripts that contain them.

This is the idiomatic way to write your test in bash:

if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then

If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional = operator rather than the ksh/bash/zsh == variant):

if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then

Converting a sentence string to a string array of words in Java

This should help,

 String s = "This is a sample sentence";
 String[] words = s.split(" ");

this will make an array with elements as the string separated by " ".

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

So as I understand now, SingleOrDefault will be good if you are querying for data that is guaranteed to be unique i.e. enforced by DB constraints like primary key.

Or is there a better way of querying for the primary key.

Assuming my TableAcc has

AccountNumber - Primary Key, integer
AccountName
AccountOpenedDate
AccountIsActive
etc.

and I want to query for an AccountNumber 987654, I use

var data = datacontext.TableAcc.FirstOrDefault(obj => obj.AccountNumber == 987654);

Java 8 Distinct by property

You can use StreamEx library:

StreamEx.of(persons)
        .distinct(Person::getName)
        .toList()

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

How to print bytes in hexadecimal using System.out.println?

byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;

for (byte theByte : test)
{
  System.out.println(Integer.toHexString(theByte));
}

NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.

you might be able to do...

test[1] = (byte) 0xFF;

I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)

How do I auto-submit an upload form when a file is selected?

The shortest solution is

<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" />