Programs & Examples On #Poplib

How to center HTML5 Videos?

.center { width:500px; margin-right:auto; margin-left:auto; }

What is console.log in jQuery?

jQuery and console.log are unrelated entities, although useful when used together.

If you use a browser's built-in dev tools, console.log will log information about the object being passed to the log function.

If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:

if (window.console) console.log('foo');

The shortcut form of this might be seen instead:

window.console&&console.log('foo');

There are other useful debugging functions as well, such as debug, dir and error. Firebug's wiki lists the available functions in the console api.

Wait until ActiveWorkbook.RefreshAll finishes - VBA

What I've done to solve this problem is save the workbook. This forces it to refresh before closing.

The same approach works for copying many formulas before performing the next operation.

Is it possible to animate scrollTop with jQuery?

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

We demonstrate features of lmfit while solving both problems.

Given

import lmfit

import numpy as np

import matplotlib.pyplot as plt


%matplotlib inline
np.random.seed(123)
# General Functions
def func_log(x, a, b, c):
    """Return values from a general log function."""
    return a * np.log(b * x) + c


# Data
x_samp = np.linspace(1, 5, 50)
_noise = np.random.normal(size=len(x_samp), scale=0.06)
y_samp = 2.5 * np.exp(1.2 * x_samp) + 0.7 + _noise
y_samp2 = 2.5 * np.log(1.2 * x_samp) + 0.7 + _noise

Code

Approach 1 - lmfit Model

Fit exponential data

regressor = lmfit.models.ExponentialModel()                # 1    
initial_guess = dict(amplitude=1, decay=-1)                # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit    

plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here

Approach 2 - Custom Model

Fit log data

regressor = lmfit.Model(func_log)                          # 1
initial_guess = dict(a=1, b=.1, c=.1)                      # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit

plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here


Details

  1. Choose a regression class
  2. Supply named, initial guesses that respect the function's domain

You can determine the inferred parameters from the regressor object. Example:

regressor.param_names
# ['decay', 'amplitude']

To make predictions, use the ModelResult.eval() method.

model = results.eval
y_pred = model(x=np.array([1.5]))

Note: the ExponentialModel() follows a decay function, which accepts two parameters, one of which is negative.

enter image description here

See also ExponentialGaussianModel(), which accepts more parameters.

Install the library via > pip install lmfit.

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/

Trees in Twitter Bootstrap

If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)

http://jsfiddle.net/mehmetatas/fXzHS/2/

$(function () {
    $('.tree li').hide();
    $('.tree li:first').show();
    $('.tree li').on('click', function (e) {
        var children = $(this).find('> ul > li');
        if (children.is(":visible")) children.hide('fast');
        else children.show('fast');
        e.stopPropagation();
    });
});

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

I had this issue recently and I resolved it by simply rolling IE8 back to IE7.

My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.

jQuery date formatting

You can try http://www.datejs.com/

 $('#idInput').val( Date.parse("Jun 18, 2017 7:00:00 PM").toString('yyyy-MM-dd'));

BR

Making an iframe responsive

The best solution to make an "iframe" responsive and fit with all device screens , simply apply this code (working great with Games sites):

iframe::-webkit-scrollbar{display:none}
.iframe{background:#fff;overflow:hidden}
.iframe iframe{width:100%;height:540px;border:0;display:block}
.iframe-content{position:absolute;width:100%;height:540px;overflow:auto;top:0;bottom:0;-webkit-overflow-scrolling:touch}

@media screen and (max-width:992px){.iframe iframe{height:720px}}
@media screen and (max-width:768px){.iframe iframe{height:720px}}
@media screen and (max-width:720px){.iframe iframe{height:720px}}
@media screen and (max-width:479px){.iframe iframe{height:480px}}
@media screen and (max-height:400px){.iframe iframe{height:360px}}

If you're looking for a responsive games container fit with all devices apply this code which uses advanced CSS @media queries.

What is the Simplest Way to Reverse an ArrayList?

ArrayList<Integer> myArray = new ArrayList<Integer>();

myArray.add(1);
myArray.add(2);
myArray.add(3);

int reverseArrayCounter = myArray.size() - 1;

for (int i = reverseArrayCounter; i >= 0; i--) {
    System.out.println(myArray.get(i));
}

HighCharts Hide Series Name from the Legend

Looks like HighChart 2.2.0 has resolved this issue. I tried it here with the same code you have, and the first series is hidden now. Could you try it with HighChart 2.2.0?

How to clear/delete the contents of a Tkinter Text widget?

this works

import tkinter as tk
inputEdit.delete("1.0",tk.END)

Hive: Filtering Data between Specified Dates when Date is a String

Try this:

select * from your_table
where date >= '2020-10-01'  

Copy a file from one folder to another using vbscripting

Please find the below code:

If ComboBox21.Value = "Delimited file" Then
    'Const txtFldrPath As String = "C:\Users\513090.CTS\Desktop\MACRO"      'Change to folder path containing text files
    Dim myValue2 As String
    myValue2 = ComboBox22.Value
    Dim txtFldrPath As Variant
    txtFldrPath = InputBox("Give the file path")
    'Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "LL.txt")
    Dim strLine() As String
    Dim LineIndex As Long
    Dim myValue As Variant
    On Error GoTo Errhandler
    myValue = InputBox("Give the DELIMITER")

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    While txtFldrPath <> vbNullString
        LineIndex = 0
        Close #1
        'Open txtFldrPath & "\" & CurrentFile For Input As #1
        Open txtFldrPath For Input As #1
        While Not EOF(1)
            LineIndex = LineIndex + 1
            ReDim Preserve strLine(1 To LineIndex)
            Line Input #1, strLine(LineIndex)
        Wend
        Close #1

        With ActiveWorkbook.Sheets(myValue2).Range("A1").Resize(LineIndex, 1)
            .Value = WorksheetFunction.Transpose(strLine)
            .TextToColumns Other:=True, OtherChar:=myValue
        End With

        'ActiveSheet.UsedRange.EntireColumn.AutoFit
        'ActiveSheet.Copy
        'ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xls"), xlNormal
        'ActiveWorkbook.Close False
       ' ActiveSheet.UsedRange.ClearContents

        CurrentFile = Dir
    Wend
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End If

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

Jacob Helwig mentions in his answer that:

It looks like rev-parse is being used without sufficient error checking before-hand

Commit 62f162f from Jeff King (peff) should improve the robustness of git rev-parse in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):

For cases where we do not match (e.g., "doesnotexist..HEAD"), we would then want to try to treat the argument as a filename.
try_difference() gets this right, and always unmunges in this case.
However, try_parent_shorthand() never unmunges, leading to incorrect error messages, or even incorrect results:

$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Clear form fields with jQuery

@using (Ajax.BeginForm("Create", "AcceptanceQualityDefect", new AjaxOptions()
{
    OnSuccess = "ClearInput",
    HttpMethod = "Post",
    UpdateTargetId = "defect-list",
    InsertionMode = InsertionMode.Replace
}, new { @id = "frmID" })) 
  1. frmID is the identification of the form
  2. OnSuccess of the operation we call the JavaScript function with the name "ClearInput"

    <script type="text/javascript">
        function ClearInput() {
            //call action for render create view
            $("#frmID").get(0).reset();
        }
    </script>
    
  3. if you do both of these right, then you will not be able to stop it from working...

Best practices to test protected methods with PHPUnit

If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:

protected static function getMethod($name) {
  $class = new ReflectionClass('MyClass');
  $method = $class->getMethod($name);
  $method->setAccessible(true);
  return $method;
}

public function testFoo() {
  $foo = self::getMethod('foo');
  $obj = new MyClass();
  $foo->invokeArgs($obj, array(...));
  ...
}

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to programmatically click a button in WPF?

The problem with the Automation API solution is, that it required a reference to the Framework assembly UIAutomationProvider as project/package dependency.

An alternative is to emulate the behaviour. In the following there is my extended solution which also condiders the MVVM-pattern with its bound commands - implemented as extension method:

public static class ButtonExtensions
{
    /// <summary>
    /// Performs a click on the button.<br/>
    /// This is the WPF-equivalent of the Windows Forms method "<see cref="M:System.Windows.Forms.Button.PerformClick" />".
    /// <para>This simulates the same behaviours as the button was clicked by the user by keyboard or mouse:<br />
    /// 1. The raising the ClickEvent.<br />
    /// 2.1. Checking that the bound command can be executed, calling <see cref="ICommand.CanExecute" />, if a command is bound.<br />
    /// 2.2. If command can be executed, then the <see cref="ICommand.Execute(object)" /> will be called and the optional bound parameter is p
    /// </para>
    /// </summary>
    /// <param name="sourceButton">The source button.</param>
    /// <exception cref="ArgumentNullException">sourceButton</exception>
    public static void PerformClick(this Button sourceButton)
    {
        // Check parameters
        if (sourceButton == null)
            throw new ArgumentNullException(nameof(sourceButton));

        // 1.) Raise the Click-event
        sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));

        // 2.) Execute the command, if bound and can be executed
        ICommand boundCommand = sourceButton.Command;
        if (boundCommand != null)
        {
            object parameter = sourceButton.CommandParameter;
            if (boundCommand.CanExecute(parameter) == true)
                boundCommand.Execute(parameter);
        }
    }
}

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

How to run a C# application at Windows startup?

first I tried the code below and it was not working

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());

Then, I changed CurrentUser with LocalMachine and it works

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());

How to vertically align elements in a div?

For me, it worked this way:

<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
    <a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>

The "a" element converted to a button, using Bootstrap classes, and it is now vertically centered inside an outer "div".

Pandas create empty DataFrame with only column names

df.to_html() has a columns parameter.

Just pass the columns into the to_html() method.

df.to_html(columns=['A','B','C','D','E','F','G'])

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You can just put // in front of $yourUrl in href:

<a href="//<?=$yourUrl?>"></a>

Is log(n!) = T(n·log(n))?

See Stirling's Approximation:

ln(n!) = n*ln(n) - n + O(ln(n))

where the last 2 terms are less significant than the first one.

Using Position Relative/Absolute within a TD?

This trick also suitable, but in this case align properties (middle, bottom etc.) won't be working.

<td style="display: block; position: relative;">
</td>

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Sometimes, I just open project structure, and click project, then choose a SDK version.

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

What is The Rule of Three?

The law of the big three is as specified above.

An easy example, in plain English, of the kind of problem it solves:

Non default destructor

You allocated memory in your constructor and so you need to write a destructor to delete it. Otherwise you will cause a memory leak.

You might think that this is job done.

The problem will be, if a copy is made of your object, then the copy will point to the same memory as the original object.

Once, one of these deletes the memory in its destructor, the other will have a pointer to invalid memory (this is called a dangling pointer) when it tries to use it things are going to get hairy.

Therefore, you write a copy constructor so that it allocates new objects their own pieces of memory to destroy.

Assignment operator and copy constructor

You allocated memory in your constructor to a member pointer of your class. When you copy an object of this class the default assignment operator and copy constructor will copy the value of this member pointer to the new object.

This means that the new object and the old object will be pointing at the same piece of memory so when you change it in one object it will be changed for the other objerct too. If one object deletes this memory the other will carry on trying to use it - eek.

To resolve this you write your own version of the copy constructor and assignment operator. Your versions allocate separate memory to the new objects and copy across the values that the first pointer is pointing to rather than its address.

How to print without newline or space?

You can try:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How to mkdir only if a directory does not already exist?

This is a simple function (Bash shell) which lets you create a directory if it doesn't exist.

#----------------------------------
# Create a directory if it doesn't exist
#------------------------------------
createDirectory() {
    if [ ! -d $1 ]
        then
        mkdir -p $1
    fi
}

You can call the above function as:

createDirectory /tmp/fooDir/BarDir

The above creates fooDir and BarDir if they don't exist. Note the "-p" option in the mkdir command which creates directories recursively.

MySQL Like multiple values

Don't forget to use parenthesis if you use this function after an AND parameter

Like this:

WHERE id=123 and(interests LIKE '%sports%' OR interests LIKE '%pub%')

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

How to remove an element from a list by index

You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.

>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
 3
>>> a
[1, 4, 5]
>>> 

How to ping a server only once from within a batch file?

I am sure you must have named the resultant bat file as "ping.bat". If you rename your file to something else say pingXXX.bat. It will definitely work. Try it out.

my batch file contains below code only

ping 172.31.29.1 -t

with file name as ping.bat enter image description here

with file name abc.bat

enter image description here

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

I guess it follows mathematical tradition. In mathematics, it is often said "let x be arbitrary real number" or like that.

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How can I add comments in MySQL?

You can use single line comments:

-- this is a comment
# this is also a comment

Or a multiline comment:

/*
   multiline
   comment
*/

Spring RequestMapping for controllers that produce and consume JSON

You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.

  • The accepts header of the request is application/json
  • @ResponseBody annotated method
  • Jackson library on classpath

You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody

Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.

How to completely remove Python from a Windows machine?

you can delete it manually.

  1. open Command Prompt
  2. cd C:\Users\<you name>\AppData\Local\Microsoft\WindowsApps
  3. del python.exe
  4. del python3.exe

Now the command prompt won't be showing it anymore

where python --> yields nothing, and you are free to install another version from source / anaconda and (after adding its address to Environment Variables -> Path) you will find that very python you just installed

Playing a video in VideoView in Android

The code seems to be flawless! Simple and plain.
So it should work on the phone. The emulator is having hard time playing videos, it happened to me too.

Try increasing the required API level to the latest, it might help!

Right click on opened project, chose Properties > Android > check the latest version on the right side...

Igor

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

Evaluate empty or null JSTL c tags

How can I validate if a String is null or empty using the c tags of JSTL?

You can use the empty keyword in a <c:if> for this:

<c:if test="${empty var1}">
    var1 is empty or null.
</c:if>
<c:if test="${not empty var1}">
    var1 is NOT empty or null.
</c:if>

Or the <c:choose>:

<c:choose>
    <c:when test="${empty var1}">
        var1 is empty or null.
    </c:when>
    <c:otherwise>
        var1 is NOT empty or null.
    </c:otherwise>
</c:choose>

Or if you don't need to conditionally render a bunch of tags and thus you could only check it inside a tag attribute, then you can use the EL conditional operator ${condition? valueIfTrue : valueIfFalse}:

<c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" />

To learn more about those ${} things (the Expression Language, which is a separate subject from JSTL), check here.

See also:

Timeout a command in bash without unnecessary delay

Here is a version that does not rely on spawning a child process - I needed a standalone script which embedded this functionality. It also does a fractional poll interval, so you can poll quicker. timeout would have been preferred - but I'm stuck on an old server

# wait_on_command <timeout> <poll interval> command
wait_on_command()
{
    local timeout=$1; shift
    local interval=$1; shift
    $* &
    local child=$!

    loops=$(bc <<< "($timeout * (1 / $interval)) + 0.5" | sed 's/\..*//g')
    ((t = loops))
    while ((t > 0)); do
        sleep $interval
        kill -0 $child &>/dev/null || return
        ((t -= 1))
    done

    kill $child &>/dev/null || kill -0 $child &>/dev/null || return
    sleep $interval
    kill -9 $child &>/dev/null
    echo Timed out
}

slow_command()
{
    sleep 2
    echo Completed normally
}

# wait 1 sec in 0.1 sec increments
wait_on_command 1 0.1 slow_command

# or call an external command
wait_on_command 1 0.1 sleep 10

How to install python developer package?

yum install python-devel will work.

If yum doesn't work then use

apt-get install python-dev

PySpark 2.0 The size or shape of a DataFrame

I think there is not similar function like data.shape in Spark. But I will use len(data.columns) rather than len(data.dtypes)

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.

Using union and order by clause in mysql

A union query can only have one master ORDER BY clause, IIRC. To get this, in each query making up the greater UNION query, add a field that will be the one field you sort by for the UNION's ORDER BY.

For instance, you might have something like

SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort

That union_sort field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.

C++ - How to append a char to char*?

Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:

char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '\0';

    return ret;
}

Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.

 

Why you don't use std::string? it has .append method to append a character at the end of a string:

std::string str;

str.append('x');
// or
str += x;

UIView Infinite 360 degree rotation animation?

@ram's answer was really helpful. Here's a Swift version of the answer.

Swift 2

private func rotateImageView() {

    UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
        self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(M_PI_2))
        }) { (finished) -> Void in
            if finished {
                self.rotateImageView()
            }
    }
}

Swift 3,4,5

private func rotateImageView() {

    UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: { () -> Void in
        self.imageView.transform = self.imageView.transform.rotated(by: .pi / 2)
    }) { (finished) -> Void in
        if finished {
            self.rotateImageView()
        }
    }
}

Sorting multiple keys with Unix sort

Use the -k option (or --key=POS1[,POS2]). It can appear multiple times and each key can have global options (such as n for numeric sort)

Android Notification Sound

1st put "yourmp3file".mp3 file in the raw folder(ie inside Res folder)

2nd in your code put..

Notification noti = new Notification.Builder(this)
.setSound(Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.yourmp3file))//*see note

This is what i put inside my onClick(View v) as only "context().getPackageName()" wont work from there as it wont get any context

Deadly CORS when http://localhost is the origin

The real problem is that if we set -Allow- for all request (OPTIONS & POST), Chrome will cancel it. The following code works for me with POST to LocalHost with Chrome

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
} 
?>

How to get object size in memory?

I don't think you can get it directly, but there are a few ways to find it indirectly.

One way is to use the GC.GetTotalMemory method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.

Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.

See Find out how much memory is being used by an object in C#? for a similar question.

gpg: no valid OpenPGP data found

I too got the same error, when I did this behind a proxy. But after I exported the following from a terminal and re-tried the same command, the problem got resolved:

export http_proxy="http://username:password@proxy_ip_addr:port/"
export https_proxy="https://username:password@proxy_ip_addr:port/"

Use of Finalize/Dispose method in C#

Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:

Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).

The pattern I've put together (and written a code snippet for) follows:

#region IDisposable implementation

//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable

// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }

/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
    Dispose( true );

    // This object will be cleaned up by the Dispose method.
    // Therefore, you should call GC.SupressFinalize to
    // take this object off the finalization queue 
    // and prevent finalization code for this object
    // from executing a second time.

    // Always use SuppressFinalize() in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize( this );
}

/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> equals false, the method has been called by the 
/// runtime from inside the finalizer and you should not reference 
/// other objects. Only unmanaged resources can be disposed.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
    // TODO If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    try
    {
        if( !this.IsDisposed )
        {
            if( isDisposing )
            {
                // TODO Release all managed resources here

                $end$
            }

            // TODO Release all unmanaged resources here



            // TODO explicitly set root references to null to expressly tell the GarbageCollector
            // that the resources have been disposed of and its ok to release the memory allocated for them.


        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );

        this.IsDisposed = true;
    }
}

//TODO Uncomment this code if this class will contain members which are UNmanaged
// 
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
//  ~$className$()
//  {
//     Dispose( false );
//  }
#endregion IDisposable implementation

Here is the code for implementing IDisposable in a derived class. Note that you do not need to explicitly list inheritance from IDisposable in the definition of the derived class.

public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)


protected override void Dispose( bool isDisposing )
{
    try
    {
        if ( !this.IsDisposed )
        {
            if ( isDisposing )
            {
                // Release all managed resources here

            }
        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );
    }
}

I've posted this implementation on my blog at: How to Properly Implement the Dispose Pattern

The property 'value' does not exist on value of type 'HTMLElement'

If you are using react you can use the as operator.

let inputValue = (document.getElementById(elementId) as HTMLInputElement).value;

C# loop - break vs. continue

To break completely out of a foreach loop, break is used;

To go to the next iteration in the loop, continue is used;

Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.

Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.

Draw Circle using css alone

You could use a .before with a content with a unicode symbol for a circle (25CF).

_x000D_
_x000D_
.circle:before {_x000D_
  content: ' \25CF';_x000D_
  font-size: 200px;_x000D_
}
_x000D_
<span class="circle"></span>
_x000D_
_x000D_
_x000D_

I suggest this as border-radius won't work in IE8 and below (I recognize the fact that the suggestion is a bit mental).

How to keep an iPhone app running on background fully operational

From ioS 7 onwards, there are newer ways for apps to run in background. Apple now recognizes that apps have to constantly download and process data constantly.

Here is the new list of all the apps which can run in background.

  1. Apps that play audible content to the user while in the background, such as a music player app
  2. Apps that record audio content while in the background.
  3. Apps that keep users informed of their location at all times, such as a navigation app
  4. Apps that support Voice over Internet Protocol (VoIP)
  5. Apps that need to download and process new content regularly
  6. Apps that receive regular updates from external accessories

You can declare app's supported background tasks in Info.plist using X Code 5+. For eg. adding UIBackgroundModes key to your app’s Info.plist file and adding a value of 'fetch' to the array allows your app to regularly download and processes small amounts of content from the network. You can do the same in the 'capabilities' tab of Application properties in XCode 5 (attaching a snapshot)

Capabilities tab in XCode 5 You can find more about this in Apple documentation

Installing MySQL Python on Mac OS X

Here's what I would install, especially if you want to use homebrew:

  • XCode and the command line tools (as suggested by @7stud, @kjti)
  • Install homebrew
  • brew install mysql-connector-c
  • pip install mysql-python

How to save username and password with Mercurial?

You can make an auth section in your .hgrc or Mercurial.ini file, like so:

[auth]
bb.prefix = https://bitbucket.org/repo/path
bb.username = foo
bb.password = foo_passwd

The ‘bb’ part is an arbitrary identifier and is used to match prefix with username and password - handy for managing different username/password combos with different sites (prefix)

You can also only specify the user name, then you will just have to type your password when you push.

I would also recommend to take a look at the keyring extension. Because it stores the password in your system’s key ring instead of a plain text file, it is more secure. It is bundled with TortoiseHg on Windows, and there is currently a discussion about distributing it as a bundled extension on all platforms.

How do I convert a list of ascii values to a string in python?

import array
def f7(list):
    return array.array('B', list).tostring()

from Python Patterns - An Optimization Anecdote

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Can we pass an array as parameter in any function in PHP?

I composed this code as an example. Hope the idea works!

<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
  function greetings($friends){
    echo "Greetings, $friends <br>";
  }
  foreach ($friends as $friend) {
  greetings($friend);
  }
?>

Spring Boot: How can I set the logging level with application.properties?

Existing answers are greats. I just want to share with you a new spring boot feature allowing to group logs and set logging level on the whole group.

Exemple from the docs :

  • Create a logging group
logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat
  • Set the logging level for group
logging.level.tomcat=TRACE

It's nice feature which brings more flexibility.

No == operator found while comparing structs in C++

Comparison doesn't work on structs in C or C++. Compare by fields instead.

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

What's the most efficient way to erase duplicates and sort a vector?

As already stated, unique requires a sorted container. Additionally, unique doesn't actually remove elements from the container. Instead, they are copied to the end, unique returns an iterator pointing to the first such duplicate element, and you are expected to call erase to actually remove the elements.

sql server invalid object name - but tables are listed in SSMS tables list

The solution is:

  • Click menu Query,
  • then click 'Change Database'.
  • Select your appropriate database name.

That's it.

Call to a member function on a non-object

function page_properties($objPortal) {    
    $objPage->set_page_title($myrow['title']);
}

looks like different names of variables $objPortal vs $objPage

Changing plot scale by a factor in matplotlib

As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

A complete example showing both x and y scaling:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

And finally I have the credits for a picture:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

How to check if String is null

To sure, you should use function to check is null and empty as below:

string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}

How to set an image's width and height without stretching it?

Do I have to add an encapsulating <div> or <span>?

I think you do. The only thing that comes to mind is padding, but for that you would have to know the image's dimensions beforehand.

Send FormData with other field in AngularJS

Assume that we want to get a list of certain images from a PHP server using the POST method.

You have to provide two parameters in the form for the POST method. Here is how you are going to do.

app.controller('gallery-item', function ($scope, $http) {

    var url = 'service.php'; 

    var data = new FormData();

    data.append("function", 'getImageList');
    data.append('dir', 'all');

    $http.post(url, data, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).then(function (response) {

          // This function handles success
        console.log('angular:', response);

    }, function (response) {

        // this function handles error

    });
});

I have tested it on my system and it works.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

Can I use Homebrew on Ubuntu?

October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -

(first, install pre-requisites using sudo apt-get install build-essential curl file git)

finally create a ~/.zprofile with the following contents: emulate sh -c '. ~/.profile'

How to validate a date?

I just do a remake of RobG solution

var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;

if (isLeap) {
  daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

npm install Error: rollbackFailedOptional

Hi I'm also new to react and I also faced this problem after so many trouble I found solution: Just run in your command prompt or terminal :

npm config set registry http://registry.npmjs.org/

This will resolve your problem. Reference link: http://blog.csdn.net/zhalcie2011/article/details/78726679

Showing an image from console in Python

In Xterm-compatible terminals, you can show the image directly in the terminal. See my answer to "PPM image to ASCII art in Python"

ImageMagick's "logo:" image in Xterm (show picture in new tab for full size viewing)

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

Why is super.super.method(); not allowed in Java?

I think if you overwrite a method and want to all the super-class version of it (like, say for equals), then you virtually always want to call the direct superclass version first, which one will call its superclass version in turn if it wants.

I think it only makes rarely sense (if at all. i can't think of a case where it does) to call some arbitrary superclass' version of a method. I don't know if that is possible at all in Java. It can be done in C++:

this->ReallyTheBase::foo();

ActiveRecord find and only return selected columns

My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

How to run iPhone emulator WITHOUT starting Xcode?

The easiest way is to use Spotlight Search. Just click CMD+Space and type in search Simulator. Just like this:

enter image description here

And in few seconds emulated device will be loaded:

enter image description here

To switch to another device you can use menu under Hardware -> Device

There are few different cool instruments you can use under Hardware menu, such as orientation change, gestures, buttons, FaceID, keyboard or audio inputs.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.

app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){ 
        res.header('Access-Control-Allow-Origin', '*'); 
        res.header('Access-Control-Allow-Methods', 'GET, POST');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        return res.send(200);

    });

Understanding inplace=True

If you don't use inplace=True or you use inplace=False you basically get back a copy.

So for instance:

testdf.sort_values(inplace=True, by='volume', ascending=False)

will alter the structure with the data sorted in descending order.

then:

testdf2 = testdf.sort_values( by='volume', ascending=True)

will make testdf2 a copy. the values will all be the same but the sort will be reversed and you will have an independent object.

then given another column, say LongMA and you do:

testdf2.LongMA = testdf2.LongMA -1

the LongMA column in testdf will have the original values and testdf2 will have the decrimented values.

It is important to keep track of the difference as the chain of calculations grows and the copies of dataframes have their own lifecycle.

How to change the font on the TextView?

It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.

 import android.content.Context;
 import android.graphics.Typeface;

public enum FontLoader {

ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");   


private final String name;
private Typeface typeFace;


private FontLoader(final String name) {
    this.name = name;

    typeFace=null;  
}

public static Typeface getTypeFace(Context context,String name){
    try {
        FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
        if(item.typeFace==null){                
            item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");                 
        }           
        return item.typeFace;
    } catch (Exception e) {         
        return null;
    }                   
}
public static Typeface getTypeFace(Context context,int id){
    FontLoader myArray[]= FontLoader.values();
    if(!(id<myArray.length)){           
        return null;
    } 
    try {
        if(myArray[id].typeFace==null){     
            myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");                       
        }       
        return myArray[id].typeFace;    
    }catch (Exception e) {          
        return null;
    }   

}

public static Typeface getTypeFaceByName(Context context,String name){      
    for(FontLoader item: FontLoader.values()){              
        if(name.equalsIgnoreCase(item.name)){
            if(item.typeFace==null){
                try{
                    item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
                }catch (Exception e) {          
                    return null;
                }   
            }
            return item.typeFace;
        }               
    }
    return null;
}   

public static void loadAllFonts(Context context){       
    for(FontLoader item: FontLoader.values()){              
        if(item.typeFace==null){
            try{
                item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
            }catch (Exception e) {
                item.typeFace=null;
            }   
        }                
    }       
}   
}

Then just use this code on you textview:

 Typeface typeFace=FontLoader.getTypeFace(context,"arial");  
 if(typeFace!=null) myTextView.setTypeface(typeFace);

Recursively find all files newer than a given time

Given a unix timestamp (seconds since epoch) of 1494500000, do:

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)"

To grep those files for "foo":

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)" -exec grep -H 'foo' '{}' \;

Merge two (or more) lists into one, in C# .NET

In the special case: "All elements of List1 goes to a new List2": (e.g. a string list)

List<string> list2 = new List<string>(list1);

In this case, list2 is generated with all elements from list1.

How can I make the Android emulator show the soft keyboard?

If you're using AVD manager add a hardware property Keyboard support and set it to false.

That should disable the shown keyboard, and show the virtual one.

Jquery - animate height toggle

Worked for me:

$(".filter-mobile").click(function() {
   if ($("#menuProdutos").height() > 0) {
      $("#menuProdutos").animate({
         height: 0
      }, 200);
   } else {
      $("#menuProdutos").animate({
         height: 500
      }, 200);
   }
});

How do I execute code AFTER a form has loaded?

You can close your form after some execution..

//YourForm.ActiveForm.Close();

    LoadingForm.ActiveForm.Close();

Converting string into datetime

Use the third party dateutil library:

from dateutil import parser
parser.parse("Aug 28 1999 12:00AM")  # datetime.datetime(1999, 8, 28, 0, 0)

It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.

It's very useful for writing tests, where readability is more important than performance.

You can install it with:

pip install python-dateutil

Rendering HTML in a WebView with custom CSS

You could use WebView.loadDataWithBaseURL

htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + htmlData;
// lets assume we have /assets/style.css file
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

And only after that WebView will be able to find and use css-files from the assets directory.

ps And, yes, if you load your html-file form the assets folder, you don't need to specify a base url.

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

C# Equivalent of SQL Server DataTypes

SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail

https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Current time formatting with Javascript

function startTime() {
    var today = new Date(),
        h = checkTime(((today.getHours() + 11) % 12 + 1)),
        m = checkTime(today.getMinutes()),
        s = checkTime(today.getSeconds());
    document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
    t = setTimeout(function () {
        startTime()
    }, 500);
}
startTime();

})();

05:12:00

How to select the first row for each group in MySQL?

Best performance and easy to use:

SELECT id, code,
SUBSTRING_INDEX( GROUP_CONCAT(price ORDER BY id DESC), ',', 1) first_found_price
FROM stocks
GROUP BY code
ORDER BY id DESC

Vertical divider doesn't work in Bootstrap 3

I think this will bring it back using 3.0

.navbar .divider-vertical {
    height: 50px;
    margin: 0 9px;
    border-right: 1px solid #ffffff;
    border-left: 1px solid #f2f2f2;
}

.navbar-inverse .divider-vertical {
    border-right-color: #222222;
    border-left-color: #111111;
}

@media (max-width: 767px) {
    .navbar-collapse .nav > .divider-vertical {
        display: none;
     }
}

Need to list all triggers in SQL Server database with table name and table's schema

I had the same task recently and I used the following for sql server 2012 db. Use management studio and connect to the database you want to search. Then execute the following script.

Select 
[tgr].[name] as [trigger name], 
[tbl].[name] as [table name]

from sysobjects tgr 

join sysobjects tbl
on tgr.parent_obj = tbl.id

WHERE tgr.xtype = 'TR'

How to put a delay on AngularJS instant search?

(See answer below for a Angular 1.3 solution.)

The issue here is that the search will execute every time the model changes, which is every keyup action on an input.

There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:

JS:

var App = angular.module('App', []);

App.controller('DisplayController', function($scope, $http, $timeout) {
    $http.get('data.json').then(function(result){
        $scope.entries = result.data;
    });

    // This is what you will bind the filter to
    $scope.filterText = '';

    // Instantiate these variables outside the watch
    var tempFilterText = '',
        filterTextTimeout;
    $scope.$watch('searchText', function (val) {
        if (filterTextTimeout) $timeout.cancel(filterTextTimeout);

        tempFilterText = val;
        filterTextTimeout = $timeout(function() {
            $scope.filterText = tempFilterText;
        }, 250); // delay 250 ms
    })
});

HTML:

<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
    <span>{{entry.content}}</span>
</div>

Convert PDF to image with high resolution

In ImageMagick, you can do "supersampling". You specify a large density and then resize down as much as desired for the final output size. For example with your image:

convert -density 600 test.pdf -background white -flatten -resize 25% test.png


enter image description here

Download the image to view at full resolution for comparison..

I do not recommend saving to JPG if you are expecting to do further processing.

If you want the output to be the same size as the input, then resize to the inverse of the ratio of your density to 72. For example, -density 288 and -resize 25%. 288=4*72 and 25%=1/4

The larger the density the better the resulting quality, but it will take longer to process.

List of Java processes

There's a lot of ways of doing this. You can use java.lang.ProcessBuilder and "pgrep" to get the process id (PID) with something like: pgrep -fl java | awk {'print $1'}. Or, if you are running under Linux, you can query the /proc directory.

I know, this seems horrible, and non portable, and even poorly implemented, I agree. But because Java actually runs in a VM, for some absurd reason that I can't really figure out after more then 15 years working the JDK, is why it isn't possible to see things outside the JVM space, it's really ridiculous with you think about it. You can do everything else, even fork and join child processes (those were an horrible way of multitasking when the world didn't know about threads or pthreads, what a hell! what's going in on with Java?! :).

This will give an immense discussion I know, but anyways, there's a very good API that I already used in my projects and it's stable enough (it's OSS so you still need to stress test every version you use before really trusting the API): https://github.com/jezhumble/javasysmon

JavaDoc: http://jezhumble.github.io/javasysmon/, search for the class com.jezhumble.javasysmon.OsProcess, she will do the trick. Hope it helped, best of luck.

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

Android - Best and safe way to stop thread

Inside of any Activity class you create a method that will assign NULL to thread instance which can be used as an alternative to the depreciated stop() method for stopping thread execution:

public class MyActivity extends Activity {

private Thread mThread;  

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


        mThread =  new Thread(){
        @Override
        public void run(){
            // Perform thread commands...
    for (int i=0; i < 5000; i++)
    {
      // do something...
    }

    // Call the stopThread() method.
            stopThread(this);
          }
        };

    // Start the thread.
        mThread.start(); 
}

private synchronized void stopThread(Thread theThread)
{
    if (theThread != null)
    {
        theThread = null;
    }
}
}

This works for me without a problem.

Apache error: _default_ virtualhost overlap on port 443

It is highly unlikely that adding NameVirtualHost *:443 is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).

If you're running a relatively stock Apache configuration, you probably have this somewhere:

<VirtualHost _default_:443>

Your best bet is to either:

  • Place your additional SSL configuration into this existing VirtualHost container, or
  • Comment out this entire VirtualHost block and create a new one. Don't forget to include all the relevant SSL options.

How to get distinct values from an array of objects in JavaScript?

Let assume we have data something like this arr=[{id:1,age:17},{id:2,age:19} ...], then we can find unique objects like this -

function getUniqueObjects(ObjectArray) {
    let uniqueIds = new Set();
    const list = [...new Set(ObjectArray.filter(obj => {
        if (!uniqueIds.has(obj.id)) {
            uniqueIds.add(obj.id);
            return obj;
        }
    }))];

    return list;
}

Check here Codepen Link

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

Environment variables for java installation

Java SE Development Kit 8u112 on a 64-bit Windows 7 or Windows 8

Set the following user environment variables (== environment variables of type user variables)

  • JAVA_HOME : C:\Program Files\Java\jdk1.8.0_112
  • JDK_HOME : %JAVA_HOME%
  • JRE_HOME : %JAVA_HOME%\jre
  • CLASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
  • PATH : your-unique-entries;%JAVA_HOME%\bin (make sure that the longish your-unique-entries does not contain any other references to another Java installation folder.

Note for Windows users on 64-bit systems:

Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'

Notice that these environment variables are derived from the "root" environment variable JAVA_HOME. This makes it easy to update your environment variables when updating the JDK. Just point JAVA_HOME to the fresh installation.

There is a blogpost explaining the rationale behind all these environment variables.

Optional recommendations

  • Add an user environment variable JAVA_TOOL_OPTIONS with value -Dfile.encoding="UTF-8". This ensures that Java (and tools such as Maven) will run with a Charset.defaultCharset() of UTF-8 (instead of the default Windows-1252). This has saved a lot of headaches when wirking with my own code and that of others, which unfortunately often assume the (sane) default encoding UTF-8.
  • When JDK is installed, it adds to the system environment variable Path an entry C:\ProgramData\Oracle\Java\javapath;. I anecdotally noticed that the links in that directory didn't get updated during an JDK installation update. So it's best to remove C:\ProgramData\Oracle\Java\javapath; from the Path system environment variable in order to have a consistent environment.

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

Can I prevent text in a div block from overflowing?

Simply use this:

white-space: pre-wrap;      /* CSS3 */   
white-space: -moz-pre-wrap; /* Firefox */    
white-space: -pre-wrap;     /* Opera <7 */   
white-space: -o-pre-wrap;   /* Opera 7 */    
word-wrap: break-word;      /* IE */

Tri-state Check box in HTML?

As I needed something like this -without any plug-in- for script-generated checkboxes in a table... I ended up with this solution:

<!DOCTYPE html>
<html>
<body>

Toto <input type="checkbox" id="myCheck1" onclick="updateChkBx(this)" /><br />
Tutu <input type="checkbox" id="myCheck2" onclick="updateChkBx(this)" /><br />
Tata <input type="checkbox" id="myCheck3" onclick="updateChkBx(this)" /><br />
Tete <input type="checkbox" id="myCheck4" onclick="updateChkBx(this)" /><br />

<script>
var chkBoxState = [];

function updateChkBx(src) {
  var idx = Number(src.id.substring(7)); // 7 to bypass the "myCheck" part in each checkbox id
  if(typeof chkBoxState[idx] == "undefined") chkBoxState[idx] = false; // make sure we can use stored state at first call
  
  // the problem comes from a click on a checkbox both toggles checked attribute and turns inderminate attribute to false
  if(chkBoxState[idx]) {
    src.indeterminate = false;
    src.checked = false;
    chkBoxState[idx] = false;
  }
  else if (!src.checked) { // passing from checked to unchecked
    src.indeterminate = true;
    src.checked = true; // force considering we are in a checked state
    chkBoxState[idx] = true;
  }
}
// to know box state, just test indeterminate, and if not indeterminate, test checked
</script>

</body>
</html>

Deleting all records in a database table

BlogPost.find_each(&:destroy)

How to spawn a process and capture its STDOUT in .NET?

You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.

Converting JSON to XML in Java

Underscore-java library has static method U.jsonToXml(jsonstring). I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";  
        System.out.println(json); 
        String xml = U.jsonToXml(json);  
        System.out.println(xml); 
    }
}

Output:

{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <name>JSON</name>
  <integer number="true">1</integer>
  <double number="true">2.0</double>
  <boolean boolean="true">true</boolean>
  <nested>
    <id number="true">42</id>
  </nested>
  <array number="true">1</array>
  <array number="true">2</array>
  <array number="true">3</array>
</root>

How to run crontab job every week on Sunday

Cron job expression in a human-readable way crontab builder

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

git checkout master

That's result something like this:

Warning: you are leaving 2 commits behind, not connected to
any of your branches:

1e7822f readme
0116b5b returned to clean django

If you want to keep them by creating a new branch, this may be a good time to do so with:
git branch new_branch_name 1e7822f25e376d6a1182bb86a0adf3a774920e1e

So, let's do it:

git merge 1e7822f25e376d6a1182bb86a0adf3a774920e1e

HQL Hibernate INNER JOIN

You can do it without having to create a real Hibernate mapping. Try this:

SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team

Syntax for a single-line Bash infinite while loop

You can try this too WARNING: this you should not do but since the question is asking for infinite loop with no end...this is how you could do it.

while [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done

Single TextView with multiple colored text

Since API 24 you have FROM_HTML_OPTION_USE_CSS_COLORS so you can define colors in CSS instead of repeating it all time with font color=" Much clearer - when you have some html and you want to highlight some predefined tags - you just need to add CSS fragment at top of your html

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

How to check if an Object is a Collection Type in Java?

if (x instanceof Collection<?>){
}

if (x instanceof Map<?,?>){
}

How to export the Html Tables data into PDF using Jspdf

Just follow these steps i can assure pdf file will be generated

    <html>
    <head>

    <title>Exporting table data to pdf Example</title>


    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="js/jspdf.js"></script>
    <script type="text/javascript" src="js/from_html.js"></script>
    <script type="text/javascript" src="js/split_text_to_size.js"></script>
    <script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
    <script type="text/javascript" src="js/cell.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>


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

            $("#exportpdf").click(function() {
                var pdf = new jsPDF('p', 'pt', 'ledger');
                // source can be HTML-formatted string, or a reference
                // to an actual DOM element from which the text will be scraped.
                source = $('#yourTableIdName')[0];

                // we support special element handlers. Register them with jQuery-style 
                // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
                // There is no support for any other type of selectors 
                // (class, of compound) at this time.
                specialElementHandlers = {
                    // element with id of "bypass" - jQuery style selector
                    '#bypassme' : function(element, renderer) {
                        // true = "handled elsewhere, bypass text extraction"
                        return true
                    }
                };
                margins = {
                    top : 80,
                    bottom : 60,
                    left : 60,
                    width : 522
                };
                // all coords and widths are in jsPDF instance's declared units
                // 'inches' in this case
                pdf.fromHTML(source, // HTML string or DOM elem ref.
                margins.left, // x coord
                margins.top, { // y coord
                    'width' : margins.width, // max width of content on PDF
                    'elementHandlers' : specialElementHandlers
                },

                function(dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('fileNameOfGeneretedPdf.pdf');
                }, margins);
            });

        });
    </script>
    </head>
    <body>
    <div id="yourTableIdName">
        <table style="width: 1020px;font-size: 12px;" border="1">
            <thead>
                <tr align="left">
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>
            </thead>


            <tbody>

                <tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
<tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
            </tbody>
        </table></div>

        <input type="button" id="exportpdf" value="Download PDF">


    </body>

    </html>

Output:

Html file output: html output

Pdf file output: pdf output

Wamp Server not goes to green color

Click wamp icon :

1- apache -> httpd.conf (A notepad file will be opened)

2- Find 80

3 -Replace with 81

Listen 12.34.56.78:81 Listen 0.0.0.0:81 Listen [::0]:81

4- Restart wamp services

!!Done

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

Best way to convert an ArrayList to a string

In Java 8 or later:

String listString = String.join(", ", list);

In case the list is not of type String, a joining collector can be used:

String listString = list.stream().map(Object::toString)
                        .collect(Collectors.joining(", "));

Copying an array of objects into another array in javascript

There are two important notes.

  1. Using array.concat() does not work using Angular 1.4.4 and jQuery 3.2.1 (this is my environment).
  2. The array.slice(0) is an object. So if you do something like newArray1 = oldArray.slice(0); newArray2 = oldArray.slice(0), the two new arrays will reference to just 1 array and changing one will affect the other.

Alternatively, using newArray1 = JSON.parse(JSON.stringify(old array)) will only copy the value, thus it creates a new array each time.

Java constant examples (Create a java file having only constants)

- Create a Class with public static final fields.

- And then you can access these fields from any class using the Class_Name.Field_Name.

- You can declare the class as final, so that the class can't be extended(Inherited) and modify....

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

If your test project is set to target a 64bit platform, the tests won't show up in the NUnit Test Adapter.

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

Service vs IntentService in the Android platform

An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.

IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.

It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.

For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.

How to clear react-native cache?

I had a similar problem, I tried to clear all the caches possible (tried almost all the solutions above) and the only thing that worked for me was to kill the expo app and to restart it.

Mailto links do nothing in Chrome but work in Firefox?

I solved the problem using this code:

_x000D_
_x000D_
    _x000D_
<button onclick="email()">Contact me !</button> _x000D_
_x000D_
<script>_x000D_
function email() {_x000D_
    var str = window.open('mailto:[email protected]', '_blank');_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

It worked for me like a charm !

echo that outputs to stderr

Here is a function for checking the exit status of the last command, showing error and terminate the script.

or_exit() {
    local exit_status=$?
    local message=$*

    if [ "$exit_status" -gt 0 ]
    then
        echo "$(date '+%F %T') [$(basename "$0" .sh)] [ERROR] $message" >&2
        exit "$exit_status"
    fi
}

Usage:

gzip "$data_dir"
    or_exit "Cannot gzip $data_dir"

rm -rf "$junk"
    or_exit Cannot remove $junk folder

The function prints out the script name and the date in order to be useful when the script is called from crontab and logs the errors.

59 23 * * * /my/backup.sh 2>> /my/error.log

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

Execute SQLite script

There are many ways to do this, one way is:

sqlite3 auction.db

Followed by:

sqlite> .read create.sql

In general, the SQLite project has really fantastic documentation! I know we often reach for Google before the docs, but in SQLite's case, the docs really are technical writing at its best. It's clean, clear, and concise.

Creating a thumbnail from an uploaded image

<?php 
error_reporting(0);

$change="";
$abc="";


 define ("MAX_SIZE","4000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["file"]["name"];
    $uploadedfile = $_FILES['file']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['file']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {

            $change='<div class="msgdiv">Unknown Image extension </div> ';
            $errors=1;
        }
        else
        {

 $size=filesize($_FILES['file']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
    $errors=1;
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);


$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);

$filename = "images/1-". $_FILES['file']['name']=time();

$filename1 = "images/2-". $_FILES['file']['name']=time();

$filename2 = "images/3-". $_FILES['file']['name']=time();

imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagejpeg($tmp2,$filename2,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}
 if(isset($_POST['Submit']) && !$errors) 
 {

   // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
    $change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
 }

?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
    <title>picture demo</title>

   <link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>


  <style type="text/css">
  .help
{
font-size:11px; color:#006600;
}
body {
     color: #000000;
 background-color:#999999 ;
    background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;


    font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; 

    }
        .msgdiv{
    width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>

  </head><body>
     <div align="center" id="err">
<?php echo $change; ?>  </div>
   <div id="space"></div>





  <div id="container" >

   <div id="con">



        <table width="502" cellpadding="0" cellspacing="0" id="main">
          <tbody>
            <tr>
              <td width="500" height="238" valign="top" id="main_right">

              <div id="posts">
              &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename; ?>" />  &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename1; ?>"  />
                <form method="post" action="" enctype="multipart/form-data" name="form1">
                <table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
               <tr><Td style="height:25px">&nbsp;</Td></tr>
        <tr>
          <td width="150"><div align="right" class="titles">Picture 
            : </div></td>
          <td width="350" align="left">
            <div align="left">
              <input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>

              </div></td>

        </tr>
        <tr><Td></Td>
        <Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
        </tr>
        <tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value="       Upload        " name="Submit"/></Td></tr>
        <tr>
          <td width="200">&nbsp;</td>
          <td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="200" align="center"><div align="left"></div></td>
                <td width="100">&nbsp;</td>
              </tr>
          </table></td>
        </tr>
      </table>
    </form>
 </div>
            </td>

        </tr>
          </tbody>
     </table>
   </div>

  </div>



</body></html>

How to remove all ListBox items?

I made on this way, and work properly to me:

if (listview1.Items.Count > 0)
        {
            for (int a = listview1.Items.Count -1; a > 0 ; a--)
            {
                listview1.Items.RemoveAt(a);
            }
                listview1.Refresh();

        }

Explaining: using "Clear()" erases only the items, do not removes then from object, using RemoveAt() to removing an item of beginning position just realocate the others [if u remove item[0], item[1] turns into [0] triggering a new internal event], so removing from the ending no affect de others position, its a Stack behavior, this way we can Stack over all items, reseting the object.

Get device token for push notification

Following code is use for the retrive the device token.

    // Prepare the Device Token for Registration (remove spaces and < >)
    NSString *devToken = [[[[deviceToken description] 
                            stringByReplacingOccurrencesOfString:@"<"withString:@""] 
                           stringByReplacingOccurrencesOfString:@">" withString:@""] 
                          stringByReplacingOccurrencesOfString: @" " withString: @""];


    NSString *str = [NSString 
                     stringWithFormat:@"Device Token=%@",devToken];
    UIAlertView *alertCtr = [[[UIAlertView alloc] initWithTitle:@"Token is " message:devToken delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
    [alertCtr show];
    NSLog(@"device token - %@",str);

setTimeout in for-loop does not print consecutive values

I had the same problem once this is how I solved it.

Suppose I want 12 delays with an interval of 2 secs

    function animate(i){
         myVar=setTimeout(function(){
            alert(i);
            if(i==12){
              clearTimeout(myVar);
              return;
            }
           animate(i+1)
         },2000)
    }

    var i=1; //i is the start point 1 to 12 that is
    animate(i); //1,2,3,4..12 will be alerted with 2 sec delay

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):

bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
               "~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));

And angular app would appear in bundle unmodified.

ReSharper "Cannot resolve symbol" even when project builds

I am using VS2015, R#10. None of the suggested solution worked for me. I deleted the contents of the bin folder of my solution and rebuild the entire solution, that seems to have resolved the issue. Before deleting the contents of the bin folder, I had tried suspending and resuming R#, doing clear cache from R# -> option -> general setting, and also manually deleting the contents from \AppData\Local\JetBrains\Transient\ReSharperPlatformVs12\v01\SolutionCaches.. Hope it helps someone.

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

How to access PHP session variables from jQuery function in a .js file?

Strangely importing directly from $_SESSION not working but have to do this to make it work :

<?php
$phpVar = $_SESSION['var'];
?>

<script>
    var variableValue= '<?php echo $phpVar; ?>';
    var imported = document.createElement('script');
    imported.src = './your/path/to.js';
    document.head.appendChild(imported);
</script>

and in to.js

$(document).ready(function(){
alert(variableValue);
// rest of js file

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

How to zip a whole folder using PHP

Try this:

$zip = new ZipArchive;
$zip->open('myzip.zip', ZipArchive::CREATE);
foreach (glob("target_folder/*") as $file) {
    $zip->addFile($file);
    if ($file != 'target_folder/important.txt') unlink($file);
}
$zip->close();

This will not zip recursively though.

How to acces external json file objects in vue.js app

Just assign the import to a data property

<script>
      import json from './json/data.json'
      export default{
          data(){
              return{
                  myJson: json
              }
          }
      }
</script>

then loop through the myJson property in your template using v-for

<template>
    <div>
        <div v-for="data in myJson">{{data}}</div>
    </div>
</template>

NOTE

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

Vue converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.

So you can create a custom option as follows:

<script>
          import MY_JSON from './json/data.json'
          export default{
              //custom option named myJson
                 myJson: MY_JSON
          }
    </script>

then loop through the custom option in your template using $options:

<template>
        <div>
            <div v-for="data in $options.myJson">{{data}}</div>
        </div>
    </template>

how to convert a string to an array in php

explode — Split a string by a string

Syntax :

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
  • $delimiter : based on which you want to split string
  • $string. : The string you want to split

Example :

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

In your example :

$str = "this is string"; 
$array = explode(' ', $str);

Java generics - why is "extends T" allowed but not "implements T"?

It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.

But I think implements would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.

The Java Glossary expresses a similar view.

Getting an option text/value with JavaScript

In jquery you could try this $("#select_id>option:selected").text()

How to implement class constructor in Visual Basic?

If you mean VB 6, that would be Private Sub Class_Initialize().

http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx

If you mean VB.NET it is Public Sub New() or Shared Sub New().

SQL datetime format to date only

SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration 
where MerchantId =@ MerchantID

SQL Server 2008: how do I grant privileges to a username?

If you want to give your user all read permissions, you could use:

EXEC sp_addrolemember N'db_datareader', N'your-user-name'

That adds the default db_datareader role (read permission on all tables) to that user.

There's also a db_datawriter role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:

EXEC sp_addrolemember N'db_datawriter', N'your-user-name'

If you need to be more granular, you can use the GRANT command:

GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName

and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.

This is all very well documented in the MSDN Books Online for SQL Server.

And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users, right-click on that user you want to give permissions to, then Properties adn at the bottom you see "Database role memberships" where you can add the user to db roles.

alt text

This compilation unit is not on the build path of a Java project

Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI):

  1. Right-Click on your project
  2. Go to "Properties"
  3. Choose "Project Natures"
  4. Click on "Add"
  5. Choose "Java"
  6. Click "Apply and Close"

How to select the nth row in a SQL database table?

It seems to me that, to be efficient, you need to 1) generate a random number between 0 and one less than the number of database records, and 2) be able to select the row at that position. Unfortunately, different databases have different random number generators and different ways to select a row at a position in a result set - usually you specify how many rows to skip and how many rows you want, but it's done differently for different databases. Here is something that works for me in SQLite:

select * 
from Table 
limit abs(random()) % (select count(*) from Words), 1;

It does depend on being able to use a subquery in the limit clause (which in SQLite is LIMIT <recs to skip>,<recs to take>) Selecting the number of records in a table should be particularly efficient, being part of the database's meta data, but that depends on the database's implementation. Also, I don't know if the query will actually build the result set before retrieving the Nth record, but I would hope that it doesn't need to. Note that I'm not specifying an "order by" clause. It might be better to "order by" something like the primary key, which will have an index - getting the Nth record from an index might be faster if the database can't get the Nth record from the database itself without building the result set.

Custom toast on Android: a simple example

Simple Way to Customize the Toast,

private void MsgDisplay(String Msg, int Size, int Grav){
    Toast toast = Toast.makeText(this, Msg, Toast.LENGTH_LONG);
    TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
    v.setTextColor(Color.rgb(241, 196, 15));
    v.setTextSize(Size);
    v.setGravity(Gravity.CENTER);
    v.setShadowLayer(1.5f, -1, 1, Color.BLACK);
    if(Grav == 1){
        toast.setGravity(Gravity.BOTTOM, 0, 120);
    }else{
        toast.setGravity(Gravity.BOTTOM, 0, 10);
    }
    toast.show();
}

Disabling the button after once click

protected void Page_Load(object sender, EventArgs e)
    {
        // prevent user from making operation twice
        btnSave.Attributes.Add("onclick", 
                               "this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");

        // ... etc. 
    }

ASP.NET Web Site or ASP.NET Web Application?

This may sound a bit obvious, but I think it's something that is misunderstood because Visual Studio 2005 only shipped with the web site originally. If your project deals with a website that is fairly limited and doesn't have a lot of logical or physical separation, the website is fine. However if it is truly a web application with different modules where many users add and update data, you are better off with the web application.

The biggest pro of the website model is that anything in the app_code section is dynamically compiled. You can make C# file updates without a full redeploy. However this comes at a great sacrifice. A lot of things happen under the covers that are difficult to control. Namespaces are difficult to control and specific DLL usage goes out the window by default for anything under app_code since everything is dynamically compiled.

The web application model does not have dynamic compilation, but you gain control over the things that I have mentioned.

If you are doing n-tier development, I highly recommend the web application model. If you are doing a limited web site or a quick and dirty implementation, the web site model may have advantages.

More detailed analysis can be found in:

$_POST not working. "Notice: Undefined index: username..."

undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.

You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.

If I was having a similar error, I'd do something like this:

$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;

If username didn't turn up, that'd mean I was screwing up somewhere. You can also,

var_dump($_POST);

To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

How to set JAVA_HOME in Mac permanently?

To set JAVA_HOME permanently in Mac, I tried following steps.

  1. Download and install Java JDK to your Mac. When you install a Java JDK version which will be installed in the following location by default in MAC.

/Library/Java/JavaVirtualMachines

  1. Open the .bash_profile file (Here My Mac version is MacOS High Sierra. You may need to open .zshrc file in some different MacOS versions).

atom ~/.bash_profile

  1. Add following to your bash_profile file.

Change the JDK version accordingly

export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home'
export PATH=$JAVA_HOME/bin:$PATH
  1. Open the Terminal and execute following.

source ~/.bash_profile

Open a new terminal and check 'echo $JAVA_HOME'

Thanks.

Prevent form submission on Enter key press

A jQuery solution.

I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.

$(selector).keyup(function(e){
  /*
   * Delay the enter key form submit till after the hidden
   * input is updated.
   */

  // No need to do anything if it's not the enter key
  // Also only e.which is needed as this is the jQuery event object.
  if (e.which !== 13) {
       return;
  }

  // Prevent form submit
  e.preventDefault();

  // Trigger the blur event.
  this.blur();

  // Submit the form.
  $(e.target).closest('form').submit();
});

Would be nice to get a more general version that fired all the delayed events rather than just the form submit.

Can you animate a height change on a UITableViewCell when selected?

Instead of beginUpdates()/endUpdates(), the recommended call is now:

tableView.performBatchUpdates(nil, completion: nil)

Apple says, regarding beginUpdates/endUpdates: "Use the performBatchUpdates(_:completion:) method instead of this one whenever possible."

See: https://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates

How do I get time of a Python program's execution?

For the data folks using Jupyter Notebook

In a cell, you can use Jupyter's %%time magic command to measure the execution time:

%%time
[ x**2 for x in range(10000)]

Output

CPU times: user 4.54 ms, sys: 0 ns, total: 4.54 ms
Wall time: 4.12 ms

This will only capture the execution time of a particular cell. If you'd like to capture the execution time of the whole notebook (i.e. program), you can create a new notebook in the same directory and in the new notebook execute all cells:

Suppose the notebook above is called example_notebook.ipynb. In a new notebook within the same directory:

# Convert your notebook to a .py script:
!jupyter nbconvert --to script example_notebook.ipynb

# Run the example_notebook with -t flag for time
%run -t example_notebook

Output

IPython CPU timings (estimated):
  User   :       0.00 s.
  System :       0.00 s.
Wall time:       0.00 s.

Android: install .apk programmatically

This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.

I lose my time before discover this.

CSS override rules and specificity

To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 trfrom rule one and add it to rule two.

table.rule1 tr td {
    background-color: #ff0000;
}

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.

Gradients on UIView and UILabels On iPhone

I realize this is an older thread, but for future reference:

As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer:

 UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
 CAGradientLayer *gradient = [CAGradientLayer layer];
 gradient.frame = view.bounds;
 gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
 [view.layer insertSublayer:gradient atIndex:0];

Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors.

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

How to change color of ListView items on focus and on click

The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.

Specifically, you'd set the textColor of your textViews to an XML resource like this one:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/black" /> <!-- default -->
</selector> 

Is there a difference between x++ and ++x in java?

When considering what the computer actually does...

++x: load x from memory, increment, use, store back to memory.

x++: load x from memory, use, increment, store back to memory.

Consider: a = 0 x = f(a++) y = f(++a)

where function f(p) returns p + 1

x will be 1 (or 2)

y will be 2 (or 1)

And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.

Generally, just use x = x + 1. It's way simpler.

Resize image in the wiki of GitHub using Markdown

This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?


In December 2015, it seems that only links to files on github.com or cloud.githubusercontent.com or the like work. Steps that worked for me in a gist:

  1. Make a gist, say Mygist.md (and optionally more files)
  2. Go to the "Write Comment" box at the end
  3. Click "Attach files ... by selecting them"; select your local image file
  4. GitHub echos a long long string where it put the image, e.g. ![khan-lasso-squared](https://cloud.githubusercontent.com/assets/1280390/12011119/596fdca4-acc2-11e5-84d0-4878164e04bb.png)
  5. Cut-paste that by hand into your Mygist.md.

But: GitHub people may change this behavior tomorrow, without documenting it.

How should I call 3 functions in order to execute them one after the other?

Since you tagged it with javascript, I would go with a timer control since your function names are 3, 5, and 8 seconds. So start your timer, 3 seconds in, call the first, 5 seconds in call the second, 8 seconds in call the third, then when it's done, stop the timer.

Normally in Javascript what you have is correct for the functions are running one after another, but since it looks like you're trying to do timed animation, a timer would be your best bet.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

If your tld's are on the classpath, typically under the WEB-INF directory, the following two tips should resolve the issue (irrespective of your environment setup):

  1. Ensure that the <uri> in the TLD and the uri in the taglib directive of your jsp pages match. The <uri> element of the tld is a unique name for the tag library.

  2. If the tld does not have a <uri> element, the Container will attempt to use the uri attribute in the taglib directive as a path to the actual TLD. for e.g. I could have a custom tld file in my WEB-INF folder and use the path to the this tld as the uri value in my JSP. However, this is a bad practice and should be avoided since the paths would then be hardcoded.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Pie chart with jQuery

Tons of great suggestions here, just going to throw ZingChart onto the stack for good measure. We recently released a jQuery wrapper for the library that makes it even easier to build and customize charts. The CDN links are in the demo below.

I'm on the ZingChart team and we're here to answer any questions any of you might have!

_x000D_
_x000D_
$('#pie-chart').zingchart({_x000D_
  "data": {_x000D_
    "type": "pie",_x000D_
    "legend": {},_x000D_
    "series": [{_x000D_
      "values": [5]_x000D_
    }, {_x000D_
      "values": [10]_x000D_
    }, {_x000D_
      "values": [15]_x000D_
    }]_x000D_
  }_x000D_
});
_x000D_
<script src="http://cdn.zingchart.com/zingchart.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://cdn.zingchart.com/zingchart.jquery.min.js"></script>_x000D_
_x000D_
<div id="pie-chart"></div>
_x000D_
_x000D_
_x000D_

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..

 if (model is ViewDataDictionary)
 {
     controller.ViewData = model as ViewDataDictionary;
 } else {
     controller.ViewData.Model = model;
 }

DataTable: How to get item value with row name and column name? (VB)

Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
     searchedValue = rows(0).Item("ColumnName2") 
End If

With FirstOrDefault:

Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
     searchedValue = row.Item("ColumnName2") 
End If

In C#:

var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
     searchedValue = row["ColumnName2"];

How can I make a ComboBox non-editable in .NET?

Stay on your ComboBox and search the DropDropStyle property from the properties window and then choose DropDownList.

dropdownlist set selected value in MVC3 Razor

just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.

Controller:

ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);

Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)

Then this is my view to render it:

<div class="editor-label">
   @Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
   @Html.DropDownList("ActionStatusId")
   @Html.ValidationMessageFor(model => model.ActionStatusId)
</div> 

I think it is pretty simple, I hope this helps! :)

Proper way of checking if row exists in table in PL/SQL block

Many ways to skin this cat. I put a simple function in each table's package...

function exists( id_in in yourTable.id%type ) return boolean is
  res boolean := false;
begin
  for c1 in ( select 1 from yourTable where id = id_in and rownum = 1 ) loop
    res := true;
    exit; -- only care about one record, so exit.
  end loop;
  return( res );
end exists;

Makes your checks really clean...

IF pkg.exists(someId) THEN
...
ELSE
...
END IF;

What is the best or most commonly used JMX Console / Client

JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!

Paging with Oracle

Just want to summarize the answers and comments. There are a number of ways doing a pagination.

Prior to oracle 12c there were no OFFSET/FETCH functionality, so take a look at whitepaper as the @jasonk suggested. It's the most complete article I found about different methods with detailed explanation of advantages and disadvantages. It would take a significant amount of time to copy-paste them here, so I won't do it.

There is also a good article from jooq creators explaining some common caveats with oracle and other databases pagination. jooq's blogpost

Good news, since oracle 12c we have a new OFFSET/FETCH functionality. OracleMagazine 12c new features. Please refer to "Top-N Queries and Pagination"

You may check your oracle version by issuing the following statement

SELECT * FROM V$VERSION

How to align iframe always in the center

Center iframe

One solution is:

_x000D_
_x000D_
div {
  text-align:center;
  width:100%;
}
iframe{
  width: 200px;
}
_x000D_
<div>
  <iframe></iframe>
</div>
_x000D_
_x000D_
_x000D_

JSFiddle: https://jsfiddle.net/h9gTm/

edit: vertical align added

css:

div {
    text-align: center;
    width: 100%;
    vertical-align: middle;
    height: 100%;
    display: table-cell;
}
.iframe{
  width: 200px;
}
div,
body,
html {
    height: 100%;
    width: 100%;
}
body{
    display: table;
}

JSFiddle: https://jsfiddle.net/h9gTm/1/

Edit: FLEX solution

Using display: flex on the <div>

div {
    display: flex;
    align-items: center;
    justify-content: center;
}

JSFiddle: https://jsfiddle.net/h9gTm/867/

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

How to start an application without waiting in a batch file?

If your exe takes arguments,

start MyApp.exe -arg1 -arg2

C++/CLI Converting from System::String^ to std::string

Check out System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni() and its friends.

Sorry can't post code now; I don't have VS on this machine to check it compiles before posting.