Programs & Examples On #Embed

To "Embed" is to place a software module, object, or application into your own application or web page.

start/play embedded (iframe) youtube-video on click of an image

You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.

How to embed a SWF file in an HTML page?

How about simple HTML5 tag embed?

<!DOCTYPE html>
<html>
<body>

<embed src="anim.swf">

</body>
</html>

Embedding a media player in a website using HTML

Here is a solution to make an accessible audio player with valid xHTML and non-intrusive javascript thanks to W3C Web Audio API :

What to do :

  1. If the browser is able to read, then we display controls
  2. If the browser is not able to read, we just render a link to the file

First of all, we check if the browser implements Web Audio API:

if (typeof Audio === 'undefined') {
    // abort
}

Then we instanciate an Audio object:

var player = new Audio('mysong.ogg');

Then we can check if the browser is able to decode this type of file :

if(!player.canPlayType('audio/ogg')) {
    // abort
}

Or even if it can play the codec :

if(!player.canPlayType('audio/ogg; codecs="vorbis"')) {
    // abort
}

Then we can use player.play(), player.pause();

I have done a tiny JQuery plugin that I called nanodio to test this.

You can check how it works on my demo page (sorry, but text is in french :p )

Just click on a link to play, and click again to pause. If the browser can read it natively, it will. If it can't, it should download the file.

This is just a little example, but you can improve it to use any element of your page as a control button or generate ones on the fly with javascript... Whatever you want.

MongoDB relationships: embed or reference?

Yes, we can use the reference in the document.To populate the another document just like sql i joins.In mongo db they dont have joins to mapping one to many relationship document.Instead that we can use populate to fulfill our scenario..

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query. Let's look at some examples.

Better you can get more information please visit :http://mongoosejs.com/docs/populate.html

How to embed PDF file with responsive width

<object data="resume.pdf" type="application/pdf" width="100%" height="800px"> 
   <p>It appears you don't have a PDF plugin for this browser.
       No biggie... you can <a href="resume.pdf">click here to
       download the PDF file.</a>
  </p>  
</object>

Embed a PowerPoint presentation into HTML

I don't know of a way to embed PowerPoint slides directly into HTML. However, there are a number of solutions online for converting a PPT file into a SWF, which can be embedded into HTML just like any other Flash movie.

Googling for 'ppt to swf' seems to give a lot of hits. Some are free, others aren't. Some handle things like animations, others just do still images. There's got to be one out there that does what you need. :)

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

How to hide the bar at the top of "youtube" even when mouse hovers over it?

The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

How to embed fonts in HTML?

I asked this a while back. The answer is basically that it doesn't work. :(

How to embed a Google Drive folder in a website

Embedding a Google Drive directory in an IFRAME

Google Drive folders can be embedded and displayed in list and grid views (in which all you can do is click a file or folder to open it on a new tab). To do so, simply replace FOLDER-ID with your own in:

List view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>

or without specifying a mode, since list mode is the default:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID" style="width:100%; height:600px; border:0;"></iframe>

Grid view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Obtaining your folder id

The id is the hash (alphanumeric gibberish) after folders/ in the URL of the folder. You can see the URL in the address bar of your browser when you open the Drive folder. For example, in:

https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2 

The Folder ID is 0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2.

Folder with G Suite/Google Apps domain

If your folder is part of a Google Apps domain, you can add the domain to the URL to alleviate the permission problems (detailed further ahead):

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Just replace MY.DOMAIN.COM and FOLDER-ID with your own.

Caveat with folders requiring permission

This technique works best for folders with public access. Folders that are shared only with certain Google accounts can cause trouble when you embed them this way, depending on which Google accounts are active on the user's browser:

  1. If the user has not logged in to any Google account, then nothing appears in the frame.
  2. If the user is logged onto an account without authorisation to access the folder, the frame will contain the message You need permission, with some buttons to Request access or Switch accounts, but if you click on this last, the frame blanks out.
  3. If the user logs into an account without proper permissions, and later adds the authorised account, on loading the embedded Drive Google will resort to the first active account, and the user will see You need permission, unless...
  4. If the URL contains a Google Suite domain, and the user is logged into that domain's account, the embedded view will work, even if the user logged to another account first.

The blank frames are because Google forbids embedding its login page in an IFRAME (presumably to prevent account stealing), via the X-Frame-Options header, which if set to SAMEORIGIN will cause any well-behaved browser to refuse to load the page if it's not in the same domain (v.g. drive.google.com). You can see this in the developer console of your browser.

TL;DR

To get a list or grid view of a Drive folder (in which all you can do is click a file or folder to open it on a new tab), use:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

or alternatively, for a Google Suite/Apps Drive:

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Replace MY.DOMAIN.COM and FOLDER-ID with your own; remove #grid to get a detailed file list.

For private folders, have your users log to the correct account before loading the page with the embedded folder; if the folder is in a Google Apps domain, you can add the domain to the URL. Else, they must log into the authorised account before any other.

(this answer is an edit of Mori's, but it was rejected as it changed his intent, somehow)

Can I embed a .png image into an html page?

use mod_rewrite to redirect the call to file.html to image.png without the url changing for the user

Have you tried just renaming the image.png file to file.html? I think most browser take mime header over file extension :)

Embed website into my site

You can embed websites into another website using the <embed> tag, like so:

<embed src="http://www.example.com" style="width:500px; height: 300px;">

You can change the height, width, and URL to suit your needs.

The <embed> tag is the most up-to-date way to embed websites, as it was introduced with HTML5.

How can I embed a YouTube video on GitHub wiki pages?

I created https://yt-embed.herokuapp.com/ to simplify this. The usage is direct, from the examples above:

[![Everything Is AWESOME](https://yt-embed.herokuapp.com/embed?v=StTqXEQ2l-Y)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

Will result in: example of usage of yt-embed

Just make a call to: https://yt-embed.herokuapp.com/embed?v=[video_id] as the image instead of https://img.youtube.com/vi/.

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

There's a pretty good write up in the Adobe KB's on 'wmode' and other attributes with regards to their effect on presentation and performance.

http://kb2.adobe.com/cps/127/tn_12701.html

How do I force files to open in the browser instead of downloading (PDF)?

Either use

<embed src="file.pdf" />

if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff

Shrink a YouTube video to responsive width

@magi182's solution is solid, but it lacks the ability to set a maximum width. I think a maximum width of 640px is necessary because otherwhise the youtube thumbnail looks pixelated.

My solution with two wrappers works like a charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I also set the padding-bottom in the inner wrapper to 50 %, because with @magi182's 56 %, a black bar on top and bottom appeared.

Embed an External Page Without an Iframe?

You could load the external page with jquery:

<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script>
<div id="testLoad"></div>
//would this help

Embedding Windows Media Player for all browsers

You could use conditional comments to get IE and Firefox to do different things

<![if !IE]>
<p> Firefox only code</p>
<![endif]>

<!--[if IE]>
<p>Internet Explorer only code</p>
<![endif]-->

The browsers themselves will ignore code that isn't meant for them to read.

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

Force youtube embed to start in 720p

This is an embed example of video played in HD 1080.

<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

Let's break apart the code:http://youtube.com/v/ video_id &vq=hd1080

Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.

So far so good, this trick works for playing full HD videos directly on webpages!

You can change the quality to 720 too. &vq=hd720

Properly embedding Youtube video into bootstrap 3.0 page

There is a Bootstrap3 native solution: http://getbootstrap.com/components/#responsive-embed

since Bootstrap 3.2.0!

If you are using Bootstrap < v3.2.0 so look into "responsive-embed.less" file of v3.2.0 - possibly you can use/copy this code in your case (it works for me in v3.1.1).

How to embed a video into GitHub README.md?

just to extend @GabLeRoux's answer:

[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)

this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.

How to embed images in email

Actually, there are two ways to include images in email.

The first way ensures that the user will see the image, even if in some cases it’s only as an attachment to the message. This method is exactly what we call as “embedding images in email" in daily life.
Essentially, you’re attaching the image to the email. The plus side is that, in one way or another, the user is sure to get the image. While the downside is two fold. Firstly, spam filters look for large, embedded images and often give you a higher spam score for embedding images in email (Lots of spammers use images to avoid having the inappropriate content in their emails read by the spam filters.). Secondly, if you pay to send your email by weight or kilobyte, this increases the size of your message. If you’re not careful, it can even make your message too big for the parameters of the email provider.

The second way to include images (and the far more common way) is the same way that you put an image on a web page. Within the email, you provide a url that is the reference to the image’s location on your server, exactly the same way that you would on a web page. This has several benefits. Firstly, you won’t get caught for spamming or for your message “weighing” too much because of the image. Secondly, you can make changes to the images after the email has been sent if you find errors in them. On the flip side, your recipient will need to actively turn on image viewing in their email client to see your images.

How to upgrade Git on Windows to the latest version?

Update (26SEP2016): It is no longer needed to uninstall your previous version of git to upgraded it to the latest; the installer package found at git win download site takes care of all. Just follow the prompts. For additional information follow instructions at installing and upgrading git.

Adding hours to JavaScript Date object?

The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.

this.setUTCHours(this.getUTCHours()+h);

will add h hours to this independent of time system peculiarities. Jason Harwig's method works as well.

How do I login and authenticate to Postgresql after a fresh install?

by default you would need to use the postgres user:

sudo -u postgres psql postgres

Convert timestamp to date in Oracle SQL

You can try the simple one

select to_date('2020-07-08T15:30:42Z','yyyy-mm-dd"T"hh24:mi:ss"Z"') from dual;

Align nav-items to right side in bootstrap-4

Here and easy Example.

<!-- Navigation bar-->

<nav class="navbar navbar-toggleable-md bg-info navbar-inverse">
    <div class="container">
        <button class="navbar-toggler" data-toggle="collapse" data-target="#mainMenu">
            <span class="navbar-toggler-icon"></span>
            </button>
        <div class="collapse navbar-collapse" id="mainMenu">
            <div class="navbar-nav ml-auto " style="width:100%">
                <a class="nav-item nav-link active" href="#">Home</a>
                <a class="nav-item nav-link" href="#">About</a>
                <a class="nav-item nav-link" href="#">Training</a>
                <a class="nav-item nav-link" href="#">Contact</a>
            </div>
        </div>
    </div>
</nav>

Remove non-ASCII characters from CSV

A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>

-i says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it like this:

angular.element('#modal').modal('hide');

Execute Insert command and return inserted Id in Sql

USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL 
    DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL 
    DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT 
AS
BEGIN
   INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition

SELECT id FROM t6;
--IDs empty.

SELECT id FROM t7;
--ID is empty.

--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/

SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the 
INSERT statement two statements before this query.*/

SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/

SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/

-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action 
up to this point in this session.*/

SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action 
up to this point in this scope in this session.*/

SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/

pandas: multiple conditions while indexing data frame - unexpected behavior

As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.

That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1:

df1 = df[(df.a != -1) & (df.b != -1)]

You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1.

For df2:

df2 = df[(df.a != -1) | (df.b != -1)]

You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1.

PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc.

How to call a method after a delay in Android

Kotlin

    Handler(Looper.getMainLooper()).postDelayed({
      //Do something after 100ms
    }, 100)

Java

    final Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms
      }
    }, 100);

How to find which git branch I am on when my disk is mounted on other server

Our git repo disk is mounted on AIX box to do BUILD.

It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.

The build server should have its own copy of the git repository, and it will be locally managed by git on the build server. The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull to update the local repository on the build server.

If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.

Run/install/debug Android applications over Wi-Fi?

first you shold connect your device with usb to pc after that run cmd and drag and drop adb.exe that is in sdk/platform-tools path and write below code :

    ....\Sdk\platform-tools\adb.exe devices

    .....\Sdk\platform-tools\adb.exe tcpip 5555

    .....\Sdk\platform-tools\adb.exe connect Ip address:5555

How to create a custom scrollbar on a div (Facebook style)

If you're looking for a Facebook like scroll bar, then I'd highly recommend you take a look at this one:

http://rocha.la/jQuery-slimScroll

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

use maven dependency

<dependency> 
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-io</artifactId> 
  <version>1.3.2</version> 
</dependency> 

or download commons-io.1.3.2.jar to your lib folder

How to get the top position of an element?

$("#myTable").offset().top;

This will give you the computed offset (relative to document) of any object.

How to stop an animation (cancel() does not work)

If you are using the animation listener, set v.setAnimationListener(null). Use the following code with all options.

v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);

How to generate random number in Bash?

Random number between 0 and 9 inclusive.

echo $((RANDOM%10))

How to add parameters to an external data query in Excel which can't be displayed graphically?

Excel's interface for SQL Server queries will not let you have a custom parameters.  A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties.  Here are the detailed steps for Excel 2010:

  1. Open Excel
  2. Goto Data tab
  3. From the From Other Sources button choose From Microsoft Query
  4. The "Choose Data Source" window will appear.  Choose a datasource and click OK.
  5. The Query Qizard
    1. Choose Column: window will appear.  The goal is to create a generic query. I recommend choosing one column from a small table.
    2. Filter Data: Just click Next
    3. Sort Order: Just click Next
    4. Finish: Just click Finish.
  6. The "Import Data" window will appear:
    1. Click the Properties... button.
      1. Choose the Definition tab
      2. In the "Command text:" section add a WHERE clause that includes Excel parameters.  It's important to add all the parameters that you want now.  For example, if I want two parameters I could add this:
        WHERE 1 = ? and 2 = ?
      3. Click OK to get back to the "Import Data" window
    2. Choose PivotTable Report
    3. Click OK
  7. You will be prompted to enter the parameters value for each parameter.
  8. Once you have enter the parameters you will be at your pivot table
  9. Go batck to the Data tab and click the connections Properties button
    1. Click the Definition tab
    2. In the "Command text:" section, Paste in the real SQL Query that you want with the same number of parameters that you defined earlier.
    3. Click the Parameters... button 
      1. enter the Prompt values for each parameter
      2. Click OK
    4. Click OK to close the properties window
  10. Congratulations, you now have parameters.

Setting unique Constraint with fluent API?

Here is an extension method for setting unique indexes more fluently:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

Will generate migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

Src: Creating Unique Index with Entity Framework 6.1 fluent API

Trust Store vs Key Store - creating with keytool

There is no difference between keystore and truststore files. Both are files in the proprietary JKS file format. The distinction is in the use: To the best of my knowledge, Java will only use the store that is referenced by the -Djavax.net.ssl.trustStore system property to look for certificates to trust when creating SSL connections. Same for keys and -Djavax.net.ssl.keyStore. But in theory it's fine to use one and the same file for trust- and keystores.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

These errors occur whenever we are using a variable that is not set.

The best way to deal with these is set error reporting on while development.

To set error reporting on:

ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);

On production servers, error reporting is off, therefore, we do not get these errors.

On the development server, however, we can set error reporting on.

To get rid of this error, we see the following example:

if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

We can initialize the variables to NULL before assigning their values or using them.

So, we can modify the code as:

$test = NULL;
if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

This will not disturb any program logic and will not produce Notice even if $test does not have value.

So, basically, its always better to set error reporting ON for development.

And fix all the errors.

And on production, error reporting should be set to off.

Check whether $_POST-value is empty

To check if the property is present, irrespective of the value, use:

if (array_key_exists('userName', $_POST)) {}

To check if the property is set (property is present and value is not null or false), use:

if (isset($_POST['userName'])) {}

To check if the property is set and not empty (not an empty string, 0 (integer), 0.0 (float), '0' (string), null, false or [] (empty array)), use:

if (!empty($_POST['userName'])) {}

Convert List<Object> to String[] in Java

If we are very sure that List<Object> will contain collection of String, then probably try this.

List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));

Display last git commit comment

git log -1 branch_name will show you the last message from the specified branch (i.e. not necessarily the branch you're currently on).

HTML Table cellspacing or padding just top / bottom

CSS?

td {
  padding-top: 2px;
  padding-bottom: 2px;
}

PHP compare two arrays and get the matched values not the difference

OK.. We needed to compare a dynamic number of product names...

There's probably a better way... but this works for me...

... because....Strings are just Arrays of characters.... :>}

//  Compare Strings ...  Return Matching Text and Differences with Product IDs...

//  From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";   

$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";   

$ProductNames = array(
    $productID1 => $productName1,
    $productID2 => $productName2
);


function compareNames($ProductNames){   

    //  Convert NameStrings to Arrays...    
    foreach($ProductNames as $id => $product_name){
        $Package1[$id] = explode(" ",$product_name);    
    }

    // Get Matching Text...
    $Matching = call_user_func_array('array_intersect', $Package1 );
    $MatchingText = implode(" ",$Matching);

    //  Get Different Text...
    foreach($Package1 as $id => $product_name_chunks){
        $Package2 = array($product_name_chunks,$Matching);
        $diff = call_user_func_array('array_diff', $Package2 );
        $DifferentText[$id] = trim(implode(" ", $diff));
    }

    $results[$MatchingText]  = $DifferentText;              
    return $results;    
}

$Results =  compareNames($ProductNames);

print_r($Results);

// Gives us this...
[EcoPlus Premio Jet] 
        [abc123] => 600
        [xyz789] => 800

How can I copy columns from one sheet to another with VBA in Excel?

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim rng As Range, r As Range
  Set rng = Intersect(Target, Range("a2:a" & Rows.Count))
  If rng Is Nothing Then Exit Sub
    For Each r In rng
      If Not IsEmpty(r.Value) Then
        r.Copy Destination:=Sheets("sheet2").Range("a2")
      End If
    Next
  Set rng = Nothing
End Sub

GoogleTest: How to skip a test?

The docs for Google Test 1.7 suggest:

"If you have a broken test that you cannot fix right away, you can add the DISABLED_ prefix to its name. This will exclude it from execution."

Examples:

// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { ... }

class DISABLED_BarTest : public ::testing::Test { ... };

// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { ... }

Neither BindingResult nor plain target object for bean name available as request attribute

the first time when you are returning your form make sure you pass the model attribute the form requires which can be done by adding the below code

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Login login)
    return "test";
}

By default the model attribute name is taken as Bean class's name with first lowercase letter

By doing this the form which expects a backing object naming "login" will be made available to it

after the form is submitted you can do the validation by passing your bean object and bindingresult as the method parameters as shown below

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(    @ModelAttribute("login") Login login,
                        BindingResult result) 

MySQL user DB does not have password columns - Installing MySQL on OSX

One pitfall I fell into is there is no password field now, it has been renamed so:

update user set password=PASSWORD("YOURPASSWORDHERE") where user='root';

Should now be:

update user set authentication_string=password('YOURPASSWORDHERE') where user='root';

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

How to select all instances of selected region in Sublime Text

Even though there are multiple answers, there is an issue using this approach. It selects all the text that matches, not only the whole words like variables.

As per "Sublime Text: Select all instances of a variable and edit variable name" and the answer in "Sublime Text: Select all instances of a variable and edit variable name", we have to start with a empty selection. That is, start using the shortcut Alt+F3 which would help selecting only the whole words.

How to get the current time in Python

Do

from time import time

t = time()
  • t - float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.

How to remove all of the data in a table using Django

Using shell,

1) For Deleting the table:

python manage.py dbshell
>> DROP TABLE {app_name}_{model_name}

2) For removing all data from table:

python manage.py shell
>> from {app_name}.models import {model_name}
>> {model_name}.objects.all().delete()

Parsing JSON in Excel VBA

To parse JSON in VBA without adding a huge library to your workbook project, I created the following solution. It's extremely fast and stores all of the keys and values in a dictionary for easy access:

Function ParseJSON(json$, Optional key$ = "obj") As Object
    p = 1
    token = Tokenize(json)
    Set dic = CreateObject("Scripting.Dictionary")
    If token(p) = "{" Then ParseObj key Else ParseArr key
    Set ParseJSON = dic
End Function

Function ParseObj(key$)
    Do: p = p + 1
        Select Case token(p)
            Case "]"
            Case "[":  ParseArr key
            Case "{"
                       If token(p + 1) = "}" Then
                           p = p + 1
                           dic.Add key, "null"
                       Else
                           ParseObj key
                       End If
            
            Case "}":  key = ReducePath(key): Exit Do
            Case ":":  key = key & "." & token(p - 1)
            Case ",":  key = ReducePath(key)
            Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
        End Select
    Loop
End Function

Function ParseArr(key$)
    Dim e&
    Do: p = p + 1
        Select Case token(p)
            Case "}"
            Case "{":  ParseObj key & ArrayID(e)
            Case "[":  ParseArr key
            Case "]":  Exit Do
            Case ":":  key = key & ArrayID(e)
            Case ",":  e = e + 1
            Case Else: dic.Add key & ArrayID(e), token(p)
        End Select
    Loop
End Function

The code above does use a few helper functions, but the above is the meat of it.

The strategy used here is to employ a recursive tokenizer. I found it interesting enough to write an article about this solution on Medium. It explains the details.

Here is the full (yet surprisingly short) code listing, including all of the helper functions:

'-------------------------------------------------------------------
' VBA JSON Parser
'-------------------------------------------------------------------
Option Explicit
Private p&, token, dic
Function ParseJSON(json$, Optional key$ = "obj") As Object
    p = 1
    token = Tokenize(json)
    Set dic = CreateObject("Scripting.Dictionary")
    If token(p) = "{" Then ParseObj key Else ParseArr key
    Set ParseJSON = dic
End Function
Function ParseObj(key$)
    Do: p = p + 1
        Select Case token(p)
            Case "]"
            Case "[":  ParseArr key
            Case "{"
                       If token(p + 1) = "}" Then
                           p = p + 1
                           dic.Add key, "null"
                       Else
                           ParseObj key
                       End If
            
            Case "}":  key = ReducePath(key): Exit Do
            Case ":":  key = key & "." & token(p - 1)
            Case ",":  key = ReducePath(key)
            Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
        End Select
    Loop
End Function
Function ParseArr(key$)
    Dim e&
    Do: p = p + 1
        Select Case token(p)
            Case "}"
            Case "{":  ParseObj key & ArrayID(e)
            Case "[":  ParseArr key
            Case "]":  Exit Do
            Case ":":  key = key & ArrayID(e)
            Case ",":  e = e + 1
            Case Else: dic.Add key & ArrayID(e), token(p)
        End Select
    Loop
End Function
'-------------------------------------------------------------------
' Support Functions
'-------------------------------------------------------------------
Function Tokenize(s$)
    Const Pattern = """(([^""\\]|\\.)*)""|[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|\w+|[^\s""']+?"
    Tokenize = RExtract(s, Pattern, True)
End Function
Function RExtract(s$, Pattern, Optional bGroup1Bias As Boolean, Optional bGlobal As Boolean = True)
  Dim c&, m, n, v
  With CreateObject("vbscript.regexp")
    .Global = bGlobal
    .MultiLine = False
    .IgnoreCase = True
    .Pattern = Pattern
    If .TEST(s) Then
      Set m = .Execute(s)
      ReDim v(1 To m.Count)
      For Each n In m
        c = c + 1
        v(c) = n.value
        If bGroup1Bias Then If Len(n.submatches(0)) Or n.value = """""" Then v(c) = n.submatches(0)
      Next
    End If
  End With
  RExtract = v
End Function
Function ArrayID$(e)
    ArrayID = "(" & e & ")"
End Function
Function ReducePath$(key$)
    If InStr(key, ".") Then ReducePath = Left(key, InStrRev(key, ".") - 1)
End Function
Function ListPaths(dic)
    Dim s$, v
    For Each v In dic
        s = s & v & " --> " & dic(v) & vbLf
    Next
    Debug.Print s
End Function
Function GetFilteredValues(dic, match)
    Dim c&, i&, v, w
    v = dic.keys
    ReDim w(1 To dic.Count)
    For i = 0 To UBound(v)
        If v(i) Like match Then
            c = c + 1
            w(c) = dic(v(i))
        End If
    Next
    ReDim Preserve w(1 To c)
    GetFilteredValues = w
End Function
Function GetFilteredTable(dic, cols)
    Dim c&, i&, j&, v, w, z
    v = dic.keys
    z = GetFilteredValues(dic, cols(0))
    ReDim w(1 To UBound(z), 1 To UBound(cols) + 1)
    For j = 1 To UBound(cols) + 1
         z = GetFilteredValues(dic, cols(j - 1))
         For i = 1 To UBound(z)
            w(i, j) = z(i)
         Next
    Next
    GetFilteredTable = w
End Function
Function OpenTextFile$(f)
    With CreateObject("ADODB.Stream")
        .Charset = "utf-8"
        .Open
        .LoadFromFile f
        OpenTextFile = .ReadText
    End With
End Function

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

XSLT - How to select XML Attribute by Attribute?

Just remove the slash after Data and prepend the root:

<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>

How to open child forms positioned within MDI parent in VB.NET?

See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx

I was able to implement the Child form inside the parent.

In the Example below Form2 should change to the name of your child form. NewMDIChild.MdiParent=me is the main form since the control that opens (shows) the child form is the parent or Me.

NewMDIChild.Show() is your child form since you associated your child form with Dim NewMDIChild As New Form2()

Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
   Dim NewMDIChild As New Form2()
   'Set the Parent Form of the Child window.
   NewMDIChild.MdiParent = Me
   'Display the new form.
   NewMDIChild.Show()
End Sub

Simple and it works.

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

remote rejected master -> master (pre-receive hook declined)

If you run $ heroku logs you may get a "hint" to what the problem is. For me, Heroku could not detect what type of app I was creating. It required me to set the buildpack. Since I was creating a Node.js app, I just had to run $ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs. You can read more about it here: https://devcenter.heroku.com/articles/buildpacks. No pushing issues after that.

I know this is an old question, but still posting this here incase someone else gets stuck.

How to build jars from IntelliJ properly?

enter image description here

As the people above says, but I have to note one point. You have to check the checkbox:

Include in project build

How do I give text or an image a transparent background using CSS?

If you are a Photoshop guy, you can also use:

 #some-element {
  background-color: hsla(170, 50%, 45%, 0.9); // **0.9 is the opacity range from 0 - 1**
 }

Or:

#some-element {
  background-color: rgba(170, 190, 45, 0.9); // **0.9 is the opacity range from 0 - 1**
}

how to prevent css inherit

The short story is that it's not possible to do what you want here. There's no CSS rule which is to "ignore some other rule". The only way around it is to write a more-specific CSS rule for the inner elements which reverts it to how it was before, which is a pain in the butt.

Take the example below:

<div class="red"> <!-- ignore the semantics, it's an example, yo! -->
    <p class="blue">
        Blue text blue text!
        <span class="notBlue">this shouldn't be blue</span>
    </p>
</div>
<div class="green">
    <p class="blue">
        Blue text!
        <span class="notBlue">blah</span>
    </p>
</div>

There's no way to make the .notBlue class revert to the parent styling. The best you can do is this:

.red, .red .notBlue {
    color: red;
}
.green, .green .notBlue {
    color: green;
}

How to pass variable number of arguments to printf/sprintf

I should have read more on existing questions in stack overflow.

C++ Passing Variable Number of Arguments is a similar question. Mike F has the following explanation:

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

This is exactly what I was looking for. I performed a test implementation like this:

void Error(const char* format, ...)
{
    char dest[1024 * 16];
    va_list argptr;
    va_start(argptr, format);
    vsprintf(dest, format, argptr);
    va_end(argptr);
    printf(dest);
}

Android and Facebook share intent

Here is what I did (for text). In the code, I copy whatever text is needed to clipboard. The first time an individual tries to use the share intent button, I pop up a notification that explains if they wish to share to facebook, they need to click 'Facebook' and then long press to paste (this is to make them aware that Facebook has BROKEN the android intent system). Then the relevant information is in the field. I might also include a link to this post so users can complain too...

private void setClipboardText(String text) { // TODO
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(text);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
        android.content.ClipData clip = android.content.ClipData.newPlainText("text label",text);
        clipboard.setPrimaryClip(clip);
    }
}

Below is a method for dealing w/prior versions

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_item_share:
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "text here");

        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); //TODO
         ClipData clip = ClipData.newPlainText("label", "text here");
         clipboard.setPrimaryClip(clip);

        setShareIntent(shareIntent); 

        break;
    }
        return super.onOptionsItemSelected(item);
}

Clear and reset form input fields

Why not use HTML-controlled items such as <input type="reset">

Can't install any package with node npm

There is a possibility that your package.json is causing this.

Parse your package.json to find the unexpected token

or

Delete your package.json file and create one through

npm install 

jQuery Force set src attribute for iframe

You cannot set FIX iframe's src or prevent javascript/form submit to change its location. However you can put script to onload of the page and change action of each dynamic link.

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

Jquery get form field value

You can get any input field value by $('input[fieldAttribute=value]').val()

here is an example

_x000D_
_x000D_
displayValue = () => {_x000D_
_x000D_
  // you can get the value by name attribute like this_x000D_
  _x000D_
  console.log('value of firstname : ' + $('input[name=firstName]').val());_x000D_
  _x000D_
  // if there is the id as lastname_x000D_
  _x000D_
  console.log('value of lastname by id : ' + $('#lastName').val());_x000D_
  _x000D_
  // get value of carType from placeholder  _x000D_
  console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());_x000D_
_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="formdiv">_x000D_
    <form name="inpForm">_x000D_
        <input type="text" name="firstName" placeholder='first name'/>_x000D_
        <input type="text" name="lastName" id='lastName' placeholder='last name'/>_x000D_
        _x000D_
        <input type="text" placeholder="carType" />_x000D_
        <input type="button" value="display value" onclick='displayValue()'/>_x000D_
        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert Set<String> to String[]?

In Java 11 we can use Collection.toArray(generator) method. The following code will create a new array of String:

Set<String> set = Set.of("one", "two", "three");
String[] array = set.toArray(String[]::new)

See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)

Having links relative to root?

Use

<a href="/fruits/index.html">Back to Fruits List</a>

or

<a href="../index.html">Back to Fruits List</a>

gpg decryption fails with no secret key error

I have solved this problem, try to use root privileges, such as sudo gpg ... I think that gpg elevated without permissions does not refer to file permissions, but system

Use of True, False, and None as return values in Python functions

One thing to ensure is that nothing can reassign your variable. If it is not a Boolean in the end, relying on truthiness will lead to bugs. The beauty of conditional programming in dynamically typed languages :).

The following prints "no".

x = False
if x:
    print 'yes'
else:
    print 'no'

Now let's change x.

x = 'False'

Now the statement prints "yes", because the string is truthy.

if x:
    print 'yes'
else:
    print 'no'

This statement, however, correctly outputs "no".

if x == True:
    print 'yes'
else:
    print 'no'

How do you fix a bad merge, and replay your good commits onto a fixed merge?

The simplest way I found was suggested by leontalbot (as a comment), which is a post published by Anoopjohn. I think its worth its own space as an answer:

(I converted it to a bash script)

#!/bin/bash
if [[ $1 == "" ]]; then
    echo "Usage: $0 FILE_OR_DIR [remote]";
    echo "FILE_OR_DIR: the file or directory you want to remove from history"
    echo "if 'remote' argument is set, it will also push to remote repository."
    exit;
fi
FOLDERNAME_OR_FILENAME=$1;

#The important part starts here: ------------------------

git filter-branch -f --index-filter "git rm -rf --cached --ignore-unmatch $FOLDERNAME_OR_FILENAME" -- --all
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now

if [[ $2 == "remote" ]]; then
    git push --all --force
fi
echo "Done."

All credits goes to Annopjohn, and to leontalbot for pointing it out.

NOTE

Be aware that the script doesn't include validations, so be sure you don't make mistakes and that you have a backup in case something goes wrong. It worked for me, but it may not work in your situation. USE IT WITH CAUTION (follow the link if you want to know what is going on).

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

On windows be sure the console is started as aministrator

Convert Uri to String and String to Uri

Try this to convert string to uri

String mystring="Hello"
Uri myUri = Uri.parse(mystring);

Uri to String

Uri uri;
String uri_to_string;
uri_to_string= uri.toString();

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

Giving my function access to outside variable

The one and probably not so good way of achieving your goal would using global variables.

You could achieve that by adding global $myArr; to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.

The much better way would be passing your array as an argument to your function:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);

No visible cause for "Unexpected token ILLEGAL"

Here is my reason:

before:

var path = "D:\xxx\util.s"

which \u is a escape, I figured it out by using Codepen's analyze JS.

after:

var path = "D:\\xxx\\util.s"

and the error fixed

ImportError: No module named 'django.core.urlresolvers'

To solve this either you down-grade the Django to any version lesser than 2.0. pip install Django==1.11.29.

Inserting a PDF file in LaTeX

The \includegraphics function has a page option for inserting a specific page of a PDF file as graphs. The default is one, but you can change it.

\includegraphics[scale=0.75,page=2]{multipage.pdf}

You can find more here.

How to set the timezone in Django?

Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems. The values are strings (xsd:string) in the form “Area/Location,” in which:

Area is a continent or ocean name. Area currently includes:

  • Africa
  • America (both North America and South America)
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Etc (administrative zone. For example, “Etc/UTC” represents Coordinated Universal Time.)
  • Indian
  • Pacific

Location is the city, island, or other regional name.

The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected. For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).

Here is a list all valid timezones

You can change time zone in your settings.py as follows

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Can I add color to bootstrap icons only using CSS?

It is actually very easy:

just use:

.icon-name{
color: #0C0;}

For example:

.icon-compass{
color: #C30;}

That's it.

Preloading images with JavaScript

This approach is a little more elaborate. Here you store all preloaded images in a container, may be a div. And after you could show the images or move it within the DOM to the correct position.

function preloadImg(containerId, imgUrl, imageId) {
    var i = document.createElement('img'); // or new Image()
    i.id = imageId;
    i.onload = function() {
         var container = document.getElementById(containerId);
         container.appendChild(this);
    };
    i.src = imgUrl;
}

Try it here, I have also added few comments

Can you delete multiple branches in one command with Git?

For pure souls who use PowerShell here the small script git branch -d $(git branch --list '3.2.*' | %{$_.Trim() })

How can I print literal curly-brace characters in a string and also use .format on it?

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

Here's the relevant part of the Python documentation for format string syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

CSV file written with Python has blank lines between each row

I'm writing this answer w.r.t. to python 3, as I've initially got the same problem.

I was supposed to get data from arduino using PySerial, and write them in a .csv file. Each reading in my case ended with '\r\n', so newline was always separating each line.

In my case, newline='' option didn't work. Because it showed some error like :

with open('op.csv', 'a',newline=' ') as csv_file:

ValueError: illegal newline value: ''

So it seemed that they don't accept omission of newline here.

Seeing one of the answers here only, I mentioned line terminator in the writer object, like,

writer = csv.writer(csv_file, delimiter=' ',lineterminator='\r')

and that worked for me for skipping the extra newlines.

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

How can I create a simple index.html file which lists all files/directories?

There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess The source code is easy to understand and provides a good starting point.

Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/

celeron dude indexer

source of historical stock data

Let me add a source I just discovered, found here.

It has lots of historical stock data in csv format and was gathered by Andy Pavlo, who according to his homepage is an "Assistant Professor in the Computer Science Department at Carnegie Mellon University".

Get width height of remote image from url

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

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

For Java:

Quantifiers documentation

X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}

Using 'starts with' selector on individual class names

this is for prefix with

$("div[class^='apple-']")

this is for starts with so you dont need to have the '-' char in there

$("div[class|='apple']")

you can find a bunch of other cool variations of the jQuery selector here https://api.jquery.com/category/selectors/

How do I reload a page without a POSTDATA warning in Javascript?

Here's a solution that should always work and doesn't remove the hash.

let currentPage = new URL(window.location.href);
currentPage.searchParams.set('r', (+new Date * Math.random()).toString(36).substring(0, 5));
window.location.href = currentPage.href;

Why use #define instead of a variable

C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.

Virtual Serial Port for Linux

You may want to look at Tibbo VSPDL for creating a linux virtual serial port using a Kernel driver -- it seems pretty new, and is available for download right now (beta version). Not sure about the license at this point, or whether they want to make it available commercially only in the future.

There are other commercial alternatives, such as http://www.ttyredirector.com/.

In Open Source, Remserial (GPL) may also do what you want, using Unix PTY's. It transmits the serial data in "raw form" to a network socket; STTY-like setup of terminal parameters must be done when creating the port, changing them later like described in RFC 2217 does not seem to be supported. You should be able to run two remserial instances to create a virtual nullmodem like com0com, except that you'll need to set up port speed etc in advance.

Socat (also GPL) is like an extended variant of Remserial with many many more options, including a "PTY" method for redirecting the PTY to something else, which can be another instance of Socat. For Unit tets, socat is likely nicer than remserial because you can directly cat files into the PTY. See the PTY example on the manpage. A patch exists under "contrib" to provide RFC2217 support for negotiating serial line settings.

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

Storing Form Data as a Session Variable

That's perfectly fine and will work. But to use sessions you have to put session_start(); on the first line of the php code. So basically

<?php
session_start();

//rest of stuff

?>

Writing sqlplus output to a file

Also note that the SPOOL output is driven by a few SQLPlus settings:

  • SET LINESIZE nn - maximum line width; if the output is longer it will wrap to display the contents of each result row.

  • SET TRIMSPOOL OFF|ON - if set OFF (the default), every output line will be padded to LINESIZE. If set ON, every output line will be trimmed.

  • SET PAGESIZE nn - number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.

Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

Try doing a FLUSH PRIVILEGES;. This MySQL bug post on that error code appears to report some success in a case similar to yours after flushing privs. 

ORA-01438: value larger than specified precision allows for this column

One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g

How to insert data into SQL Server

I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

Numpy: Checking if a value is NaT

Another way would be to catch the exeption:

def is_nat(npdatetime):
    try:
        npdatetime.strftime('%x')
        return False
    except:
        return True

Writing List of Strings to Excel CSV File in Python

A sample - write multiple rows with boolean column (using example above by GaretJax and Eran?).

import csv
RESULT = [['IsBerry','FruitName'],
          [False,'apple'],
          [True, 'cherry'],
          [False,'orange'],
          [False,'pineapple'],
          [True, 'strawberry']]
with open("../datasets/dashdb.csv", 'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(RESULT)

Result:

df_data_4 = pd.read_csv('../datasets/dashdb.csv')
df_data_4.head()

Output:

   IsBerry  FruitName
   0    False   apple
   1    True    cherry
   2    False   orange
   3    False   pineapple
   4    True    strawberry

SQL Server Script to create a new user

Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.

Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:

CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO

Here is how you create a User with db_owner privileges using the Login you just declared:

Use YourDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
    CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
    EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO

Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).

However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.

UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.

Using GregorianCalendar with SimpleDateFormat

Why such complications?

public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException 
{
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = fmt.parse(dd_mm_yy);
    GregorianCalendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    return cal;
}

The VMware Authorization Service is not running

I've also had this problem recently.

The solution that worked for me was to uninstall vmware, restart windows, and the reinstall vmware.

Upgrade Node.js to the latest version on Mac OS

I use Node version manager (called n) for it.

npm install -g n

then

n latest

OR

n stable

jQuery AJAX form data serialize using PHP

Try this

 $(document).ready(function(){
    var form=$("#myForm");
    $("#smt").click(function(){
    $.ajax({
            type:"POST",
            url:form.attr("action"),
            data:$("#myForm input").serialize(),//only input
            success: function(response){
                console.log(response);  
            }
        });
    });
    });

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

Sort Java Collection

You can use java Custom Class for the purpose of sorting.

RegEx to extract all matches from string using RegExp.exec

We are finally beginning to see a built-in matchAll function, see here for the description and compatibility table. It looks like as of May 2020, Chrome, Edge, Firefox, and Node.js (12+) are supported but not IE, Safari, and Opera. Seems like it was drafted in December 2018 so give it some time to reach all browsers, but I trust it will get there.

The built-in matchAll function is nice because it returns an iterable. It also returns capturing groups for every match! So you can do things like

// get the letters before and after "o"
let matches = "stackoverflow".matchAll(/(\w)o(\w)/g);

for (match of matches) {
    console.log("letter before:" + match[1]);
    console.log("letter after:" + match[2]);
}

arrayOfAllMatches = [...matches]; // you can also turn the iterable into an array

It also seem like every match object uses the same format as match(). So each object is an array of the match and capturing groups, along with three additional properties index, input, and groups. So it looks like:

[<match>, <group1>, <group2>, ..., index: <match offset>, input: <original string>, groups: <named capture groups>]

For more information about matchAll there is also a Google developers page. There are also polyfills/shims available.

How to format a floating number to fixed width in Python

It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings:

numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print(f'{number:9.4f}')

Prints:

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000

How to install APK from PC?

  1. Connect Android device to PC via USB cable and turn on USB storage.
  2. Copy .apk file to attached device's storage.
  3. Turn off USB storage and disconnect it from PC.
  4. Check the option Settings ? Applications ? Unknown sources OR Settings > Security > Unknown Sources.
  5. Open FileManager app and click on the copied .apk file. If you can't fine the apk file try searching or allowing hidden files. It will ask you whether to install this app or not. Click Yes or OK.

This procedure works even if ADB is not available.

How do I get the path of a process in Unix / Linux

In Linux every process has its own folder in /proc. So you could use getpid() to get the pid of the running process and then join it with the path /proc to get the folder you hopefully need.

Here's a short example in Python:

import os
print os.path.join('/proc', str(os.getpid()))

Here's the example in ANSI C as well:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


int
main(int argc, char **argv)
{
    pid_t pid = getpid();

    fprintf(stdout, "Path to current process: '/proc/%d/'\n", (int)pid);

    return EXIT_SUCCESS;
}

Compile it with:

gcc -Wall -Werror -g -ansi -pedantic process_path.c -oprocess_path 

Can't bind to 'formGroup' since it isn't a known property of 'form'

RC5 FIX

You need to import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms' in your controller and add it to directives in @Component. That will fix the problem.

After you fix that, you will probably get another error because you didn't add formControlName="name" to your input in form.

RC6/RC7/Final release FIX

To fix this error, you just need to import ReactiveFormsModule from @angular/forms in your module. Here's the example of a basic module with ReactiveFormsModule import:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

To explain further, formGroup is a selector for directive named FormGroupDirective that is a part of ReactiveFormsModule, hence the need to import it. It is used to bind an existing FormGroup to a DOM element. You can read more about it on Angular's official docs page.

Android : Capturing HTTP Requests with non-rooted android device

I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above

https://play.google.com/store/apps/details?id=org.sandroproxy.drony

It intercepts the requests and are shown on a LOG

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

How can I make a CSS glass/blur effect work for an overlay?

Here's a solution that works with fixed backgrounds, if you have a fixed background and you have some overlayed elements and you need blured backgrounds for them, this solution works:

Image we have this simple HTML:

<body> <!-- or any wrapper -->
   <div class="content">Some Texts</div>
</body>

A fixed background for <body> or the wrapper element:

body {
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

And here for example we have a overlayed element with a white transparent background:

.content {
  background-color: rgba(255, 255, 255, 0.3);
  position: relative;
}

Now we need to use the exact same background image of our wrapper for our overlay elements too, i use it as a :before psuedo-class:

.content:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: blur(5px);
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

Since the fixed background works in a same way in both wrapper and overlayed elements, we have the background in exactly same scroll position of the overlayed element and we can simply blur it. Here's a working fiddle, tested in Firefox, Chrome, Opera and Edge: https://jsfiddle.net/0vL2rc4d/

NOTE: In firefox there's a bug that makes screen flicker when scrolling and there are fixed blurred backgrounds. if there's any fix, let me know

Forcing a postback

Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo - just in case the website goes offline. Worked well for me.

StringBuilder sbScript = new StringBuilder();

sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");

this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());

Run class in Jar file

You want:

java -cp myJar.jar myClass

The Documentation gives the following example:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Passing an array by reference in C?

In plain C you can use a pointer/size combination in your API.

void doSomething(MyStruct* mystruct, size_t numElements)
{
    for (size_t i = 0; i < numElements; ++i)
    {
        MyStruct current = mystruct[i];
        handleElement(current);
    }
}

Using pointers is the closest to call-by-reference available in C.

How do I install Maven with Yum?

Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type

sudo dnf install maven

Now test the installation, just run maven in a random directory

mvn

And it will fail, because you did not specify a goal, e.g. mvn package

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.102 s
[INFO] Finished at: 2017-11-14T13:45:00+01:00
[INFO] Final Memory: 8M/176M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build

[...]

SSH to Elastic Beanstalk instance

If you are using elastic bean and EB CLI, just use eb ssh to login to instance. You can use options as specified in the following link http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-ssh.html

AngularJS - Find Element with attribute

Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.

The way is that the child directive can require the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:

<div parent-directive>
  <div child-directive></div>
  <div child-directive></div>
</div>

Then the directives can be coded like:

app.directive('parentDirective', function($window) {
  return {
    controller: function($scope) {
      var registeredElements = [];
      this.registerElement = function(childElement) {
        registeredElements.push(childElement);
      }
    }
  };
});

app.directive('childDirective', function() {
  return {
    require: '^parentDirective',
    template: '<span>Child directive</span>',
    link: function link(scope, iElement, iAttrs, parentController) {
      parentController.registerElement(iElement);
    }
   };
});

You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview

Importing Excel files into R, xlsx or xls

I would definitely try the read.xls function in the gdata package, which is considerably more mature than the xlsx package. It may require Perl ...

Visual Studio breakpoints not being hit

If anyone is using Visual Studio 2017 and IIS and is trying to debug a web site project, the following worked for me:

  1. Attach the web site project to IIS.
  2. Add it to the solution with File -> Add -> Existing Web Site... and select the project from the inetpub/wwwroot directory.
  3. Right-click on the web site project in the solution explorer and select Property Pages -> Start Options
  4. Click on Specific Page and select the startup page (For service use Service.svc, for web site use Default.aspx or the custom name for the page you selected).
  5. Click on Use custom server and write

http(s)://localhost/(web site name as appears in IIS)

for example: http://localhost/MyWebSite

That's it! Don't forget to make sure the web site is running on the IIS and that the web site you wish to debug is selected as the startup project (Right-click -> Set as StartUp Project).

Original post: How to Debug Your ASP.NET Projects Running Under IIS

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

How to remove the focus from a TextBox in WinForms?

I made this on my custom control, i done this onFocus()

this.Parent.Focus();

So if texbox focused - it instantly focus textbox parent (form, or panel...) This is good option if you want to make this on custom control.

How to change Vagrant 'default' machine name?

This is the way I've assigned names to individual VMs. Change YOURNAMEHERE to your desired name.

Contents of Vagrantfile:

Vagrant.configure("2") do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "precise32"

  # The url from where the 'config.vm.box' box will be fetched if it
  # doesn't already exist on the user's system.
  config.vm.box_url = "http://files.vagrantup.com/precise32.box"

  config.vm.define :YOURNAMEHERE do |t|
  end

end

Terminal output:

$ vagrant status
Current machine states:

YOURNAMEHERE             not created (virtualbox)

How to determine whether a substring is in a different string

with in: substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True

How to activate an Anaconda environment

If this happens you would need to set the PATH for your environment (so that it gets the right Python from the environment and Scripts\ on Windows).

Imagine you have created an environment called py33 by using:

conda create -n py33 python=3.3 anaconda

Here the folders are created by default in Anaconda\envs, so you need to set the PATH as:

set PATH=C:\Anaconda\envs\py33\Scripts;C:\Anaconda\envs\py33;%PATH%

Now it should work in the command window:

activate py33

The line above is the Windows equivalent to the code that normally appears in the tutorials for Mac and Linux:

$ source activate py33

More info: https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/8T8i11gO39U

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Strangest language feature

Don't know if it is a feature or not. For some, yes, but for others it might be an annoying behavior. Anyway, I think it's worth mentioning.

In Python, the builtin function round() behaves a bit differently between Python 2x and Python 3x.

For Py 2x,

>>> round(0.4)
0.0
>>> round(0.5)
1.0
>>> round(0.51)
1.0
>>> round(1.5)
2.0

For Py 3x,

>>> round(0.4)
0
>>> round(0.5)
0
>>> round(0.51)
1
>>> round(1.5)
2

I'm just not familiar with the way round() in Py 3x works with 0.

Docs for round() in Py 2x and Py 3x.

Laravel form html with PUT method for PUT routes

You CAN add css clases, and any type of attributes you need to blade template, try this:

{{ Form::open(array('url' => '/', 'method' => 'PUT', 'class'=>'col-md-12')) }}
.... wathever code here
{{ Form::close() }}

If you dont want to go the blade way you can add a hidden input. This is the form Laravel does, any way:

Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form. (Laravel docs)

<form class="col-md-12" action="<?php echo URL::to('/');?>/post/<?=$post->postID?>" method="POST">

    <!-- Rendered blade HTML form use this hidden. Dont forget to put the form method to POST -->

    <input name="_method" type="hidden" value="PUT">

    <div class="form-group">
        <textarea type="text" class="form-control input-lg" placeholder="Text Here" name="post"><?=$post->post?></textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary btn-lg btn-block" type="submit" value="Edit">Edit</button>
    </div>
</form>

How to scroll UITableView to specific position

[tableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

This will take your tableview to the first row.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

How to tell which disk Windows Used to Boot

You type diskpart, list disk and check disks for boot.
Ex:

dispart 
list disk 
select disk 0 
detail disk

The disk with Boot volume is disk with windows installed:

enter image description here

Adding value labels on a matplotlib bar chart

If you only want to add Datapoints above the bars, you could easily do it with:

 for i in range(len(frequencies)): # your number of bars
    plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
    y = y_values[i]+1, #takes your y values as vertical positioning argument 
    s = data_labels[i], # the labels you want to add to the data
    size = 9) # font size of datalabels

See whether an item appears more than once in a database column

How about:

select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;

Switch with if, else if, else, and loops inside case

Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:

boolean found = false;

case 1:

for (Element arrayItem : array) {
    if (arrayItem == whateverValue) {
        found = true;    
    } // else if ...
}
if (found) {
    break;
}
case 2:

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

What is the difference between procedural programming and functional programming?

None of the answers here show idiomatic functional programming. The recursive factorial answer is great for representing recursion in FP, but the majority of code is not recursive so I don't think that answer is fully representative.

Say you have an arrays of strings, and each string represents an integer like "5" or "-200". You want to check this input array of strings against your internal test case (Using integer comparison). Both solutions are shown below

Procedural

arr_equal(a : [Int], b : [Str]) -> Bool {
    if(a.len != b.len) {
        return false;
    }

    bool ret = true;
    for( int i = 0; i < a.len /* Optimized with && ret*/; i++ ) {
        int a_int = a[i];
        int b_int = parseInt(b[i]);
        ret &= a_int == b_int;  
    }
    return ret;
}

Functional

eq = i, j => i == j # This is usually a built-in
toInt = i => parseInt(i) # Of course, parseInt === toInt here, but this is for visualization

arr_equal(a : [Int], b : [Str]) -> Bool =
    zip(a, b.map(toInt)) # Combines into [Int, Int]
   .map(eq)
   .reduce(true, (i, j) => i && j) # Start with true, and continuously && it with each value

While pure functional languages are generally research languages (As the real-world likes free side-effects), real-world procedural languages will use the much simpler functional syntax when appropriate.

This is usually implemented with an external library like Lodash, or available built-in with newer languages like Rust. The heavy lifting of functional programming is done with functions/concepts like map, filter, reduce, currying, partial, the last three of which you can look up for further understanding.

Addendum

In order to be used in the wild, the compiler will normally have to work out how to convert the functional version into the procedural version internally, as function call overhead is too high. Recursive cases such as the factorial shown will use tricks such as tail call to remove O(n) memory usage. The fact that there are no side effects allows functional compilers to implement the && ret optimization even when the .reduce is done last. Using Lodash in JS, obviously does not allow for any optimization, so it is a hit to performance (Which isn't usually a concern with web development). Languages like Rust will optimize internally (And have functions such as try_fold to assist && ret optimization).

How do you test a public/private DSA keypair?

I found a way that seems to work better for me:

ssh-keygen -y -f <private key file>

That command will output the public key for the given private key, so then just compare the output to each *.pub file.

Position absolute but relative to parent

div#father {
    position: relative;
}
div#son1 {
    position: absolute;
    /* put your coords here */
}
div#son2 {
    position: absolute;
    /* put your coords here */
}

What's the difference between [ and [[ in Bash?

[[ is bash's improvement to the [ command. It has several enhancements that make it a better choice if you write scripts that target bash. My favorites are:

  1. It is a syntactical feature of the shell, so it has some special behavior that [ doesn't have. You no longer have to quote variables like mad because [[ handles empty strings and strings with whitespace more intuitively. For example, with [ you have to write

    if [ -f "$file" ]
    

    to correctly handle empty strings or file names with spaces in them. With [[ the quotes are unnecessary:

    if [[ -f $file ]]
    
  2. Because it is a syntactical feature, it lets you use && and || operators for boolean tests and < and > for string comparisons. [ cannot do this because it is a regular command and &&, ||, <, and > are not passed to regular commands as command-line arguments.

  3. It has a wonderful =~ operator for doing regular expression matches. With [ you might write

    if [ "$answer" = y -o "$answer" = yes ]
    

    With [[ you can write this as

    if [[ $answer =~ ^y(es)?$ ]]
    

    It even lets you access the captured groups which it stores in BASH_REMATCH. For instance, ${BASH_REMATCH[1]} would be "es" if you typed a full "yes" above.

  4. You get pattern matching aka globbing for free. Maybe you're less strict about how to type yes. Maybe you're okay if the user types y-anything. Got you covered:

    if [[ $ANSWER = y* ]]
    

Keep in mind that it is a bash extension, so if you are writing sh-compatible scripts then you need to stick with [. Make sure you have the #!/bin/bash shebang line for your script if you use double brackets.

See also

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

How to use a ViewBag to create a dropdownlist?

Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:

Send Country list and City list and Other list you need to show in View:

HomeController Code:

[HttpGet]
        public ActionResult NewAgahi() // New Advertising
        {
            //--------------------------------------------------------
            // ??????? ?? ?????? ???? ????? ??? ??? ?? ???
            Country_Repository blCountry = new Country_Repository();
            Ostan_Repository blOstan = new Ostan_Repository();
            City_Repository blCity = new City_Repository();
            Mahale_Repository blMahale = new Mahale_Repository();
            Agahi_Repository blAgahi = new Agahi_Repository();

            var vm = new NewAgahi_ViewModel();
            vm.Country = blCountry.Select();
            vm.Ostan = blOstan.Select();
            vm.City = blCity.Select();
            vm.Mahale = blMahale.Select();
            //vm.Agahi = blAgahi.Select();

            return View(vm);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult NewAgahi(Agahi agahi)
        {

            if (ModelState.IsValid == true)
            {
                Agahi_Repository blAgahi = new Agahi_Repository();

                agahi.Date = DateTime.Now.Date;
                agahi.UserId = 1048;
                agahi.GroupId = 1;


                if (blAgahi.Add(agahi) == true)
                {
                    //Success
                    return JavaScript("alert('??? ??')");

                }
                else
                {
                    //Fail
                    return JavaScript("alert('????? ?? ???')");

            }

Viewmodel Code:

using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectName.ViewModels
{
    public class NewAgahi_ViewModel // ???? ??????? ???? ?? ??? ??? ?? ?? ???
    { 

        public IEnumerable<Country> Country { get; set; }

        public IEnumerable<Ostan> Ostan { get; set; }

        public IEnumerable<City> City { get; set; }

        public IQueryable<Mahale> Mahale { get; set; }

        public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }

    }
}

View Code:

@model ProjectName.ViewModels.NewAgahi_ViewModel

..... .....

@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))

 @Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))

Country_Repository Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;

namespace ProjectName.Models.Repositories
{
    public class Country_Repository : IDisposable
    {
        private MyWebSiteDBEntities db = null;


        public Country_Repository()
        {
            db = new DomainModels.MyWebSiteDBEntities();
        }

        public Boolean Add(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Add(entity);
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges()); 
                                                                //return "True";
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message;
                //return e.Message;
                return false;
            }
        }


        public bool Update(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message; // ?? ?????????? ??? ???? ?????? ?????? ??? ?? ?????

                return false;
            }
        }

        public bool Delete(Country entity, bool autoSave = true)
        {
            try
            {
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(int id, bool autoSave = true)
        {
            try
            {
                var entity = db.Country.Find(id);
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public Country Find(int id)
        {
            try
            {
                return db.Country.Find(id);
            }
            catch
            {
                return null;
            }
        }


        public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
        {
            try
            {
                return db.Country.Where(predicate);
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<Country> Select()
        {
            try
            {
                return db.Country.AsQueryable();
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
        {
            try
            {
                return db.Country.Select(selector);
            }
            catch
            {
                return null;
            }
        }

        public int GetLastIdentity()
        {
            try
            {
                if (db.Country.Any())
                    return db.Country.OrderByDescending(p => p.id).First().id;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }

        public int Save()
        {
            try
            {
                return db.SaveChanges();
            }
            catch
            {
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.db != null)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        ~Country_Repository()
        {
            Dispose(false);
        }
    }
}

Is there a way to override class variables in Java?

Of course using private attributes, and getters and setters would be the recommended thing to do, but I tested the following, and it works... See the comment in the code

class Dad
{
    protected static String me = "dad";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected static String me = "son";

    /* 
    Adding Method printMe() to this class, outputs son 
    even though Attribute me from class Dad can apparently not be overridden
    */

    public void printMe()
    {
        System.out.println(me);
    }
}

class Tester
{
    public static void main(String[] arg)
    {
        new Son().printMe();
    }
}

Sooo ... did I just redefine the rules of inheritance or did I put Oracle into a tricky situation ? To me, protected static String me is clearly overridden, as you can see when you execute this program. Also, it does not make any sense to me why attributes should not be overridable.

Where are $_SESSION variables stored?

How does it work? How does it know it's me?

Most sessions set a user-key(called the sessionid) on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key and runs to the server to get your variables.

If you mistakenly clear the cache, then your user-key will also be cleared. You won't be able to get your variables from the server any more since you don't know your id.

How to create a stopwatch using JavaScript?

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

Convert a string to an enum in C#

I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.

StatusEnum MyStatus = Enum<StatusEnum>.Parse("Active");

The blogpost is Enums – Better syntax, improved performance and TryParse in NET 3.5.

And code: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs

Does SVG support embedding of bitmap images?

You can use a data: URL to embed a Base64 encoded version of an image. But it's not very efficient and wouldn't recommend embedding large images. Any reason linking to another file is not feasible?

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

How to check undefined in Typescript

Late to the story but I think some details are overlooked?

if you use

if (uemail !== undefined) {
  //some function
}

You are, technically, comparing variable uemail with variable undefined and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefined may actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

To be correct one would have to declare a constant of type undefined for example:

const _undefined: undefined

and then test by:

if (uemail === _undefined) {
  //some function
}

This test will return true as uemail now equals both value & type of _undefined as _undefined is now properly declared to be of type undefined.

Another way would be

if (typeof(uemail) === 'undefined') {
  //some function
}

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.

How to exit a 'git status' list in a terminal?

My preferred combo is Gq, which prints all diffs and then exits.

You can type h to show the help commands for interacting with less, which prints this to console:

                   SUMMARY OF LESS COMMANDS

      Commands marked with * may be preceded by a number, N.
      Notes in parentheses indicate the behavior if N is given.

  h  H                 Display this help.
  q  :q  Q  :Q  ZZ     Exit.
 ---------------------------------------------------------------------------

                           MOVING

  e  ^E  j  ^N  CR  *  Forward  one line   (or N lines).
  y  ^Y  k  ^K  ^P  *  Backward one line   (or N lines).
  f  ^F  ^V  SPACE  *  Forward  one window (or N lines).
  b  ^B  ESC-v      *  Backward one window (or N lines).
  z                 *  Forward  one window (and set window to N).
  w                 *  Backward one window (and set window to N).
  ESC-SPACE         *  Forward  one window, but don't stop at end-of-file.
  d  ^D             *  Forward  one half-window (and set half-window to N).
  u  ^U             *  Backward one half-window (and set half-window to N).
  ESC-)  RightArrow *  Left  one half screen width (or N positions).
  ESC-(  LeftArrow  *  Right one half screen width (or N positions).
  F                    Forward forever; like "tail -f".
  r  ^R  ^L            Repaint screen.
  R                    Repaint screen, discarding buffered input.
        ---------------------------------------------------
        Default "window" is the screen height.
        Default "half-window" is half of the screen height.
 ---------------------------------------------------------------------------

                          SEARCHING

  /pattern          *  Search forward for (N-th) matching line.
  ?pattern          *  Search backward for (N-th) matching line.
  n                 *  Repeat previous search (for N-th occurrence).
  N                 *  Repeat previous search in reverse direction.
  ESC-n             *  Repeat previous search, spanning files.
  ESC-N             *  Repeat previous search, reverse dir. & spanning files.
  ESC-u                Undo (toggle) search highlighting.
        ---------------------------------------------------
        Search patterns may be modified by one or more of:
        ^N or !  Search for NON-matching lines.
        ^E or *  Search multiple files (pass thru END OF FILE).
        ^F or @  Start search at FIRST file (for /) or last file (for ?).
        ^K       Highlight matches, but don't move (KEEP position).
        ^R       Don't use REGULAR EXPRESSIONS.
 ---------------------------------------------------------------------------

                           JUMPING

  g  <  ESC-<       *  Go to first line in file (or line N).
  G  >  ESC->       *  Go to last line in file (or line N).
  p  %              *  Go to beginning of file (or N percent into file).
  t                 *  Go to the (N-th) next tag.
  T                 *  Go to the (N-th) previous tag.
  {  (  [           *  Find close bracket } ) ].
  }  )  ]           *  Find open bracket { ( [.
  ESC-^F <c1> <c2>  *  Find close bracket <c2>.
  ESC-^B <c1> <c2>  *  Find open bracket <c1> 
        ---------------------------------------------------

Downloading an entire S3 bucket?

To add another GUI option, we use WinSCP's S3 functionality. It's very easy to connect, only requiring your access key and secret key in the UI. You can then browse and download whatever files you require from any accessible buckets, including recursive downloads of nested folders.

Since it can be a challenge to clear new software through security and WinSCP is fairly prevalent, it can be really beneficial to just use it rather than try to install a more specialized utility.

android button selector

You can't achieve text size change with a state list drawable. To change text color and text size do this:

Text color

To change the text color, you can create color state list resource. It will be a separate resource located in res/color/ directory. In layout xml you have to set it as the value for android:textColor attribute. The color selector will then contain something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/text_pressed" />
    <item android:color="@color/text_normal" />
</selector>

Text size

You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.

Probably the easiest solution might be utilizing View.onTouchListener() and handle the up and down events accordingly. Use something like this:

view.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // change text size to the "pressed value"
                return true;
            case MotionEvent.ACTION_UP:
                // change text size to the "normal value"
                return true;
            default:
                return false;
            }
        }
});

A different solution might be to extend the view and override the setPressed(Boolean) method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).

Join a list of items with different types as string in Python

Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:

>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]

If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.

>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']

All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

overlay two images in android to set an imageview

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

Solution #1 (via XML):

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />
</layer-list>

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));

Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

(I haven't tested this code so there may be a mistake, but this general outline should work.)

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

What is the difference between association, aggregation and composition?

Composition: This is where once you destroy an object (School), another object (Classrooms) which is bound to it would get destroyed too. Both of them can't exist independently.

Aggregation: This is sorta the exact opposite of the above (Composition) association where once you kill an object (Company), the other object (Employees) which is bound to it can exist on its own.

Association.
Composition and Aggregation are the two forms of association.

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

Hash and salt passwords in C#

Use the System.Web.Helpers.Crypto NuGet package from Microsoft. It automatically adds salt to the hash.

You hash a password like this: var hash = Crypto.HashPassword("foo");

You verify a password like this: var verified = Crypto.VerifyHashedPassword(hash, "foo");

How to create range in Swift?

I created the following extension:

extension String {
    func substring(from from:Int, to:Int) -> String? {
        if from<to && from>=0 && to<self.characters.count {
            let rng = self.startIndex.advancedBy(from)..<self.startIndex.advancedBy(to)
            return self.substringWithRange(rng)
        } else {
            return nil
        }
    }
}

example of use:

print("abcde".substring(from: 1, to: 10)) //nil
print("abcde".substring(from: 2, to: 4))  //Optional("cd")
print("abcde".substring(from: 1, to: 0))  //nil
print("abcde".substring(from: 1, to: 1))  //nil
print("abcde".substring(from: -1, to: 1)) //nil

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Python: How to increase/reduce the fontsize of x and y tick labels?

It is simpler than I thought it would be.

To set the font size of the x-axis ticks:

x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)

To do it for the y-axis ticks:

y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

The arguments rotation and fontsize can easily control what I was after.

Reference: http://matplotlib.org/api/axes_api.html

Error inflating when extending a class

The thing to understand here is that:

The constructor ViewClassName(Context context, AttributeSet attrs ) is called when inflating the customView via xml. You see you are not using the new keyword to instantiate your object i.e. you are not doing new GhostSurfaceCameraView(). Doing this you are calling the first constructor i.e. public View (Context context).

Whereas when inflating view from XML, i.e. when using setContentView(R.layout.ghostviewscreen); or using findViewById, you, NO, not you!, the android system calls the ViewClassName(Context context, AttributeSet attrs ) constructor.

This is clear when reading the documentation : "Constructor that is called when inflating a view from XML." See: https://developer.android.com/reference/android/view/View.html#View(android.content.Context,%20android.util.AttributeSet)

Hence, never forget basic polymorphism and never forget reading through the documentation. It saves a ton of headache.

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal class from the tutorial you were reading.

First of all your Animal class with the Json Annotations for the subclasses.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "Dog"),

    @JsonSubTypes.Type(value = Cat.class, name = "Cat") }
)
public abstract class Animal {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Then your subclasses, Dog and Cat.

public class Dog extends Animal {

    private String breed;

    public Dog() {

    }

    public Dog(String name, String breed) {
        setName(name);
        setBreed(breed);
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }
}

public class Cat extends Animal {

    public String getFavoriteToy() {
        return favoriteToy;
    }

    public Cat() {}

    public Cat(String name, String favoriteToy) {
        setName(name);
        setFavoriteToy(favoriteToy);
    }

    public void setFavoriteToy(String favoriteToy) {
        this.favoriteToy = favoriteToy;
    }

    private String favoriteToy;

}

As you can see, there is nothing special for Cat and Dog, the only one that know about them is the abstract class Animal, so when deserializing, you'll target to Animal and the ObjectMapper will return the actual instance as you can see in the following test:

public class Test {

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        Animal myDog = new Dog("ruffus","english shepherd");

        Animal myCat = new Cat("goya", "mice");

        try {
            String dogJson = objectMapper.writeValueAsString(myDog);

            System.out.println(dogJson);

            Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);

            System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());

            String catJson = objectMapper.writeValueAsString(myCat);

            Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);

            System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());



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

    }
}

Output after running the Test class:

{"@type":"Dog","name":"ruffus","breed":"english shepherd"}

Deserialized dogJson Class: Dog

{"@type":"Cat","name":"goya","favoriteToy":"mice"}

Deserialized catJson Class: Cat

Hope this helps,

Jose Luis

Get a pixel from HTML Canvas?

function GetPixel(context, x, y)
{
    var p = context.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);  
    return hex;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

Where are static variables stored in C and C++?

It depends on the platform and compiler that you're using. Some compilers store directly in the code segment. Static variables are always only accessible to the current translation unit and the names are not exported thus the reason name collisions never occur.

How does the modulus operator work?

It gives you the remainder of a division.

int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c

How to create and write to a txt file using VBA

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
    Console.ReadLine()

End Sub()

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

How to find all occurrences of a substring?

Come, let us recurse together.

def locations_of_substring(string, substring):
    """Return a list of locations of a substring."""

    substring_length = len(substring)    
    def recurse(locations_found, start):
        location = string.find(substring, start)
        if location != -1:
            return recurse(locations_found + [location], location+substring_length)
        else:
            return locations_found

    return recurse([], 0)

print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]

No need for regular expressions this way.

mongo - couldn't connect to server 127.0.0.1:27017

Start monogdb service using

sudo service mongod start 

then from the new window or terminal start mongo client using

mongo

How can I get the application's path in a .NET console application?

You can create a folder name as Resources within the project using Solution Explorer,then you can paste a file within the Resources.

private void Form1_Load(object sender, EventArgs e) {
    string appName = Environment.CurrentDirectory;
    int l = appName.Length;
    int h = appName.LastIndexOf("bin");
    string ll = appName.Remove(h);                
    string g = ll + "Resources\\sample.txt";
    System.Diagnostics.Process.Start(g);
}

Private class declaration

You can't have private class but you can have second class:

public class App14692708 {
    public static void main(String[] args) {
        PC pc = new PC();
        System.out.println(pc);
    }
}

class PC {
    @Override
    public String toString() {
        return "I am PC instance " + super.toString();
    }
}

Also remember that static inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass. So if you don't want to use "closures", use static inner class.

What is Model in ModelAndView from Spring MVC?

new ModelAndView("welcomePage", "WelcomeMessage", message);

is shorthand for

ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);

Looking at the code above, you can see the view name is "welcomePage". Your ViewResolver (usually setup in .../WEB-INF/spring-servlet.xml) will translate this into a View. The last line of the code sets an attribute in your model (addObject("WelcomeMessage", message)). That's where the model comes into play.

Rename a file using Java

You want to utilize the renameTo method on a File object.

First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.

If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.

Is there an API to get bank transaction and bank balance?

I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.

Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.

In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.

This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.

OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory

Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx

How can I set a css border on one side only?

    div{
    border-left:solid red 3px;
    border-right:solid violet 4px;
    border-top:solid blue 4px;
    border-bottom:solid green 4px;
    background:grey;
    width:100px; height:50px
}

DEMO

Try-catch speeding up my code?

One of the Roslyn engineers who specializes in understanding optimization of stack usage took a look at this and reports to me that there seems to be a problem in the interaction between the way the C# compiler generates local variable stores and the way the JIT compiler does register scheduling in the corresponding x86 code. The result is suboptimal code generation on the loads and stores of the locals.

For some reason unclear to all of us, the problematic code generation path is avoided when the JITter knows that the block is in a try-protected region.

This is pretty weird. We'll follow up with the JITter team and see whether we can get a bug entered so that they can fix this.

Also, we are working on improvements for Roslyn to the C# and VB compilers' algorithms for determining when locals can be made "ephemeral" -- that is, just pushed and popped on the stack, rather than allocated a specific location on the stack for the duration of the activation. We believe that the JITter will be able to do a better job of register allocation and whatnot if we give it better hints about when locals can be made "dead" earlier.

Thanks for bringing this to our attention, and apologies for the odd behaviour.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

A more un-obtrusive way (assuming you use jQuery):

HTML:

<a id="my-link" href="page.html">page link</a>

Javascript:

$('#my-link').click(function(e)
{
    e.preventDefault();
});

The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.

Git error on git pull (unable to update local ref)

with gitbach line commande, use git update-ref to update reference of your local branch:

$ git update-ref -d refs/remotes/origin/[locked branch name]

then pull using $ git pull

[locked branch name] is the name of the branch that the error is happening because of mismatch of commit Ids.

Link entire table row?

Example: http://xxjjnn.com/linktablerow.html

Link entire row:

<table>
  <tr onclick="location.href='SomeWherrrreOverTheWebsiiiite.html'">**
    <td> ...content... </td>
    <td> ...content... </td>
    ...
  </tr>
</table>

Iff you'd like to do highlight on mouseover for the entire row, then:

<table class="nogap">
  <tr class="lovelyrow" onclick="location.href='SomeWherrrreOverTheWebsiiiite.html'">**
     ...
  </tr>
</table>

with something like the following for css, which will remove the gap between the table cells and change the background on hover:

tr.lovelyrow{
  background-color: hsl(0,0%,90%);
}

tr.lovelyrow:hover{
  background-color: hsl(0,0%,40%);
  cursor: pointer;
}

table.nogap{
  border-collapse: collapse;
}

Iff you are using Rails 3.0.9 then you might find this example code useful:

Sea has many Fish, Fish has many Scales, here is snippet of app/view/fish/index.erb

<table>
<% @fishies.each do |fish| %>
  <tr onclick="location.href='<%= sea_fish_scales_path(@sea, fish) %>'"> 
    <td><%= fish.title %></td>
  </tr>
<% end %>
</table>

with @fishies and @sea are defined in app/controllers/seas_controller.rb

PHP Using RegEx to get substring of a string

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

php.net/preg-match

SELECT COUNT in LINQ to SQL C#

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

Java - How do I make a String array with values?

You could do something like this

String[] myStrings = { "One", "Two", "Three" };

or in expression

functionCall(new String[] { "One", "Two", "Three" });

or

String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };

Java - Find shortest path between 2 points in a distance weighted map

Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.

While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!

form with no action and where enter does not reload page

Two way to solve :

  1. form's action value is "javascript:void(0);".
  2. add keypress event listener for the form to prevent submitting.

Passing JavaScript array to PHP through jQuery $.ajax

Use the JQuery Serialize function

http://docs.jquery.com/Ajax/serialize

Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks.

How to combine two or more querysets in a Django view?

You can use the QuerySetChain class below. When using it with Django's paginator, it should only hit the database with COUNT(*) queries for all querysets and SELECT() queries only for those querysets whose records are displayed on the current page.

Note that you need to specify template_name= if using a QuerySetChain with generic views, even if the chained querysets all use the same model.

from itertools import islice, chain

class QuerySetChain(object):
    """
    Chains multiple subquerysets (possibly of different models) and behaves as
    one queryset.  Supports minimal methods needed for use with
    django.core.paginator.
    """

    def __init__(self, *subquerysets):
        self.querysets = subquerysets

    def count(self):
        """
        Performs a .count() for all subquerysets and returns the number of
        records as an integer.
        """
        return sum(qs.count() for qs in self.querysets)

    def _clone(self):
        "Returns a clone of this queryset chain"
        return self.__class__(*self.querysets)

    def _all(self):
        "Iterates records in all subquerysets"
        return chain(*self.querysets)

    def __getitem__(self, ndx):
        """
        Retrieves an item or slice from the chained set of results from all
        subquerysets.
        """
        if type(ndx) is slice:
            return list(islice(self._all(), ndx.start, ndx.stop, ndx.step or 1))
        else:
            return islice(self._all(), ndx, ndx+1).next()

In your example, the usage would be:

pages = Page.objects.filter(Q(title__icontains=cleaned_search_term) |
                            Q(body__icontains=cleaned_search_term))
articles = Article.objects.filter(Q(title__icontains=cleaned_search_term) |
                                  Q(body__icontains=cleaned_search_term) |
                                  Q(tags__icontains=cleaned_search_term))
posts = Post.objects.filter(Q(title__icontains=cleaned_search_term) |
                            Q(body__icontains=cleaned_search_term) | 
                            Q(tags__icontains=cleaned_search_term))
matches = QuerySetChain(pages, articles, posts)

Then use matches with the paginator like you used result_list in your example.

The itertools module was introduced in Python 2.3, so it should be available in all Python versions Django runs on.

How to find which columns contain any NaN value in Pandas dataframe

This worked for me,

1. For getting Columns having at least 1 null value. (column names)

data.columns[data.isnull().any()]

2. For getting Columns with count, with having at least 1 null value.

data[data.columns[data.isnull().any()]].isnull().sum()

[Optional] 3. For getting percentage of the null count.

data[data.columns[data.isnull().any()]].isnull().sum() * 100 / data.shape[0]

How do you add an image?

In order to add attributes, XSL wants

<xsl:element name="img">
     (attributes)
</xsl:element>

instead of just

<img>
     (attributes)
</img>

Although, yes, if you're just copying the element as-is, you don't need any of that.

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

For me both keys for sql-mode worked. Whether I used

# dash no quotes
sql-mode=NO_ENGINE_SUBSTITUTION

or

# underscore no quotes
sql_mode=NO_ENGINE_SUBSTITUTION

in the my.ini file made no difference and both were accepted, as far as I could test it.

What actually made a difference was a missing newline at the end of the my.ini file.

So everyone having problems with this or similar problems with my.ini/my.cnf: Make sure there is a blank line at the end of the file!

Tested using MySQL 5.7.27.

JavaScript variable assignments from tuples

Javascript 1.7 added destructured assignment which allows you to do essentially what you are after.

function getTuple(){
   return ["Bob", 24];
}
var [a, b] = getTuple();
// a === "bob" , b === 24 are both true

Pass multiple optional parameters to a C# function

C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

The activity must be exported or contain an intent-filter

Sometimes if you change the starting activity you have to click edit in the run dropdown play button and in app change the Launch Options Activity to the one you have set the LAUNCHER intent filter in the manifest.

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

proxy_servers:
    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

Then in cmd Anaconda Power Prompt (base) PS C:\Users\user> run:

conda update -n root conda

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

Reset IntelliJ UI to Default

All above answers are correct, but you loose configuration settings.

But if your IDE's only themes or fonts are changed or some UI related issues and you want to restore to default theme, then just delete

${user.home}/.IntelliJIdea13/config/options/options.xml

file while IDE is not running, then after next restart IDE's theme will gets reset to default.

SQL Server : Columns to Rows

You can use the UNPIVOT function to convert the columns into rows:

select id, entityId,
  indicatorname,
  indicatorvalue
from yourtable
unpivot
(
  indicatorvalue
  for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;

Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.

You could also use CROSS APPLY with UNION ALL to convert the columns:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  select 'Indicator1', Indicator1 union all
  select 'Indicator2', Indicator2 union all
  select 'Indicator3', Indicator3 union all
  select 'Indicator4', Indicator4 
) c (indicatorname, indicatorvalue);

Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  values
  ('Indicator1', Indicator1),
  ('Indicator2', Indicator2),
  ('Indicator3', Indicator3),
  ('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);

Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot 
  = stuff((select ','+quotename(C.column_name)
           from information_schema.columns as C
           where C.table_name = 'yourtable' and
                 C.column_name like 'Indicator%'
           for xml path('')), 1, 1, '')

set @query 
  = 'select id, entityId,
        indicatorname,
        indicatorvalue
     from yourtable
     unpivot
     (
        indicatorvalue
        for indicatorname in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

SQL Query NOT Between Two Dates

How about trying:

select * from 'test_table'
where end_date < CAST('2009-12-15' AS DATE)
or start_date > CAST('2010-01-02' AS DATE)

which will return all date ranges which do not overlap your date range at all.

Retrieving values from nested JSON Object

JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
    JSONObject secObject = (JSONObject) jsonChildArray.get(1);

I think this should work, but i do not have the possibility to test it at the moment..

no target device found android studio 2.1.1

This happened to me on android studio version 4 after doing an update to the IDE. The "invalidate caches and restart" option fixed it.

What should main() return in C and C++?

The return value of main() shows how the program exited. If the return value is zero it means that the execution was successful while any non-zero value will represent that something went bad in the execution.

What is the HTML unicode character for a "tall" right chevron?

From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.

In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).

Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family list or to use a downloadable font. See my Guide to using special characters in HTML.

Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?

Pattern matching using a wildcard

glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

> glob2rx("blue*")
[1] "^blue"

The returned object is a regular expression.

Given your data:

x <- c('red','blue1','blue2', 'red2')

we can pattern match using grep() or similar tools:

> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE  TRUE  TRUE FALSE

As for the selecting rows problem you posted

> a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2

or via subset():

> with(a, subset(a, subset = grepl(grx, x)))
      x
2 blue1
3 blue2

Hope that explains what grob2rx() does and how to use it?

How do you get the current page number of a ViewPager for Android?

getCurrentItem(), doesn't actually give the right position for the first and the last page I fixed it adding this code:

public void CalcPostion() {    
    current = viewPager.getCurrentItem();

    if ((last == current) && (current != 1) && (current != 0)) {
        current = current + 1;
        viewPager.setCurrentItem(current);
    }
    if ((last == 1) && (current == 1)) {
        last = 0;
        current = 0;
    }
    display();
    last = current;
}

How do I enable php to work with postgresql?

I installed PHP on windows IIS using Windows Platform Installer (WP?). WP? creates a "PHP Manager" tool in "Internet Information Services (IIS) Manager" console. I am configuring PHP using this tool.

in http://php.net/manual/en/pdo.installation.php says:

PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file: extension=php_pdo.dll

so i activated the extension using PHP Manager and now PDO works fine

PHP manager simple added the following two lines in my php.ini, you can add the lines by hand. Of course you must restart the web server.

[PHP_PDO_PGSQL]
extension=php_pdo_pgsql.dll

for each loop in Objective-C for accessing NSMutable dictionary

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}

Function to close the window in Tkinter

def quit(self):
    self.root.destroy()

Add parentheses after destroy to call the method.

When you use command=self.root.destroy you pass the method to Tkinter.Button without the parentheses because you want Tkinter.Button to store the method for future calling, not to call it immediately when the button is created.

But when you define the quit method, you need to call self.root.destroy() in the body of the method because by then the method has been called.