Programs & Examples On #Qcompleter

A QCompleter is a class from the Qt toolkit which provides completions based on an item model.

How can I convert a VBScript to an executable (EXE) file?

Here are a couple possible solutions...

I have not tried all of these myself yet, but I will be trying them all soon.

Note: I do not have any personal or financial connection to any of these tools.

1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.

The exe produced appears to be a true EXE.

From their website:

VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:

1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.

This solution should work even if wscript/cscript is not installed on the computer.

Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.


2) Compile and Convert VBS to EXE...:
ExeScript

The current version is 3.5.

This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).

It seems to work in a similar way to the previous solution.

According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"

WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...


3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.

Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.

How to serve .html files with Spring

You can still continue to use the same View resolver but set the suffix to empty.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
    p:prefix="/WEB-INF/jsp/" p:suffix="" />

Now your code can choose to return either index.html or index.jsp as shown in below sample -

@RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
    return "/test.jsp";
}

@RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
    return "/test.html";
}   

How do I set the maximum line length in PyCharm?

For PyCharm 4

File >> Settings >> Editor >> Code Style: Right margin (columns)

suggestion: Take a look at other options in that tab, they're very helpful

Setting the height of a DIV dynamically

inspired by @jason-bunting, same thing for either height or width:

function resizeElementDimension(element, doHeight) {
  dim = (doHeight ? 'Height' : 'Width')
  ref = (doHeight ? 'Top' : 'Left')

  var x = 0;
  var body = window.document.body;
  if(window['inner' + dim])
    x = window['inner' + dim]
  else if (body.parentElement['client' + dim])
    x = body.parentElement['client' + dim]
  else if (body && body['client' + dim])
    x = body['client' + dim]

  element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + "px");
}

Configure DataSource programmatically in Spring Boot

If you want more datesource configs e.g.

spring.datasource.test-while-idle=true 
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1

you could use below code

@Bean
public DataSource dataSource() {
    DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestWhileIdle(testWhileIdle);     
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
    dataSource.setValidationQuery(validationQuery);
    return dataSource;
}

refer: Spring boot jdbc Connection

How to pass command-line arguments to a PowerShell ps1 file

After digging through the PowerShell documentation, I discovered some useful information about this issue. You can't use the $args if you used the param(...) at the beginning of your file; instead you will need to use $PSBoundParameters. I copy/pasted your code into a PowerShell script, and it worked as you'd expect in PowerShell version 2 (I am not sure what version you were on when you ran into this issue).

If you are using $PSBoundParameters (and this ONLY works if you are using param(...) at the beginning of your script), then it is not an array, it is a hash table, so you will need to reference it using the key / value pair.

param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
    $Script:args+= "`$$key=" + $PSBoundParameters["$key"] + "  "
}
write-host $Script:args

And when called with...

PS> ./foo.ps1 a b c d

The result is...

Num Args:  4
$p1=a  $p2=b  $p3=c  $p4=d

Seedable JavaScript random number generator

OK, here's the solution I settled on.

First you create a seed value using the "newseed()" function. Then you pass the seed value to the "srandom()" function. Lastly, the "srandom()" function returns a pseudo random value between 0 and 1.

The crucial bit is that the seed value is stored inside an array. If it were simply an integer or float, the value would get overwritten each time the function were called, since the values of integers, floats, strings and so forth are stored directly in the stack versus just the pointers as in the case of arrays and other objects. Thus, it's possible for the value of the seed to remain persistent.

Finally, it is possible to define the "srandom()" function such that it is a method of the "Math" object, but I'll leave that up to you to figure out. ;)

Good luck!

JavaScript:

// Global variables used for the seeded random functions, below.
var seedobja = 1103515245
var seedobjc = 12345
var seedobjm = 4294967295 //0x100000000

// Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
{
    return [seednum]
}

// Works like Math.random(), except you provide your own seed as the first argument.
function srandom(seedobj)
{
    seedobj[0] = (seedobj[0] * seedobja + seedobjc) % seedobjm
    return seedobj[0] / (seedobjm - 1)
}

// Store some test values in variables.
var my_seed_value = newseed(230951)
var my_random_value_1 = srandom(my_seed_value)
var my_random_value_2 = srandom(my_seed_value)
var my_random_value_3 = srandom(my_seed_value)

// Print the values to console. Replace "WScript.Echo()" with "alert()" if inside a Web browser.
WScript.Echo(my_random_value_1)
WScript.Echo(my_random_value_2)
WScript.Echo(my_random_value_3)

Lua 4 (my personal target environment):

-- Global variables used for the seeded random functions, below.
seedobja = 1103515.245
seedobjc = 12345
seedobjm = 4294967.295 --0x100000000

-- Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
    return {seednum}
end

-- Works like random(), except you provide your own seed as the first argument.
function srandom(seedobj)
    seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
    return seedobj[1] / (seedobjm - 1)
end

-- Store some test values in variables.
my_seed_value = newseed(230951)
my_random_value_1 = srandom(my_seed_value)
my_random_value_2 = srandom(my_seed_value)
my_random_value_3 = srandom(my_seed_value)

-- Print the values to console.
print(my_random_value_1)
print(my_random_value_2)
print(my_random_value_3)

How can I call a function using a function pointer?

This has been more than adequately answered, but you may find this useful: The Function Pointer Tutorials. It is a truly comprehensive treatment of the subject in five chapters!

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

Benefits of using the conditional ?: (ternary) operator

If you need multiple branches on the same condition, use an if:

if (A == 6)
  f(1, 2, 3);
else
  f(4, 5, 6);

If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:

f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );

Also, you can use the ternary operator in initialization.

const int i = (A == 6)? 1 : 4;

Doing that with if is very messy:

int i_temp;
if (A == 6)
   i_temp = 1;
else
   i_temp = 4;
const int i = i_temp;

You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.

Adding options to select with javascript

The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.

var firstSelect = document.getElementById('first select elements id'),
    secondSelect = document.getElementById('second select elements id'),
    optionsHTML = [],
    i = 12;

for (; i < 100; i += 1) {
  optionsHTML.push("<option value=\"Age" + i + "\">Age" + i + "</option>";
}

firstSelect.innerHTML = optionsHTML.join('\n');
secondSelect.innerHTML = optionsHTML.join('\n');

Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

How do you search an amazon s3 bucket?

I tried in the following way

aws s3 ls s3://Bucket1/folder1/2019/ --recursive |grep filename.csv

This outputs the actual path where the file exists

2019-04-05 01:18:35     111111 folder1/2019/03/20/filename.csv

Pythonic way to check if a list is sorted or not

Lazy

from itertools import tee

def is_sorted(l):
    l1, l2 = tee(l)
    next(l2, None)
    return all(a <= b for a, b in zip(l1, l2))

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same error and the problem is that I had not correctly installed Composer.

I am using Windows and I installed Composer-Setup.exe from getcomposer.org and when you have more than one version of PHP installed you must select the version that you are running at this point of the installation

enter image description here

Best way to compare dates in Android

Calendar toDayCalendar = Calendar.getInstance();
Date date1 = toDayCalendar.getTime();


Calendar tomorrowCalendar = Calendar.getInstance();
tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
Date date2 = tomorrowCalendar.getTime();

// date1 is a present date and date2 is tomorrow date

if ( date1.compareTo(date2) < 0 ) {

  //  0 comes when two date are same,
  //  1 comes when date1 is higher then date2
  // -1 comes when date1 is lower then date2

 }

How do I get the current username in Windows PowerShell?

$username=( ( Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username ) -split '\\' )[1]

$username

The second username is for display only purposes only if you copy and paste it.

How to check if a particular service is running on Ubuntu

Based on this answer on a similar topic https://askubuntu.com/a/58406
I prefer: /etc/init.d/postgres status

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

I love jQuery's method chaining. Simply do...

    var value = $("#text").val().replace('.',':');

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');

How do I install a custom font on an HTML site

Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.

You declare it in the CSS like this:

 @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
 @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');}

Then, you can just reference it like the other standard fonts:

 h3 { font-family: Delicious, sans-serif; }

So, in this case,

<html>
   <head>
    <style>
      @font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); } 
      h1 {
         font-family: JuneBug
      }
    </style>
   </head>
   <body>
      <h1>Hey, June</h1>
   </body>
</html>

And you just need to put the JUNEBUG.TFF in the same location as the html file.

I downloaded the font from the dafont.com website:

http://www.dafont.com/junebug.font

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Fuzzy matching using T-SQL

Since the first release of Master Data Services, you've got access to more advanced fuzzy logic algorithms than what SOUNDEX implements. So provided that you've got MDS installed, you'll be able to find a function called Similarity() in the mdq schema (MDS database).

More info on how it works: http://blog.hoegaerden.be/2011/02/05/finding-similar-strings-with-fuzzy-logic-functions-built-into-mds/

Random number from a range in a Bash Script

PORT=$(($RANDOM%63000+2001)) is close to what you want I think.

PORT=$(($RANDOM$RANDOM$RANDOM%63000+2001)) gets around the size limitation that troubles you. Since bash makes no distinctions between a number variable and a string variable, this works perfectly well. The "number" $RANDOM can be concatenated like a string, and then used as a number in a calculation. Amazing!

How can I disable a button on a jQuery UI dialog?

You can disable a button when you construct the dialog:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog({_x000D_
    modal: true,_x000D_
    buttons: [_x000D_
      { text: "Confirm", click: function() { $(this).dialog("close"); }, disabled: true },_x000D_
      { text: "Cancel", click: function() { $(this).dialog("close"); } }_x000D_
    ]_x000D_
  });_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog" title="Confirmation">_x000D_
  <p>Proceed?</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or you can disable it anytime after the dialog is created:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog({_x000D_
    modal: true,_x000D_
    buttons: [_x000D_
      { text: "Confirm", click: function() { $(this).dialog("close"); }, "class": "confirm" },_x000D_
      { text: "Cancel", click: function() { $(this).dialog("close"); } }_x000D_
    ]_x000D_
  });_x000D_
  setTimeout(function() {_x000D_
    $("#dialog").dialog("widget").find("button.confirm").button("disable");_x000D_
  }, 2000);_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog" title="Confirmation">_x000D_
  <p>Button will disable after two seconds.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Include jQuery in the JavaScript Console

Run this in your console

var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-3.4.1.min.js";document.getElementsByTagName('head')[0].appendChild(script);

It creates a new script tag, fills it with jQuery and appends to the head.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Getting output of system() calls in Ruby

As a direct system(...) replacement you may use Open3.popen3(...)

Further discussion: http://tech.natemurray.com/2007/03/ruby-shell-commands.html

Count number of records returned by group by

Following for PrestoDb, where FirstField can have multiple values:

select *
            , concat(cast(cast((ThirdTable.Total_Records_in_Group * 100 / ThirdTable.Total_Records_in_baseTable) as DECIMAL(5,2)) as varchar), '%') PERCENTage
from 
(
    SELECT FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable, count(*) Total_Records_in_Group
    FROM BaseTable FirstTable
    JOIN (
            SELECT FK1, count(*) AS Total_Records_in_baseTable 
            FROM BaseTable
            GROUP BY FK1
        ) SecondTable
    ON FirstTable.FirstField = SecondTable.FK1
    GROUP BY FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable
    ORDER BY FirstTable.FirstField, FirstTable.SecondField
) ThirdTable

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case, I got this error because of an empty packages.config file. This caused the NUGET package manager to fail and show the error Root element is missing. The resolution was to copy over elements from another non-empty file and then change it according to the needs.

Example (packages.config):

<?xml version="1.0" encoding="utf-8"?>
<packages>
 <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net451"/>
 <package id="Newtonsoft.Json" version="5.0.4" targetFramework="net451"/>
</packages>

How can I commit files with git?

in standart Vi editor in this situation you should

  1. press Esc
  2. type ":wq" (without quotes)
  3. Press Enter

Load a Bootstrap popover content with AJAX. Is this possible?

IN 2015, this is the best answer

$('.popup-ajax').mouseenter(function() {
   var i = this
   $.ajax({
      url: $(this).attr('data-link'), 
      dataType: "html", 
      cache:true, 
      success: function( data{
         $(i).popover({
            html:true,
            placement:'left',
            title:$(i).html(),
            content:data
         }).popover('show')
      }
   })
});

$('.popup-ajax').mouseout(function() {
  $('.popover:visible').popover('destroy')
});

How can I dynamically add a directive in AngularJS?

You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:

.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">{{text}}</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );
      };
    }
  };
});

You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.

A warning - comparison between signed and unsigned integer expressions

or use this header library and write:

// |notEqaul|less|lessEqual|greater|greaterEqual
if(sweet::equal(valueA,valueB))

and don't care about signed/unsigned or different sizes

How to create a Date in SQL Server given the Day, Month and Year as Integers

CREATE DATE USING MONTH YEAR IN SQL::

DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL

/**Region For Create Date**/
        DECLARE @FromDate DATE=NULL
        DECLARE @ToDate DATE=NULL

    SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
    SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/

Howto? Parameters and LIKE statement SQL

you have to do:

LIKE '%' + @param + '%'

What is /dev/null 2>&1?

>> /dev/null redirects standard output (stdout) to /dev/null, which discards it.

(The >> seems sort of superfluous, since >> means append while > means truncate and write, and either appending to or writing to /dev/null has the same net effect. I usually just use > for that reason.)

2>&1 redirects standard error (2) to standard output (1), which then discards it as well since standard output has already been redirected.

Google Play app description formatting

Include emojis; copy and paste them to the description:

http://getemoji.com

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

How to sort ArrayList<Long> in decreasing order?

Using List.sort() and Comparator.comparingLong()

numberList.sort(Comparator.comparingLong(x -> -x));

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

How do I use Docker environment variable in ENTRYPOINT array?

After much pain, and great assistance from @vitr et al above, i decided to try

  • standard bash substitution
  • shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

In my case I was getting latin cross sign instead of nbsp, even that a page was correctly encoded into the UTF-8. Nothing of above helped in resolving the issue and I tried all.

In the end changing font for IE (with browser specific css) helped, I was using Helvetica-Nue as a body font changing to the Arial resolved the issue .

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [DataMember]
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Angular and Django Rest Framework.

I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.

Bad Request, Your browser sent a request that this server could not understand

I got Bad Request, Your browser sent a request that this server could not understand when I tried to download a file to the target machine using curl.
I solved it by instead using scp to copy the file from the source machine to the target machine.

How to compile Go program consisting of multiple files?

You can use

go build *.go 
go run *.go

both will work also you may use

go build .
go run .

Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How to set lifetime of session

As long as the User does not delete their cookies or close their browser, the session should stay in existence.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

I had similar message and after several searches online and doing all suggestions, nothing helped. Finally I found the solution. In my IIS server, under the application pool advance option, there is an option for "Enable 32-Bit Applications" - that was changed from false to true and after restarting IIS server, My program started generating pdf files.

Convert time fields to strings in Excel

The below worked for me

  • First copy the content say "1:00:15" in notepad
  • Then select a new column where you need to copy the text from notepad.
  • Then right click and select format cell option and in that select numbers tab and in that tab select the option "Text".
  • Now copy the content from notepad and paste in this Excel column. it will be text but in format "1:00:15".

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

Whoops, looks like something went wrong. Laravel 5.0

In Laravel 5.5, I had the same issue

.env

was added to .gitignore.

So Either remove ".env" it from .gitignore file.

or add it forcefully

git add .env -f

And Deploy it. It will work.

If above does not help. Try generating the Key Again

php artisan key:generate

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Open Android Studio and under the Tools you will find the AVD manager. Click on it and ensure that you have a valid virtual device with the SDK downloaded (click "download" in the Actions column if shown). Then ensure that the correct virtual device is selected on the toolbar.

Laravel 5 route not defined, while it is?

i had the same issue and find the solution lately.

you should check if your route is rather inside a route::group

like here:

Route::group(['prefix' => 'Auth', 'as' => 'Auth.', 'namespace' => 'Auth', 'middleware' => 'Auth']

if so you should use it in the view file. like here:

!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => 'Auth.preferences/' . Auth::user()->id]) !!}

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

Plotting histograms from grouped data in a pandas DataFrame

With recent version of Pandas, you can do df.N.hist(by=df.Letter)

Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.

Loading .sql files from within PHP

Are you sure that its not one query per line? Your text editor may be wrapping lines, but in reality each query may be on a single line.

At any rate, olle's method seems best. If you have reasons to run queries one at time, you should be able to read in your file line by line, then use the semicolon at the end of each query to delimit. You're much better off reading in a file line by line than trying to split an enormous string, as it will be much kinder to your server's memory. Example:

$query  = '';
$handle = @fopen("/sqlfile.sql", "r");

if ($handle) {
    while (!feof($handle)) {
        $query.= fgets($handle, 4096);

        if (substr(rtrim($query), -1) === ';') {
            // ...run your query, then unset the string
            $query = '';
        }
    }

    fclose($handle);
}

Obviously, you'll need to consider transactions and the rest if you're running a whole lot of queries in a batch, but it's probably not a big deal for a new-install script.

Get difference between two lists

this could be even faster than Mark's list comprehension:

list(itertools.filterfalse(set(temp2).__contains__, temp1))

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

Write string to output stream

Wrap your OutputStream with a PrintWriter and use the print methods on that class. They take in a String and do the work for you.

Invalid syntax when using "print"?

You need parentheses:

print(2**100)

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

If you are using netbeans 7 and greater with oracle xe do the following on netbeans :

  1. go to services tab
  2. under servers, remove glassfish
  3. add back glassfish server
  4. input port number 9090 for http access

Glassfish can use that one if available or some random port number is created

How to set URL query params in Vue with Vue-Router

For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).

an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign

this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });

jQuery adding 2 numbers from input fields

This code works, can you compare it with yours?

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>HTML Tutorial</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <meta charset="windows-1252">
<script>

$(document).ready(function(){
    var a = $("#a").val();
    var b = $("#b").val();   
    $("#submit").on("click", function(){
        var sum = a + b;
        alert(sum);         
    })
})
</script>
</head>
<body>
   <input type="text" id="a" name="option"> 
   <input type="text" id="b" name="task"> 
<input id="submit" type="button" value="press me">

</body>

</html>

Appending values to dictionary in Python

It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []. So assuming that you have list1 that you want to append to the list for 'MORPHINE' you should do:

drug_dictionary['MORPHINE'].append(list1)

You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0] etc.

To traverse the lists stored against key you would do:

for listx in drug_dictionary['MORPHINE'] :
  do stuff on listx

How to find good looking font color if background color is known?

Personally I don't think we can find out an algorithm to calculate the most matched text color by specifying the background color.

I think currently the artist should have a list of color pairs which has good reading quality, we can add them to a table, and set one of these pairs randomly as our reading theme...

this is much reasonable, and we won't get ugly color pairs....

Why am I getting this redefinition of class error?

the implementation in the cpp file should be in the form

gameObject::gameObject()
    {
    x = 0;
    y = 0;
    }
gameObject::gameObject(int inx, int iny)
    {
        x = inx;
        y = iny;
    }

gameObject::~gameObject()
    {
    //
    }
int gameObject::add()
    {
        return x+y;
    }

not within a class gameObject { } definition block

Objective C - Assign, Copy, Retain

Updated Answer for Changed Documentation

The information is now spread across several guides in the documentation. Here's a list of required reading:

The answer to this question now depends entirely on whether you're using an ARC-managed application (the modern default for new projects) or forcing manual memory management.

Assign vs. Weak - Use assign to set a property's pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you'll want to use weak so you're not trying to access a deallocated object (illegal access of a memory address - "EXC_BAD_ACCESS") if you don't perform proper cleanup.

Retain vs. Copy - Declared properties use retain by default (so you can simply omit it altogether) and will manage the object's reference count automatically whether another object is assigned to the property or it's set to nil; Use copy to automatically send the newly-assigned object a -copy message (which will create a copy of the passed object and assign that copy to the property instead - useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).

String.Replace ignoring case

Lots of suggestions using Regex. How about this extension method without it:

public static string Replace(this string str, string old, string @new, StringComparison comparison)
{
    @new = @new ?? "";
    if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(@new, comparison))
        return str;
    int foundAt = 0;
    while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1)
    {
        str = str.Remove(foundAt, old.Length).Insert(foundAt, @new);
        foundAt += @new.Length;
    }
    return str;
}

How do I select elements of an array given condition?

For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.

In [8]: arr
Out[8]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.]])

In [9]: arr*(arr % 2 == 0).astype(np.int) 
Out[9]: 
array([[ 0.,  2.,  0.,  4.,  0.],
       [ 6.,  0.,  8.,  0., 10.]])

Method has the same erasure as another method in type

The problem is that Set<Integer> and Set<String> are actually treated as a Set from the JVM. Selecting a type for the Set (String or Integer in your case) is only syntactic sugar used by the compiler. The JVM can't distinguish between Set<String> and Set<Integer>.

Select all 'tr' except the first one

I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:

tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */

They both function in exactly the same way (in the context of HTML tables anyway) as:

tr:not(:first-child)

How to load a controller from another controller in codeigniter?

You can't load a controller from a controller in CI - unless you use HMVC or something.

You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.

UPDATE

After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.

If this is the case, you'd get a cleaner solution by getting creative with your routes.

For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.

You can set up routes like this:

$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";

Then, you can call method 1 with a URL like http://site.com/method_1 and method 2 with http://site.com/method_2.

Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.


You could also go with remapping your controllers.

From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":

public function _remap($method)
{
    if ($method == 'some_method')
    {
        $this->$method();
    }
    else
    {
        $this->default_method();
    }
}

How to display both icon and title of action inside ActionBar?

'always|withText' will work if there is sufficient room, otherwise it will only place icon. You can test it on your phone with rotation.

<item android:id="@id/menu_item"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />

How do I increase memory on Tomcat 7 when running as a Windows Service?

If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8

08/14/2019  10:24 PM           116,648 Tomcat-Custom.exe
08/14/2019  10:24 PM           119,720 Tomcat-Customw.exe
               2 File(s)        236,368 bytes

Running the "w" terminated executable will let you configure Xmx in the Java tab
enter image description here

Comments in Android Layout xml

The World Wide Web Consortium (W3C) actually defined a comment interface. The definition says all the characters between the starting ' <!--' and ending '-->' form a part of comment content and no lexical check is done on the content of a comment.

More details are available on developer.android.com site.

So you can simply add your comment in between any starting and ending tag. In Eclipse IDE simply typing <!-- would auto complete the comment for you. You can then add your comment text in between.

For example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".TicTacToe" >

 <!-- This is a comment -->

</LinearLayout>

Purpose of specifically mentioning in between is because you cannot use it inside a tag.

For example:

<TextView 
    android:text="@string/game_title"
    <!-- This is a comment -->
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"/>

is wrong and will give following error

 Element type "TextView" must be followed by either attribute specifications, ">" or "/>".

How make background image on newsletter in outlook?

You can use it only in body tag or in tables. Something like this:

<table width="100%" background="YOUR_IMAGE_URL" style="STYLES YOU WANT (i.e. background-repeat)">

This worked for me.

Get query from java.sql.PreparedStatement

You can add log4jdbc to your project. This adds logging of sql commands as they execute + a lot of other information.

http://code.google.com/p/log4jdbc/wiki/FAQ

MySQL DROP all tables, ignoring foreign keys

From http://www.devdaily.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys:

SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;

(Note that this answers how to disable foreign key checks in order to be able to drop the tables in arbitrary order. It does not answer how to automatically generate drop-table statements for all existing tables and execute them in a single script. Jean's answer does.)

change the date format in laravel view page

You can use Carbon::createFromTimestamp

BLADE

{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}

How to send a “multipart/form-data” POST in Android with Volley

Another solution, very light with high performance with payload large:

Android Asynchronous Http Client library: http://loopj.com/android-async-http/

private static AsyncHttpClient client = new AsyncHttpClient();

private void uploadFileExecute(File file) {

    RequestParams params = new RequestParams();

    try { params.put("photo", file); } catch (FileNotFoundException e) {}

    client.post(getUrl(), params,

        new AsyncHttpResponseHandler() {

            public void onSuccess(String result) {

                Log.d(TAG,"uploadFile response: "+result);

            };

            public void onFailure(Throwable arg0, String errorMsg) {

                Log.d(TAG,"uploadFile ERROR!");

            };

        }

    );

}

How to git-svn clone the last n revisions from a Subversion repository?

... 7 years later, in the desert, a tumbleweed blows by ...

I wasn't satisfied with the accepted answer so I created some scripts to do this for you available on Github. These should help anyone who wants to use git svn clone but doesn't want to clone the entire repository and doesn't want to hunt for a specific revision to clone from in the middle of the history (maybe you're cloning a bunch of repos). Here we can just clone the last N revisions:

Use git svn clone to clone the last 50 revisions

# -u    The SVN URL to clone
# -l    The limit of revisions
# -o    The output directory

./git-svn-cloneback.sh -u https://server/project/trunk -l 50 -o myproj --authors-file=svn-authors.txt

Find the previous N revision from an SVN repo

# -u    The SVN URL to clone
# -l    The limit of revisions

./svn-lookback.sh -u https://server/project/trunk -l 5     

What is the purpose of meshgrid in Python / NumPy?

Short answer

The purpose of meshgrid is to help remplace Python loops (slow interpreted code) by vectorized operations within C NumPy library.

Borrowed from this site.

enter image description here

x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

meshgrid is used to create pairs of coordinates between -4 and +4 with .25 increments in each direction X and Y. Each pair is then used to find R, and Z from it. This way of preparing "a grid" of coordinates is frequently used in plotting 3D surfaces, or coloring 2D surfaces.


Details: Python for-loop vs NumPy vector operation

To take a more simple example, let's say we have two sequences of values,

a = [2,7,9,20]    
b = [1,6,7,9]    ?

and we want to perform an operation on each possible pair of values, one taken from the first list, one taken from the second list. We also want to store the result. For example, let's say we want to get the sum of the values for each possible pair.

Slow and laborious method

c = []    
for i in range(len(b)):    
    row = []    
    for j in range(len(a)):    
        row.append (a[j] + b[i])
    c.append (row)    
print (c)

Result:

[[3, 8, 10, 21],
 [8, 13, 15, 26],
 [9, 14, 16, 27],
 [11, 16, 18, 29]]

Python is interpreted, these loops are relatively slow to execute.

Fast and easy method

meshgrid is intended to remove the loops from the code. It returns two arrays (i and j below) which can be combined to scan all the existing pairs like this:

i,j = np.meshgrid (a,b)    
c = i + j    
print (c)

Result:

[[ 3  8 10 21]
 [ 8 13 15 26]
 [ 9 14 16 27]
 [11 16 18 29]]

Meshgrid under the hood

The two arrays prepared by meshgrid are:

(array([[ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20]]),

 array([[1, 1, 1, 1],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [9, 9, 9, 9]]))

These arrays are created by repeating the values provided. One contains the values in identical rows, the other contains the other values in identical columns. The number of rows and column is determined by the number of elements in the other sequence.

The two arrays created by meshgrid are therefore shape compatible for a vector operation. Imagine x and y sequences in the code at the top of page having a different number of elements, X and Y resulting arrays will be shape compatible anyway, not requiring any broadcast.

Origin

numpy.meshgrid comes from MATLAB, like many other NumPy functions. So you can also study the examples from MATLAB to see meshgrid in use, the code for the 3D plotting looks the same in MATLAB.

iPhone Navigation Bar Title text color

In order to make Erik B's great solution more useable across the different UIVIewCOntrollers of your app I recommend adding a category for UIViewController and declare his setTitle:title method inside. Like this you will get the title color change on all view controllers without the need of duplication.

One thing to note though is that you do not need [super setTItle:tilte]; in Erik's code and that you will need to explicitly call self.title = @"my new title" in your view controllers for this method to be called

@implementation UIViewController (CustomeTitleColor)

- (void)setTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];

        titleView.textColor = [UIColor blueColor]; // Change to desired color

        self.navigationItem.titleView = titleView;
        [titleView release];
    }
    titleView.text = title;
    [titleView sizeToFit];
}

@end

GridLayout and Row/Column Span Woe

Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="First"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Second"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Third"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"        
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"
    android:text="fourth"/>

</android.support.v7.widget.GridLayout>

How do I use ROW_NUMBER()?

You can use Row_Number for limit query result.

Example:

SELECT * FROM (
    select row_number() OVER (order by createtime desc) AS ROWINDEX,* 
    from TABLENAME ) TB
WHERE TB.ROWINDEX between 0 and 10

-- With above query, I will get PAGE 1 of results from TABLENAME.

I want to use CASE statement to update some records in sql server 2005

If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN in the UPDATE:

declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
 ('AAA','BBB'),
 ('CCC','DDD'),
 ('EEE','FFF')

update ts set LastName = ToName
from dbo.TestStudents ts
       inner join
     @ToDo t
       on
         ts.LastName = t.FromName

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.

PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:

  1. PHP started as a very basic CGI. PHP has progressed very far since its early stage, but it happened in small steps. PHP already had many millions of users by the time it became the embed-able and flexible C library that it is today, most of whom were dependent on its earlier model of execution, so it hasn't yet made a solid attempt to escape the CGI model internally. Even the command line interface invokes the PHP library (libphp5.so on Linux, php5ts.dll on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.

Note that PHP does have extensions to provide event loops (such as libevent) and threads (such as pthreads) in PHP userspace, but very, very, few of the applications use these.

  1. PHP still has significant issues with garbage collection. Although these issues have been consistently improving (likely its greatest step to end the life cycle as described above), even the best attempts at creating long-running PHP applications require being restarted on a regular basis. This also makes it unpractical for real-time applications.

PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.

Initialize/reset struct to zero/null

 struct x myX;
 ...
 memset(&x, 0, sizeof(myX));

Pretty git branch graphs

git -c core.pager='less -SRF' log --oneline --graph --decorate

This is my terminal variation, similar to many answers here. I like to adjust the flags passed to less to prevent word wrapping.

example output

I set this to an alias for quick access since the command is a bit cumbersome.

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

The other answers don't seem to address why close() is really necessary? * 2

Doubt on the answer "HttpClient resource deallocation".

It is mentioned in old 3.x httpcomponents doc, which is long back and has a lot difference from 4.x HC. Besides the explanation is so brief that doesn't say what this underlying resource is.

I did some research on 4.5.2 release source code, found the implementations of CloseableHttpClient:close() basically only closes its connection manager.

(FYI) That's why when you use a shared PoolingClientConnectionManager and call client close(), exception java.lang.IllegalStateException: Connection pool shut down will occur. To avoid, setConnectionManagerShared works.

I prefer not do CloseableHttpClient:close() after every single request

I used to create a new http client instance when doing request and finally close it. In this case, it'd better not to call close(). Since, if connection manager doesn't have "shared" flag, it'll be shutdown, which is too expensive for a single request.

In fact, I also found in library clj-http, a Clojure wrapper over Apache HC 4.5, doesn't call close() at all. See func request in file core.clj

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

How do I run a simple bit of code in a new thread?

Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.

diff current working copy of a file with another branch's committed copy

Also: git diff master..feature foo

Since git diff foo master:foo doesn't work on directories for me.

How do I convert a calendar week into a date in Excel?

=(MOD(R[-1]C-1,100)*7+DATE(INT(R[-1]C/100+2000),1,1)-2)

yyww as the given week exp:week 51 year 2014 will be 1451

How do I make a simple makefile for gcc on Linux?

all: program
program.o: program.h headers.h

is enough. the rest is implicit

Windows service on Local Computer started and then stopped error

I came across the same issue. My service is uploading/receiving XMLS and write the errors to the Event Log.

When I went to the Event Log, I tried to filter it. It prompt me that the Event Log was corrupted.

I cleared the Event Log and all OK.

Generate a range of dates using SQL

Another simple way to get 365 days from today would be:

SELECT (TRUNC(sysdate) + (LEVEL-366)) AS DATE_ID
FROM DUAL connect by level <=( (sysdate)-(sysdate-366));

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

How can I get the count of line in a file in an efficient way?

Quick and dirty, but it does the job:

import java.io.*;

public class Counter {

    public final static void main(String[] args) throws IOException {
        if (args.length > 0) {
            File file = new File(args[0]);
            System.out.println(countLines(file));
        }
    }

    public final static int countLines(File file) throws IOException {
        ProcessBuilder builder = new ProcessBuilder("wc", "-l", file.getAbsolutePath());
        Process process = builder.start();
        InputStream in = process.getInputStream();
        LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
        String line = reader.readLine();
        if (line != null) {
            return Integer.parseInt(line.trim().split(" ")[0]);
        } else {
            return -1;
        }
    }

}

How do I deal with corrupted Git object files?

Recovering from Repository Corruption is the official answer.

The really short answer is: find uncorrupted objects and copy them.

How to auto-format code in Eclipse?

The secret is simple: Ctrl+Shift+F

Having issues with a MySQL Join that needs to meet multiple conditions

You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR. For example WHERE a='1' AND (b='123' OR b='234').

SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc

Is there any way to do HTTP PUT in python

You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:

pip install requests

More on installing requests.

Then setup the put request:

import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.

How to convert Rows to Columns in Oracle?

 select * FROM doc_tab
    PIVOT
    (
    Min(document_id)
    FOR document_type IN ('Voters ID','Pan card','Drivers licence')
    ) 

outputs as this

enter image description here

sql fiddle demo here

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

How do I create a readable diff of two spreadsheets using git diff?

Hmmm. From the Excel menu choose Window -> Compare side by side?

Use Toast inside Fragment

When calling Toast inside android fragment:

1. Activity mActivity=this.getActivity();  

2. Toast.makeText(mActivity,"Text you want to display",Toast.LENGTH_SHORT).show();

This works for me.

Bootstrap 3 Horizontal and Vertical Divider

Do you have to use Bootstrap for this? Here's a basic HTML/CSS example for obtaining this look that doesn't use any Bootstrap:

HTML:

<div class="bottom">
    <div class="box-content right">Rich Media Ad Production</div>
    <div class="box-content right">Web Design & Development</div>
    <div class="box-content right">Mobile Apps Development</div>
    <div class="box-content">Creative Design</div>
</div>
<div>
    <div class="box-content right">Web Analytics</div>
    <div class="box-content right">Search Engine Marketing</div>
    <div class="box-content right">Social Media</div>
    <div class="box-content">Quality Assurance</div>
</div>

CSS:

.box-content {
    display: inline-block;
    width: 200px;
    padding: 10px;
}

.bottom {
    border-bottom: 1px solid #ccc;
}

.right {
    border-right: 1px solid #ccc;
}

Here is the working Fiddle.


UPDATE

If you must use Bootstrap, here is a semi-responsive example that achieves the same effect, although you may need to write a few additional media queries.

HTML:

<div class="row">
    <div class="col-xs-3">Rich Media Ad Production</div>
    <div class="col-xs-3">Web Design & Development</div>
    <div class="col-xs-3">Mobile Apps Development</div>
    <div class="col-xs-3">Creative Design</div>
</div>
<div class="row">
    <div class="col-xs-3">Web Analytics</div>
    <div class="col-xs-3">Search Engine Marketing</div>
    <div class="col-xs-3">Social Media</div>
    <div class="col-xs-3">Quality Assurance</div>
</div>

CSS:

.row:not(:last-child) {
    border-bottom: 1px solid #ccc;
}

.col-xs-3:not(:last-child) {
    border-right: 1px solid #ccc;
}

Here is another working Fiddle.

Note:

Note that you may also use the <hr> element to insert a horizontal divider in Bootstrap as well if you'd like.

"Actual or formal argument lists differs in length"

You try to instantiate an object of the Friends class like this:

Friends f = new Friends(friendsName, friendsAge);

The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:

Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);

Webpack how to build production code and how to use it

After observing number of viewers to this question I decided to conclude an answer from Vikramaditya and Sandeep.

To build the production code the first thing you have to create is production configuration with optimization packages like,

  new webpack.optimize.CommonsChunkPlugin('common.js'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

Then in the package.json file you can configure the build procedure with this production configuration

"scripts": {
    "build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},

now you have to run the following command to initiate the build

npm run build

As per my production build configuration webpack will build the source to ./dist directory.

Now your UI code will be available in ./dist/ directory. Configure your server to serve these files as static assets. Done!

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Loop through all nested dictionary values?

Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield (key, value)
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)

Prints

a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6

Set the maximum character length of a UITextField

I have open sourced a UITextField subclass, STATextField, that offers this functionality (and much more) with its maxCharacterLength property.

Django MEDIA_URL and MEDIA_ROOT

Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }} won't work in your templates. To fix this,in your settings.py, make sure you add

django.core.context_processors.media

in your TEMPLATE_CONTEXT_PROCESSORS.

Deleting rows with MySQL LEFT JOIN

MySQL allows you to use the INNER JOIN clause in the DELETE statement to delete rows from a table and the matching rows in another table.

For example, to delete rows from both T1 and T2 tables that meet a specified condition, you use the following statement:

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition;

Notice that you put table names T1 and T2 between the DELETE and FROM keywords. If you omit T1 table, the DELETE statement only deletes rows in T2 table. Similarly, if you omitT2 table, the DELETE statement will delete only rows in T1 table.

Hope this help.

Why are #ifndef and #define used in C++ header files?

#ifndef <token>
/* code */
#else
/* code to include if the token is defined */
#endif

#ifndef checks whether the given token has been #defined earlier in the file or in an included file; if not, it includes the code between it and the closing #else or, if no #else is present, #endif statement. #ifndef is often used to make header files idempotent by defining a token once the file has been included and checking that the token was not set at the top of that file.

#ifndef _INCL_GUARD
#define _INCL_GUARD
#endif

What is a raw type and why shouldn't we use it?

Here's another case where raw types will bite you:

public class StrangeClass<T> {
  @SuppressWarnings("unchecked")
  public <X> X getSomethingElse() {
    return (X)"Testing something else!";
  }

  public static void main(String[] args) {
    final StrangeClass<String> withGeneric    = new StrangeClass<>();
    final StrangeClass         withoutGeneric = new StrangeClass();
    final String               value1,
                               value2;

    // Compiles
    value1 = withGeneric.getSomethingElse();

    // Produces compile error:
    // incompatible types: java.lang.Object cannot be converted to java.lang.String
    value2 = withoutGeneric.getSomethingElse();
  }
}

This is counter-intuitive because you'd expect the raw type to only affect methods bound to the class type parameter, but it actually also affects generic methods with their own type parameters.

As was mentioned in the accepted answer, you lose all support for generics within the code of the raw type. Every type parameter is converted to its erasure (which in the above example is just Object).

Location for session files in Apache/PHP

I believe its in /tmp/. Check your phpinfo function though, it should say session.save_path in there somewhere.

Font Awesome 5 font-family issue

The problem is in the font-weight.
For Font Awesome 5 you have to use {font-weight:900}

How can I find the location of origin/master in git, and how do I change it?

I am a git newbie as well. I had the same problem with 'your branch is ahead of origin/master by N commits' messages. Doing the suggested 'git diff origin/master' did show some diffs that I did not care to keep. So ...

Since my git clone was for hosting, and I wanted an exact copy of the master repo, and did not care to keep any local changes, I decided to save off my entire repo, and create a new one:

(on the hosting machine)

mv myrepo myrepo
git clone USER@MASTER_HOST:/REPO_DIR myrepo

For expediency, I used to make changes to the clone on my hosting machine. No more. I will make those changes to the master, git commit there, and do a git pull. Hopefully, this should keep my git clone on the hosting machine in complete sync.

/Nara

How to get browser width using JavaScript code?

An important addition to Travis' answer; you need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth(). What i did ;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
</body>

and call aWidth variable anywhere afterwards.

ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like rubygems.org.

$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem

Display an image with Python

In a much simpler way, you can do the same using

from PIL import Image

image = Image.open('image.jpg')
image.show()

Postgresql SQL: How check boolean field with null and True,False Value?

I'm not expert enough in the inner workings of Postgres to know why your query with the double condition in the WHERE clause be not working. But one way to get around this would be to use a UNION of the two queries which you know do work:

SELECT * FROM table_name WHERE boolean_column IS NULL
UNION
SELECT * FROM table_name WHERE boolean_column = FALSE

You could also try using COALESCE:

SELECT * FROM table_name WHERE COALESCE(boolean_column, FALSE) = FALSE

This second query will replace all NULL values with FALSE and then compare against FALSE in the WHERE condition.

Python: how to capture image from webcam on click using OpenCV

This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('s'): 

        check, frame = video_capture.read()
        cv2.imshow("Capturing", frame)
        cv2.imwrite(filename='saved_img.jpg', img=frame)
        video_capture.release()
        img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
        img_new = cv2.imshow("Captured Image", img_new)
        cv2.waitKey(1650)
        print("Image Saved")
        print("Program End")
        cv2.destroyAllWindows()

        break
    elif cv2.waitKey(1) & 0xFF == ord('q'):
        print("Turning off camera.")
        video_capture.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

output

enter image description here

Also, You can check out my GitHub code

Replace duplicate spaces with a single space in T-SQL

I typically use this approach:

declare @s varchar(50)
set @s = 'TEST         TEST'
select REPLACE(REPLACE(REPLACE(@s,' ','[o][c]'),'[c][o]',''),'[o][c]',' ')

Avoid web.config inheritance in child web application using inheritInChildApplications

As the commenters for the previous answer mentioned, you cannot simply add the line...

<location path="." inheritInChildApplications="false">

...just below <configuration>. Instead, you need to wrap the individual web.config sections for which you want to disable inheritance. For example:

<!-- disable inheritance for the connectionStrings section -->
<location path="." inheritInChildApplications="false">
   <connectionStrings>
   </connectionStrings>
</location>

<!-- leave inheritance enabled for appSettings -->
<appSettings>
</appSettings>

<!-- disable inheritance for the system.web section -->
<location path="." inheritInChildApplications="false">
   <system.web>
        <webParts>
        </webParts>
        <membership>
        </membership>

        <compilation>
        </compilation>
      </system.web>
 </location>

While <clear /> may work for some configuration sections, there are some that instead require a <remove name="..."> directive, and still others don't seem to support either. In these situations, it's probably appropriate to set inheritInChildApplications="false".

How to process each output line in a loop?

For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
 {

    // code when element is disabled

  }

Restoring Nuget References?

You need to Enable NuGet package restore at the VS solution level for the restore missing package to work.

enter image description here

Gson: Directly convert String to JsonObject (no POJO)

I believe this is a more easy approach:

public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{

    public JsonElement serialize(HibernateProxy object_,
        Type type_,
        JsonSerializationContext context_) {
        return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
        // that will convert enum object to its ordinal value and convert it to json element

    }

    public static <T> T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                    .getImplementation();
        }
        return entity;
    }
}

And then you will be able to call it like this:

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
        .create();

This way all the hibernate objects will be converted automatically.

Numeric for loop in Django templates

{% with ''|center:n as range %}
{% for _ in range %}
    {{ forloop.counter }}
{% endfor %}
{% endwith %}

Clearing <input type='file' /> using jQuery

The .clone() thing does not work in Opera (and possibly others). It keeps the content.

The closest method here for me was Jonathan's earlier, however ensuring that the field preserved its name, classes, etc made for messy code in my case.

Something like this might work well (thanks to Quentin too):

function clearInput($source) {
    var $form = $('<form>')
    var $targ = $source.clone().appendTo($form)
    $form[0].reset()
    $source.replaceWith($targ)
}

Open a Web Page in a Windows Batch FIle

start did not work for me.

I used:

firefox http://www.stackoverflow.com

or

chrome http://www.stackoverflow.com

Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.

Getting java.net.SocketTimeoutException: Connection timed out in android

If you are using Kotlin + Retrofit + Coroutines then just use try and catch for network operations like,

viewModelScope.launch(Dispatchers.IO) {
        try {
            val userListResponseModel = apiEndPointsInterface.usersList()
            returnusersList(userListResponseModel)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

Where, Exception is type of kotlin and not of java.lang

This will handle every exception like,

  1. HttpException
  2. SocketTimeoutException
  3. FATAL EXCEPTION: DefaultDispatcher etc

Here is my usersList() function

@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel

Note: Your RetrofitClient Classs must have this as client

OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)

Ansible: Store command's stdout in new variable?

In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:

tasks:
       - shell: echo $(cat /etc/issue | awk {'print $7'})
         register: echo_content

       - shell: echo "It works"
         when: echo_content.stdout == "12"
         register: out
       - debug: var=out.stdout_lines

How should I log while using multiprocessing in Python?

As of 2020 it seems there is a simpler way of logging with multiprocessing.

This function will create the logger. You can set the format here and where you want your output to go (file, stdout):

def create_logger():
    import multiprocessing, logging
    logger = multiprocessing.get_logger()
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter(\
        '[%(asctime)s| %(levelname)s| %(processName)s] %(message)s')
    handler = logging.FileHandler('logs/your_file_name.log')
    handler.setFormatter(formatter)

    # this bit will make sure you won't have 
    # duplicated messages in the output
    if not len(logger.handlers): 
        logger.addHandler(handler)
    return logger

In the init you instantiate the logger:

if __name__ == '__main__': 
    from multiprocessing import Pool
    logger = create_logger()
    logger.info('Starting pooling')
    p = Pool()
    # rest of the code

Now, you only need to add this reference in each function where you need logging:

logger = create_logger()

And output messages:

logger.info(f'My message from {something}')

Hope this helps.

Returning value from Thread

You can use a local final variable array. The variable needs to be of non-primitive type, so you can use an array. You also need to synchronize the two threads, for example using a CountDownLatch:

public void test()
{   
    final CountDownLatch latch = new CountDownLatch(1);
    final int[] value = new int[1];
    Thread uiThread = new HandlerThread("UIHandler"){
        @Override
        public void run(){
            value[0] = 2;
            latch.countDown(); // Release await() in the test thread.
        }
    };
    uiThread.start();
    latch.await(); // Wait for countDown() in the UI thread. Or could uiThread.join();
    // value[0] holds 2 at this point.
}

You can also use an Executor and a Callable like this:

public void test() throws InterruptedException, ExecutionException
{   
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Integer> callable = new Callable<Integer>() {
        @Override
        public Integer call() {
            return 2;
        }
    };
    Future<Integer> future = executor.submit(callable);
    // future.get() returns 2 or raises an exception if the thread dies, so safer
    executor.shutdown();
}

What is your favorite C programming trick?

using __FILE__ and __LINE__ for debugging

#define WHERE fprintf(stderr,"[LOG]%s:%d\n",__FILE__,__LINE__);

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

Find running median from a stream of integers

An intuitive way to think about this is that if you had a full balanced binary search tree, then the root would be the median element, since there there would be the same number of smaller and greater elements. Now, if the tree isn't full this won't be quite the case since there will be elements missing from the last level.

So what we can do instead is have the median, and two balanced binary trees, one for elements less than the median, and one for elements greater than the median. The two trees must be kept at the same size.

When we get a new integer from the data stream, we compare it to the median. If it's greater than the median, we add it to the right tree. If the two tree sizes differ more than 1, we remove the min element of the right tree, make it the new median, and put the old median in the left tree. Similarly for smaller.

Passing a variable from one php include file to another: global vs. not

This is all you have to do:

In front.inc

global $name;
$name = 'james';

How to add values in a variable in Unix shell scripting?

Here's a simple example to add two variables:

var1=4
var2=3
let var3=$var1+$var2
echo $var3

How to decode a Base64 string?

There are no PowerShell-native commands for Base64 conversion - yet (as of PowerShell [Core] 7.1), but adding dedicated cmdlets has been suggested.
For now, direct use of .NET is needed.

Important:

  • Base64 encoding is an encoding of binary data using bytes whose values are constrained to a well-defined 64-character subrange of the ASCII character set representing printable characters, devised at a time when sending arbitrary bytes was problematic, especially with the high bit set (byte values > 0x7f).

  • Therefore, you must always specify explicitly what character encoding the Base64 bytes do / should represent.

Ergo:

  • on converting TO Base64, you must first obtain a byte representation of the string you're trying to encode using the character encoding the consumer of the Base64 string expects.

  • on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that was used to create the Base64 representation.

Examples:

Note:

  • The following examples convert to and from UTF-8 encoded strings:

  • To convert to and from UTF-16LE ("Unicode") instead, substitute [Text.Encoding]::Unicode for [Text.Encoding]::UTF8

Convert TO Base64:

PS> [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Motörhead'))
TW90w7ZyaGVhZA==

Convert FROM Base64:

PS> [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('TW90w7ZyaGVhZA=='))
Motörhead

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Currently, Microsoft don't provide download option for '2007 Office System Driver: Data Connectivity Components' and click on first answer for '2007 Office System Driver: Data Connectivity Components' redirect to Cnet where getting download link creates confusion.

That's why who use SQL Server 2014 and latest version of SQL Server in Windows 10 click on below link for download this component which resolve your problem : - Microsoft Access Database Engine 2010

Happy Coding!

What is the iOS 5.0 user agent string?

I found a more complete listing at user agent string. BTW, this site has more than just iOS user agent strings. Also, the home page will "break down" the user agent string of your current browser for you.

Create a Date with a set timezone without using a string representation

const date = new Date("2020-12-16 17:45:00 UTC");

Works fine.

Postgres could not connect to server

This happened to me when I upgraded from 9.3.4 to 9.5 as the databases are incompatible without upgrading.

I used pg_upgrade as follows:

Stop postgres

$ brew services stop postgresql

Upgrade the databases:

$ pg_upgrade \
   -d /usr/local/var/postgres \
   -D /usr/local/var/postgres9.5 \
   -b /usr/local/Cellar/postgresql/9.3.4/bin/ \
   -B /usr/local/Cellar/postgresql/9.5.0/bin/ \
   -v

Archive the old databases:

 $ mv /usr/local/var/postgres /usr/local/var/postgres9.3.save
 $ mv /usr/local/var/postgres9.5 /usr/local/var/postgres

Restart postgres:

 $ brew services start postgresql

Updated Gems (for rails / active record) :

 $ gem uninstall pg
 $ gem uninstall activerecord-postgresql-adapter
 $ bundle install

Counting DISTINCT over multiple columns

I found this when I Googled for my own issue, found that if you count DISTINCT objects, you get the correct number returned (I'm using MySQL)

SELECT COUNT(DISTINCT DocumentID) AS Count1, 
  COUNT(DISTINCT DocumentSessionId) AS Count2
  FROM DocumentOutputItems

Tooltip with HTML content without JavaScript

Another similar way to do it by css:

_x000D_
_x000D_
#img {  }_x000D_
#img:hover {visibility:hidden}_x000D_
#thistext {font-size:22px;color:white }_x000D_
#thistext:hover {color:black;}_x000D_
#hoverme {width:50px;height:50px;}_x000D_
_x000D_
#hoverme:hover { _x000D_
background-color:green;_x000D_
position:absolute ;_x000D_
left:300px;_x000D_
top:100px;_x000D_
width:40%;_x000D_
height:20%;_x000D_
}
_x000D_
<p id="hoverme"><img id="img" src="http://a.deviantart.net/avatars/l/o/lol-cat.jpg"></img><span id="thistext">LOCATZ!!!!</span></p>
_x000D_
_x000D_
_x000D_

Try it: http://jsfiddle.net/FdBu7/

And here is some links about transitions and new ways to do it: http://www.w3schools.com/css3/css3_transitions.asp http://dev.opera.com/articles/view/css3-show-and-hide/

Copy text from nano editor to shell

1) Ctrl + 6 to mark the text that you want to copy

2) Ctrl + k to cut the text and Ctrl + u to paste back to the original place

3) Go to the desired line where you want to paste the code marked in step (2). Ctrl + u to paste it.

Hope it helps.

Visual Studio Code Automatic Imports

In the tsconfig.app.json, a standard Angular 10 app has:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

Once I changed the include like to be:

  "include": [
    "src/**/*.d.ts",
    "src/**/*.ts"
  ]

It worked for me It worked for me

How to write logs in text file when using java.util.logging.Logger

Maybe this is what you need...

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * LogToFile class
 * This class is intended to be use with the default logging class of java
 * It save the log in an XML file  and display a friendly message to the user
 * @author Ibrabel <[email protected]>
 */
public class LogToFile {

    protected static final Logger logger=Logger.getLogger("MYLOG");
    /**
     * log Method 
     * enable to log all exceptions to a file and display user message on demand
     * @param ex
     * @param level
     * @param msg 
     */
    public static void log(Exception ex, String level, String msg){

        FileHandler fh = null;
        try {
            fh = new FileHandler("log.xml",true);
            logger.addHandler(fh);
            switch (level) {
                case "severe":
                    logger.log(Level.SEVERE, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case "warning":
                    logger.log(Level.WARNING, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Warning", JOptionPane.WARNING_MESSAGE);
                    break;
                case "info":
                    logger.log(Level.INFO, msg, ex);
                    if(!msg.equals(""))
                        JOptionPane.showMessageDialog(null,msg,
                            "Info", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case "config":
                    logger.log(Level.CONFIG, msg, ex);
                    break;
                case "fine":
                    logger.log(Level.FINE, msg, ex);
                    break;
                case "finer":
                    logger.log(Level.FINER, msg, ex);
                    break;
                case "finest":
                    logger.log(Level.FINEST, msg, ex);
                    break;
                default:
                    logger.log(Level.CONFIG, msg, ex);
                    break;
            }
        } catch (IOException | SecurityException ex1) {
            logger.log(Level.SEVERE, null, ex1);
        } finally{
            if(fh!=null)fh.close();
        }
    }

    public static void main(String[] args) {

        /*
            Create simple frame for the example
        */
        JFrame myFrame = new JFrame();
        myFrame.setTitle("LogToFileExample");
        myFrame.setSize(300, 100);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setLocationRelativeTo(null);
        JPanel pan = new JPanel();
        JButton severe = new JButton("severe");
        pan.add(severe);
        JButton warning = new JButton("warning");
        pan.add(warning);
        JButton info = new JButton("info");
        pan.add(info);

        /*
            Create an exception on click to use the LogToFile class
        */
        severe.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"severe","You can't divide anything by zero");
                }

            }

        });

        warning.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"warning","You can't divide anything by zero");
                }

            }

        });

        info.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                int j = 20, i = 0;
                try {
                    System.out.println(j/i);
                } catch (ArithmeticException ex) {
                    log(ex,"info","You can't divide anything by zero");
                }

            }

        });

        /*
            Add the JPanel to the JFrame and set the JFrame visible
        */
        myFrame.setContentPane(pan);
        myFrame.setVisible(true);
    }
}

How to make a phone call in android and come back to my activity when the call is done?

Steps:

1)Add the required permissions in the Manifest.xml file.

<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2)Create a listener for the phone state changes.

public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        //when this state occurs, and your flag is set, restart your app
    Intent i = context.getPackageManager().getLaunchIntentForPackage(
                            context.getPackageName());
    //For resuming the application from the previous state
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Uncomment the following if you want to restart the application instead of bring to front.
    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(i);
    }
}
}

3)Initialize the listener in your OnCreate

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP with FLAG_ACTIVITY_SINGLE_TOP

Reference this Answer

Renaming columns in Pandas

Another option is to rename using a regular expression:

import pandas as pd
import re

df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})

df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
   a  b  c
0  1  3  5
1  2  4  6

Google Maps Api v3 - find nearest markers

Here is another function that works great for me, returns distance in kilometers:

 function distance(lat1, lng1, lat2, lng2) {
        var radlat1 = Math.PI * lat1 / 180;
        var radlat2 = Math.PI * lat2 / 180;
        var radlon1 = Math.PI * lng1 / 180;
        var radlon2 = Math.PI * lng2 / 180;
        var theta = lng1 - lng2;
        var radtheta = Math.PI * theta / 180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist);
        dist = dist * 180 / Math.PI;
        dist = dist * 60 * 1.1515;

        //Get in in kilometers
        dist = dist * 1.609344;

        return dist;
    }

How to make an HTTP request + basic auth in Swift

I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.

I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "[email protected]"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

Hope this helps offers a solution to someone trying to avoid using 3rd party code for their POST requests!

I lose my data when the container exits

You might want to look at docker volumes if you you want to persist the data in your container. Visit https://docs.docker.com/engine/tutorials/dockervolumes/. The docker documentation is a very good place to start

Creating email templates with Django

From the docs, to send HTML e-mail you want to use alternative content-types, like this:

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

You'll probably want two templates for your e-mail - a plain text one that looks something like this, stored in your templates directory under email.txt:

Hello {{ username }} - your account is activated.

and an HTMLy one, stored under email.html:

Hello <strong>{{ username }}</strong> - your account is activated.

You can then send an e-mail using both those templates by making use of get_template, like this:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

plaintext = get_template('email.txt')
htmly     = get_template('email.html')

d = Context({ 'username': username })

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

TABLOCK vs TABLOCKX

Big difference, TABLOCK will try to grab "shared" locks, and TABLOCKX exclusive locks.

If you are in a transaction and you grab an exclusive lock on a table, EG:

SELECT 1 FROM TABLE WITH (TABLOCKX)

No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.

TABLOCK only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED (default). If your isolation level is higher, for example: SERIALIZABLE, shared locks are held until the end of a transaction.


Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK). However, if transaction A holds a shared lock on a table, transaction B will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.


Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).

In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.

In general you would not use TABLOCK or TABLOCKX unless you absolutely needed it for some edge case.

Setting the User-Agent header for a WebClient request

const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null)
{
    var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
    var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
    if (knownRequestHeadersField != null)
    {
        string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
                    knownRequestHeaders[39] = ua;
    }
}

decompiling DEX into Java sourcecode

To clarify somewhat, there are two major paths you might take here depending on what you want to accomplish:

Decompile the Dalvik bytecode (dex) into readable Java source. You can do this easily with dex2jar and jd-gui, as fred mentions. The resulting source is useful to read and understand the functionality of an app, but will likely not produce 100% usable code. In other words, you can read the source, but you can't really modify and repackage it. Note that if the source has been obfuscated with proguard, the resulting source code will be substantially more difficult to untangle.

The other major alternative is to disassemble the bytecode to smali, an assembly language designed for precisely this purpose. I've found that the easiest way to do this is with apktool. Once you've got apktool installed, you can just point it at an apk file, and you'll get back a smali file for each class contained in the application. You can read and modify the smali or even replace classes entirely by generating smali from new Java source (to do this, you could compile your .java source to .class files with javac, then convert your .class files to .dex files with Android's dx compiler, and then use baksmali (smali disassembler) to convert the .dex to .smali files, as described in this question. There might be a shortcut here). Once you're done, you can easily package the apk back up with apktool again. Note that apktool does not sign the resulting apk, so you'll need to take care of that just like any other Android application.

If you go the smali route, you might want to try APK Studio, an IDE that automates some of the above steps to assist you with decompiling and recompiling an apk and installing it on a device.

In short, your choices are pretty much either to decompile into Java, which is more readable but likely irreversible, or to disassemble to smali, which is harder to read but much more flexible to make changes and repackage a modified app. Which approach you choose would depend on what you're looking to achieve.

Lastly, the suggestion of dare is also of note. It's a retargeting tool to convert .dex and .apk files to java .class files, so that they can be analyzed using typical java static analysis tools.

What's the difference between an element and a node in XML?

Different W3C specifications define different sets of "Node" types.

Thus, the DOM spec defines the following types of nodes:

  • Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType
  • DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • DocumentType -- no children
  • EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
  • Attr -- Text, EntityReference
  • ProcessingInstruction -- no children
  • Comment -- no children
  • Text -- no children
  • CDATASection -- no children
  • Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Notation -- no children

The XML Infoset (used by XPath) has a smaller set of nodes:

  • The Document Information Item
  • Element Information Items
  • Attribute Information Items
  • Processing Instruction Information Items
  • Unexpanded Entity Reference Information Items
  • Character Information Items
  • Comment Information Items
  • The Document Type Declaration Information Item
  • Unparsed Entity Information Items
  • Notation Information Items
  • Namespace Information Items
  • XPath has the following Node types:

    • root nodes
    • element nodes
    • text nodes
    • attribute nodes
    • namespace nodes
    • processing instruction nodes
    • comment nodes

    The answer to your question "What is the difference between an element and a node" is:

    An element is a type of node. Many other types of nodes exist and serve different purposes.

    How to add not null constraint to existing column in MySQL

    Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:

    ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;
    

    A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a column comment, you need to specify it in the MODIFY statement along with the data type and the NOT NULL, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable query, modify it to include the NOT NULL constraint, and paste it into your ALTER TABLE... MODIFY... query.

    Matching strings with wildcard

    Using of WildcardPattern from System.Management.Automation may be an option.

    pattern = new WildcardPattern(patternString);
    pattern.IsMatch(stringToMatch);
    

    Visual Studio UI may not allow you to add System.Management.Automation assembly to References of your project. Feel free to add it manually, as described here.

    Clear contents of cells in VBA using column reference

    As Gary's Student mentioned, you would need to remove the dot before Cells to make the code work as you originally wrote it. I can't be sure, since you only included the one line of code, but the error you got when you deleted the dots might have something to do with how you defined your variables.

    I ran your line of code with the variables defined as integers and it worked:

    Sub TestClearLastColumn()
    
        Dim LastColData As Long
            Set LastColData = Range("A1").End(xlToRight).Column
    
        Dim LastRowData As Long
            Set LastRowData = Range("A1").End(xlDown).Row
    
        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
    
    End Sub
    

    I don't think a With statement is appropriate to the line of code you shared, but if you were to use one, the With would be at the start of the line that defines the object you are manipulating. Here is your code rewritten using an unnecessary With statement:

    With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
        .ClearContents
    End With
    

    With statements are designed to save you from retyping code and to make your coding easier to read. It becomes useful and appropriate if you do more than one thing with an object. For example, if you wanted to also turn the column red and add a thick black border, you might use a With statement like this:

    With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
        .ClearContents
        .Interior.Color = vbRed
        .BorderAround Color:=vbBlack, Weight:=xlThick
    End With
    

    Otherwise you would have to declare the range for each action or property, like this:

        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).Interior.Color = vbRed
        Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).BorderAround Color:=vbBlack, Weight:=xlThick
    

    I hope this gives you a sense for why Gary's Student believed the compiler might be expecting a With (even though it was inappropriate) and how and when a With can be useful in your code.

    SQL grouping by month and year

    If you want to stay having the field in datetime datatype, try using this:

    SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
    FROM [Order] o
    WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3')
    GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0)
    

    It it also easy to change to group by hours, days, weeks, years...
    I hope it is of use to someone,

    Regards!

    SQL Server AS statement aliased column within WHERE statement

    This would work on your edited question !

    SELECT * FROM (SELECT <Column_List>,  
    ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) )  
    AS distance 
    FROM poi_table) TMP
    WHERE distance < 500; 
    

    How do I import a CSV file in R?

    You would use the read.csv function; for example:

    dat = read.csv("spam.csv", header = TRUE)
    

    You can also reference this tutorial for more details.

    Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

    How to do something before on submit?

    You can use onclick to run some JavaScript or jQuery code before submitting the form like this:

    <script type="text/javascript">
        beforeSubmit = function(){
            if (1 == 1){
                //your before submit logic
            }        
            $("#formid").submit();            
        }
    </script>
    <input type="button" value="Click" onclick="beforeSubmit();" />
    

    How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

    In regards to JavaScript:

    The === operator works the same as the == operator, but it requires that its operands have not only the same value, but also the same data type.

    For example, the sample below will display 'x and y are equal', but not 'x and y are identical'.

    var x = 4;
    var y = '4';
    if (x == y) {
        alert('x and y are equal');
    }
    if (x === y) {
        alert('x and y are identical');
    }
    

    "VT-x is not available" when I start my Virtual machine

    You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

    Creating a procedure in mySql with parameters

    (IN @brugernavn varchar(64)**)**,IN @password varchar(64))
    

    The problem is the )

    Easiest way to split a string on newlines in .NET?

    I'm currently using this function (based on other answers) in VB.NET:

    Private Shared Function SplitLines(text As String) As String()
        Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
    End Function
    

    It tries to split on the platform-local newline first, and then falls back to each possible newline.

    I've only needed this inside one class so far. If that changes, I will probably make this Public and move it to a utility class, and maybe even make it an extension method.

    Here's how to join the lines back up, for good measure:

    Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
        Return String.Join(Environment.NewLine, lines)
    End Function
    

    How to copy multiple files in one layer using a Dockerfile?

    It might be worth mentioning that you can also create a .dockerignore file, to exclude the files that you don't want to copy:

    https://docs.docker.com/engine/reference/builder/#dockerignore-file

    Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

    Can a table have two foreign keys?

    Yes, MySQL allows this. You can have multiple foreign keys on the same table.

    Get more details here FOREIGN KEY Constraints

    Using Apache POI how to read a specific excel column

    Here is the code to read the excel data by column.

    public ArrayList<String> extractExcelContentByColumnIndex(int columnIndex){
            ArrayList<String> columndata = null;
            try {
                File f = new File("sample.xlsx")
                FileInputStream ios = new FileInputStream(f);
                XSSFWorkbook workbook = new XSSFWorkbook(ios);
                XSSFSheet sheet = workbook.getSheetAt(0);
                Iterator<Row> rowIterator = sheet.iterator();
                columndata = new ArrayList<>();
    
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
    
                        if(row.getRowNum() > 0){ //To filter column headings
                            if(cell.getColumnIndex() == columnIndex){// To match column index
                                switch (cell.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    columndata.add(cell.getNumericCellValue()+"");
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    columndata.add(cell.getStringCellValue());
                                    break;
                                }
                            }
                        }
                    }
                }
                ios.close();
                System.out.println(columndata);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return columndata;
        }
    

    Adding headers when using httpClient.GetAsync

    The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:

    client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
    client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);
    

    Running CMake on Windows

    There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

    How to capture a backspace on the onkeydown event

    not sure if it works outside of firefox:

    callback (event){
      if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
        // do something
      }
    }
    

    if not, replace event.DOM_VK_BACK_SPACE with 8 and event.DOM_VK_DELETE with 46 or define them as constant (for better readability)

    Cannot create PoolableConnectionFactory

    This is the actual cause of the problem:

    Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    You have a database communication link problem. Make sure that your application have network access to your database (and the firewall isn't blocking ports to your database).

    Tensorflow: how to save/restore a model?

    Tensorflow 2 Docs

    Saving Checkpoints

    Adapted from the docs

    # -------------------------
    # -----  Toy Context  -----
    # -------------------------
    import tensorflow as tf
    
    
    class Net(tf.keras.Model):
        """A simple linear model."""
    
        def __init__(self):
            super(Net, self).__init__()
            self.l1 = tf.keras.layers.Dense(5)
    
        def call(self, x):
            return self.l1(x)
    
    
    def toy_dataset():
        inputs = tf.range(10.0)[:, None]
        labels = inputs * 5.0 + tf.range(5.0)[None, :]
        return (
            tf.data.Dataset.from_tensor_slices(dict(x=inputs, y=labels)).repeat().batch(2)
        )
    
    
    def train_step(net, example, optimizer):
        """Trains `net` on `example` using `optimizer`."""
        with tf.GradientTape() as tape:
            output = net(example["x"])
            loss = tf.reduce_mean(tf.abs(output - example["y"]))
        variables = net.trainable_variables
        gradients = tape.gradient(loss, variables)
        optimizer.apply_gradients(zip(gradients, variables))
        return loss
    
    
    # ----------------------------
    # -----  Create Objects  -----
    # ----------------------------
    
    net = Net()
    opt = tf.keras.optimizers.Adam(0.1)
    dataset = toy_dataset()
    iterator = iter(dataset)
    ckpt = tf.train.Checkpoint(
        step=tf.Variable(1), optimizer=opt, net=net, iterator=iterator
    )
    manager = tf.train.CheckpointManager(ckpt, "./tf_ckpts", max_to_keep=3)
    
    # ----------------------------
    # -----  Train and Save  -----
    # ----------------------------
    
    ckpt.restore(manager.latest_checkpoint)
    if manager.latest_checkpoint:
        print("Restored from {}".format(manager.latest_checkpoint))
    else:
        print("Initializing from scratch.")
    
    for _ in range(50):
        example = next(iterator)
        loss = train_step(net, example, opt)
        ckpt.step.assign_add(1)
        if int(ckpt.step) % 10 == 0:
            save_path = manager.save()
            print("Saved checkpoint for step {}: {}".format(int(ckpt.step), save_path))
            print("loss {:1.2f}".format(loss.numpy()))
    
    
    # ---------------------
    # -----  Restore  -----
    # ---------------------
    
    # In another script, re-initialize objects
    opt = tf.keras.optimizers.Adam(0.1)
    net = Net()
    dataset = toy_dataset()
    iterator = iter(dataset)
    ckpt = tf.train.Checkpoint(
        step=tf.Variable(1), optimizer=opt, net=net, iterator=iterator
    )
    manager = tf.train.CheckpointManager(ckpt, "./tf_ckpts", max_to_keep=3)
    
    # Re-use the manager code above ^
    
    ckpt.restore(manager.latest_checkpoint)
    if manager.latest_checkpoint:
        print("Restored from {}".format(manager.latest_checkpoint))
    else:
        print("Initializing from scratch.")
    
    for _ in range(50):
        example = next(iterator)
        # Continue training or evaluate etc.
    
    

    More links

    Checkpoints capture the exact value of all parameters (tf.Variable objects) used by a model. Checkpoints do not contain any description of the computation defined by the model and thus are typically only useful when source code that will use the saved parameter values is available.

    The SavedModel format on the other hand includes a serialized description of the computation defined by the model in addition to the parameter values (checkpoint). Models in this format are independent of the source code that created the model. They are thus suitable for deployment via TensorFlow Serving, TensorFlow Lite, TensorFlow.js, or programs in other programming languages (the C, C++, Java, Go, Rust, C# etc. TensorFlow APIs).

    (Highlights are my own)


    Tensorflow < 2


    From the docs:

    Save

    # Create some variables.
    v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
    v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)
    
    inc_v1 = v1.assign(v1+1)
    dec_v2 = v2.assign(v2-1)
    
    # Add an op to initialize the variables.
    init_op = tf.global_variables_initializer()
    
    # Add ops to save and restore all the variables.
    saver = tf.train.Saver()
    
    # Later, launch the model, initialize the variables, do some work, and save the
    # variables to disk.
    with tf.Session() as sess:
      sess.run(init_op)
      # Do some work with the model.
      inc_v1.op.run()
      dec_v2.op.run()
      # Save the variables to disk.
      save_path = saver.save(sess, "/tmp/model.ckpt")
      print("Model saved in path: %s" % save_path)
    

    Restore

    tf.reset_default_graph()
    
    # Create some variables.
    v1 = tf.get_variable("v1", shape=[3])
    v2 = tf.get_variable("v2", shape=[5])
    
    # Add ops to save and restore all the variables.
    saver = tf.train.Saver()
    
    # Later, launch the model, use the saver to restore variables from disk, and
    # do some work with the model.
    with tf.Session() as sess:
      # Restore variables from disk.
      saver.restore(sess, "/tmp/model.ckpt")
      print("Model restored.")
      # Check the values of the variables
      print("v1 : %s" % v1.eval())
      print("v2 : %s" % v2.eval())
    

    simple_save

    Many good answer, for completeness I'll add my 2 cents: simple_save. Also a standalone code example using the tf.data.Dataset API.

    Python 3 ; Tensorflow 1.14

    import tensorflow as tf
    from tensorflow.saved_model import tag_constants
    
    with tf.Graph().as_default():
        with tf.Session() as sess:
            ...
    
            # Saving
            inputs = {
                "batch_size_placeholder": batch_size_placeholder,
                "features_placeholder": features_placeholder,
                "labels_placeholder": labels_placeholder,
            }
            outputs = {"prediction": model_output}
            tf.saved_model.simple_save(
                sess, 'path/to/your/location/', inputs, outputs
            )
    

    Restoring:

    graph = tf.Graph()
    with restored_graph.as_default():
        with tf.Session() as sess:
            tf.saved_model.loader.load(
                sess,
                [tag_constants.SERVING],
                'path/to/your/location/',
            )
            batch_size_placeholder = graph.get_tensor_by_name('batch_size_placeholder:0')
            features_placeholder = graph.get_tensor_by_name('features_placeholder:0')
            labels_placeholder = graph.get_tensor_by_name('labels_placeholder:0')
            prediction = restored_graph.get_tensor_by_name('dense/BiasAdd:0')
    
            sess.run(prediction, feed_dict={
                batch_size_placeholder: some_value,
                features_placeholder: some_other_value,
                labels_placeholder: another_value
            })
    

    Standalone example

    Original blog post

    The following code generates random data for the sake of the demonstration.

    1. We start by creating the placeholders. They will hold the data at runtime. From them, we create the Dataset and then its Iterator. We get the iterator's generated tensor, called input_tensor which will serve as input to our model.
    2. The model itself is built from input_tensor: a GRU-based bidirectional RNN followed by a dense classifier. Because why not.
    3. The loss is a softmax_cross_entropy_with_logits, optimized with Adam. After 2 epochs (of 2 batches each), we save the "trained" model with tf.saved_model.simple_save. If you run the code as is, then the model will be saved in a folder called simple/ in your current working directory.
    4. In a new graph, we then restore the saved model with tf.saved_model.loader.load. We grab the placeholders and logits with graph.get_tensor_by_name and the Iterator initializing operation with graph.get_operation_by_name.
    5. Lastly we run an inference for both batches in the dataset, and check that the saved and restored model both yield the same values. They do!

    Code:

    import os
    import shutil
    import numpy as np
    import tensorflow as tf
    from tensorflow.python.saved_model import tag_constants
    
    
    def model(graph, input_tensor):
        """Create the model which consists of
        a bidirectional rnn (GRU(10)) followed by a dense classifier
    
        Args:
            graph (tf.Graph): Tensors' graph
            input_tensor (tf.Tensor): Tensor fed as input to the model
    
        Returns:
            tf.Tensor: the model's output layer Tensor
        """
        cell = tf.nn.rnn_cell.GRUCell(10)
        with graph.as_default():
            ((fw_outputs, bw_outputs), (fw_state, bw_state)) = tf.nn.bidirectional_dynamic_rnn(
                cell_fw=cell,
                cell_bw=cell,
                inputs=input_tensor,
                sequence_length=[10] * 32,
                dtype=tf.float32,
                swap_memory=True,
                scope=None)
            outputs = tf.concat((fw_outputs, bw_outputs), 2)
            mean = tf.reduce_mean(outputs, axis=1)
            dense = tf.layers.dense(mean, 5, activation=None)
    
            return dense
    
    
    def get_opt_op(graph, logits, labels_tensor):
        """Create optimization operation from model's logits and labels
    
        Args:
            graph (tf.Graph): Tensors' graph
            logits (tf.Tensor): The model's output without activation
            labels_tensor (tf.Tensor): Target labels
    
        Returns:
            tf.Operation: the operation performing a stem of Adam optimizer
        """
        with graph.as_default():
            with tf.variable_scope('loss'):
                loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
                        logits=logits, labels=labels_tensor, name='xent'),
                        name="mean-xent"
                        )
            with tf.variable_scope('optimizer'):
                opt_op = tf.train.AdamOptimizer(1e-2).minimize(loss)
            return opt_op
    
    
    if __name__ == '__main__':
        # Set random seed for reproducibility
        # and create synthetic data
        np.random.seed(0)
        features = np.random.randn(64, 10, 30)
        labels = np.eye(5)[np.random.randint(0, 5, (64,))]
    
        graph1 = tf.Graph()
        with graph1.as_default():
            # Random seed for reproducibility
            tf.set_random_seed(0)
            # Placeholders
            batch_size_ph = tf.placeholder(tf.int64, name='batch_size_ph')
            features_data_ph = tf.placeholder(tf.float32, [None, None, 30], 'features_data_ph')
            labels_data_ph = tf.placeholder(tf.int32, [None, 5], 'labels_data_ph')
            # Dataset
            dataset = tf.data.Dataset.from_tensor_slices((features_data_ph, labels_data_ph))
            dataset = dataset.batch(batch_size_ph)
            iterator = tf.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes)
            dataset_init_op = iterator.make_initializer(dataset, name='dataset_init')
            input_tensor, labels_tensor = iterator.get_next()
    
            # Model
            logits = model(graph1, input_tensor)
            # Optimization
            opt_op = get_opt_op(graph1, logits, labels_tensor)
    
            with tf.Session(graph=graph1) as sess:
                # Initialize variables
                tf.global_variables_initializer().run(session=sess)
                for epoch in range(3):
                    batch = 0
                    # Initialize dataset (could feed epochs in Dataset.repeat(epochs))
                    sess.run(
                        dataset_init_op,
                        feed_dict={
                            features_data_ph: features,
                            labels_data_ph: labels,
                            batch_size_ph: 32
                        })
                    values = []
                    while True:
                        try:
                            if epoch < 2:
                                # Training
                                _, value = sess.run([opt_op, logits])
                                print('Epoch {}, batch {} | Sample value: {}'.format(epoch, batch, value[0]))
                                batch += 1
                            else:
                                # Final inference
                                values.append(sess.run(logits))
                                print('Epoch {}, batch {} | Final inference | Sample value: {}'.format(epoch, batch, values[-1][0]))
                                batch += 1
                        except tf.errors.OutOfRangeError:
                            break
                # Save model state
                print('\nSaving...')
                cwd = os.getcwd()
                path = os.path.join(cwd, 'simple')
                shutil.rmtree(path, ignore_errors=True)
                inputs_dict = {
                    "batch_size_ph": batch_size_ph,
                    "features_data_ph": features_data_ph,
                    "labels_data_ph": labels_data_ph
                }
                outputs_dict = {
                    "logits": logits
                }
                tf.saved_model.simple_save(
                    sess, path, inputs_dict, outputs_dict
                )
                print('Ok')
        # Restoring
        graph2 = tf.Graph()
        with graph2.as_default():
            with tf.Session(graph=graph2) as sess:
                # Restore saved values
                print('\nRestoring...')
                tf.saved_model.loader.load(
                    sess,
                    [tag_constants.SERVING],
                    path
                )
                print('Ok')
                # Get restored placeholders
                labels_data_ph = graph2.get_tensor_by_name('labels_data_ph:0')
                features_data_ph = graph2.get_tensor_by_name('features_data_ph:0')
                batch_size_ph = graph2.get_tensor_by_name('batch_size_ph:0')
                # Get restored model output
                restored_logits = graph2.get_tensor_by_name('dense/BiasAdd:0')
                # Get dataset initializing operation
                dataset_init_op = graph2.get_operation_by_name('dataset_init')
    
                # Initialize restored dataset
                sess.run(
                    dataset_init_op,
                    feed_dict={
                        features_data_ph: features,
                        labels_data_ph: labels,
                        batch_size_ph: 32
                    }
    
                )
                # Compute inference for both batches in dataset
                restored_values = []
                for i in range(2):
                    restored_values.append(sess.run(restored_logits))
                    print('Restored values: ', restored_values[i][0])
    
        # Check if original inference and restored inference are equal
        valid = all((v == rv).all() for v, rv in zip(values, restored_values))
        print('\nInferences match: ', valid)
    

    This will print:

    $ python3 save_and_restore.py
    
    Epoch 0, batch 0 | Sample value: [-0.13851789 -0.3087595   0.12804556  0.20013677 -0.08229901]
    Epoch 0, batch 1 | Sample value: [-0.00555491 -0.04339041 -0.05111827 -0.2480045  -0.00107776]
    Epoch 1, batch 0 | Sample value: [-0.19321944 -0.2104792  -0.00602257  0.07465433  0.11674127]
    Epoch 1, batch 1 | Sample value: [-0.05275984  0.05981954 -0.15913513 -0.3244143   0.10673307]
    Epoch 2, batch 0 | Final inference | Sample value: [-0.26331693 -0.13013336 -0.12553    -0.04276478  0.2933622 ]
    Epoch 2, batch 1 | Final inference | Sample value: [-0.07730117  0.11119192 -0.20817074 -0.35660955  0.16990358]
    
    Saving...
    INFO:tensorflow:Assets added to graph.
    INFO:tensorflow:No assets to write.
    INFO:tensorflow:SavedModel written to: b'/some/path/simple/saved_model.pb'
    Ok
    
    Restoring...
    INFO:tensorflow:Restoring parameters from b'/some/path/simple/variables/variables'
    Ok
    Restored values:  [-0.26331693 -0.13013336 -0.12553    -0.04276478  0.2933622 ]
    Restored values:  [-0.07730117  0.11119192 -0.20817074 -0.35660955  0.16990358]
    
    Inferences match:  True
    

    A table name as a variable

    For static queries, like the one in your question, table names and column names need to be static.

    For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.

    Here is an example of a script used to compare data between the same tables of different databases:

    Static query:

    SELECT * FROM [DB_ONE].[dbo].[ACTY]
    EXCEPT
    SELECT * FROM [DB_TWO].[dbo].[ACTY]
    

    Since I want to easily change the name of table and schema, I have created this dynamic query:

    declare @schema varchar(50)
    declare @table varchar(50)
    declare @query nvarchar(500)
    
    set @schema = 'dbo'
    set @table = 'ACTY'
    
    set @query = 'SELECT * FROM [DB_ONE].[' + @schema + '].[' + @table + '] EXCEPT SELECT * FROM [DB_TWO].[' + @schema + '].[' + @table + ']'
    
    EXEC sp_executesql @query
    

    Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL

    How to get a microtime in Node.js?

    To work with more precision than Date.now(), but with milliseconds in float precision:

    function getTimeMSFloat() {
        var hrtime = process.hrtime();
        return ( hrtime[0] * 1000000 + hrtime[1] / 1000 ) / 1000;
    }
    

    Call a Subroutine from a different Module in VBA

    Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

    How to use RANK() in SQL Server

    You have already grouped by ContenderNum, no need to partition again by it. Use Dense_rank()and order by totals desc. In short,

    SELECT contendernum,totals, **DENSE_RANK()** 
    OVER (ORDER BY totals **DESC**) 
    AS xRank 
    FROM
    (
       SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
       FROM dbo.Cat1GroupImpersonation
       GROUP BY ContenderNum
    ) AS a
    

    java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

    you can covert domain to IP address because every Domain have specific IP address, then you will solve that issue. I hope this will help you.