Programs & Examples On #Mass emails

WPF Button with Image

<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top"  Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
    <StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
        <Image HorizontalAlignment="Left"  Source="image/bg/Save.png" Height="36" Width="124" />
        <TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
    </StackPanel>
</Button>

Export to CSV via PHP

You can export the date using this command.

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

First you must load the data from the mysql server in to a array

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

How about using the history replacement function to add the site into the browsers history?

Try executing the following as soon as the window loads-

history.replaceState("example", "title", "http://www.example.com");

This should hopefully make it so even if it is the first page they have accessed, the URL you define in the code will be what they're taken to when they click back.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

For me this worked:

git reset --hard

and then

git pull origin <*current branch>

after that

git checkout <*branch>

Excel - Combine multiple columns into one column

Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.

Private Sub MergeProjectNameColumns()
    Dim rngRowCount As Integer
    Dim i As Integer

    'Loop through column C and simply copy the text over to B if it is not blank
    rngRowCount = Range(dataRange).Rows.Count
    ActiveCell.Offset(0, 0).Select
    ActiveCell.Offset(0, 2).Select
    For i = 1 To rngRowCount
        If (Len(RTrim(ActiveCell.Value)) > 0) Then
            Dim currentValue As String
            currentValue = ActiveCell.Value
            ActiveCell.Offset(0, -1) = currentValue
        End If
        ActiveCell.Offset(1, 0).Select
    Next i

    'Now delete the unused column
    Columns("C").Select

    selection.Delete Shift:=xlToLeft
End Sub

Java, Check if integer is multiple of a number

Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:

if (j % 4 == 0) {
     // j is an exact multiple of 4
}

Using a dispatch_once singleton model in Swift

This is my implementation. It also prevents the programmer from creating a new instance:

let TEST = Test()

class Test {

    private init() {
        // This is a private (!) constructor
    }
}

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

error: command 'gcc' failed with exit status 1 while installing eventlet

If it is still not working, you can try this

sudo apt-get install build-essential

in my case, it solved the problem.

How to get the current branch name in Git?

Why not use git-aware shell prompt, which would tell you name of current branch? git status also helps.


How git-prompt.sh from contrib/ does it (git version 2.3.0), as defined in __git_ps1 helper function:

  1. First, there is special case if rebase in progress is detected. Git uses unnamed branch (detached HEAD) during the rebase process to make it atomic, and original branch is saved elsewhere.

  2. If the .git/HEAD file is a symbolic link (a very rare case, from the ancient history of Git), it uses git symbolic-ref HEAD 2>/dev/null

  3. Else, it reads .git/HEAD file. Next steps depends on its contents:

    • If this file doesn't exist, then there is no current branch. This usually happens if the repository is bare.

    • If it starts with 'ref: ' prefix, then .git/HEAD is symref (symbolic reference), and we are on normal branch. Strip this prefix to get full name, and strip refs/heads/ to get short name of the current branch:

      b="${head#ref: }"
      # ...
      b=${b##refs/heads/}
      
    • If it doesn't start with 'ref: ', then it is detached HEAD (anonymous branch), pointing directly to some commit. Use git describe ... to write the current commit in human-readable form.

I hope that helps.

Can I send a ctrl-C (SIGINT) to an application on Windows?

The closest that I've come to a solution is the SendSignal 3rd party app. The author lists source code and an executable. I've verified that it works under 64-bit windows (running as a 32-bit program, killing another 32-bit program), but I've not figured out how to embed the code into a windows program (either 32-bit or 64-bit).

How it works:

After much digging around in the debugger I discovered that the entry point that actually does the behavior associated with a signal like ctrl-break is kernel32!CtrlRoutine. The function had the same prototype as ThreadProc, so it can be used with CreateRemoteThread directly, without having to inject code. However, that's not an exported symbol! It's at different addresses (and even has different names) on different versions of Windows. What to do?

Here is the solution I finally came up with. I install a console ctrl handler for my app, then generate a ctrl-break signal for my app. When my handler gets called, I look back at the top of the stack to find out the parameters passed to kernel32!BaseThreadStart. I grab the first param, which is the desired start address of the thread, which is the address of kernel32!CtrlRoutine. Then I return from my handler, indicating that I have handled the signal and my app should not be terminated. Back in the main thread, I wait until the address of kernel32!CtrlRoutine has been retrieved. Once I've got it, I create a remote thread in the target process with the discovered start address. This causes the ctrl handlers in the target process to be evaluated as if ctrl-break had been pressed!

The nice thing is that only the target process is affected, and any process (even a windowed process) can be targeted. One downside is that my little app can't be used in a batch file, since it will kill it when it sends the ctrl-break event in order to discover the address of kernel32!CtrlRoutine.

(Precede it with start if running it in a batch file.)

Get The Current Domain Name With Javascript (Not the path, etc.)

I figure it ought to be as simple as this:

url.split("/")[2]

Iterate through object properties

The above answers are a bit annoying because they don't explain what you do inside the for loop after you ensure it's an object: YOU DON'T ACCESS IT DIRECTLY! You are actually only delivered the KEY that you need to apply to the OBJ:

var obj = {
  a: "foo",
  b: "bar",
  c: "foobar"
};

// We need to iterate the string keys (not the objects)
for(var someKey in obj)
{
  // We check if this key exists in the obj
  if (obj.hasOwnProperty(someKey))
  {
    // someKey is only the KEY (string)! Use it to get the obj:
    var myActualPropFromObj = obj[someKey]; // Since dynamic, use [] since the key isn't literally named "someKey"

    // NOW you can treat it like an obj
    var shouldBeBar = myActualPropFromObj.b;
  }
}

This is all ECMA5 safe. Even works in the lame JS versions like Rhino ;)

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

Can't find/install libXtst.so.6?

Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.

Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.

Identifying Exception Type in a handler Catch Block

Alternatively:

var exception = err as Web2PDFException; 

if ( excecption != null ) 
{ 
     Web2PDFException wex = exception; 
     .... 
}

MySQL Great Circle Distance (Haversine formula)

If you add helper fields to the coordinates table, you can improve response time of the query.

Like this:

CREATE TABLE `Coordinates` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'id for the object',
`type` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'type',
`sin_lat` FLOAT NOT NULL COMMENT 'sin(lat) in radians',
`cos_cos` FLOAT NOT NULL COMMENT 'cos(lat)*cos(lon) in radians',
`cos_sin` FLOAT NOT NULL COMMENT 'cos(lat)*sin(lon) in radians',
`lat` FLOAT NOT NULL COMMENT 'latitude in degrees',
`lon` FLOAT NOT NULL COMMENT 'longitude in degrees',
INDEX `lat_lon_idx` (`lat`, `lon`)
)    

If you're using TokuDB, you'll get even better performance if you add clustering indexes on either of the predicates, for example, like this:

alter table Coordinates add clustering index c_lat(lat);
alter table Coordinates add clustering index c_lon(lon);

You'll need the basic lat and lon in degrees as well as sin(lat) in radians, cos(lat)*cos(lon) in radians and cos(lat)*sin(lon) in radians for each point. Then you create a mysql function, smth like this:

CREATE FUNCTION `geodistance`(`sin_lat1` FLOAT,
                              `cos_cos1` FLOAT, `cos_sin1` FLOAT,
                              `sin_lat2` FLOAT,
                              `cos_cos2` FLOAT, `cos_sin2` FLOAT)
    RETURNS float
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY INVOKER
   BEGIN
   RETURN acos(sin_lat1*sin_lat2 + cos_cos1*cos_cos2 + cos_sin1*cos_sin2);
   END

This gives you the distance.

Don't forget to add an index on lat/lon so the bounding boxing can help the search instead of slowing it down (the index is already added in the CREATE TABLE query above).

INDEX `lat_lon_idx` (`lat`, `lon`)

Given an old table with only lat/lon coordinates, you can set up a script to update it like this: (php using meekrodb)

$users = DB::query('SELECT id,lat,lon FROM Old_Coordinates');

foreach ($users as $user)
{
  $lat_rad = deg2rad($user['lat']);
  $lon_rad = deg2rad($user['lon']);

  DB::replace('Coordinates', array(
    'object_id' => $user['id'],
    'object_type' => 0,
    'sin_lat' => sin($lat_rad),
    'cos_cos' => cos($lat_rad)*cos($lon_rad),
    'cos_sin' => cos($lat_rad)*sin($lon_rad),
    'lat' => $user['lat'],
    'lon' => $user['lon']
  ));
}

Then you optimize the actual query to only do the distance calculation when really needed, for example by bounding the circle (well, oval) from inside and outside. For that, you'll need to precalculate several metrics for the query itself:

// assuming the search center coordinates are $lat and $lon in degrees
// and radius in km is given in $distance
$lat_rad = deg2rad($lat);
$lon_rad = deg2rad($lon);
$R = 6371; // earth's radius, km
$distance_rad = $distance/$R;
$distance_rad_plus = $distance_rad * 1.06; // ovality error for outer bounding box
$dist_deg_lat = rad2deg($distance_rad_plus); //outer bounding box
$dist_deg_lon = rad2deg($distance_rad_plus/cos(deg2rad($lat)));
$dist_deg_lat_small = rad2deg($distance_rad/sqrt(2)); //inner bounding box
$dist_deg_lon_small = rad2deg($distance_rad/cos(deg2rad($lat))/sqrt(2));

Given those preparations, the query goes something like this (php):

$neighbors = DB::query("SELECT id, type, lat, lon,
       geodistance(sin_lat,cos_cos,cos_sin,%d,%d,%d) as distance
       FROM Coordinates WHERE
       lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d
       HAVING (lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d) OR distance <= %d",
  // center radian values: sin_lat, cos_cos, cos_sin
       sin($lat_rad),cos($lat_rad)*cos($lon_rad),cos($lat_rad)*sin($lon_rad),
  // min_lat, max_lat, min_lon, max_lon for the outside box
       $lat-$dist_deg_lat,$lat+$dist_deg_lat,
       $lon-$dist_deg_lon,$lon+$dist_deg_lon,
  // min_lat, max_lat, min_lon, max_lon for the inside box
       $lat-$dist_deg_lat_small,$lat+$dist_deg_lat_small,
       $lon-$dist_deg_lon_small,$lon+$dist_deg_lon_small,
  // distance in radians
       $distance_rad);

EXPLAIN on the above query might say that it's not using index unless there's enough results to trigger such. The index will be used when there's enough data in the coordinates table. You can add FORCE INDEX (lat_lon_idx) to the SELECT to make it use the index with no regards to the table size, so you can verify with EXPLAIN that it is working correctly.

With the above code samples you should have a working and scalable implementation of object search by distance with minimal error.

Remove CSS class from element with JavaScript (no jQuery)

function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }

How can I see the request headers made by curl when sending a request to the server?

A command like the one below will show three sections: request headers, response headers and data (separated by CRLF). It avoids technical information and syntactical noise added by curl.

curl -vs www.stackoverflow.com 2>&1 | sed '/^* /d; /bytes data]$/d; s/> //; s/< //'

The command will produce the following output:

GET / HTTP/1.1
Host: www.stackoverflow.com
User-Agent: curl/7.54.0
Accept: */*

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=UTF-8
Location: https://stackoverflow.com/
Content-Length: 149
Accept-Ranges: bytes
Date: Wed, 16 Jan 2019 20:28:56 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-bma1622-BMA
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1547670537.588756,VS0,VE105
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Set-Cookie: prov=e4b211f7-ae13-dad3-9720-167742a5dff8; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly

<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="https://stackoverflow.com/">here</a></body>

Description:

  • -vs - add headers (-v) but remove progress bar (-s)
  • 2>&1 - combine stdout and stderr into single stdout
  • sed - edit response produced by curl using the commands below
  • /^* /d - remove lines starting with '* ' (technical info)
  • /bytes data]$/d - remove lines ending with 'bytes data]' (technical info)
  • s/> // - remove '> ' prefix
  • s/< // - remove '< ' prefix

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

The cause of this error for me was...

ng-if="{{myTrustSrc(chat.src)}}"

in my template

It causes the function myTrustSrc in my controller to be called in an endless loop. If I remove the ng-if from this line, then the problem is solved.

<iframe ng-if="chat.src" id='chat' name='chat' class='chat' ng-src="{{myTrustSrc(chat.src)}}"></iframe>

The function is only called a few times when ng-if isn't used. I still wonder why the function is called more than once with ng-src?

This is the function in the controller

$scope.myTrustSrc = function(src) {
    return $sce.trustAsResourceUrl(src);
}

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

Eclipse reports rendering library more recent than ADT plug-in

Change the Target version to new updates you have. Otherwise, change what SDK version you have in the Android manifest file.

android:minSdkVersion="8"
android:targetSdkVersion="18"

HTML "overlay" which allows clicks to fall through to elements behind it

Generally, this isn't a great idea. Taking your scenario, if you had evil intentions, you could hide everything underneath your "overlay". Then, when a user clicks on a link they think should take them to bankofamerica.com, instead it triggers the hidden link which takes them to myevilsite.com.

That said, event bubbling works, and if it's within an application, it's not a big deal. The following code is an example. Clicking the blue area pops up an alert, even though the alert is set on the red area. Note that the orange area does NOT work, because the event will propagate through the PARENT elements, so your overlay needs to be inside whatever element you're observing the clicks on. In your scenario, you may be out of luck.

<html>
<head>
</head>
<body>
    <div id="outer" style="position:absolute;height:50px;width:60px;z-index:1;background-color:red;top:5px;left:5px;" onclick="alert('outer')"> 
        <div id="nested" style="position:absolute;height:50px;width:60px;z-index:2;background-color:blue;top:15px;left:15px;">
        </div>
    </div>
    <div id="separate" style="position:absolute;height:50px;width:60px;z-index:3;background-color:orange;top:25px;left:25px;">
    </div>
</body>
</html>

git: patch does not apply

It happens when you mix UNIX and Windows git clients because Windows doesn't really have the concept of the "x" bit so your checkout of a rw-r--r-- (0644) file under Windows is "promoted" by the msys POSIX layer to be rwx-r-xr-x (0755). git considers that mode difference to be basically the same as a textual difference in the file, so your patch does not directly apply. I think your only good option here is to set core.filemode to false (using git-config).

Here's a msysgit issue with some related info: http://code.google.com/p/msysgit/issues/detail?id=164 (rerouted to archive.org's 3 Dec 2013 copy)

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How to unlock android phone through ADB

I would like to share my way, first of all i had Huawei ascend p7 and my touch screen stopped handling touch, so none of the above solutions helped me to be unlock the phone, i have found a better clever way to do it since i can see the screen on thus i thought that my display is 1080 x 1920 px thus i had to simulate a drawing on my photoshop with keypad with (x,y) so i can try instead with input mouse tap command.

screenshot of simulation

Since i have pin lock as you can see in the picture, i have got all the (x,y) for all the numbers on the screen to simulate touch and unlock my screen and have to backup my data, thus if my password is 123 i did all the following commands

adb shell input mouse tap 100 1150
adb shell input mouse tap 500 1150
adb shell input mouse tap 900 1150

And then my phone just got unlocked, i hope it was helpful.

SQL how to increase or decrease one for a int column in one command

If my understanding is correct, updates should be pretty simple. I would just do the following.

UPDATE TABLE SET QUANTITY = QUANTITY + 1 and
UPDATE TABLE SET QUANTITY = QUANTITY - 1 where QUANTITY > 0

You may need additional filters to just update a single row instead of all the rows.

For inserts, you can cache some unique id related to your record locally and check against this cache and decide whether to insert or not. The alternative approach is to always insert and check for PK violation error and ignore since this is a redundant insert.

Why do we not have a virtual constructor in C++?

two reasons I can think of:

Technical reason

The object exists only after the constructor ends.In order for the constructor to be dispatched using the virtual table , there has to be an existing object with a pointer to the virtual table , but how can a pointer to the virtual table exist if the object still doesn't exist? :)

Logic reason

You use the virtual keyword when you want to declare a somewhat polymorphic behaviour. But there is nothing polymorphic with constructors , constructors job in C++ is to simply put an object data on the memory . Since virtual tables (and polymorphism in general) are all about polymorphic behaviour rather on polymorphic data , There is no sense with declaring a virtual constructor.

How to fix "unable to write 'random state' " in openssl

Or this in windows powershell

$env:RANDFILE=".rnd"

Linq select object from list depending on objects attribute

I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single will throw an exception use First, or FirstOrDefault();

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Also if you want to get list of all items marked as correct you may try:

List<Answer> correctedAnswers =  Answers.Where(a => a.Correct).ToList();

If your desired result is Single, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison

a == a.Correct

is wrong in the statement. Your single query should be:

Answer answer = Answers.Single(a => a.Correct == true);

Or shortly as:

Answer answer = Answers.Single(a => a.Correct);

Date only from TextBoxFor()

The Template Editor will work for display purposes only. If you use the same editor (which makes sense because its an editor) and you supplied a value like 31/01/2010 - you'll get an error message saying the format is invalid.

(How) can I count the items in an enum?

Here is the best way to do it in compilation time. I have used the arg_var count answer from here.

#define PP_NARG(...) \
     PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) \
         PP_ARG_N(__VA_ARGS__)

#define PP_ARG_N( \
          _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
         _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
         _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
         _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
         _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
         _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
         _61,_62,_63,N,...) N
#define PP_RSEQ_N() \
         63,62,61,60,                   \
         59,58,57,56,55,54,53,52,51,50, \
         49,48,47,46,45,44,43,42,41,40, \
         39,38,37,36,35,34,33,32,31,30, \
         29,28,27,26,25,24,23,22,21,20, \
         19,18,17,16,15,14,13,12,11,10, \
         9,8,7,6,5,4,3,2,1,0

#define TypedEnum(Name, ...)                                      \
struct Name {                                                     \
    enum {                                                        \
        __VA_ARGS__                                               \
    };                                                            \
    static const uint32_t Name##_MAX = PP_NARG(__VA_ARGS__);      \
}

#define Enum(Name, ...) TypedEnum(Name, __VA_ARGS__)

To declare an enum:

Enum(TestEnum, 
Enum_1= 0,
Enum_2= 1,
Enum_3= 2,
Enum_4= 4,
Enum_5= 8,
Enum_6= 16,
Enum_7= 32);

the max will be available here:

int array [TestEnum::TestEnum_MAX];
for(uint32_t fIdx = 0; fIdx < TestEnum::TestEnum_MAX; fIdx++)
{
     array [fIdx] = 0;
}

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

a href link for entire div in HTML/CSS

Going off of what Surreal Dreams said, it's probably best to style the anchor tag in my experience, but it really does depend on what you are doing. Here's an example:

Html:

<div class="parent-div">
  <a href="#">Test</a>
  <a href="#">Test</a>
  <a href="#">Test</a>
</div>

Then the CSS:

.parent-div {
  width: 200px;
}
a {
  display:block;
  background-color: #ccc;
  color: #000;
  text-decoration:none;
  padding:10px;
  margin-bottom:1px;
}
a:hover {
  background-color: #ddd;
}

http://jsbin.com/zijijuduqo/1/edit?html,css,output

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

How do I use Maven through a proxy?

Those are caused most likely by 2 issues:

  1. You need to add proxy configuration to your settings.xml. Here's a trick in your username field. Make sure it looks like domain\username. Setting domain there and putting this exact slash is important '\'. You might want to use <![CDATA[]]> tag if your password contains non xml-friendly characters.
  2. I've noticed maven 2.2.0 does not work sometimes through a proxy at all, where 2.2.1 works perfectly fine.

If some of those are omitted - maven could fail with random error messages.

Just hope I've saved somebody from googling around this issue for 6 hours, like I did.

print call stack in C or C++

Of course the next question is: will this be enough ?

The main disadvantage of stack-traces is that why you have the precise function being called you do not have anything else, like the value of its arguments, which is very useful for debugging.

If you have access to gcc and gdb, I would suggest using assert to check for a specific condition, and produce a memory dump if it is not met. Of course this means the process will stop, but you'll have a full fledged report instead of a mere stack-trace.

If you wish for a less obtrusive way, you can always use logging. There are very efficient logging facilities out there, like Pantheios for example. Which once again could give you a much more accurate image of what is going on.

C# Return Different Types?

use the dynamic keyword as return type.

 private dynamic getValuesD<T>()
    {
        if (typeof(T) == typeof(int))
        {
            return 0;
        }
        else if (typeof(T) == typeof(string))
        {
            return "";
        }
        else if (typeof(T) == typeof(double))
        {
            return 0;
        }
        else
        {
            return false;
        }
    }

        int res = getValuesD<int>();
        string res1 = getValuesD<string>();
        double res2 = getValuesD<double>();
        bool res3 = getValuesD<bool>();

// dynamic keyword is preferable to use in this case instead of an object type

// because dynamic keyword keeps the underlying structure and data type so that // you can directly inspect and view the value.

// in object type, you have to cast the object to a specific data type to view // the underlying value.

regards,

Abhijit

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

What are the best PHP input sanitizing functions?

It depends on the kind of data you are using. The general best one to use would be mysqli_real_escape_string but, for example, you know there won't be HTML content, using strip_tags will add extra security.

You can also remove characters you know shouldn't be allowed.

Why does npm install say I have unmet dependencies?

Some thing in the similar vein, I would add one other step.

Note that on npm version > 1.4.9, 'npm install' does install devDependencies. First try removing existing modules and cache:

remove node_modules $ rm -rf node_modules/
run $ npm cache clean

Then try:

npm install --dev
npm update --dev

This at least will resolve the recursive dependency resolution.

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

SSH keys are meant to be private so a 644 permission is too open.

Binary references to set Permissions

 r(read) = 4
 w(write) = 2
 x(execute) = 1

So by adding these numbers and by passing the summed digit to chmod command,We set the permission of file/directory. The first digit sets permission for the owner, second digit for group and the third one for all other users on the system who have no right to the file.

A permission of 644 means 
(4+2) = read/write permission for the owner
(4) = read permission for the group 
(4) = read permission for all other users 
 

By changing the the permission of the file to 400 using

chmod 400 <filename>

solves the issue. As it makes the key read-only accessible to the owner.

Ref: https://www.linux.com/training-tutorials/understanding-linux-file-permissions/

H2 in-memory database. Table not found

When opening the h2-console, the JDBC URL must match the one specified in the properties:

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb

spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

spring.h2.console.enabled=true

enter image description here

Which seems obvious, but I spent hours figuring this out..

Android Studio 3.0 Flavor Dimension Issue

Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
    production {
        dimension 'yourAppName' //you just need to add this line
        //here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.

    }

    staging {
        dimension 'yourAppName' //added here also
        applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
        //or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
        //versionNameSuffix "-staging"

    }

    develop {
        dimension 'yourAppName' //add here too
        applicationIdSuffix ".develop"
        //versionNameSuffix "-develop"

    }

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

Use the google Chrome Extension called Allow-Control-Allow-Origin: *. It modifies the CORS headers on the fly in your application.

IntelliJ: Error:java: error: release version 5 not supported

By default, your "Project bytecode version isn't set in maven project.

It thinks that your current version is 5.

Solution 1:

Just go to "Project Settings>Build, Execution...>compiler>java compiler" and then change your bytecode version to your current java version.

Solution 2:

Adding below build plugin in POM file:

 <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

SQL Inner join more than two tables

select * from Employee inner join [Order] 
On Employee.Employee_id=[Order].Employee_id
inner join Book 
On Book.Book_id=[Order].Book_id
inner join Book_Author
On Book_Author.Book_id=Book.Book_id
inner join Author
On Book_Author.Author_id=Author.Author_id;

deleting rows in numpy array

numpy provides a simple function to do the exact same thing: supposing you have a masked array 'a', calling numpy.ma.compress_rows(a) will delete the rows containing a masked value. I guess this is much faster this way...

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

How to add element into ArrayList in HashMap

#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next());  //name
al.add(s.next());  //category
al.add(s.nextInt()); //fee
d.put(id, al);
 }

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

That's the error you get when a function makes too many recursive calls to itself. It might be doing this because the base case is never met (and therefore it gets stuck in an infinite loop) or just by making an large number of calls to itself. You could replace the recursive calls with while loops.

Index all *except* one item in python

Note that if variable is list of lists, some approaches would fail. For example:

v1 = [[range(3)] for x in range(4)]
v2 = v1[:3]+v1[4:] # this fails
v2

For the general case, use

removed_index = 1
v1 = [[range(3)] for x in range(4)]
v2 = [x for i,x in enumerate(v1) if x!=removed_index]
v2

How do I programmatically set device orientation in iOS 7?

I was in a similar problem than you. I need to lock device orientation for some screens (like Login) and allow rotation in others.

After a few changes and following some answers below I did it by:

  • Enabling all the orientations in the Project's Info.plist.

enter image description here

  • Disabling orientation in those ViewControllers where I need the device not to rotate, like in the Login screen in my case. I needed to override shouldAutorotate method in this VC:

-(BOOL)shouldAutorotate{ return NO; }

Hope this will work for you.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

A different case in which I encountered this was when I was using echo to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:

echo "{"thumbnailWidth": 640}" | myscript.py

Note that the JSON string itself has quotes and I should have done:

echo '{"thumbnailWidth": 640}' | myscript.py

As it was, this is what the python script received: {thumbnailWidth: 640}; the double quotes were effectively stripped.

PHP - Check if two arrays are equal

!=== will not work because it's a syntax error. The correct way is !== (not three "equal to" symbols)

byte array to pdf

Usually this happens if something is wrong with the byte array.

File.WriteAllBytes("filename.PDF", Byte[]);

This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

Asynchronous implementation of this is also available.

public static System.Threading.Tasks.Task WriteAllBytesAsync 
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

Java Date - Insert into database

You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

You need MouseClick instead of Click event handler, reference.

switch (e.Button) {

    case MouseButtons.Left:
    // Left click
    break;

    case MouseButtons.Right:
    // Right click
    break;
    ...
}

How to get a list of installed android applications and pick one to run

Get All the apps:

    PackageManager pm = getContext().getPackageManager();
    List<ApplicationInfo> apps = pm.getInstalledApplications(0);

Check if installed app then open:

if((app.flags & (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP | ApplicationInfo.FLAG_SYSTEM)) > 0) {
                String app_package = app.packageName;
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(app_package);
context.startActivity(launchIntent);

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)

@ModelType System.Web.Mvc.HandleErrorInfo

    @Code
        ViewData("Title") = "Error"
        Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
        //To log error with Elmah
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
    End Code

<h2>
    Sorry, an error occurred while processing your request.<br />

    @item.ActionName<br />
    @item.ControllerName<br />
    @item.Exception.Message
</h2> 

It is simply!

How do I count unique values inside a list

In addition, use collections.Counter to refactor your code:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b']
[2, 1, 1]

Deploying just HTML, CSS webpage to Tomcat

Here's my step in Ubuntu 16.04 and Tomcat 8.

  1. Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.

    cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}

  2. Add your html, css, js, to your folder.

  3. Open "http://localhost:8080/{yourfolder}" in browser

Notes:

  1. If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.

  2. The folder META-INF with context.xml is needed.

SQL: Insert all records from one table to another table without specific the columns

Use this

SELECT *
INTO new_table_name
FROM current_table_name

Mocking member variables of a class using Mockito

If you can't change the member variable, then the other way around this is to use powerMockit and call

Second second = mock(Second.class)
when(second.doSecond()).thenReturn("Stubbed Second");
whenNew(Second.class).withAnyArguments.thenReturn(second);

Now the problem is that ANY call to new Second will return the same mocked instance. But in your simple case this will work.

What is the difference between a heuristic and an algorithm?

A heuristic is usually an optimization or a strategy that usually provides a good enough answer, but not always and rarely the best answer. For example, if you were to solve the traveling salesman problem with brute force, discarding a partial solution once its cost exceeds that of the current best solution is a heuristic: sometimes it helps, other times it doesn't, and it definitely doesn't improve the theoretical (big-oh notation) run time of the algorithm

add item to dropdown list in html using javascript

i think you have only defined the function. you are not triggering it anywhere.

please do

window.onload = addList();

or trigger it on some other event

after its definition

see this fiddle

HTML Table different number of columns in different rows

Colspan:

<table>
   <tr>
      <td> Row 1 Col 1</td>
      <td> Row 1 Col 2</td>
</tr>
<tr>
      <td colspan=2> Row 2 Long Col</td>
</tr>
</table>

Call to undefined function mysql_query() with Login

You are mixing the deprecated mysql extension with mysqli.

Try something like:

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

Maximum execution time in phpMyadmin

Your change should work. However, there are potentially few php.ini configuration files with the 'xampp' stack. Try to identify whether or not there's an 'apache' specific php.ini. One potential location is:

C:\xampp\apache\bin\php.ini

Copying text outside of Vim with set mouse=a enabled

You can use :set mouse& in the vim command line to enable copy/paste of text selected using the mouse. You can then simply use the middle mouse button or shiftinsert to paste it.

How to use LINQ Distinct() with multiple fields

Distinct method returns distinct elements from a sequence.

If you take a look on its implementation with Reflector, you'll see that it creates DistinctIterator for your anonymous type. Distinct iterator adds elements to Set when enumerating over collection. This enumerator skips all elements which are already in Set. Set uses GetHashCode and Equals methods for defining if element already exists in Set.

How GetHashCode and Equals implemented for anonymous type? As it stated on msdn:

Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

So, you definitely should have distinct anonymous objects, when iterating on distinct collection. And result does not depend on how many fields you use for your anonymous type.

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

As everyone else has said, there isn't one in html; however, you could use PUG/Jade. In fact I do this often.

It would look something like this:

select
  - var i = 1
  while i <= 100
    option=i++

This would produce: screenshot of htmltojade.org

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Ajax forms work asynchronously using Javascript. So it is required, to load the script files for execution. Even though it's a small performance compromise, the execution happens without postback.

We need to understand the difference between the behaviours of both Html and Ajax forms.

Ajax:

  1. Won't redirect the form, even you do a RedirectAction().

  2. Will perform save, update and any modification operations asynchronously.

Html:

  1. Will redirect the form.

  2. Will perform operations both Synchronously and Asynchronously (With some extra code and care).

Demonstrated the differences with a POC in below link. Link

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Regex: Remove lines containing "help", etc

If you're on Windows, try findstr. Third-party tools are not needed:

findstr /V /L "searchstring" inputfile.txt > outputfile.txt

It supports regex's too! Just read the tool's help findstr /?.

P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...

I just ran this on a 1 GB log file, and it literally took 3 seconds.

Original purpose of <input type="hidden">?

I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.

Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.

This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):

type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".

<input type=hidden name=customerid value="c2415-345-8563">

While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.

Convert string to JSON Object

Without eval:

Your original string was not an actual string.

jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

The easiest way to to wrap it all with a single quote.

 jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'

Then you can combine two steps to parse it to JSON:

 $.parseJSON(jsonObj.slice(1,-1))

Passing ArrayList from servlet to JSP

here list attribute name set in request request.setAttribute("List",list); and ArrayList list=new ArrayList();

<%

ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List");

out.print(a);

for(int i=0;i<a.size();i++)

{
    out.println(a.get(i));

}


%>

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

Cannot edit in read-only editor VS Code

Click on the file and hover on Preferences. there you will find the first option as Settings and click on that. There search run code. and scroll and find the option code runner: Run in Terminal. now check the option below it

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have posted a similar solution for the same problem,

visit How to use javascript to set attribute of selected web element using selenium Webdriver using java?

Here First we have find the element in my case I have found the element using xpath then we have traverse through the list of elements and then We have cast the driver object to the Executor object and create a script here the first argument is the element and second argument is the property and the third argument is the new value

List<WebElement> unselectableDiv = driver
                .findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));

        for (WebElement element : unselectableDiv) {

            // System.out.println( "**** Checking the size of div "+unselectableDiv.size());

            JavascriptExecutor js = (JavascriptExecutor) driver;

            String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";

            js.executeScript(scriptSetAttr, element, "unselectable", "off");

            System.out.println(" *****   check value of Div property " + element.getAttribute("unselectable"));

        }

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

change

public static final String URL = "http://api-Location";

to

public static final String URL = "https://api-Location"

it's happen because i'm using 000webhostapp app

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:

float distance = (float) loc.distanceTo(loc2);

Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?

Bootstrap 4 - Inline List?

Bootstrap4

Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.

<ul class="list-inline">
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>

Where does the iPhone Simulator store its data?

You can try using the below code

NSString *fileName = @"Demo.pdf";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSLog(@"File path%@",pdfFileName);

What is the difference between Cygwin and MinGW?

Wikipedia does a comparison here.

From Cygwin's website:

  • Cygwin is a Linux-like environment for Windows. It consists of two parts: A DLL (cygwin1.dll) which acts as a Linux API emulation layer providing substantial Linux API functionality.
  • A collection of tools which provide Linux look and feel.

From Mingw's website:

MinGW ("Minimalistic GNU for Windows") is a collection of freely available and freely distributable Windows specific header files and import libraries combined with GNU toolsets that allow one to produce native Windows programs that do not rely on any 3rd-party C runtime DLLs

Performing user authentication in Java EE / JSF using j_security_check

It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.

HTML - how can I show tooltip ONLY when ellipsis is activated

This was my solution, works as a charm!

    $(document).on('mouseover', 'input, span', function() {
      var needEllipsis = $(this).css('text-overflow') && (this.offsetWidth < this.scrollWidth);
      var hasNotTitleAttr = typeof $(this).attr('title') === 'undefined';
      if (needEllipsis === true) {
          if(hasNotTitleAttr === true){
            $(this).attr('title', $(this).val());
          }
      }
      if(needEllipsis === false && hasNotTitleAttr == false){
        $(this).removeAttr('title');
      }
  });

mysql - move rows from one table to another

To move and delete specific records by selecting using WHERE query,

BEGIN TRANSACTION;
Insert Into A SELECT * FROM B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count=""  And contact_person= "" limit 0,2000;
delete from B where Id In (select Id from B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000);
commit;

MySQL Error 1215: Cannot add foreign key constraint

I had the same problem.
I solved it doing this:

I created the following line in the
primary key: (id int(11) unsigned NOT NULL AUTO_INCREMENT)

I found out this solution after trying to import a table in my schema builder. If it works for you, let me know!

Good luck!

Felipe Tércio

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Convert a date format in PHP

date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));

MVC 4 client side validation not working

  @section Scripts
 {
<script src="../Scripts/jquery.validate-vsdoc.js"></script>
<script src="../Scripts/jquery.validate.js"></script>
<script src="../Scripts/jquery.validate.min.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.min.js"></script>
}

Output in a table format in Java's System.out

Using j-text-utils you may print to console a table like: enter image description here

And it as simple as:

TextTable tt = new TextTable(columnNames, data);                                                         
tt.printTable();   

The API also allows sorting and row numbering ...

How does Spring autowire by name when more than one matching bean is found?

Another way of achieving the same result is to use the @Value annotation:

public class Main {
     private Country country;

     @Autowired
     public void setCountry(@Value("#{country}") Country country) {
          this.country = country;
     }
}

In this case, the "#{country} string is an Spring Expression Language (SpEL) expression which evaluates to a bean named country.

JAX-WS and BASIC authentication, when user names and passwords are in a database

If you put the username and password at clientside into the request this way:

URL url = new URL("http://localhost:8080/myapplication?wsdl");
MyWebService webservice = new MyWebServiceImplService(url).getMyWebServiceImplPort();
Map<String, Object> requestContext = ((BindingProvider) webservice).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "myusername");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "mypassword");

and call your webservice

String response = webservice.someMethodAtMyWebservice("test");

Then you can read the Basic Authentication string like this at the server side (you have to add some checks and do some exceptionhandling):

@Resource
WebServiceContext webserviceContext;

public void someMethodAtMyWebservice(String parameter) {
    MessageContext messageContext = webserviceContext.getMessageContext();
    Map<String, ?> httpRequestHeaders = (Map<String, ?>) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
    List<?> authorizationList = (List<?>) httpRequestHeaders.get("Authorization");
    if (authorizationList != null && !authorizationList.isEmpty()) {
        String basicString = (String) authorizationList.get(0);
        String encodedBasicString = basicString.substring("Basic ".length());
        String decoded = new String(Base64.getDecoder().decode(encodedBasicString), StandardCharsets.UTF_8);
        String[] splitter = decoded.split(":");
        String usernameFromBasicAuth = splitter[0];
        String passwordFromBasicAuth = splitter[1];
    }

Calling Oracle stored procedure from C#?

It's basically the same mechanism as for a non query command with:

  • command.CommandText = the name of the stored procedure
  • command.CommandType = CommandType.StoredProcedure
  • As many calls to command.Parameters.Add as the number of parameters the sp requires
  • command.ExecuteNonQuery

There are plenty of examples out there, the first one returned by Google is this one

There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection

How to stop the Timer in android?

I had a similar problem and it was caused by the placement of the Timer initialisation.

It was placed in a method that was invoked oftener.

Try this:

Timer waitTimer;

  void exampleMethod() {

   if (waitTimer == null ) {
    //initialize your Timer here
    ...
   }

The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.

socket connect() vs bind()

bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)

Excel: last character/string match in a string

A simple way to do that in VBA is:

YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))

How to connect to remote Oracle DB with PL/SQL Developer?

Username : username
Password : password
Database : //123.45.67.89:1521/TEST
Connect as : Normal

this work for me and (version 13.0.6.1911 64 bit)

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I hope this helps somebody else. I was suffering with this while working on a project a few years ago and then a job in a newer project started failing a few days ago. I found this post and was trying to recollect what I had modified in my project and then I remembered that I had changed my maven pom and removed the entry for maven-jar-plugin. When you build a jar whose purpose is to be executable, you need to include this so that certain entries get written into the manifest. I opened the old project, copied that entry (with some modifications for project name) and it worked.

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

matplotlib does not show my drawings although I call pyplot.show()

What solved my problem was just using the below two lines in ipython notebook at the top

%matplotib inline
%pylab inline

And it worked. I'm using Ubuntu16.04 and ipython-5.1

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

How do you do exponentiation in C?

or you could just write the power function, with recursion as a added bonus

int power(int x, int y){
      if(y == 0)
        return 1;
     return (x * power(x,y-1) );
    }

yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!

json_encode(): Invalid UTF-8 sequence in argument

Using this code might help. It solved my problem!

mb_convert_encoding($post["post"],'UTF-8','UTF-8');

or like that

mb_convert_encoding($string,'UTF-8','UTF-8');

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

How to parse JSON array in jQuery?

Using .NET 3.5 FIX

All of you are slightly wrong, but the combination of all of your efforts has paid off!

Instead of eval('([' + jsonData + '])'); do

success: function(msg){
var data = eval(msg.d);
var i=0;
for(i=0;i<data.length;i++){
    data[i].parametername /// do whatever you want here.
};

I don't know anything about the whole "don't use eval," but what I do know is that by doing the '([' + msg + '])' you are nesting those objects deeper, instead of up a level.

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

npm install errors with Error: ENOENT, chmod

I think your compiled coffee script is missing from the published npm package. Try writing a prepublish command.

How to make/get a multi size .ico file?

Visual Studio Resource Editor (free as VS 2013 Community edition) can import PNG (and other formats) and export ICO.

Working Soap client example

The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.

public class SOAPClientSAAJ {

public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);



    SOAPPart soapPart=soapResponse.getSOAPPart();
    // SOAP Envelope
    SOAPEnvelope envelope=soapPart.getEnvelope();
    SOAPBody soapBody = envelope.getBody();

    @SuppressWarnings("unchecked")
    Iterator<Node> itr=soapBody.getChildElements();
    while (itr.hasNext()) {

        Node node=(Node)itr.next();
        if (node.getNodeType()==Node.ELEMENT_NODE) {
            System.out.println("reading Node.ELEMENT_NODE");
            Element ele=(Element)node;
            System.out.println("Body childs : "+ele.getLocalName());

            switch (ele.getNodeName()) {

          case "VerifyEmailResponse":
             NodeList statusNodeList = ele.getChildNodes();

             for(int i=0;i<statusNodeList.getLength();i++){
               Element emailResult = (Element) statusNodeList.item(i);
               System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
                switch (emailResult.getNodeName()) {

                case "VerifyEmailResult":
                    NodeList emailResultList = emailResult.getChildNodes();

                    for(int j=0;j<emailResultList.getLength();j++){
                      Element emailResponse = (Element) emailResultList.item(j);
                      System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
                       switch (emailResponse.getNodeName()) {
                       case "ResponseText":
                           System.out.println(emailResponse.getTextContent());
                           break;
                        case "ResponseCode":
                          System.out.println(emailResponse.getTextContent());
                           break;
                        case "LastMailServer":
                          System.out.println(emailResponse.getTextContent());
                          break;
                        case "GoodEmail":
                          System.out.println(emailResponse.getTextContent());
                       default:
                          break;
                       }
                    }
                    break;
                default:
                   break;
                }
             }


             break;


          default:
             break;
          }

        } else if (node.getNodeType()==Node.TEXT_NODE) {
            System.out.println("reading Node.TEXT_NODE");
            //do nothing here most likely, as the response nearly never has mixed content type
            //this is just for your reference
        }
    }
    // print SOAP Response
    System.out.println("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println("");
    System.out.println("------");

    return soapMessage;
}

}

What is the simplest way to get indented XML with line breaks from XmlDocument?

As adapted from Erika Ehrli's blog, this should do it:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

How can I make my match non greedy in vim?

If you're more comfortable PCRE regex syntax, which

  1. supports the non-greedy operator ?, as you asked in OP; and
  2. doesn't require backwhacking grouping and cardinality operators (an utterly counterintuitive vim syntax requirement since you're not matching literal characters but specifying operators); and
  3. you have [g]vim compiled with perl feature, test using

    :ver and inspect features; if +perl is there you're good to go)

try search/replace using

:perldo s///

Example. Swap src and alt attributes in img tag:

<p class="logo"><a href="/"><img src="/caminoglobal_en/includes/themes/camino/images/header_logo.png" alt=""></a></p>

:perldo s/(src=".*?")\s+(alt=".*?")/$2 $1/

<p class="logo"><a href="/"><img alt="" src="/caminoglobal_en/includes/themes/camino/images/header_logo.png"></a></p>

How to convert UTF-8 byte[] to string?

Using (byte)b.ToString("x2"), Outputs b4b5dfe475e58b67

public static class Ext {

    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex) {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }

    public static byte[] ToHexBytes(this string hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return new byte[0];

        int l = hex.Length / 2;
        var b = new byte[l];
        for (int i = 0; i < l; ++i) {
            b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return b;
    }

    public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
    {
        if (bytes == null && bytesToCompare == null) return true; // ?
        if (bytes == null || bytesToCompare == null) return false;
        if (object.ReferenceEquals(bytes, bytesToCompare)) return true;

        if (bytes.Length != bytesToCompare.Length) return false;

        for (int i = 0; i < bytes.Length; ++i) {
            if (bytes[i] != bytesToCompare[i]) return false;
        }
        return true;
    }

}

Is it possible to find out the users who have checked out my project on GitHub?

If by "checked out" you mean people who have cloned your project, then no it is not possible. You don't even need to be a GitHub user to clone a repository, so it would be infeasible to track this.

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

How do I auto size a UIScrollView to fit its content

Because a scrollView can have other scrollViews or different inDepth subViews tree, run in depth recursively is preferable. enter image description here

Swift 2

extension UIScrollView {
    //it will block the mainThread
    func recalculateVerticalContentSize_synchronous () {
        let unionCalculatedTotalRect = recursiveUnionInDepthFor(self)
        self.contentSize = CGRectMake(0, 0, self.frame.width, unionCalculatedTotalRect.height).size;
    }

    private func recursiveUnionInDepthFor (view: UIView) -> CGRect {
        var totalRect = CGRectZero
        //calculate recursevly for every subView
        for subView in view.subviews {
            totalRect =  CGRectUnion(totalRect, recursiveUnionInDepthFor(subView))
        }
        //return the totalCalculated for all in depth subViews.
        return CGRectUnion(totalRect, view.frame)
    }
}

Usage

scrollView.recalculateVerticalContentSize_synchronous()

How to load external webpage in WebView

I used this code that was cool. but have an error. " neterr_cleartext_not_permitted" show when you use this code then you will face this problem..

I got a solution of this.you have to add this in your AndroidManifest.xml near about Application

android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" /> // ignore if you already added. outside of Application.

How can I prevent a window from being resized with tkinter?

Traceback (most recent call last):
  File "tkwindowwithlabel5.py", line 23, in <module>
    main()
  File "tkwindowwithlabel5.py", line 16, in main
    window.resizeable(width = True, height =True)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1935, in                
  __getattr__
    return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'resizeable'

is what you will get with the first answer. tk does support min and max size

window.minsize(width = X, height = x)
window.maxsize(width = X, height = x)

i figured it out but just trying the first one. using python3 with tk.

Error:(23, 17) Failed to resolve: junit:junit:4.12

If none of these answers for you, try clearing the Android Studio cache/restart. That was the only thing that worked for me:

From the file menu option, I selected "invalidate caches/restart".

https://teamtreehouse.com/community/gradle-project-sync-failed-7

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
{
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");
}

How to square or raise to a power (elementwise) a 2D numpy array?

>>> import numpy
>>> print numpy.power.__doc__

power(x1, x2[, out])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in
`x2`.  `x1` and `x2` must be broadcastable to the same shape.

Parameters
----------
x1 : array_like
    The bases.
x2 : array_like
    The exponents.

Returns
-------
y : ndarray
    The bases in `x1` raised to the exponents in `x2`.

Examples
--------
Cube each element in a list.

>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

Raise the bases to different exponents.

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])
>>>

Precision

As per the discussed observation on numerical precision as per @GarethRees objection in comments:

>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)

>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677

>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241

Performance

>>> c    = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )

>>> import zmq
>>> aClk = zmq.Stopwatch()

>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L)                #   5 663 [usec]

>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L)                #   6 395 [usec]

>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L)                #   6 930 [usec]

>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L)                #   6 285 [usec]

>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L)             # 384 515 [usec]

How to deep watch an array in angularjs?

Here is a comparison of the 3 ways you can watch a scope variable with examples:

$watch() is triggered by:

$scope.myArray = [];
$scope.myArray = null;
$scope.myArray = someOtherArray;

$watchCollection() is triggered by everything above AND:

$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value

$watch(..., true) is triggered by EVERYTHING above AND:

$scope.myArray[0].someProperty = "someValue";

JUST ONE MORE THING...

$watch() is the only one that triggers when an array is replaced with another array even if that other array has the same exact content.

For example where $watch() would fire and $watchCollection() would not:

$scope.myArray = ["Apples", "Bananas", "Orange" ];

var newArray = [];
newArray.push("Apples");
newArray.push("Bananas");
newArray.push("Orange");

$scope.myArray = newArray;

Below is a link to an example JSFiddle that uses all the different watch combinations and outputs log messages to indicate which "watches" were triggered:

http://jsfiddle.net/luisperezphd/2zj9k872/

How to escape apostrophe (') in MySql?

Here's an example:

SELECT * FROM pubs WHERE name LIKE "%John's%"

Just use double quotes to enclose the single quote.

If you insist in using single quotes (and the need to escape the character):

SELECT * FROM pubs WHERE name LIKE '%John\'s%'

Algorithm to compare two images

This is just a suggestion, it might not work and I'm prepared to be called on this.

This will generate false positives, but hopefully not false negatives.

  1. Resize both of the images so that they are the same size (I assume that the ratios of widths to lengths are the same in both images).

  2. Compress a bitmap of both images with a lossless compression algorithm (e.g. gzip).

  3. Find pairs of files that have similar file sizes. For instance, you could just sort every pair of files you have by how similar the file sizes are and retrieve the top X.

As I said, this will definitely generate false positives, but hopefully not false negatives. You can implement this in five minutes, whereas the Porikil et. al. would probably require extensive work.

Early exit from function?

if you are looking for a script to avoid submitting form when some errors found, this method should work

function verifyData(){
     if (document.MyForm.FormInput.value.length == "") {
          alert("Write something!");
     }
     else {
          document.MyForm.submit();
     }
}

change the Submit Button type to "button"

<input value="Save" type="button" onClick="verifyData()">

hope this help.

Class has no initializers Swift

Not a specific answer to your question but I had got this error when I hadn't set an initial value for an enum while declaring it as a property. I assigned a initial value to the enum to resolve this error. Posting here as it might help someone.

How to make rectangular image appear circular with CSS

Building on the answer from @fzzle - to achieve a circle from a rectangle without defining a fixed height or width, the following will work. The padding-top:100% keeps a 1:1 ratio for the circle-cropper div. Set an inline background image, center it, and use background-size:cover to hide any excess.

CSS

.circle-cropper {
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50%;
  border-radius: 50%;
  width: 100%;
  padding-top: 100%;
}

HTML

<div class="circle-cropper" role="img" style="background-image:url(myrectangle.jpg);"></div>

Android 6.0 Marshmallow. Cannot write to SD Card

Right. So I've finally got to the bottom of the problem: it was a botched in-place OTA upgrade.

My suspicions intensified after my Garmin Fenix 2 wasn't able to connect via bluetooth and after googling "Marshmallow upgrade issues". Anyway, a "Factory reset" fixed the issue.

Surprisingly, the reset did not return the phone to the original Kitkat; instead, the wipe process picked up the OTA downloaded 6.0 upgrade package and ran with it, resulting (I guess) in a "cleaner" upgrade.

Of course, this meant that the phone lost all the apps that I'd installed. But, freshly installed apps, including mine, work without any changes (i.e. there is backward compatibility). Whew!

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master

How can I include all JavaScript files in a directory via JavaScript file?

It can be done fully client side, but all javascript file names must be specified. For example, as array items:

function loadScripts(){
   var directory = 'script/';
   var extension = '.js';
   var files = ['model', 'view', 'controller'];  
   for (var file of files){ 
       var path = directory + file + extension; 
       var script = document.createElement("script");
       script.src = path;
       document.body.appendChild(script);
   } 
 }

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

For cv::Mat_<T> mat just use mat(row, col)

Accessing elements of a matrix with specified type cv::Mat_< _Tp > is more comfortable, as you can skip the template specification. This is pointed out in the documentation as well.

code:

cv::Mat1d mat0 = cv::Mat1d::zeros(3, 4);
std::cout << "mat0:\n" << mat0 << std::endl;
std::cout << "element: " << mat0(2, 0) << std::endl;
std::cout << std::endl;

cv::Mat1d mat1 = (cv::Mat1d(3, 4) <<
    1, NAN, 10.5, NAN,
    NAN, -99, .5, NAN,
    -70, NAN, -2, NAN);
std::cout << "mat1:\n" << mat1 << std::endl;
std::cout << "element: " << mat1(0, 2) << std::endl;
std::cout << std::endl;

cv::Mat mat2 = cv::Mat(3, 4, CV_32F, 0.0);
std::cout << "mat2:\n" << mat2 << std::endl;
std::cout << "element: " << mat2.at<float>(2, 0) << std::endl;
std::cout << std::endl;

output:

mat0:
[0, 0, 0, 0;
 0, 0, 0, 0;
 0, 0, 0, 0]
element: 0

mat1:
[1, nan, 10.5, nan;
 nan, -99, 0.5, nan;
 -70, nan, -2, nan]
element: 10.5

mat2:
[0, 0, 0, 0;
 0, 0, 0, 0;
 0, 0, 0, 0]
element: 0

How can I inspect the file system of a failed `docker build`?

The top answer works in the case that you want to examine the state immediately prior to the failed command.

However, the question asks how to examine the state of the failed container itself. In my situation, the failed command is a build that takes several hours, so rewinding prior to the failed command and running it again takes a long time and is not very helpful.

The solution here is to find the container that failed:

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                          PORTS               NAMES
6934ada98de6        42e0228751b3        "/bin/sh -c './utils/"   24 minutes ago      Exited (1) About a minute ago                       sleepy_bell

Commit it to an image:

$ docker commit 6934ada98de6
sha256:7015687976a478e0e94b60fa496d319cdf4ec847bcd612aecf869a72336e6b83

And then run the image [if necessary, running bash]:

$ docker run -it 7015687976a4 [bash -il]

Now you are actually looking at the state of the build at the time that it failed, instead of at the time before running the command that caused the failure.

How to get difference between two dates in Year/Month/Week/Day?

Days: (endDate - startDate).Days
Weeks: (endDate - startDate).Days / 7
Years: Months / 12
Months: A TimeSpan only provides Days, so use the following code to get the number of whole months between a specified start and end date. For example, the number of whole months between 01/10/2000 and 02/10/2000 is 1. The the number of whole months between 01/10/2000 and 02/09/2000 is 0.

    public int getMonths(DateTime startDate, DateTime endDate)
    {
        int months = 0;

        if (endDate.Month <= startDate.Month)
        {
            if (endDate.Day < startDate.Day)
            {
                months = (12 * (endDate.Year - startDate.Year - 1))
                       + (12 - startDate.Month + endDate.Month - 1);
            }
            else if (endDate.Month < startDate.Month)
            {
                months = (12 * (endDate.Year - startDate.Year - 1))
                       + (12 - startDate.Month + endDate.Month);
            }
            else  // (endDate.Month == startDate.Month) && (endDate.Day >= startDate.Day)
            {
                months = (12 * (endDate.Year - startDate.Year));
            }
        }
        else if (endDate.Day < startDate.Day)
        {
            months = (12 * (endDate.Year - startDate.Year))
                   + (endDate.Month - startDate.Month) - 1;
        }
        else  // (endDate.Month > startDate.Month) && (endDate.Day >= startDate.Day)
        {
            months = (12 * (endDate.Year - startDate.Year))
                   + (endDate.Month - startDate.Month);
        }

        return months;
    }

Finding all possible combinations of numbers to reach a given sum

import java.util.*;

public class Main{

     int recursionDepth = 0;
     private int[][] memo;

     public static void main(String []args){
         int[] nums = new int[] {5,2,4,3,1};
         int N = nums.length;
         Main main =  new Main();
         main.memo = new int[N+1][N+1];
         main._findCombo(0, N-1,nums, 8, 0, new LinkedList() );
         System.out.println(main.recursionDepth);
     }


       private void _findCombo(
           int from,
           int to,
           int[] nums,
           int targetSum,
           int currentSum,
           LinkedList<Integer> list){

            if(memo[from][to] != 0) {
                currentSum = currentSum + memo[from][to];
            }

            if(currentSum > targetSum) {
                return;
            }

            if(currentSum ==  targetSum) {
                System.out.println("Found - " +list);
                return;
            }

            recursionDepth++;

           for(int i= from ; i <= to; i++){
               list.add(nums[i]);
               memo[from][i] = currentSum + nums[i];
               _findCombo(i+1, to,nums, targetSum, memo[from][i], list);
                list.removeLast();
           }

     }
}

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

Force drop mysql bypassing foreign key constraint

You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -enter image description here

How to convert SQL Query result to PANDAS Data Structure?

resoverall is a sqlalchemy ResultProxy object. You can read more about it in the sqlalchemy docs, the latter explains basic usage of working with Engines and Connections. Important here is that resoverall is dict like.

Pandas likes dict like objects to create its data structures, see the online docs

Good luck with sqlalchemy and pandas.

return, return None, and no return at all?

In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)

Syntax for a single-line Bash infinite while loop

For simple process watching use watch instead

Convert a matrix to a 1 dimensional array

try c()

x = matrix(1:9, ncol = 3)

x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

c(x)

[1] 1 2 3 4 5 6 7 8 9

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

How to use sed to replace only the first occurrence in a file?

A possible solution here might be to tell the compiler to include the header without it being mentioned in the source files. IN GCC there are these options:

   -include file
       Process file as if "#include "file"" appeared as the first line of
       the primary source file.  However, the first directory searched for
       file is the preprocessor's working directory instead of the
       directory containing the main source file.  If not found there, it
       is searched for in the remainder of the "#include "..."" search
       chain as normal.

       If multiple -include options are given, the files are included in
       the order they appear on the command line.

   -imacros file
       Exactly like -include, except that any output produced by scanning
       file is thrown away.  Macros it defines remain defined.  This
       allows you to acquire all the macros from a header without also
       processing its declarations.

       All files specified by -imacros are processed before all files
       specified by -include.

Microsoft's compiler has the /FI (forced include) option.

This feature can be handy for some common header, like platform configuration. The Linux kernel's Makefile uses -include for this.

Emulate a 403 error page

Refresh the page after sending the 403:

<?php 
header('HTTP/1.0 403 Forbidden');
?>
<html><head>
<meta http-equiv="refresh" content="0;URL=http://my.error.page">
</head><body></body></html>

How to get all table names from a database?

@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{ 

    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
    DatabaseMetaData md = con.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
    List<String> tables = new ArrayList<String>();
    String db = "";
    while (rs.next()) {
        tables.add(rs.getString(3));
        db = rs.getString(1);
    }
    List<String> database = new ArrayList<String>();
    database.add(db);
    databaseTables.put("database", database);
    Collections.reverse(tables);
    databaseTables.put("tables", tables);
    return new ObjectMapper().writeValueAsString(databaseTables);
}

@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{ 
    System.out.println("...tablename......"+tablename);
    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();       
     Statement st = con.createStatement();
     String sql = "select * from "+tablename;
     ResultSet rs = st.executeQuery(sql);
     ResultSetMetaData metaData = rs.getMetaData();
     int rowCount = metaData.getColumnCount();    
     List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
     HashMap<String,String> columnDetails = new HashMap<String,String>();
     for (int i = 0; i < rowCount; i++) {
         columnDetails = new HashMap<String,String>();
         Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
         method.setAccessible(true);
         com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
         columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
         columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
         columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
         columnDetails.put("columnColl", field.getCollation());
         columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
         if (field.isPrimaryKey()) {
             columnDetails.put("columnKEY", "PRI");
         } else if(field.isMultipleKey()) {
             columnDetails.put("columnKEY", "MUL");
         } else if(field.isUniqueKey()) {
             columnDetails.put("columnKEY", "UNI");
         } else {
             columnDetails.put("columnKEY", "");
         }
         columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
         databaseColumns.add(columnDetails);
     }
    HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
    Collections.reverse(databaseColumns);
    tableColumns.put("columns", databaseColumns);
    return new ObjectMapper().writeValueAsString(tableColumns);
}

How do you render primitives as wireframes in OpenGL?

use this function: void glPolygonMode( GLenum face, GLenum mode);

face : Specifies the polygons that mode applies to. can be GL_FRONT for front side of the polygone and GL_BACK for his back and GL_FRONT_AND_BACK for both.

mode : Three modes are defined and can be specified in mode:

GL_POINT :Polygon vertices that are marked as the start of a boundary edge are drawn as points.

GL_LINE : Boundary edges of the polygon are drawn as line segments. (your target)

GL_FILL : The interior of the polygon is filled.

P.S : glPolygonMode controls the interpretation of polygons for rasterization in the graphics pipeline.

for more information look at the OpenGL reference pages in khronos group : https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glPolygonMode.xhtml

Unable to import a module that is definitely installed

I had colorama installed via pip and I was getting "ImportError: No module named colorama"

So I searched with "find", found the absolute path and added it in the script like this:

import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama 

And it worked.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

How to set data attributes in HTML elements

Vanilla Javascript solution

HTML

<div id="mydiv" data-myval="10"></div>

JavaScript:

  • Using DOM's getAttribute() property

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • Using JavaScript's dataset property

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    

Sort a list of tuples by 2nd item (integer value)

For an in-place sort, use

foo = [(list of tuples)]
foo.sort(key=lambda x:x[0]) #To sort by first element of the tuple

Callback to a Fragment from a DialogFragment

Activity involved is completely unaware of the DialogFragment.

Fragment class:

public class MyFragment extends Fragment {
int mStackLevel = 0;
public static final int DIALOG_FRAGMENT = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        mStackLevel = savedInstanceState.getInt("level");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("level", mStackLevel);
}

void showDialog(int type) {

    mStackLevel++;

    FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
    Fragment prev = getActivity().getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    switch (type) {

        case DIALOG_FRAGMENT:

            DialogFragment dialogFrag = MyDialogFragment.newInstance(123);
            dialogFrag.setTargetFragment(this, DIALOG_FRAGMENT);
            dialogFrag.show(getFragmentManager().beginTransaction(), "dialog");

            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case DIALOG_FRAGMENT:

                if (resultCode == Activity.RESULT_OK) {
                    // After Ok code.
                } else if (resultCode == Activity.RESULT_CANCELED){
                    // After Cancel code.
                }

                break;
        }
    }
}

}

DialogFragment class:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(int num){

    MyDialogFragment dialogFragment = new MyDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("num", num);
    dialogFragment.setArguments(bundle);

    return dialogFragment;

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.ERROR)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton(R.string.ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                        }
                    }
            )
            .setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                }
            })
            .create();
}
}

Installing NumPy via Anaconda in Windows

I had the same problem, getting the message "ImportError: No module named numpy".

I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:

conda list

So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:

conda install numpy

After I did that, the error with the import numpy was gone

How to wait till the response comes from the $http request, in angularjs?

FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put

myservice.$loaded().then(function() {$rootScope.myservice = myservice;});

and in the view I just did

ng-if="myservice" ng-init="somevar=myfunct()"

in the first/parent view element/wrapper so the controller can run everything inside

myfunct()

without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.

Removing leading zeroes from a field in a SQL statement

I had the same need and used this:

select 
    case 
        when left(column,1) = '0' 
        then right(column, (len(column)-1)) 
        else column 
      end

How to view file history in Git?

I like to use gitk name_of_file

This shows a nice list of the changes that happened to a file at each commit, instead of showing the changes to all the files. Makes it easier to track down something that happened.

What is an example of the Liskov Substitution Principle?

This formulation of the LSP is way too strong:

If for each object o1 of type S there is an object o2 of type T such that for all programs P de?ned in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.

Which basically means that S is another, completely encapsulated implementation of the exact same thing as T. And I could be bold and decide that performance is part of the behavior of P...

So, basically, any use of late-binding violates the LSP. It's the whole point of OO to to obtain a different behavior when we substitute an object of one kind for one of another kind!

The formulation cited by wikipedia is better since the property depends on the context and does not necessarily include the whole behavior of the program.

How to pass the values from one jsp page to another jsp without submit button?

You could do it in either of this ways , triggering an onclick on a form button like this,

<form id="myform" name="myform" method="post" action="demo2.jsp">
    <input type="text"  name="usnername" />
    <input type="text" name="password"/>        
    <input type="button" value="go" onclick="submitForm" />
</form>

And using javascript,

        function submitForm() {                
            document.forms[0].submit();
            return true;
        }

or you could also try Ajax to post your page

here is the link jQueryAjax

And also nice startup examples using Ajax and here

Hope this helps !!

Get day of week in SQL Server 2005/2008

EUROPE:

declare @d datetime;
set @d=getdate();
set @dow=((datepart(dw,@d) + @@DATEFIRST-2) % 7+1);

How to get cookie's expire time

You can set your cookie value containing expiry and get your expiry from cookie value.

// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);

// get
if (isset($_COOKIE["mycookie"])) {
  list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}

// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee

Split Strings into words with multiple word boundary delimiters

First of all, I don't think that your intention is to actually use punctuation as delimiters in the split functions. Your description suggests that you simply want to eliminate punctuation from the resultant strings.

I come across this pretty frequently, and my usual solution doesn't require re.

One-liner lambda function w/ list comprehension:

(requires import string):

split_without_punc = lambda text : [word.strip(string.punctuation) for word in 
    text.split() if word.strip(string.punctuation) != '']

# Call function
split_without_punc("Hey, you -- what are you doing?!")
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']


Function (traditional)

As a traditional function, this is still only two lines with a list comprehension (in addition to import string):

def split_without_punctuation2(text):

    # Split by whitespace
    words = text.split()

    # Strip punctuation from each word
    return [word.strip(ignore) for word in words if word.strip(ignore) != '']

split_without_punctuation2("Hey, you -- what are you doing?!")
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']

It will also naturally leave contractions and hyphenated words intact. You can always use text.replace("-", " ") to turn hyphens into spaces before the split.

General Function w/o Lambda or List Comprehension

For a more general solution (where you can specify the characters to eliminate), and without a list comprehension, you get:

def split_without(text: str, ignore: str) -> list:

    # Split by whitespace
    split_string = text.split()

    # Strip any characters in the ignore string, and ignore empty strings
    words = []
    for word in split_string:
        word = word.strip(ignore)
        if word != '':
            words.append(word)

    return words

# Situation-specific call to general function
import string
final_text = split_without("Hey, you - what are you doing?!", string.punctuation)
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']

Of course, you can always generalize the lambda function to any specified string of characters as well.

How can I change the Y-axis figures into percentages in a barplot?

In principle, you can pass any reformatting function to the labels parameter:

+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %  

Or

+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign 

Reproducible example:

library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))

ggplot(df, aes(x,y)) + 
  geom_point() +
  scale_y_continuous(labels = function(x) paste0(x*100, "%"))

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Check if element exists in jQuery

How do I check if an element exists

if ($("#mydiv").length){  }

If it is 0, it will evaluate to false, anything more than that true.

There is no need for a greater than, less than comparison.

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

Place cursor at the end of text in EditText

You should be able to achieve that with the help of EditText's method setSelection(), see here

Join two sql queries

I would just use a Union

In your second query add the extra column name and add a '' in all the corresponding locations in the other queries

Example

//reverse order to get the column names
select top 10 personId, '' from Telephone//No Column name assigned 
Union 
select top 10 personId, loanId from loan

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

To make it work, instead of ignoring it, you can install the m2e connector for the maven-dependency-plugin:
https://github.com/ianbrandt/m2e-maven-dependency-plugin

Here is how you would do it in Eclipse:

  1. go to Window/Preferences/Maven/Discovery/
  2. enter Catalog URL: http://download.eclipse.org/technology/m2e/discovery/directory-1.4.xml
  3. click Open Catalog
  4. choose the m2e-maven-dependency-plugin
  5. enjoy

What is size_t in C?

This is a platform-specific typedef. For example, on a particular machine, it might be unsigned int or unsigned long. You should use this definition for more portability of your code.

What is the main difference between Collection and Collections in Java?

Collection, as its javadoc says is "The root interface in the collection hierarchy." This means that every single class implementing Collection in any form is part of the Java Collections Framework.

The Collections Framework is Java's native implementation of data structure classes (with implementation specific properties) which represent a group of objects which are somehow related to each other and thus can be called a collection.

Collections is merely an utility method class for doing certain operations, for example adding thread safety to your ArrayList instance by doing this:

List<MyObj> list = Collections.synchronizedList(new Arraylist<MyObj>());

The main difference in my opinion is that Collection is base interface which you may use in your code as a type for object (although I wouldn't directly recommend that) while Collections just provides useful operations for handling the collections.

Find index of last occurrence of a sub-string using T-SQL

If you are using Sqlserver 2005 or above, using REVERSE function many times is detrimental to performance, below code is more efficient.

DECLARE @FilePath VARCHAR(50) = 'My\Super\Long\String\With\Long\Words'
DECLARE @FindChar VARCHAR(1) = '\'

-- Shows text before last slash
SELECT LEFT(@FilePath, LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath))) AS Before
-- Shows text after last slash
SELECT RIGHT(@FilePath, CHARINDEX(@FindChar,REVERSE(@FilePath))-1) AS After
-- Shows the position of the last slash
SELECT LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath)) AS LastOccuredAt

Multiple GitHub Accounts & SSH Config

I used,

Host github.com
   HostName github.com
   IdentityFile ~/.ssh/github_rsa
   User [email protected]

It wokred fine.

Use the above setting in your .ssh/config file for different rsa keys for different usernames.

How to inject window into a service?

With the release of angular 2.0.0-rc.5 NgModule was introduced. The previous solution stopped working for me. This is what I did to fix it:

app.module.ts:

@NgModule({        
  providers: [
    { provide: 'Window',  useValue: window }
  ],
  declarations: [...],
  imports: [...]
})
export class AppModule {}

In some component:

import { Component, Inject } from '@angular/core';

@Component({...})
export class MyComponent {
    constructor (@Inject('Window') window: Window) {}
}

You could also use an OpaqueToken instead of the string 'Window'

Edit:

The AppModule is used to bootstrap your application in main.ts like this:

import { platformBrowserDynamic  } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule)

For more information about NgModule read the Angular 2 documentation: https://angular.io/docs/ts/latest/guide/ngmodule.html

What is an HttpHandler in ASP.NET

In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler interface.

ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

ASP.NET offers a few default HTTP handlers:

  • Page Handler (.aspx): handles Web pages
  • User Control Handler (.ascx): handles Web user control pages
  • Web Service Handler (.asmx): handles Web service pages
  • Trace Handler (trace.axd): handles trace functionality

You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example

  • delivery of dynamically created images (charts for example) or resized pictures.
  • RSS feeds which emit RSS-formated XML

You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property.

The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.

Swift - how to make custom header for UITableView?

If you are using custom cell as header, add the following.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerView = UIView()
        let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
        headerView.addSubview(headerCell)
        return headerView
    }

If you want to have simple view, add the following.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView:UIView =  UIView()
    return headerView
}

How to manually set REFERER header in Javascript?

You can not change the REFERRER property. What you are asking is to spoof the request.

Just in case you want the referrer to be set like you have opened a url directly or for the fist time{http referrer=null} then reload the page

location.reload();

Creating a new empty branch for a new project

The best solution is to create a new branch with --orphan option as shown below

git checkout --orphan <branch name>

By this you will be able to create a new branch and directly checkout to the new branch. It will be a parentless branch.

By default the --orphan option doesn't remove the files in the working directory, so you can delete the working directory files by this:

git rm --cached -r

In details what the --orphan does:

--orphan <new_branch>
Create a new orphan branch, named <new_branch>, started from <start_point> and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

The index and the working tree are adjusted as if you had previously run git checkout <start_point>. This allows you to start a new history that records a set of paths similar to <start_point> by easily running git commit -a to make the root commit.

This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.

If you want to start a disconnected history that records a set of paths that is totally different from the one of <start_point>, then you should clear the index and the working tree right after creating the orphan branch by running git rm -rf . from the top level of the working tree. Afterwards you will be ready to prepare your new files, repopulating the working tree, by copying them from elsewhere, extracting a tarball, etc.

How to run the Python program forever?

for OS's that support select:

import select

# your code

select.select([], [], [])

Tips for debugging .htaccess rewrite rules

If you are working with url, You might want to check if you "Enable Mod Rewrite"

JQUERY: Uncaught Error: Syntax error, unrecognized expression

Try this (ES5)

console.log($("#" +  d));

ES6

console.log($(`#${d}`));

Get DOM content of cross-domain iframe

There is a simple way.

  1. You create an iframe which have for source something like "http://your-domain.com/index.php?url=http://the-site-you-want-to-get.com/unicorn

  2. Then, you just get this url with $_GET and display the contents with file_get_contents($_GET['url']);

You will obtain an iframe which has a domain same than yours, then you will be able to use the $("iframe").contents().find("body") to manipulate the content.

Multiple SQL joins

You can use something like this :

SELECT
    Books.BookTitle,
    Books.Edition,
    Books.Year,
    Books.Pages,
    Books.Rating,
    Categories.Category,
    Publishers.Publisher,
    Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

Extracting text from HTML file using Python

You can use html2text method in the stripogram library also.

from stripogram import html2text
text = html2text(your_html_string)

To install stripogram run sudo easy_install stripogram

Set a default font for whole iOS app?

As @Randall in his answer mentioned iOS 5.0+ UIAppearance proxy can be used to customize the appearance of all instances of a class read more.

UILabel.appearance().font = .systemFont(ofSize: 17, weight: .regular)

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?