Programs & Examples On #Timer jobs

Timer Jobs are recurring background processes that are managed by a Scheduler. A timer job would consist of three parts: Timer Job Definitions, Timer Job Instances, and Timer Job Schedules.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

Cast Double to Integer in Java

Use the doubleNumber.intValue(); method.

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

Sometimes adding a WCF Service Reference generates an empty reference.cs

When this happens, look in the Errors window and the Output window to see if there are any error messages. If that doesn't help, try running svcutil.exe manually, and see if there are any error messages.

How does RewriteBase work in .htaccess

In my own words, after reading the docs and experimenting:

You can use RewriteBase to provide a base for your rewrites. Consider this

# invoke rewrite engine
    RewriteEngine On
    RewriteBase /~new/

# add trailing slash if missing
    rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]

This is a real rule I used to ensure that URLs have a trailing slash. This will convert

http://www.example.com/~new/page

to

http://www.example.com/~new/page/

By having the RewriteBase there, you make the relative path come off the RewriteBase parameter.

Select specific row from mysql table

SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;

you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)

List of ANSI color escape sequences

How about:

ECMA-48 - Control Functions for Coded Character Sets, 5th edition (June 1991) - A standard defining the color control codes, that is apparently supported also by xterm.

SGR 38 and 48 were originally reserved by ECMA-48, but were fleshed out a few years later in a joint ITU, IEC, and ISO standard, which comes in several parts and which (amongst a whole lot of other things) documents the SGR 38/48 control sequences for direct colour and indexed colour:

There's a column for xterm in this table on the Wikipedia page for ANSI escape codes

Namespace not recognized (even though it is there)

I resolved this issue by right clicking on the folder containing the files and choosing Exclude From Project and then right clicking again and selecting Include In Project (you first have to enable Show All Files to make the excluded folder visible)

Remove style attribute from HTML tags

In addition to Lorenzo Marcon's answer:

Using preg_replace to select everything except style attribute:

$html = preg_replace('/(<p.+?)style=".+?"(>.+?)/i', "$1$2", $html);

Filtering DataGridView without changing datasource

I found a simple way to fix that problem. At binding datagridview you've just done: datagridview.DataSource = dataSetName.Tables["TableName"];

If you code like:

datagridview.DataSource = dataSetName;
datagridview.DataMember = "TableName";

the datagridview will never load data again when filtering.

Changing button text onclick

var count=0;
document.getElementById("play").onclick = function(){


if(count%2 =="1"){

                document.getElementById("video").pause();
                document.getElementById("play").innerHTML ="Pause";
            }else {

            document.getElementById("video").play();
            document.getElementById("play").innerHTML ="Play";

            }
            ++count;

AngularJS - value attribute for select

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):

HTML:

<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

Javascript:

App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>

and

<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

SELECT * FROM table where Date(col) = 'date'

How To Save Canvas As An Image With canvas.toDataURL()?

You can use canvas2image to prompt for download.

I had the same issue, here's a simple example that both adds the image to the page and forces the browser to download it:

<html>
    <head>
        <script src="http://hongru.github.io/proj/canvas2image/canvas2image.js"></script>
        <script>
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25,25,100,100); 
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
            }

            function to_image(){
                var canvas = document.getElementById("thecanvas");
                document.getElementById("theimage").src = canvas.toDataURL();
                Canvas2Image.saveAsPNG(canvas);
            }
        </script>
    </head>
    <body onload="draw()">
        <canvas width=200 height=200 id="thecanvas"></canvas>
        <div><button onclick="to_image()">Draw to Image</button></div>
        <image id="theimage"></image>
    </body>
</html>

De-obfuscate Javascript code to make it readable again

From the first link on google;

function call_func(_0x41dcx2) {
 var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
 var _0x41dcx4 = document['createElement']('div');
 var _0x41dcx5 = _0x41dcx3['id'];
 var _0x41dcx6 = _0x41dcx3['Student_name'];
 var _0x41dcx7 = _0x41dcx3['student_dob'];
 var _0x41dcx8 = '<b>ID:</b>';
 _0x41dcx8 += '<a href="/learningyii/index.php?r=student/view&amp; id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student Name:</b>';
 _0x41dcx8 += _0x41dcx6;
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student DOB:</b>';
 _0x41dcx8 += _0x41dcx7;
 _0x41dcx8 += '<br/>';
 _0x41dcx4['innerHTML'] = _0x41dcx8;
 _0x41dcx4['setAttribute']('class', 'view');
 $('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};

It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

Style input element to fill remaining width of its container

Here is a simple and clean solution without using JavaScript or table layout hacks. It is similar to this answer: Input text auto width filling 100% with other elements floating

It is important to wrap the input field with a span which is display:block. Next thing is that the button has to come first and the the input field second.

Then you can float the button to the right and the input field fills the remaining space.

_x000D_
_x000D_
form {_x000D_
    width: 500px;_x000D_
    overflow: hidden;_x000D_
    background-color: yellow;_x000D_
}_x000D_
input {_x000D_
    width: 100%;_x000D_
}_x000D_
span {_x000D_
    display: block;_x000D_
    overflow: hidden;_x000D_
    padding-right:10px;_x000D_
}_x000D_
button {_x000D_
    float: right;_x000D_
}
_x000D_
<form method="post">_x000D_
     <button>Search</button>_x000D_
     <span><input type="text" title="Search" /></span>_x000D_
</form>
_x000D_
_x000D_
_x000D_

A simple fiddle: http://jsfiddle.net/v7YTT/90/

Update 1: If your website is targeted towards modern browsers only, I suggest using flexible boxes. Here you can see the current support.

Update 2: This even works with multiple buttons or other elements that share the full with with the input field. Here is an example.

Compare two dates in Java

in my case, I just had to do something like this :

date1.toString().equals(date2.toString())

And it worked!

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

Accessing Objects in JSON Array (JavaScript)

Use a loop

for(var i = 0; i < obj.length; ++i){
   //do something with obj[i]
   for(var ind in obj[i]) {
        console.log(ind);
        for(var vals in obj[i][ind]){
            console.log(vals, obj[i][ind][vals]);
        }
   }
}

Demo: http://jsfiddle.net/maniator/pngmL/

MongoDB vs Firebase

Firebase is a suite of features .

  • Realtime Database
  • Hosting
  • Authentication
  • Storage
  • Cloud Messaging
  • Remote Config
  • Test Lab
  • Crash Reporting
  • Notifications
  • App Indexing
  • Dynamic Links
  • Invites
  • AdWords
  • AdMob

I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .

When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .

  1. Are there many aggregation queries that gets executed .(Like in case of reporting tool or BI tool ) . If Yes dont go for Firebase
  2. Do i need to perform lot of transaction . (If yes then i would not like to go with firebase) (Tranactions are somewhat easy though after introduction of functions but that is also a overhead if lot of transactions needs to be maintained)
  3. What timeline do i have to get things up and running .(Firebase is very easy to setup and integrate ).
  4. Do i have expertise to scale up the DB and trouble shoot DB related stuffs . (Firebase is more like SAAS so no need to worry about scaleability)

Make Frequency Histogram for Factor Variables

Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country

barplot(summary(df$Country))

Filtering array of objects with lodash based on property value

With lodash:

const myArr = [ {name: "john", age: 23},
                {name: "john", age: 43},
                {name: "jim", age: 101},
                {name: "bob", age: 67} ];

const johnArr = _.filter(myArr, person => person.name === 'john');
console.log(johnArr)

enter image description here

Vanilla JavaScript:

const myArr = [ {name: "john", age: 23},
                {name: "john", age: 43},
                {name: "jim", age: 101},
                {name: "bob", age: 67} ];

const johnArr = myArr.filter(person => person.name === 'john');
console.log(johnArr);

enter image description here

How to select all rows which have same value in some column

You can do this without a JOIN:

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

Demo: SQL Fiddle

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

MacOS uses /usr/libexec/java_home to find the current Java Version. One way to bypass is to change the plist file as explained by @void256 above. Other ways is to take the backup of the java_home and replace it with your own script java_home having the code
echo $JAVA_HOME

Now export the JAVA_HOME to the desired version of the SDK by adding the following commands to the ~/.bash_profile. export JAVA_HOME="/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home" launchctl setenv JAVA_HOME $JAVA_HOME /// Make the environment variable global

Run the command source ~/.bash_profile to the run the above commands.

Anytime one needs to change the JAVA_HOME he can reset the JAVA_HOME value in the ~/.bash_profile file.

Installing ADB on macOS

Note for zsh users: replace all references to ~/.bash_profile with ~/.zshrc.

Option 1 - Using Homebrew

This is the easiest way and will provide automatic updates.

  1. Install the homebrew package manager

     /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
    
  2. Install adb

     brew install android-platform-tools
    
  3. Start using adb

     adb devices
    

Option 2 - Manually (just the platform tools)

This is the easiest way to get a manual installation of ADB and Fastboot.

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Navigate to https://developer.android.com/studio/releases/platform-tools.html and click on the SDK Platform-Tools for Mac link.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip platform-tools-latest*.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv platform-tools/ ~/.android-sdk-macosx/platform-tools
    
  6. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  7. Refresh your bash profile (or restart your terminal app)

     source ~/.bash_profile
    
  8. Start using adb

     adb devices
    

Option 3 - Manually (with SDK Manager)

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Download the Mac SDK Tools from the Android developer site under "Get just the command line tools". Make sure you save them to your Downloads folder.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip tools_r*-macosx.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv tools/ ~/.android-sdk-macosx/tools
    
  6. Run the SDK Manager

     sh ~/.android-sdk-macosx/tools/android
    
  7. Uncheck everything but Android SDK Platform-tools (optional)

enter image description here

  1. Click Install Packages, accept licenses, click Install. Close the SDK Manager window.

enter image description here

  1. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  2. Refresh your bash profile (or restart your terminal app)

    source ~/.bash_profile
    
  3. Start using adb

    adb devices
    

Make javascript alert Yes/No Instead of Ok/Cancel

In an attempt to solve a similar situation I've come across this example and adapted it. It uses JQUERY UI Dialog as Nikhil D suggested. Here is a look at the code:

HTML:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="box" value="Confirm the thing?" />
<div id="dialog-confirm"></div>

JavaScript:

$('#box').click(function buttonAction() {
  $("#dialog-confirm").html("Do you want to do the thing?");

  // Define the Dialog and its properties.
  $("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    title: "Do the thing?",
    height: 250,
    width: 400,
    buttons: {
      "Yes": function() {
        $(this).dialog('close');
        alert("Yes, do the thing");
      },
      "No": function() {
        $(this).dialog('close');
        alert("Nope, don't do the thing");
      }
    }
  });
});

$('#box').click(buttonAction);

I have a few more tweaks I need to do to make this example work for my application. Will update this if I see it fit into the answer. Hope this helps someone.

Get the _id of inserted document in Mongo database in NodeJS

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Option to ignore case with .contains method?

private boolean containsIgnoreCase(List<String> list, String soughtFor) {
    for (String current : list) {
        if (current.equalsIgnoreCase(soughtFor)) {
            return true;
        }
    }
    return false;
}

MySQL create stored procedure syntax with delimiter

Here is the sample MYSQL Stored Procedure with delimiter and how to call..

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
  IN loc_username VARCHAR(255),
  IN loc_password VARCHAR(255)
)
BEGIN

  SELECT user_id,
         user_name,
         user_emailid,
         user_profileimage,
         last_update
    FROM tbl_user
   WHERE user_name = loc_username
     AND password = loc_password
     AND status = 1;

END $$

DELIMITER ;

and call by, mysql_connection specification and

$loginCheck="call sp_user_login('".$username."','".$password."');";

it will return the result from the procedure.

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

What is phtml, and when should I use a .phtml extension rather than .php?

To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.

Opening Android Settings programmatically

To achieve this just use an Intent using the constant ACTION_SETTINGS, specifically defined to show the System Settings:

startActivity(new Intent(Settings.ACTION_SETTINGS));

startActivityForResult() is optional, only if you want to return some data when the settings activity is closed.

startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);

here you can find a list of contants to show specific settings or details of an aplication.

Using sudo with Python script

subprocess.Popen creates a process and opens pipes and stuff. What you are doing is:

  • Start a process sudo -S
  • Start a process mypass
  • Start a process mount -t vboxsf myfolder /home/myuser/myfolder

which is obviously not going to work. You need to pass the arguments to Popen. If you look at its documentation, you will notice that the first argument is actually a list of the arguments.

Is it possible to embed animated GIFs in PDFs?

I haven't tested it but apparently you can add quicktime animations to a pdf (no idea why). So the solution would be to export the animated gif to quicktime and add it to the pdf.

Here the solution that apparently works:

  1. Open the GIF in Quicktime and save as MOV (Apparently it works with other formats too, you'll have to try it out).
  2. Insert the MOV into the PDF (with Adobe InDesign (make sure to set Object> Interactive> film options > Embed in PDF) - It should work with Adobe Acrobat Pro DC too: see link
  3. Save the PDF.

See this link (German)

jQuery click not working for dynamically created items

$("#container").delegate("span", "click", function (){
    alert(11);
});

Is there any way to delete local commits in Mercurial?

hg strip is what you are looking for. It's analogous of git reset if you familiar with git.

Use console:

  1. You need to know the revision number. hg log -l 10. This command shows the last 10 commits. Find commit you are looking for. You need 4 digit number from changeset line changeset: 5888:ba6205914681

  2. Then hg strip -r 5888 --keep. This removes the record of the commit but keeps all files modified and then you could recommit them. (if you want to delete files to just remove --keep hg strip -r 5888

Load HTML page dynamically into div with jQuery

There's a jQuery plugin out there called pjax it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."

The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.

What pjax does is that it listens on specified page elements such as <a>. Then when the <a href=""></a> element is invoked, the target page is fetched with either the X-PJAX header, or a specified fragment.

Example:

<script type="text/javascript">
  $(document).pjax('a', '#pjax-container');
</script>

Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.

(meaning you want to replace #pjax-container on the current page with #pjax-container from the remote page)

When <a> is invoked, it will fetch the link with the request header X-PJAX and will look for the contents of #pjax-container in the result. If the result is #pjax-container, the container on the current page will be replaced with the new result.

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="jquery.pjax.js"></script> 
  <script type="text/javascript">
    $(document).pjax('a', '#pjax-container');
  </script> 
</head>
<body>
  <h1>My Site</h1>
  <div class="container" id="pjax-container">
    Go to <a href="/page2">next page</a>.
  </div>
</body>
</html>

If #pjax-container is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container.

Example server side code of page2:

//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
  Go to <a href="/page1">next page</a>.
</div>
//else send full page

If you can't change server-side code, then the fragment option is an alternative.

$(document).pjax('a', '#pjax-container', { 
  fragment: '#pjax-container' 
});

Note that fragment is an older pjax option and appears to fetch the child element of requested element.

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

Spring MVC @PathVariable with dot (.) is getting truncated

Here's an approach that relies purely on java configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class MvcConfig extends WebMvcConfigurationSupport{

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setUseSuffixPatternMatch(false);
        handlerMapping.setUseTrailingSlashMatch(false);
        return handlerMapping;
    }
}

How to use Python to execute a cURL command?

import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

maybe?

if you are trying to send a file

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

ahh thanks @LukasGraf now i better understand what his original code is doing

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

How to Auto-start an Android Application?

I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).

Add the permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Add receiver and service:

<receiver android:enabled="true" android:name=".BootUpReceiver"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>
<service android:name="Launcher" />

Create class Launcher:

public class Launcher extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new AsyncTask<Service, Void, Service>() {

            @Override
            protected Service doInBackground(Service... params) {
                Service service = params[0];
                PackageManager pm = service.getPackageManager();
                try {
                    Intent target = pm.getLaunchIntentForPackage("your.package.id");
                    if (target != null) {
                        service.startActivity(target);
                        synchronized (this) {
                            wait(3000);
                        }
                    } else {
                        throw new ActivityNotFoundException();
                    }
                } catch (ActivityNotFoundException | InterruptedException ignored) {
                }
                return service;
            }

            @Override
            protected void onPostExecute(Service service) {
                service.stopSelf();
            }

        }.execute(this);

        return START_STICKY;
    }
}

Create class BootUpReceiver to do action after android reboot.

For example launch MainActivity:

public class BootUpReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent target = new Intent(context, MainActivity.class);  
        target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(target);  
    }
}

Address validation using Google Maps API

I know that this post is a bit old but incase anyone finds it still relevant you might want to check out the free geocoding services offered by USC College. This does included address validation via ajax and static calls. The only catch is that they request a link back and only offer allotments of 2500 calls. More than fair. https://webgis.usc.edu/Services/AddressValidation/Default.aspx

Capture Video of Android's Screen

I didn't implement it but still i am giving you an idea to do this.

First of all get the code to take a screenshot of Android device. And Call the same function for creating Images after an interval of times. Add then find the code to create video from frames/images.

Edit

see this link also and modify it according to your screen dimension .The main thing is to divide your work into several small tasks and then combine it as your need.

FFMPEG is the best way to do this. but once i have tried but it is a very long procedure. First you have to download cygwin and Native C++ library and lot of stuff and connect then you are able to work on FFMPEG (it is built in C++).

Calculating a directory's size using Python?

The accepted answer doesn't take into account hard or soft links, and would count those files twice. You'd want to keep track of which inodes you've seen, and not add the size for those files.

import os
def get_size(start_path='.'):
    total_size = 0
    seen = {}
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                stat = os.stat(fp)
            except OSError:
                continue

            try:
                seen[stat.st_ino]
            except KeyError:
                seen[stat.st_ino] = True
            else:
                continue

            total_size += stat.st_size

    return total_size

print get_size()

How to close TCP and UDP ports via windows command line

  1. open cmd

    • type in netstat -a -n -o

    • find TCP [the IP address]:[port number] .... #[target_PID]# (ditto for UDP)

    • (Btw, kill [target_PID] didn't work for me)

  2. CTRL+ALT+DELETE and choose "start task manager"

    • Click on "Processes" tab

    • Enable "PID" column by going to: View > Select Columns > Check the box for PID

    • Find the PID of interest and "END PROCESS"

  3. Now you can rerun the server on [the IP address]:[port number] without a problem

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

How can I get the name of an object in Python?

Variable names can be found in the globals() and locals() dicts. But they won't give you what you're looking for above. "bla" will contain the value of each item of my_list, not the variable.

How do I remove the old history from a git repository?

There are too many answers here which are not current and some don't fully explain the consequences. Here's what worked for me for trimming down the history using latest git 2.26:

First create a dummy commit. This commit will appear as the first commit in your truncated repo. You need this because this commit will hold all base files for the history you are keeping. The SHA is the ID of the previous commit of the commit you want to keep (in this example, 8365366). The string 'Initial' will show up as commit message of the first commit. If you are using Windows, type below command from Git Bash command prompt.

# 8365366 is id of parent commit after which you want to preserve history
echo 'Initial' | git commit-tree 8365366^{tree}

Above command will print SHA, for example, d10f7503bc1ec9d367da15b540887730db862023.

Now just type:

# d10f750 is commit ID from previous command
git rebase --onto d10f750 8365366

This will first put all files as-of commit 8365366 in to the dummy commit d10f750. Then it will play back all commits after 8365366 over the top of d10f750. Finally master branch pointer will be updated to last commit played back.

Now if you want to push these truncated repo, just do git push -f.

Few things to keep in mind (these applies to other methods as well as this one): Tags are not transferred. While commit IDs and timestamps are preserved, you will see GitHub show these commits in lumpsum heading like Commits on XY date.

Fortunately it is possible to keep truncated history as "archive" and later you can join back trimmed repo with archive repo. For doing this, see this guide.

What does "while True" mean in Python?

To answer your question directly: while the loop condition is True. Which it always is, in this particular bit of code.

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Integrated application pool mode

When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.

There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.

Classic application pool mode

When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.

This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.

Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.

Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?

Original source: Introduction to IIS Architecture

Joining three tables using MySQL

SELECT *
FROM user u
JOIN user_clockits uc ON u.user_id=uc.user_id
JOIN clockits cl ON cl.clockits_id=uc.clockits_id
WHERE user_id = 158

Loop through a comma-separated shell variable

You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.

variable=abc,def,ghij
for i in $(echo $variable | sed "s/,/ /g")
do
    # call your procedure/other scripts here below
    echo "$i"
done

Instead of the echo "$i" call above, between the do and done inside the for loop, you can invoke your procedure proc "$i".


Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change IFS and then parse your variable.


Hope this helps.

Read CSV file column by column

We can use the core java stuff alone to read the CVS file column by column. Here is the sample code I have wrote for my requirement. I believe that it will help for some one.

 BufferedReader br = new BufferedReader(new FileReader(csvFile));
    String line = EMPTY;
    int lineNumber = 0;

    int productURIIndex = -1;
    int marketURIIndex = -1;
    int ingredientURIIndex = -1;
    int companyURIIndex = -1;

    // read comma separated file line by line
    while ((line = br.readLine()) != null) {
        lineNumber++;
        // use comma as line separator
        String[] splitStr = line.split(COMMA);
        int splittedStringLen = splitStr.length;

        // get the product title and uri column index by reading csv header
        // line
        if (lineNumber == 1) {
            for (int i = 0; i < splittedStringLen; i++) {
                if (splitStr[i].equals(PRODUCTURI_TITLE)) {
                    productURIIndex = i;
                    System.out.println("product_uri index:" + productURIIndex);
                }

                if (splitStr[i].equals(MARKETURI_TITLE)) {
                    marketURIIndex = i;
                    System.out.println("marketURIIndex:" + marketURIIndex);
                }

                if (splitStr[i].equals(COMPANYURI_TITLE)) {
                    companyURIIndex = i;
                    System.out.println("companyURIIndex:" + companyURIIndex);
                }

                if (splitStr[i].equals(INGREDIENTURI_TITLE)) {
                    ingredientURIIndex = i;
                    System.out.println("ingredientURIIndex:" + ingredientURIIndex);
                }
            }
        } else {
            if (splitStr != null) {
                String conditionString = EMPTY;
                // avoiding arrayindexoutboundexception when the line
                // contains only ,,,,,,,,,,,,,
                for (String s : splitStr) {
                    conditionString = s;
                }
                if (!conditionString.equals(EMPTY)) {
                    if (productURIIndex != -1) {
                        productCVSUriList.add(splitStr[productURIIndex]);
                    }
                    if (companyURIIndex != -1) {
                        companyCVSUriList.add(splitStr[companyURIIndex]);
                    }
                    if (marketURIIndex != -1) {
                        marketCVSUriList.add(splitStr[marketURIIndex]);
                    }
                    if (ingredientURIIndex != -1) {
                        ingredientCVSUriList.add(splitStr[ingredientURIIndex]);
                    }
                }
            }
        }

How to convert rdd object to dataframe in spark

One needs to create a schema, and attach it to the Rdd.

Assuming val spark is a product of a SparkSession.builder...

    import org.apache.spark._
    import org.apache.spark.sql._       
    import org.apache.spark.sql.types._

    /* Lets gin up some sample data:
     * As RDD's and dataframes can have columns of differing types, lets make our
     * sample data a three wide, two tall, rectangle of mixed types.
     * A column of Strings, a column of Longs, and a column of Doubules 
     */
    val arrayOfArrayOfAnys = Array.ofDim[Any](2,3)
    arrayOfArrayOfAnys(0)(0)="aString"
    arrayOfArrayOfAnys(0)(1)=0L
    arrayOfArrayOfAnys(0)(2)=3.14159
    arrayOfArrayOfAnys(1)(0)="bString"
    arrayOfArrayOfAnys(1)(1)=9876543210L
    arrayOfArrayOfAnys(1)(2)=2.71828

    /* The way to convert an anything which looks rectangular, 
     * (Array[Array[String]] or Array[Array[Any]] or Array[Row], ... ) into an RDD is to 
     * throw it into sparkContext.parallelize.
     * http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.SparkContext shows
     * the parallelize definition as 
     *     def parallelize[T](seq: Seq[T], numSlices: Int = defaultParallelism)
     * so in our case our ArrayOfArrayOfAnys is treated as a sequence of ArraysOfAnys.
     * Will leave the numSlices as the defaultParallelism, as I have no particular cause to change it. 
     */
    val rddOfArrayOfArrayOfAnys=spark.sparkContext.parallelize(arrayOfArrayOfAnys)

    /* We'll be using the sqlContext.createDataFrame to add a schema our RDD.
     * The RDD which goes into createDataFrame is an RDD[Row] which is not what we happen to have.
     * To convert anything one tall and several wide into a Row, one can use Row.fromSeq(thatThing.toSeq)
     * As we have an RDD[somethingWeDontWant], we can map each of the RDD rows into the desired Row type. 
     */     
    val rddOfRows=rddOfArrayOfArrayOfAnys.map(f=>
        Row.fromSeq(f.toSeq)
    )

    /* Now to construct our schema. This needs to be a StructType of 1 StructField per column in our dataframe.
     * https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.types.StructField shows the definition as
     *   case class StructField(name: String, dataType: DataType, nullable: Boolean = true, metadata: Metadata = Metadata.empty)
     * Will leave the two default values in place for each of the columns:
     *        nullability as true, 
     *        metadata as an empty Map[String,Any]
     *   
     */

    val schema = StructType(
        StructField("colOfStrings", StringType) ::
        StructField("colOfLongs"  , LongType  ) ::
        StructField("colOfDoubles", DoubleType) ::
        Nil
    )

    val df=spark.sqlContext.createDataFrame(rddOfRows,schema)
    /*
     *      +------------+----------+------------+
     *      |colOfStrings|colOfLongs|colOfDoubles|
     *      +------------+----------+------------+
     *      |     aString|         0|     3.14159|
     *      |     bString|9876543210|     2.71828|
     *      +------------+----------+------------+
    */ 
    df.show 

Same steps, but with fewer val declarations:

    val arrayOfArrayOfAnys=Array(
        Array("aString",0L         ,3.14159),
        Array("bString",9876543210L,2.71828)
    )

    val rddOfRows=spark.sparkContext.parallelize(arrayOfArrayOfAnys).map(f=>Row.fromSeq(f.toSeq))

    /* If one knows the datatypes, for instance from JDBC queries as to RDBC column metadata:
     * Consider constructing the schema from an Array[StructField].  This would allow looping over 
     * the columns, with a match statement applying the appropriate sql datatypes as the second
     *  StructField arguments.   
     */
    val sf=new Array[StructField](3)
    sf(0)=StructField("colOfStrings",StringType)
    sf(1)=StructField("colOfLongs"  ,LongType  )
    sf(2)=StructField("colOfDoubles",DoubleType)        
    val df=spark.sqlContext.createDataFrame(rddOfRows,StructType(sf.toList))
    df.show

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

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

Windows command to get service status?

You can call net start "service name" on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.

How to create a new branch from a tag?

My branch list (only master now)

branch list

My tag list (have three tags)

tag list

Switch to new branch feature/codec from opus_codec tag

git checkout -b feature/codec opus_codec

switch to branch

How to find when a web page was last updated

There is another way to find the page update which could be useful for some occasions (if works:).

If the page has been indexed by Google, or by Wayback Machine you can try to find out what date(s) was(were) saved by them (these methods do not work for any page, and have some limitations, which are extensively investigated in this webmasters.stackexchange question's answers. But in many cases they can help you to find out the page update date(s):

  1. Google way: Go by link https://www.google.com.ua/search?q=site%3Awww.example.com&biw=1855&bih=916&source=lnt&tbs=cdr%3A1%2Ccd_min%3A1%2F1%2F2000%2Ccd_max%3A&tbm=
    • You can change text in search field by any page URL you want.
    • For example, the current stackoverflow question page search gives us as a result May 14, 2014 - which is the question creation date: enter image description here
  2. Wayback machine way: Go by link https://web.archive.org/web/*/www.example.com
    • for this stackoverflow page wayback machine gives us more results: Saved 6 times between June 7, 2014 and November 23, 2016., and you can view all saved copies for each date

How do I download a tarball from GitHub using cURL?

with a specific dir:

cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx

How to center a table of the screen (vertically and horizontally)

This fixes the box dead center on the screen:

HTML

<table class="box" border="1px">
    <tr>
        <td>
            my content
        </td>
    </tr>
</table>

CSS

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:fixed;
    margin-left:-150px; /* half of width */
    margin-top:-150px;  /* half of height */
    top:50%;
    left:50%;
}

View Results

http://jsfiddle.net/bukov/wJ7dY/168/

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I like the other suggestions but I would rather not update the machine.config for a single application. I suggest that you just add it to the web.config / app.config. Here is what I needed to use the MySql Connector/NET that I "bin" deployed.

<system.data>
    <DbProviderFactories >
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
</system.data>

Invalidating JSON Web Tokens

An approach I've been considering is to always have an iat (issued at) value in the JWT. Then when a user logs out, store that timestamp on the user record. When validating the JWT just compare the iat to the last logged out timestamp. If the iat is older, then it's not valid. Yes, you have to go to the DB, but I'll always be pulling the user record anyway if the JWT is otherwise valid.

The major downside I see to this is that it'd log them out of all their sessions if they're in multiple browsers, or have a mobile client too.

This could also be a nice mechanism for invalidating all JWTs in a system. Part of the check could be against a global timestamp of the last valid iat time.

How to create text file and insert data to that file on Android

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
 strwrt=FileWriter(File("sdcard/${NamaFile}"))
            strwrt.write(teks)
            strwrt.close()

after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

syntax error when using command line in python

Don't type python test.py from inside the Python interpreter. Type it at the command prompt, like so:

cmd.exe

python test.py

Unable to use Intellij with a generated sources folder

I'm using Maven (SpringBoot application) solution is:

  1. Right click project folder
  2. Select Maven
  3. Select Generate Sources And Update Folders

Then, Intellij automatically import generated sources to project.

Why does ++[[]][+[]]+[+[]] return the string "10"?

  1. Unary plus given string converts to number
  2. Increment operator given string converts and increments by 1
  3. [] == ''. Empty String
  4. +'' or +[] evaluates 0.

    ++[[]][+[]]+[+[]] = 10 
    ++[''][0] + [0] : First part is gives zeroth element of the array which is empty string 
    1+0 
    10
    

How to use subprocess popen Python

It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can do the correct tokenization for args (I'm using Blender's example of the call):

import shlex
from subprocess import Popen, PIPE
command = shlex.split('swfdump /tmp/filename.swf/ -d')
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

https://docs.python.org/3/library/subprocess.html

Fitting polynomial model to data in R

The easiest way to find the best fit in R is to code the model as:

lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)

After using step down AIC regression

lm.s <- step(lm.1)

Content Type application/soap+xml; charset=utf-8 was not supported by service

I had the same problem, got it working by "binding" de service with the service behaviour by doing this :

Gave a name to the behaviour

<serviceBehaviors>
        <behavior name="YourBehaviourNameHere">

And making a reference to your behaviour in your service

<services>
  <service name="WCFTradeLibrary.TradeService" behaviorConfiguration="YourBehaviourNameHere">

The whole thing would be :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000"
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
          <readerQuotas maxDepth="32"
               maxArrayLength="200000000"
               maxStringContentLength="200000000"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
     <service name="WCFTradeLibrary.TradeService" behaviourConfiguration="YourBehaviourNameHere">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="WCFTradeLibrary.ITradeService">          
         </endpoint>
     </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="YourBehaviourNameHere">
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faul`enter code here`ts for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception info`enter code here`rmation -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

How to get highcharts dates in the x axis?

Highcharts will automatically try to find the best format for the current zoom-range. This is done if the xAxis has the type 'datetime'. Next the unit of the current zoom is calculated, it could be one of:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • year

This unit is then used find a format for the axis labels. The default patterns are:

second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'

If you want the day to be part of the "hour"-level labels you should change the dateTimeLabelFormats option for that level include %d or %e. These are the available patters:

  • %a: Short weekday, like 'Mon'.
  • %A: Long weekday, like 'Monday'.
  • %d: Two digit day of the month, 01 to 31.
  • %e: Day of the month, 1 through 31.
  • %b: Short month, like 'Jan'.
  • %B: Long month, like 'January'.
  • %m: Two digit month number, 01 through 12.
  • %y: Two digits year, like 09 for 2009.
  • %Y: Four digits year, like 2009.
  • %H: Two digits hours in 24h format, 00 through 23.
  • %I: Two digits hours in 12h format, 00 through 11.
  • %l (Lower case L): Hours in 12h format, 1 through 11.
  • %M: Two digits minutes, 00 through 59.
  • %p: Upper case AM or PM.
  • %P: Lower case AM or PM.
  • %S: Two digits seconds, 00 through 59

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

How do I render a shadow?

by styled component

const StyledView = styled.View`
      border-width: 1;
      border-radius: 2;
      border-color: #ddd;
      border-bottom-width: 0;
      shadow-color: #000;
      shadow-offset: {width: 0, height: 2};
      shadow-opacity: 0.8;
      shadow-radius: 2;
      elevation: 1;     
`

or by styles

const styles = StyleSheet.create({
  containerStyle: {
    borderWidth: 1,
    borderRadius: 2,
    borderColor: '#ddd',
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 2,
    elevation: 1,
    marginLeft: 5,
    marginRight: 5,
    marginTop: 10,
  }
})

Different color for each bar in a bar chart; ChartJS

here is how I dealed: I pushed an array "colors", with same number of entries than number of datas. For this I added a function "getRandomColor" at the end of the script. Hope it helps...

for (var i in arr) {
    customers.push(arr[i].customer);
    nb_cases.push(arr[i].nb_cases);
    colors.push(getRandomColor());
}

window.onload = function() {
    var config = {
        type: 'pie',
        data: {
            labels: customers,
            datasets: [{
                label: "Nomber of cases by customers",
                data: nb_cases,
                fill: true,
                backgroundColor: colors 
            }]
        },
        options: {
            responsive: true,
            title: {
                display: true,
                text: "Cases by customers"
            },
        }
    };

    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx, config);
};

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

How to align an input tag to the center without specifying the width?

You can use the following CSS for your input field:

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

Then,update your input field as following:

<input class="center-block" type="button" value="Some Button">

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.

Use:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

OR

target_link_libraries(XXX PUBLIC pthread)

OR

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

Connect over ssh using a .pem file

For AWS if the user is ubuntu use the following to connect to remote server.

chmod 400 mykey.pem

ssh -i mykey.pem ubuntu@your-ip

Remove '\' char from string c#

Try to replace

string result = line.Replace("\\","");

PHP 7: Missing VCRUNTIME140.dll

For things like this, you don't blindly keep clicking 'Next', 'Next', and 'I Agree'.

WAMP informs you about this during and before installation:

The MSVC runtime libraries VC9, VC10, VC11 are required for Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions with VC11. Runtimes VC13, VC14 is required for PHP 7 and Apache 2.4.17

VC9 Packages (Visual C++ 2008 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=5582 http://www.microsoft.com/en-us/download/details.aspx?id=2092

VC10 Packages (Visual C++ 2010 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=8328 http://www.microsoft.com/en-us/download/details.aspx?id=13523

VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679

VC13 Packages] (Visual C++ 2013[) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=40784

VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=48145

You must install both 32 and 64bit versions, even if you do not use Wampserver 64 bit.

IMPORTANT NOTE: Be sure to to run all Microsoft Visual C++ installations with administrator privileges (right click ? Run as Administrator). Just missing this small step wasted my entire day.

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

How to adjust layout when soft keyboard appears

In Xamarin register below code in your activity

 WindowSoftInputMode = Android.Views.SoftInput.AdjustResize | Android.Views.SoftInput.AdjustPan

I used a Relative Layout if you're using Constraint Layout, the above code will work code below

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

What is the opposite of evt.preventDefault();

Here's something useful...

First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.

<a href="https://www.google.com.br" target="_blank" id="link">Google</a>

<script type="text/javascript">
    $(document).ready(function() {
        $("#link").click(function(e) {

            // Prevent default action
            e.preventDefault();

            // Here you'll put your code, what you want to execute before default action
            alert(123); 

            // Prevent infinite loop
            $(this).unbind('click');

            // Execute default action
            e.currentTarget.click();
        });
    });
</script>

How do I replace text in a selection?

Windows
1- Find: CTRL + F
2- Select-in: Alt + Enter

Now you can change all the selection in one shot like "seen-on-tv" ST homepage Spot.

Credit goes to : https://superuser.com/a/921806/342825

Add class to <html> with Javascript?

Like this:

var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)

root.setAttribute( 'class', 'myCssClass' );

Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)

root.className += ' myCssClass';

Or, depending on the required browser support, you can use the classList.add() method:

root.classList.add('myCssClass');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist

UPDATE:

A more elegant solution for referencing the HTML element might be this:

var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
//  root.classList.add('myCssClass');
//

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I just found in my case Kaspersky Internet Security 2019 Firewall was blocking net access for python. Disabling firewall working smoothly. Or adding a exception rules for python app and all file extension with *.py will also work.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I have added a Maven/Java project with 1 Domain class with the following features:

  • Unit or Integration testing with the plugins Surefire and Failsafe.
  • Findbugs.
  • Test coverage via Jacoco.

Where are the Jacoco results? After testing and running 'mvn clean', you can find the results in 'target/site/jacoco/index.html'. Open this file in the browser.

Enjoy!

I tried to keep the project as simple as possible. The project puts many suggestions from these posts together in an example project. Thank you, contributors!

Clearing _POST array fully

It may appear to be overly awkward, but you're probably better off unsetting one element at a time rather than the entire $_POST array. Here's why: If you're using object-oriented programming, you may have one class use $_POST['alpha'] and another class use $_POST['beta'], and if you unset the array after first use, it will void its use in other classes. To be safe and not shoot yourself in the foot, just drop in a little method that will unset the elements that you've just used: For example:

private function doUnset()
{
    unset($_POST['alpha']);
    unset($_POST['gamma']);
    unset($_POST['delta']);
    unset($_GET['eta']);
    unset($_GET['zeta']);
}

Just call the method and unset just those superglobal elements that have been passed to a variable or argument. Then, the other classes that may need a superglobal element can still use them.

However, you are wise to unset the superglobals as soon as they have been passed to an encapsulated object.

VB.NET: how to prevent user input in a ComboBox

---- in form level Declaration of cbx veriable---

Dim cbx as string

Private Sub comboBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Enter
    cbx = Me.comboBox1.Text
End Sub

Private Sub comboBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Leave
    Me.comboBox1.Text = cbx
End Sub

How to determine the Schemas inside an Oracle Data Pump Export file

Step 1: Here is one simple example. You have to create a SQL file from the dump file using SQLFILE option.

Step 2: Grep for CREATE USER in the generated SQL file (here tables.sql)

Example here:

$ impdp directory=exp_dir dumpfile=exp_user1_all_tab.dmp  logfile=imp_exp_user1_tab sqlfile=tables.sql

Import: Release 11.2.0.3.0 - Production on Fri Apr 26 08:29:06 2013

Copyright (c) 1982, 2011, Oracle and/or its affiliates. All rights reserved.

Username: / as sysdba

Processing object type SCHEMA_EXPORT/PRE_SCHEMA/PROCACT_SCHEMA Job "SYS"."SYS_SQL_FILE_FULL_01" successfully completed at 08:29:12

$ grep "CREATE USER" tables.sql

CREATE USER "USER1" IDENTIFIED BY VALUES 'S:270D559F9B97C05EA50F78507CD6EAC6AD63969E5E;BBE7786A5F9103'

Lot of datapump options explained here http://www.acehints.com/p/site-map.html

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

Getting list of pixel values from PIL

If you have numpy installed you can try:

data = numpy.asarray(im)

(I say "try" here, because it's unclear why getdata() isn't working for you, and I don't know whether asarray uses getdata, but it's worth a test.)

SQL Server function to return minimum date (January 1, 1753)

You could write a User Defined Function that returns the min date value like this:

select cast(-53690 as datetime)

Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.

Alternately, you could use this query if you prefer it for better readability:

select cast('1753-1-1' as datetime)

Example Function

create function dbo.DateTimeMinValue()
returns datetime as
begin
    return (select cast(-53690 as datetime))
end

Usage

select dbo.DateTimeMinValue() as DateTimeMinValue

DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000

Get SSID when WIFI is connected

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

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

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

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When to use extern in C++

It's all about the linkage.

The previous answers provided good explainations about extern.

But I want to add an important point.

You ask about extern in C++ not in C and I don't know why there is no answer mentioning about the case when extern comes with const in C++.

In C++, a const variable has internal linkage by default (not like C).

So this scenario will lead to linking error:

Source 1 :

const int global = 255; //wrong way to make a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

It need to be like this:

Source 1 :

extern const int global = 255; //a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

Apply CSS Style to child elements

This code can do the trick as well, using the SCSS syntax

.parent {
  & > * {
    margin-right: 15px;
    &:last-child {
      margin-right: 0;
    }
  }
}

Android Lint contentDescription warning

ContentDescription needed for the Android accessibility. Particularly for the screen reader feature. If you don't support Android accessibility you can ignore it with setup Lint.

So just create lint.xml.

<?xml version="1.0" encoding="UTF-8"?>
<lint>

    <issue id="ContentDescription" severity="ignore" />

</lint>

And put it to the app folder.

enter image description here

How can I do SELECT UNIQUE with LINQ?

The Distinct() is going to mess up the ordering, so you'll have to the sorting after that.

var uniqueColors = 
               (from dbo in database.MainTable 
                 where dbo.Property == true 
                 select dbo.Color.Name).Distinct().OrderBy(name=>name);

Multiple returns from a function

Some might prefer returning multiple values as object:

function test() {
    $object = new stdClass();

    $object->x = 'value 1';
    $object->y = 'value 2';

    return $object;
}

And call it like this:

echo test()->x;

Or:

$test = test();
echo $test->y;

Javascript get Object property Name

Like the other answers you can do theTypeIs = Object.keys(myVar)[0]; to get the first key. If you are expecting more keys, you can use

Object.keys(myVar).forEach(function(k) {
    if(k === "typeA") {
        // do stuff
    }
    else if (k === "typeB") {
        // do more stuff
    }
    else {
        // do something
    }
});

Getting activity from context in android

If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.

It is untested and i coded it right . but i am conveying a way to achieve what you want.

First of all create and Interface

interface TaskCompleteListener<T> {
   public void onProfileClicked(T result);
}



public class ProfileView extends LinearLayout
{
    private TaskCompleteListener<String> callback;
    TextView profileTitleTextView;
    ImageView profileScreenImageButton;
    boolean isEmpty;
    ProfileData data;
    String name;

    public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
    {
        super(context, attrs);
        ......
        ......
    }
    public setCallBack( TaskCompleteListener<String> cb) 
    {
      this.callback = cb;
    }
    //Heres where things get complicated
    public void onClick(View v)
    {
        callback.onProfileClicked("Pass your result or any type");
    }
}

And implement this to any Activity.

and call it like

ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
               {
                   public void onProfileClicked(String resultStringFromProfileView){}
               });

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

Creating and Update Laravel Eloquent

like @JuanchoRamone posted above (thank @Juancho) it's very useful for me, but if your data is array you should modify a little like this:

public static function createOrUpdate($data, $keys) {
    $record = self::where($keys)->first();
    if (is_null($record)) {
        return self::create($data);
    } else {
        return $record->update($data);
    }
}

Free tool to Create/Edit PNG Images?

I use Pixlr - an online photo editor, it has great filters and user friendly interface.

HTML CSS Invisible Button

Use CSS background:transparent; to your button/div.

JSFiddle

Can't clone a github repo on Linux via HTTPS

I had the same problem and error. In my case it was the https_proxy not set. Setting the https_proxy environment variable fixed the issue.

$ export https_proxy=https://<porxy_addres>:<proxy_port>

Example:

$ export https_proxy=https://my.proxy.company.com:8000

Hope this help somebody.

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

This worked for me when I encountered the same issue on my KitKat. Remove your account from the device (Settings > Accounts > Google > Remove Account)

Remove the following data: Settings> Applications > All> Downloads > delete data. Settings> Applications > All> Play Store> delete data. Settings> Apps > All> Google Services Framework (or if they have it in English: Google Service Framework) > delete data.

Log in again and it was fixed for me.

Javascript Print iframe contents only

an alternate option, which may or may not be suitable, but cleaner if it is:

If you always want to just print the iframe from the page, you can have a separate "@media print{}" stylesheet that hides everything besides the iframe. Then you can just print the page normally.

Hide/Show Action Bar Option Menu Item for different fragments

This is one way of doing this:

add a "group" to your menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <group
        android:id="@+id/main_menu_group">
         <item android:id="@+id/done_item"
              android:title="..."
              android:icon="..."
              android:showAsAction="..."/>
    </group>
</menu>

then, add a

Menu menu;

variable to your activity and set it in your override of onCreateOptionsMenu:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    // inflate your menu here
}

After, add and use this function to your activity when you'd like to show/hide the menu:

public void showOverflowMenu(boolean showMenu){
    if(menu == null)
        return;
    menu.setGroupVisible(R.id.main_menu_group, showMenu);
}

I am not saying this is the best/only way, but it works well for me.

Dealing with float precision in Javascript

From this post: How to deal with floating point number precision in JavaScript?

You have a few options:

  • Use a special datatype for decimals, like decimal.js
  • Format your result to some fixed number of significant digits, like this: (Math.floor(y/x) * x).toFixed(2)
  • Convert all your numbers to integers

How do I make a splash screen?

Another approach is achieved by using CountDownTimer

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.splashscreen);

 new CountDownTimer(5000, 1000) { //5 seconds
      public void onTick(long millisUntilFinished) {
          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
      }

     public void onFinish() {
          startActivity(new Intent(SplashActivity.this, MainActivity.class));
          finish();
     }

  }.start();
}

How can I convert tabs to spaces in every file of a directory?

Use backslash-escaped sed.

On linux:

  • Replace all tabs with 1 hyphen inplace, in all *.txt files:

    sed -i $'s/\t/-/g' *.txt
    
  • Replace all tabs with 1 space inplace, in all *.txt files:

    sed -i $'s/\t/ /g' *.txt
    
  • Replace all tabs with 4 spaces inplace, in all *.txt files:

    sed -i $'s/\t/    /g' *.txt
    

On a mac:

  • Replace all tabs with 4 spaces inplace, in all *.txt files:

    sed -i '' $'s/\t/    /g' *.txt
    

Change color of Label in C#

I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:

myLabel.ForeColor = System.Drawing.Color.Red;

Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:

myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)

Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".

An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.

A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.

How can I export tables to Excel from a webpage

Far and away, the cleanest, easiest export from tables to Excel is Jquery DataTables Table Tools plugin. You get a grid that sorts, filters, orders, and pages your data, and with just a few extra lines of code and two small files included, you get export to Excel, PDF, CSV, to clipboard and to the printer.

This is all the code that's required:

  $(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

So, quick to deploy, no browser limitations, no server-side language required, and most of all very EASY to understand. It's a win-win. The one thing it does have limits on, though, is strict formatting of columns.

If formatting and colors are absolute dealbreakers, the only 100% reliable, cross browser method I've found is to use a server-side language to process proper Excel files from your code. My solution of choice is PHPExcel It is the only one I've found so far that positively handles export with formatting to a MODERN version of Excel from any browser when you give it nothing but HTML. Let me clarify though, it's definitely not as easy as the first solution, and also is a bit of a resource hog. However, on the plus side it also can output direct to PDF as well. And, once you get it configured, it just works, every time.

UPDATE - September 15, 2016: TableTools has been discontinued in favor of a new plugin called "buttons" These tools perform the same functions as the old TableTools extension, but are FAR easier to install and they make use of HTML5 downloads for modern browsers, with the capability to fallback to the original Flash download for browsers that don't support the HTML5 standard. As you can see from the many comments since I posted this response in 2011, the main weakness of TableTools has been addressed. I still can't recommend DataTables enough for handling large amounts of data simply, both for the developer and the user.

Get name of current class?

import sys

def class_meta(frame):
    class_context = '__module__' in frame.f_locals
    assert class_context, 'Frame is not a class context'

    module_name = frame.f_locals['__module__']
    class_name = frame.f_code.co_name
    return module_name, class_name

def print_class_path():
    print('%s.%s' % class_meta(sys._getframe(1)))

class MyClass(object):
    print_class_path()

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

I find it useful, because when I didn't know about env, before I started to write script I was doing this:

type nodejs > scriptname.js #or any other environment

and then I was modifying that line in the file into shebang.
I was doing this, because I didn't always remember where is nodejs on my computer -- /usr/bin/ or /bin/, so for me env is very useful. Maybe there are details with this, but this is my reason

ASP.NET MVC passing an ID in an ActionLink to the controller

The ID will work with @ sign in front also, but we have to add one parameter after that. that is null

look like:

@Html.ActionLink("Label Name", "Name_Of_Page_To_Redirect", "Controller", new {@id="Id_Value"}, null)

How to get current SIM card number in Android?

Getting the Phone Number, IMEI, and SIM Card ID

TelephonyManager tm = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);        

For SIM card, use the getSimSerialNumber()

    //---get the SIM card ID---
    String simID = tm.getSimSerialNumber();
    if (simID != null)
        Toast.makeText(this, "SIM card ID: " + simID, 
        Toast.LENGTH_LONG).show();

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

    //---get the phone number---
    String telNumber = tm.getLine1Number();
    if (telNumber != null)        
        Toast.makeText(this, "Phone number: " + telNumber, 
        Toast.LENGTH_LONG).show();

IMEI number of the phone, use the getDeviceId()

    //---get the IMEI number---
    String IMEI = tm.getDeviceId();
    if (IMEI != null)        
        Toast.makeText(this, "IMEI number: " + IMEI, 
        Toast.LENGTH_LONG).show();

Permissions needed

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Create tap-able "links" in the NSAttributedString of a UILabel?

Yes this is possible albeit very confusing to figure out at first. I will go a step further and show you how you can even click on any area in the text as well.

With this method you can have UI Label tha is:

  • Multiline Friendly
  • Autoshrink Friendly
  • Clickable Friendly (yes, even individual characters)
  • Swift 5

Step 1:

Make the UILabel have the properties for Line Break of 'Truncate Tail' and set a minimum font scale.

If you are unfamiliar with font scale just remember this rule:

minimumFontSize/defaultFontSize = fontscale

In my case I wanted 7.2 to be the minimum font size and my starting font size was 36. Therefore, 7.2 / 36 = 0.2

enter image description here

Step 2:

If you do not care about the labels being clickable and just wanted a working multiline label you are done!

HOWEVER, if you want the labels to be clickable read on...

Add this following extension I created

extension UILabel {

    func setOptimalFontSize(maxFontSize:CGFloat,text:String){
        let width = self.bounds.size.width

        var font_size:CGFloat = maxFontSize //Set the maximum font size.
        var stringSize = NSString(string: text).size(withAttributes: [.font : self.font.withSize(font_size)])
        while(stringSize.width > width){
            font_size = font_size - 1
            stringSize = NSString(string: text).size(withAttributes: [.font : self.font.withSize(font_size)])
        }

        self.font = self.font.withSize(font_size)//Forcefully change font to match what it would be graphically.
    }
}

It's used like this (just replace <Label> with your actual label name):

<Label>.setOptimalFontSize(maxFontSize: 36.0, text: formula)

This extension is needed because auto shrink does NOT change the 'font' property of the label after it auto-shrinks so you have to deduce it by calculating it the same way it does by using .size(withAttributes) function which simulates what it's size would be with that particular font.

This is necessary because the solution for detecting where to click on the label requires the exact font size to be known.

Step 3:

Add the following extension:

extension UITapGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
        // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)

        let mutableAttribString = NSMutableAttributedString(attributedString: label.attributedText!)
        mutableAttribString.addAttributes([NSAttributedString.Key.font: label.font!], range: NSRange(location: 0, length: label.attributedText!.length))

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 6
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.alignment = .center
        mutableAttribString.addAttributes([.paragraphStyle: paragraphStyle], range: NSMakeRange(0, mutableAttribString.string.count))

        let textStorage = NSTextStorage(attributedString: mutableAttribString)

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines

        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)

        textStorage.addLayoutManager(layoutManager)

        let labelSize = label.bounds.size

        textContainer.size = labelSize

        // Find the tapped character location and compare it to the specified range
        let locationOfTouchInLabel = self.location(in: label)

        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        //let textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                              //(labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
        let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

        //let locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                        // locationOfTouchInLabel.y - textContainerOffset.y);
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)

        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        print("IndexOfCharacter=",indexOfCharacter)

        print("TargetRange=",targetRange)
        return NSLocationInRange(indexOfCharacter, targetRange)
    }

}

You will need to modify this extension for your particular multiline situation. In my case you will notice that I use a paragraph style.

let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 6
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.alignment = .center
        mutableAttribString.addAttributes([.paragraphStyle: paragraphStyle], range: NSMakeRange(0, mutableAttribString.string.count))

Make sure to change this in the extension to what you are actually using for your line spacing so that everything calculates correctly.

Step 4:

Add the gestureRecognizer to the label in viewDidLoad or where you think is appropriate like so (just replace <Label> with your label name again:

<Label>.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(tapLabel(gesture:))))

Here is a simplified example of my tapLabel function (just replace <Label> with your UILabel name):

@IBAction func tapLabel(gesture: UITapGestureRecognizer) {
        guard let text = <Label>.attributedText?.string else {
            return
        }

        let click_range = text.range(of: "(a/ß)")

        if gesture.didTapAttributedTextInLabel(label: <Label>, inRange: NSRange(click_range!, in: text)) {
           print("Tapped a/b")
        }else {
           print("Tapped none")
        }
    }

Just a note in my example, my string is BED = N * d * [ RBE + ( d / (a/ß) ) ], so I was just getting the range of the a/ß in this case. You could add "\n" to the string to add a newline and whatever text you wanted after and test this to find a string on the next line and it will still find it and detect the click correctly!

That's it! You are done. Enjoy a multiline clickable label.

Changing the default title of confirm() in JavaScript?

You can always use a hidden div and use javascript to "popup" the div and have buttons that are like yes and or no. Pretty easy stuff to do.

INFO: No Spring WebApplicationInitializer types detected on classpath

My silly reason was: Build Automatically was disabled!

Is there a need for range(len(a))?

What if you need to access two elements of the list simultaneously?

for i in range(len(a[0:-1])):
    something_new[i] = a[i] * a[i+1]

You can use this, but it's probably less clear:

for i, _ in enumerate(a[0:-1]):
     something_new[i] = a[i] * a[i+1]

Personally I'm not 100% happy with either!

Cross-Origin Request Headers(CORS) with PHP headers

Many description internet-wide don't mention that specifying Access-Control-Allow-Origin is not enough. Here is a complete example that works for me:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
        header('Access-Control-Allow-Headers: token, Content-Type');
        header('Access-Control-Max-Age: 1728000');
        header('Content-Length: 0');
        header('Content-Type: text/plain');
        die();
    }

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');

    $ret = [
        'result' => 'OK',
    ];
    print json_encode($ret);

How to determine if string contains specific substring within the first X characters

Adding on from the answer below i have created this method:

    public static bool ContainsInvalidStrings(IList<string> invalidStrings,string stringToCheck)
    {

        foreach (string invalidString in invalidStrings)
        {
            var index = stringToCheck.IndexOf(invalidString, StringComparison.InvariantCultureIgnoreCase);
            if (index != -1)
            {
                return true;
            }
        }
        return false;
    }

it can be used like this:

            var unsupportedTypes = new List<string>()
        {
            "POINT Empty",
            "MULTIPOINT",
            "MULTILINESTRING",
            "MULTIPOLYGON",
            "GEOMETRYCOLLECTION",
            "CIRCULARSTRING",
            "COMPOUNDCURVE",
            "CURVEPOLYGON",
            "MULTICURVE",
            "TRIANGLE",
            "TIN",
            "POLYHEDRALSURFACE"
        };


            bool hasInvalidValues =   ContainsInvalidStrings(unsupportedTypes,possibleWKT);

you can check for multiple invalid values this way.

Couldn't load memtrack module Logcat Error

This error, as you can read on the question linked in comments above, results to be:

"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."

The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:

  • package="com.example.hive" in <manifest> tag,
  • android:name="com.sit.gems.app.GemsApplication" for <application>
  • and android:name="com.sit.gems.activity" in <activity>

As you know, these things do not prevent your app to be displayed. But I think:

the Couldn't load memtrack module error could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.

For better using and with few things, this can be resolved by following these tips:


1. Try an other emulator...

And even a real device! The memtrack module error seems related to your emulator. So change it into Run configuration, don't forget to change the API too.


2. OpenGL error logs

For OpenGl errors, as called unimplemented OpenGL ES API, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java, it might help you):

<uses-feature android:glEsVersion="0x00020000"></uses-feature>  
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />

3. Use the same package

Don't declare different package names to all the tags in Manifest. You should have the same for Manifest, Activities, etc. Something like this looks right:

<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sit.gems.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- don't set a package name in <application> -->
    <application ... >

        <!-- then, declare the activities -->
        <activity
            android:name="com.sit.gems.activity.SplashActivity" ... >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- same package here -->
        <activity
            android:name="com.sit.gems.activity.HomeActivity" ... >
        </activity>
    </application>
</manifest>  

4. Don't get lost with layouts:

You should set another layout for SplashScreenActivity.java because you're not using the TabHost for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:

// inside SplashScreen class
setContentView(R.layout.splash_screen);

// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" 
     android:gravity="center"
     android:text="@string/appname" />  

Avoid using a layout in activities which don't use it.


5. Splash Screen?

Finally, I don't understand clearly the purpose of your SplashScreenActivity. It sets a content view and directly finish. This is useless.

As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity. Therefore, you should do this and don't use the TabHost layout ;):

// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set your splash_screen layout
        setContentView(R.layout.splash_screen);

        // create a new Thread
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sleep during 800ms
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // start HomeActivity
                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                SplashActivity.this.finish();
            }
        }).start();
    }
}  

I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.

Bootstrap 3: how to make head of dropdown link clickable in navbar

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

What is "pom" packaging in maven?

Real life use case

At a Java-heavy company we had a python project that needed to go into a Nexus artifact repository. Python doesn't really have binaries, so simply just wanted to .tar or .zip the python files and push. The repo already had maven integration, so we used <packaging>pom</packaging> designator with the maven assembly plugin to package the python project as a .zip and upload it.

The steps are outlined in this SO post

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Set LIMIT with doctrine 2?

$query_ids = $this->getEntityManager()
      ->createQuery(
        "SELECT e_.id
        FROM MuzichCoreBundle:Element e_
        WHERE [...]
        GROUP BY e_.id")
     ->setMaxResults(5)
     ->setMaxResults($limit) 
    ;

HERE in the second query the result of the first query should be passed ..

$query_select = "SELECT e
      FROM MuzichCoreBundle:Element e 
      WHERE e.id IN (".$query_ids->getResult().")
      ORDER BY e.created DESC, e.name DESC"
    ;


$query = $this->getEntityManager()
      ->createQuery($query_select)
      ->setParameters($params)
      ->setMaxResults($limit);
    ;

$resultCollection = $query->getResult();

Convert a string to int using sql query

Also be aware that when converting from numeric string ie '56.72' to INT you may come up against a SQL error.

Conversion failed when converting the varchar value '56.72' to data type int.

To get around this just do two converts as follows:

STRING -> NUMERIC -> INT

or

SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT)

When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):

INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA

Prevent cell numbers from incrementing in a formula in Excel

TL:DR
row lock = A$5
column lock = $A5
Both = $A$5

Below are examples of how to use the Excel lock reference $ when creating your formulas

To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5

To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5

To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5

Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.

MySQL - UPDATE query based on SELECT Query

For same table,

UPDATE PHA_BILL_SEGMENT AS PHA,
     (SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG 
       FROM PHA_BILL_SEGMENT
        GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
        HAVING REG > 1) T
    SET PHA.BILL_DATE = PHA.BILL_DATE + 2
 WHERE PHA.BILL_ID = T.BILL_ID;

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

Why doesn't file_get_contents work?

//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?php    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

What is a "callback" in C and how are they implemented?

Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event() and data pointers to a framework function watch_events() (for example). When an event happens, your function is called with your data and some event-specific data.

Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

Changing the text on a label

Use the config method to change the value of the label:

top = Tk()

l = Label(top)
l.pack()

l.config(text = "Hello World", width = "50")

How to delete duplicates on a MySQL table?

This works for large tables:

 CREATE Temporary table duplicates AS select max(id) as id, url from links group by url having count(*) > 1;

 DELETE l from links l inner join duplicates ld on ld.id = l.id WHERE ld.id IS NOT NULL;

To delete oldest change max(id) to min(id)

Ruby on Rails: How do I add placeholder text to a f.text_field?

I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:

text_field_tag :attr, "", placeholder: "placeholder text"

Java: notify() vs. notifyAll() all over again

However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.

That is not correct. o.notifyAll() wakes all of the threads that are blocked in o.wait() calls. The threads are only allowed to return from o.wait() one-by-one, but they each will get their turn.


Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?

In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time.

Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.


In many cases, the code to await a condition will be written as a loop:

synchronized(o) {
    while (! IsConditionTrue()) {
        o.wait();
    }
    DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();
}

That way, if an o.notifyAll() call wakes more than one waiting thread, and the first one to return from the o.wait() makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Different between parseInt() and valueOf() in java?

If you check the Integer class you will find that valueof call parseInt method. The big difference is caching when you call valueof API . It cache if the value is between -128 to 127 Please find below the link for more information

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

What does the ">" (greater-than sign) CSS selector mean?

> (greater-than sign) is a CSS Combinator.

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS3:

  1. descendant selector (space)
  2. child selector (>)
  3. adjacent sibling selector (+)
  4. general sibling selector (~)

Note: < is not valid in CSS selectors.

enter image description here

For example:

<!DOCTYPE html>
<html>
<head>
<style>
div > p {
    background-color: yellow;
}
</style>
</head>
<body>

<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <span><p>Paragraph 3 in the div.</p></span> <!-- not Child but Descendant -->
</div>

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

</body>
</html>

Output:

enter image description here

More information about CSS Combinators

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you do not like double quotes like me, this will work for you with single quotes:

$value = Input::get('q');
$books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();

return view('pages/search/index', compact('books'));

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

How do I get the current mouse screen coordinates in WPF?

This works without having to use forms or import any DLLs:

   using System.Windows;
   using System.Windows.Input;

    /// <summary>
    /// Gets the current mouse position on screen
    /// </summary>
    private Point GetMousePosition()
    {
        // Position of the mouse relative to the window
        var position = Mouse.GetPosition(Window);

        // Add the window position
        return new Point(position.X + Window.Left, position.Y + Window.Top);
    }

Window vs Page vs UserControl for WPF navigation?

A Window object is just what it sounds like: its a new Window for your application. You should use it when you want to pop up an entirely new window. I don't often use more than one Window in WPF because I prefer to put dynamic content in my main Window that changes based on user action.

A Page is a page inside your Window. It is mostly used for web-based systems like an XBAP, where you have a single browser window and different pages can be hosted in that window. It can also be used in Navigation Applications like sellmeadog said.

A UserControl is a reusable user-created control that you can add to your UI the same way you would add any other control. Usually I create a UserControl when I want to build in some custom functionality (for example, a CalendarControl), or when I have a large amount of related XAML code, such as a View when using the MVVM design pattern.

When navigating between windows, you could simply create a new Window object and show it

var NewWindow = new MyWindow();
newWindow.Show();

but like I said at the beginning of this answer, I prefer not to manage multiple windows if possible.

My preferred method of navigation is to create some dynamic content area using a ContentControl, and populate that with a UserControl containing whatever the current view is.

<Window x:Class="MyNamespace.MainWindow" ...>
    <DockPanel>
        <ContentControl x:Name="ContentArea" />
    </DockPanel>
</Window>

and in your navigate event you can simply set it using

ContentArea.Content = new MyUserControl();

But if you're working with WPF, I'd highly recommend the MVVM design pattern. I have a very basic example on my blog that illustrates how you'd navigate using MVVM, using this pattern:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example" Height="350" Width="525">

   <Window.Resources>
      <DataTemplate DataType="{x:Type local:HomeViewModel}">
         <local:HomeView /> <!-- This is a UserControl -->
      </DataTemplate>
      <DataTemplate DataType="{x:Type local:ProductsViewModel}">
         <local:ProductsView /> <!-- This is a UserControl -->
      </DataTemplate>
   </Window.Resources>

   <DockPanel>
      <!-- Navigation Buttons -->
      <Border DockPanel.Dock="Left" BorderBrush="Black"
                                    BorderThickness="0,0,1,0">
         <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
               <DataTemplate>
                  <Button Content="{Binding Name}"
                          Command="{Binding DataContext.ChangePageCommand,
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          CommandParameter="{Binding }"
                          Margin="2,5"/>
               </DataTemplate>
            </ItemsControl.ItemTemplate>
         </ItemsControl>
      </Border>

      <!-- Content Area -->
      <ContentControl Content="{Binding CurrentPageViewModel}" />
   </DockPanel>
</Window>

Screenshot1 Screenshot2

Is there a way to remove unused imports and declarations from Angular 2+?

There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.

In the article the author explains it like this:

Make a stand alone tslint file that has the following in it:

{
  "extends": ["tslint-etc"],
  "rules": {
    "no-unused-declaration": true
  }
}

Then run the following command to fix the imports:

 tslint --config tslint-imports.json --fix --project .

Consider fixing any other errors it throws. (I did)

Then check the project works by building it:

ng build

or

ng build name_of_project --configuration=production 

End: If it builds correctly, you have successfully removed imports automatically!

NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.

How to show all privileges from a user in oracle?

Another useful resource:

http://psoug.org/reference/roles.html

  • DBA_SYS_PRIVS
  • DBA_TAB_PRIVS
  • DBA_ROLE_PRIVS

How does Tomcat locate the webapps directory?

Find server.xml at $CATALINA_BASE/conf/server.xml

Find appBase attribute in <Host> element

by default it will be something like : <Host name="localhost" appBase="webapps ...>

Change appBase to your required path. There are different way people put it, but I use

/c:/myfolder/newwebapps

Remember, no slash at the end, but at start. Also note it's direction as well.

Install mysql-python (Windows)

You're going to want to add Python to your Path Environment Variable in this way. Go to:

  1. My Computer
  2. System Properties
  3. Advance System Settings
  4. Under the "Advanced" tab click the button that says "Environment Variables"
  5. Then under System Variables you are going to want to add / change the following variables: PYTHONPATH and Path. Here is a paste of what my variables look like:

PYTHONPATH

C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts

Path

C:\Program Files\MySQL\MySQL Utilities 1.3.5\;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts

Your Path's might be different, so please adjust them, but this configuration works for me and you should be able to run MySQL after making these changes.

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

Cassini runs your website as your own user identity when you start up the Visual Studio application. IIS runs your website as an App Pool Identity. Unless the App Pool Identity is granted access to the Database, you get errors.

IIS introduced App Pool Identity to improve security. You can run websites under the default App Pool Identity, or Create a new App Pool with its own name, or Create a new App Pool with its own name that runs under a User Account (usually Domain Account).

In networked situations (that are not in Azure) you can make a new App Pool run under an Active Directory Domain user account; I prefer this over the machine account. Doing so gives granular security and granular access to network resources, including databases. Each website runs on a different App Pool (and each of those runs under its own Domain User account).

Continue to use Windows Integrated Security in all Connection Strings. In SQL Server, add the Domain users as logins and grant permissions to databases, tables, SP etc. on a per website basis. E.g. DB1 used by Website1 has a login for User1 because Website1 runs on an App Pool as User1.

One challenge with deploying from the Visual Studio built-in DB (e.g. LocalDB) and built-in Web Server to a production environment derives from the fact that the developer's user SID and its ACLs are not to be used in a secure production environment. Microsoft provides tools for deployment. But pity the poor developer who is accustomed to everything just working out of the box in the new easy VS IDE with localDB and localWebServer, because these tools will be hard to use for that developer, especially for such a developer lacking SysAdmin and DBAdmin support or their specialized knowledge. Nonetheless deploying to Azure is easier than the enterprise network situation mentioned above.

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

There seems to be many solutions out there that worked with downgrading npm versions. For me, the solution was

npm install -force

I tried the downgrading of npm versions, modifying my npm prefix config to match the npm directory, and clearing cache. None of these worked, but apparently they worked for others, so it may be worth a shot.

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

I'd add that in case of really odd behavior - where you spend a couple of hours saying WTF - try manually deleting the /webapps/yourwebapp/WEB-INF/classes directory. A java source file that was moved to another package will not have its compiled class file deleted - at least in the case of an exploded web-application on TC. This can seriously drive you crazy with unpredictable behavior, especially with an annotated servlet.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Connecting PostgreSQL 9.2.1 with Hibernate

This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>



        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>



       <mapping class="org.javabrains.sanjaya.dto.UserDetails"/>

    </session-factory>
</hibernate-configuration>

Hash function for a string

Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.

if your values are strings, here are some examples for bad hash functions:

  1. string[0] - the ASCII characters a-Z are way more often then others
  2. string.lengh() - the most probable value is 1

Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.

How to convert a string or integer to binary in Ruby?

If you're only working with the single digits 0-9, it's likely faster to build a lookup table so you don't have to call the conversion functions every time.

lookup_table = Hash.new
(0..9).each {|x|
    lookup_table[x] = x.to_s(2)
    lookup_table[x.to_s] = x.to_s(2)
}
lookup_table[5]
=> "101"
lookup_table["8"]
=> "1000"

Indexing into this hash table using either the integer or string representation of a number will yield its binary representation as a string.

If you require the binary strings to be a certain number of digits long (keep leading zeroes), then change x.to_s(2) to sprintf "%04b", x (where 4 is the minimum number of digits to use).

Output ("echo") a variable to a text file

After some trial and error, I found that

$computername = $env:computername

works to get a computer name, but sending $computername to a file via Add-Content doesn't work.

I also tried $computername.Value.

Instead, if I use

$computername = get-content env:computername

I can send it to a text file using

$computername | Out-File $file

How to change the color of an svg element?

if you want to change the color dynamically:

  1. Open de svg in a code editor
  2. Add or rewrite the attribute of fill of every path to fill="currentColor"
  3. Now, that svg will take the color of your font color so you can do something like:
svg {
    color : "red";
}

How do I float a div to the center?

Try margin: 0 auto, the div will need a fixed with.

What is the difference between a Docker image and a container?

As many answers pointed this out: You build Dockerfile to get an image and you run image to get a container.

However, following steps helped me get a better feel for what Docker image and container are:

1) Build Dockerfile:

docker build -t my_image dir_with_dockerfile

2) Save the image to .tar file

docker save -o my_file.tar my_image_id

my_file.tar will store the image. Open it with tar -xvf my_file.tar, and you will get to see all the layers. If you dive deeper into each layer you can see what changes were added in each layer. (They should be pretty close to commands in the Dockerfile).

3) To take a look inside of a container, you can do:

sudo docker run -it my_image bash

and you can see that is very much like an OS.

How to negate 'isblank' function

If you're trying to just count how many of your cells in a range are not blank try this:

=COUNTA(range)

Example: (assume that it starts from A1 downwards):

---------    
Something 
---------
Something
---------

---------
Something
---------

---------
Something
---------

=COUNTA(A1:A6) returns 4 since there are two blank cells in there.

IF formula to compare a date with current date and return result

You can enter the following formula in the cell where you want to see the Overdue or Not due result:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))

This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue, otherwise it is set to Not due.

jQuery event handlers always execute in order they were bound - any way around this?

Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)

$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.bind(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    var handlers = this.data('events')[name.split('.')[0]];
    // take out the handler we just inserted from the end
    var copy = {1: null};

    var last = 0, lastValue = null;
    $.each(handlers, function(name, value) {
        //console.log(name + ": " + value);
        var isNumber = !isNaN(name);
        if(isNumber) {last = name; lastValue = value;};

        var key = isNumber ? (parseInt(name) + 1) : name;
        copy[key] = value;
    });
    copy[1] = lastValue;
    this.data('events')[name.split('.')[0]] = copy;
};

How can I repeat a character in Bash?

Simplest is to use this one-liner in csh/tcsh:

printf "%50s\n" '' | tr '[:blank:]' '[=]'

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

The problem with editing JavaScript like you can CSS and HTML is that there is no clean way to propagate the changes. JavaScript can modify the DOM, send Ajax requests, and dynamically modify existing objects and functions at runtime. So, once you have loaded a page with JavaScript, it might be completely different after the JavaScript has run. The browser would have to keep track of every modification your JavaScript code performs so that when you edit the JS, it rolls back the changes to a clean page.

But, you can modify JavaScript dynamically a few other ways:

  • JavaScript injections in the URL bar: javascript: alert (1);
  • Via a JavaScript console (there's one built into Firefox, Chrome, and newer versions of IE
  • If you want to modify the JavaScript files as they are served to your browser (i.e. grabbing them in transit and modifying them), then I can't offer much help. I would suggest using a debugging proxy: http://www.fiddler2.com/fiddler2/

The first two options are great because you can modify any JavaScript variables and functions currently in scope. However, you won't be able to modify the code and run it with a "just-served" page like you can with the third option.

Other than that, as far as I know, there is no edit-and-run JavaScript editor in the browser. Hope this helps,

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

@DCookie

I just want to point out that you can leave off the lines that say

EXCEPTION  
  WHEN OTHERS THEN    
    RAISE;

You'll get the same effect if you leave off the exception block all together, and the line number reported for the exception will be the line where the exception is actually thrown, not the line in the exception block where it was re-raised.

Best lightweight web server (only static content) for Windows

Have a look at mongoose:

  • single executable
  • very small memory footprint
  • allows multiple worker threads
  • easy to install as service
  • configurable with a configuration file if required

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

Newline in markdown table?

Just for those that are trying to do this on Jira. Just add \\ at the end of each line and a new line will be created:

|Something|Something else \\ that's rather long|Something else|

Will render this:

enter image description here

Source: Text breaks on Jira

filename and line number of Python script

Thanks to mcandre, the answer is:

#python3
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print(frameinfo.filename, frameinfo.lineno)

How to use a Java8 lambda to sort a stream in reverse order?

In simple, using Comparator and Collection you can sort like below in reversal order using JAVA 8

import java.util.Comparator;;
import java.util.stream.Collectors;

Arrays.asList(files).stream()
    .sorted(Comparator.comparing(File::getLastModified).reversed())
    .collect(Collectors.toList());

Jquery validation plugin - TypeError: $(...).validate is not a function

For me problem solved by changing http://ajax... into https://ajax... (add an S to http)

https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js

Responsive design with media query : screen size?

The screen widths Bootstrap v3.x uses are as follows:

  • Extra small devices Phones (<768px) / .col-xs-
  • Small devices Tablets (=768px) / .col-sm-
  • Medium devices Desktops (=992px) / .col-md-
  • Large devices Desktops (=1200px) / .col-lg-

So, these are good to use and work well in practice.

How to delete specific characters from a string in Ruby?

Do as below using String#tr :

 "((String1))".tr('()', '')
 # => "String1"

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my experience, the most friendly way of dealing with this is to have a function that converts a string into a table of values.

There are many splitter functions available on the web, you'll easily find one for whatever if your flavour of SQL.

You can then do...

SELECT * FROM table WHERE id IN (SELECT id FROM split(@list_of_ids))

Or

SELECT * FROM table INNER JOIN (SELECT id FROM split(@list_of_ids)) AS list ON list.id = table.id

(Or similar)

New Intent() starts new instance with Android: launchMode="singleTop"

This should do the trick.

<activity ... android:launchMode="singleTop" />

When you create an intent to start the app use:

Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

This is that should be needed.

Replace line break characters with <br /> in ASP.NET MVC Razor view

Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!

<span style="white-space: pre-line">@Model.CommentText</span>

How do I put double quotes in a string in vba?

I prefer the answer of tabSF . implementing the same to your answer. here below is my approach

Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"

StringBuilder vs String concatenation in toString() in Java

Make the toString method as readable as you possibly can!

The sole exception for this in my book is if you can prove to me that it consumes significant resources :) (Yes, this means profiling)

Also note that the Java 5 compiler generates faster code than the handwritten "StringBuffer" approach used in earlier versions of Java. If you use "+" this and future enhancements comes for free.

Java AES and using my own Key

Edit:

As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.

    SecureRandom sr = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);

    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
    Cipher aes = Cipher.getInstance("AES");
    aes.init(Cipher.ENCRYPT_MODE, key);

===========

Old Answer

You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).

Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.

byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit

SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"

For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"

Bootstrap 4 navbar color

I got it. This is very simple. Using the class bg you can achieve this easily.

Let me show you:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>

This gives you the default blue navbar

If you want to change your favorite color, then simply use the style tag within the nav:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">

Bootstrap 3: Text overlay on image

try the following example. Image overlay with text on image. demo

<div class="thumbnail">
  <img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..."   />
  <div class="caption post-content">  
  </div> 
  <div class="details">
    <h3>Robots!</h3>
    <p>Lorem ipsum dolor sit amet</p>   
  </div>  
</div>

css

.post-content {
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
    opacity: 0.5;
    top:0;
    left:0;
    min-width: 500px;
    min-height: 500px; 
    position: absolute;
    color: #ffffff; 
}

.thumbnail{
    position:relative;

}
.details {
    position: absolute; 
    z-index: 2; 
    top: 0;
    color: #ffffff; 
}

Setting background images in JFrame

There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is:

  1. Create a subclass of JComponent.
  2. Override the paintComponent(Graphics g) method to paint the image that you want to display.
  3. Set the content pane of the JFrame to be this subclass.

Some sample code:

class ImagePanel extends JComponent {
    private Image image;
    public ImagePanel(Image image) {
        this.image = image;
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

// elsewhere
BufferedImage myImage = ImageIO.read(...);
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));

Note that this code does not handle resizing the image to fit the JFrame, if that's what you wanted.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

are you using jquery and prototype on the same page by any chance?

If so, use jquery noConflict mode, otherwise you are overwriting prototypes $ function.

noConflict mode is activated by doing the following:

<script src="jquery.js"></script>
<script>jQuery.noConflict();</script>

Note: by doing this, the dollar sign variable no longer represents the jQuery object. To keep from rewriting all your jQuery code, you can use this little trick to create a dollar sign scope for jQuery:

jQuery(function ($) {
    // The dollar sign will equal jQuery in this scope
});

// Out here, the dollar sign still equals Prototype

python - checking odd/even numbers and changing outputs on number size

1) How do I check if it's even or odd? I tried "if number/2 == int" in the hope that it might do something, and the internet tells me to do "if number%2==0", but that doesn't work.

def isEven(number):
        return number % 2 == 0

Matching strings with wildcard

*X*YZ* = string contains X and contains YZ

@".*X.*YZ"

X*YZ*P = string starts with X, contains YZ and ends with P.

@"^X.*YZ.*P$"