Programs & Examples On #Stochastic

A stochastic system is a system which state depends or some random elements making its behavior non-deterministic. Questions with this tag should cover topics regarding random variables and non-determenistic systems.

Android Device Chooser -- device not showing up

This note from the Android Developer site is what worked for me:

Enable USB debugging on your device. On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development. On Android 4.0 and newer, it's in Settings > Developer options. Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.

Check if an apt-get package is installed and then install it if it's not on Linux

I had a similar requirement when running test locally instead of in docker. Basically I only wanted to install any .deb files found if they weren't already installed.

# If there are .deb files in the folder, then install them
if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
  for file in *.deb; do
    # Only install if not already installed (non-zero exit code)
    dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
    if [ $? != 0 ]; then
        dpkg -i ${file}
    fi;
  done;
else
  err "No .deb files found in '$PWD'"
fi

I guess they only problem I can see is that it doesn't check the version number of the package so if .deb file is a newer version, then this wouldn't overwrite the currently installed package.

_tkinter.TclError: no display name and no $DISPLAY environment variable

I had this same issue trying to run a simple tkinter app remotely on a Raspberry Pi. In my case I did want to display the tkinter GUI on the pi display, but I want to be able to execute it over SSH from my host machine. I was also not using matplotlib, so that wasn't the cause of my issue. I was able to resolve the issue by setting the DISPLAY environment variable as the error suggests with the command:

export DISPLAY=:0.0

A good explanation of what the display environment variable is doing and why the syntax is so odd can be found here: https://askubuntu.com/questions/432255/what-is-display-environment-variable

Error: Could not find or load main class

If the class is in a package

package thepackagename;

public class TheClassName {
  public static final void main(String[] cmd_lineParams)  {
     System.out.println("Hello World!");
  } 
}

Then calling:

java -classpath . TheClassName

results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:

java -classpath . thepackagename.TheClassName

And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.

To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.

Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

How to list the certificates stored in a PKCS12 keystore with keytool?

What is missing in the question and all the answers is that you might need the passphrase to read public data from the PKCS#12 (.pfx) keystore. If you need a passphrase or not depends on how the PKCS#12 file was created. You can check the ASN1 structure of the file (by running it through a ASN1 parser, openssl or certutil can do this too), if the PKCS#7 data (e.g. OID prefix 1.2.840.113549.1.7) is listed as 'encrypted' or with a cipher-spec or if the location of the data in the asn1 tree is below an encrypted node, you won't be able to read it without knowledge of the passphrase. It means your 'openssl pkcs12' command will fail with errors (output depends on the version). For those wondering why you might be interested in the certificate of a PKCS#12 without knowledge of the passphrase. Imagine you have many keystores and many phassphrases and you are really bad at keeping them organized and you don't want to test all combinations, the certificate inside the file could help you find out which password it might be. Or you are developing software to migrate/renew a keystore and you need to decide in advance which procedure to initiate based on the contained certicate without user interaction. So the latter examples work without passphrase depending on the PKCS#12 structure.

Just wanted to add that, because I didn't find an answer myself and spend a lot of time to figure it out.

What's the best visual merge tool for Git?

So for the git merge, you can try:

  • DiffMerge to visually compare and merge files on Windows, OS X and Linux.

    DiffMerge

  • Meld, is a visual diff and merge tool.

    Meld is a visual diff and merge tool

  • KDiff3, a diff and merge program), which compares or merges 2 or 3 text input files/dirs.
  • opendiff (part of Xcode Tools on macOS), a command line utility which launches the FileMerge application from Terminal to graphically compare files or directories, including merging.

is python capable of running on multiple cores?

I converted the script to Python3 and ran it on my Raspberry Pi 3B+:

import time
import threading

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(100):
                        f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("Sequential run time: %.2f seconds" % (time.time() - start_time))

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print("Parallel run time: %.2f seconds" % (time.time() - start_time))

python3 t.py

Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds

For me, running parallel was quicker.

How to write to a JSON file in the correct format

To make this work on Ubuntu Linux:

  1. I installed the Ubuntu package ruby-json:

    apt-get install ruby-json
    
  2. I wrote the script in ${HOME}/rubybin/jsonDEMO

  3. $HOME/.bashrc included:

    ${HOME}/rubybin:${PATH}
    

(On this occasion I also typed the above on the bash command line.)

Then it worked when I entered on the command line:

jsonDemo

What is the difference between a data flow diagram and a flow chart?

The difference between a data flow diagram (DFD) and a flow chart (FC) are that a data flow diagram typically describes the data flow within a system and the flow chart usually describes the detailed logic of a business process.

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Vlookup is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)

This is what you would put in column B on sheet 2

=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)

Setting Sheet1!A$1:B$6 and Sheet1!A$1:A$6 as named ranges makes it a little more user friendly.

Why when I transfer a file through SFTP, it takes longer than FTP?

Several factors affect speed of SFTP transfer:

  1. Encryption. Though symmetric encryption is fast, it's not that fast to be unnoticed. If you comparing speeds on fast network (100mbit or larger), encryption becomes a break for your process.
  2. Hash calculation and checking.
  3. Buffer copying. SFTP running on top of SSH causes each data block to be copied at least 6 times (3 times on each side) more comparing to plain FTP where data in best cases can be passed to network interface without being copied at all. And block copy takes a bit of time as well.

How to store standard error in a variable

This is an interesting problem to which I hoped there was an elegant solution. Sadly, I end up with a solution similar to Mr. Leffler, but I'll add that you can call useless from inside a Bash function for improved readability:

#!/bin/bash

function useless {
    /tmp/useless.sh | sed 's/Output/Useless/'
}

ERROR=$(useless)
echo $ERROR

All other kind of output redirection must be backed by a temporary file.

Setting a windows batch file variable to the day of the week

This turned out way more complex then I first suspected, and I guess that's what intrigued me, I searched every where and all the methods given wouldnt work on Windows 7.

So I have an alternate solution which uses a Visual Basic Script.

The batch creates and executes the script(DayOfWeek.vbs), assigns the scripts output (Monday, Tuesday etc) to a variable (dow), the variable is then checked and another variable (dpwnum) assigned with the days number, afterwards the VBS is deleted hope it helps:

@echo off

REM Create VBS that will get day of week in same directory as batch
echo wscript.echo WeekdayName(Weekday(Date))>>DayOfWeek.vbs

REM Cycle through output to get day of week i.e monday,tuesday etc
for /f "delims=" %%a in ('cscript /nologo DayOfWeek.vbs') do @set dow=%%a

REM delete vbs
del DayOfWeek.vbs

REM Used for testing outputs days name
echo %dow%

REM Case of the days name is important must have a capital letter at start
REM Check days name and assign value depending
IF %dow%==Monday set downum=0
IF %dow%==Tuesday set downum=1
IF %dow%==Wednesday set downum=2
IF %dow%==Thursday set downum=3
IF %dow%==Friday set downum=4
IF %dow%==Saturday set downum=5
IF %dow%==Sunday set downum=6

REM print the days number 0-mon,1-tue ... 6-sun
echo %downum%

REM set a file name using day of week number
set myfile=%downum%.bak

echo %myfile%

pause
exit

EDIT:

Though I turned to VBS, It can be done in pure batch, took me a while to get it working and a lot of searching lol, but this seems to work:

 @echo off
SETLOCAL enabledelayedexpansion
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
    if "!count!" GTR "0" GOTO next
    set dow=%%D
    SET /a count+=1
)
:next
echo %dow%
pause

The only caveat for you on the above batch is that its day of weeks are from 1-7 and not 0-6

System has not been booted with systemd as init system (PID 1). Can't operate

This worked for me (using WSL)

sudo /etc/init.d/redis start

(for any other service, check the init.d folder for filenames)

Context.startForegroundService() did not then call Service.startForeground()

This error also occurs on Android 8+ when Service.startForeground(int id, Notification notification) is called while id is set to 0.

id int: The identifier for this notification as per NotificationManager.notify(int, Notification); must not be 0.

Filename timestamp in Windows CMD batch script getting truncated

See Stack Overflow question How to get current datetime on Windows command line, in a suitable format for using in a filename?.

Create a file, date.bat:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-3 delims=/:/ " %%a in ('time /t') do (set mytime=%%a-%%b-%%c)
set mytime=%mytime: =% 
echo %mydate%_%mytime%

Run date.bat:

C:\>date.bat
2012-06-14_12-47-PM

UPDATE:

You can also do it with one line like this:

for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g

Make element fixed on scroll

You can do this with css too.

just use position:fixed; for what you want to be fixed when you scroll down.

you can have some examples here:

http://davidwalsh.name/demo/css-fixed-position.php

http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html

Difference between objectForKey and valueForKey?

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

Symbol for any number of any characters in regex?

Do you mean

.*

. any character, except newline character, with dotall mode it includes also the newline characters

* any amount of the preceding expression, including 0 times

What is the best way to iterate over a dictionary?

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

How do I remove the blue styling of telephone numbers on iPhone/iOS?

An old question but as none of the above answers were good for me i post how i resolved it

I have a phone number in a list:

<li class="phone_menu">+555 5 555 55 55</li>

css:

.phone_menu{
  color:orange;
}

But on iPad/iPhone it was black, so i just added this to the css:

.phone_menu a{
  color:orange;
}

How to call a JavaScript function from PHP?

Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).

<td onClick= loadxml()><i>Click for Details</i></td>

function loadxml()
{
    result = loadScriptWithAjax("/script.php?event=button_clicked");
    alert(result);
}

// script.php
<?php
    if($_GET['event'] == 'button_clicked')
        echo "\"You clicked a button\"";
?>

Install Windows Service created in Visual Studio

Stealth Change in VS 2010 and .NET 4.0 and Later

No public installers with the RunInstallerAttribute.Yes attribute could be found

There is an alias change or compiler cleanup in .NET that may reveal this little tweak for your specific case.

If you have the following code …

RunInstaller(true)   // old alias  

You may need to update it to

RunInstallerAttribute(true)  // new property spelling

It is like an alias changed under the covers at compile time or at runtime and you will get this error behavior. The above explicit change to RunInstallerAttribute(true) fixed it in all of our install scenarios on all machines.

After you add project or service installer then check for the “old” RunInstaller(true) and change it to the new RunInstallerAttribute(true)

Implicit function declarations in C

Because of historical reasons going back to the very first version of C, functions are assumed to have an implicit definition of int function(int arg1, int arg2, int arg3, etc).

Edit: no, I was wrong about int for the arguments. Instead it passes whatever type the argument is. So it could be an int or a double or a char*. Without a prototype the compiler will pass whatever size the argument is and the function being called had better use the correct argument type to receive it.

For more details look up K&R C.

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

How can I get onclick event on webview in android?

On Click event On webView works in onTouch like this:

imagewebViewNewsChart.setOnTouchListener(new View.OnTouchListener(){

  @Override   
  public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction()==MotionEvent.ACTION_MOVE){                        
       return false;     
    }

    if (event.getAction()==MotionEvent.ACTION_UP){    
        startActivity(new Intent(this,Example.class));                

    } 

    return false;                 
  }                       
});

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Execute command on all files in a directory

The accepted/high-voted answers are great, but they are lacking a few nitty-gritty details. This post covers the cases on how to better handle when the shell path-name expansion (glob) fails, when filenames contain embedded newlines/dash symbols and moving the command output re-direction out of the for-loop when writing the results to a file.

When running the shell glob expansion using * there is a possibility for the expansion to fail if there are no files present in the directory and an un-expanded glob string will be passed to the command to be run, which could have undesirable results. The bash shell provides an extended shell option for this using nullglob. So the loop basically becomes as follows inside the directory containing your files

 shopt -s nullglob

 for file in ./*; do
     cmdToRun [option] -- "$file"
 done

This lets you safely exit the for loop when the expression ./* doesn't return any files (if the directory is empty)

or in a POSIX compliant way (nullglob is bash specific)

 for file in ./*; do
     [ -f "$file" ] || continue
     cmdToRun [option] -- "$file"
 done

This lets you go inside the loop when the expression fails for once and the condition [ -f "$file" ] check if the un-expanded string ./* is a valid filename in that directory, which wouldn't be. So on this condition failure, using continue we resume back to the for loop which won't run subsequently.

Also note the usage of -- just before passing the file name argument. This is needed because as noted previously, the shell filenames can contain dashes anywhere in the filename. Some of the shell commands interpret that and treat them as a command option when the name are not quoted properly and executes the command thinking if the flag is provided.

The -- signals the end of command line options in that case which means, the command shouldn't parse any strings beyond this point as command flags but only as filenames.


Double-quoting the filenames properly solves the cases when the names contain glob characters or white-spaces. But *nix filenames can also contain newlines in them. So we de-limit filenames with the only character that cannot be part of a valid filename - the null byte (\0). Since bash internally uses C style strings in which the null bytes are used to indicate the end of string, it is the right candidate for this.

So using the printf option of shell to delimit files with this NULL byte using the -d option of read command, we can do below

( shopt -s nullglob; printf '%s\0' ./* ) | while read -rd '' file; do
    cmdToRun [option] -- "$file"
done

The nullglob and the printf are wrapped around (..) which means they are basically run in a sub-shell (child shell), because to avoid the nullglob option to reflect on the parent shell, once the command exits. The -d '' option of read command is not POSIX compliant, so needs a bash shell for this to be done. Using find command this can be done as

while IFS= read -r -d '' file; do
    cmdToRun [option] -- "$file"
done < <(find -maxdepth 1 -type f -print0)

For find implementations that don't support -print0 (other than the GNU and the FreeBSD implementations), this can be emulated using printf

find . -maxdepth 1 -type f -exec printf '%s\0' {} \; | xargs -0 cmdToRun [option] --

Another important fix is to move the re-direction out of the for-loop to reduce a high number of file I/O. When used inside the loop, the shell has to execute system-calls twice for each iteration of the for-loop, once for opening and once for closing the file descriptor associated with the file. This will become a bottle-neck on your performance for running large iterations. Recommended suggestion would be to move it outside the loop.

Extending the above code with this fixes, you could do

( shopt -s nullglob; printf '%s\0' ./* ) | while read -rd '' file; do
    cmdToRun [option] -- "$file"
done > results.out

which will basically put the contents of your command for each iteration of your file input to stdout and when the loop ends, open the target file once for writing the contents of the stdout and saving it. The equivalent find version of the same would be

while IFS= read -r -d '' file; do
    cmdToRun [option] -- "$file"
done < <(find -maxdepth 1 -type f -print0) > results.out

HTML5 Dynamically create Canvas

 <html>
 <head></head>
 <body>
 <canvas id="canvas" width="300" height="300"></canvas>
 <script>
  var sun = new Image();
  var moon = new Image();
  var earth = new Image();
  function init() {
  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
  moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
  window.requestAnimationFrame(draw);
  }

  function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0, 0, 300, 300);

  ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
  ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
  ctx.save();
  ctx.translate(150, 150);

  // Earth
  var time = new Date();
  ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * 
  time.getMilliseconds());
  ctx.translate(105, 0);
  ctx.fillRect(10, -19, 55, 31); 
  ctx.drawImage(earth, -12, -12);

   // Moon
  ctx.save();
  ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * 
  time.getMilliseconds());
  ctx.translate(0, 28.5);
  ctx.drawImage(moon, -3.5, -3.5);
  ctx.restore();

  ctx.restore();

   ctx.beginPath();
   ctx.arc(150, 150, 105, 0, Math.PI * 2, false);
   ctx.stroke();

   ctx.drawImage(sun, 0, 0, 300, 300);

   window.requestAnimationFrame(draw);
    }

   init();
   </script>
   </body>
   </html>

Codeigniter $this->db->get(), how do I return values for a specific row?

You simply use this in one row.

$query = $this->db->get_where('mytable',array('id'=>'3'));

How to produce an csv output file from stored procedure in SQL Server

I think it is possible to use bcp command. I am also new to this command but I followed this link and it worked for me.

'was not declared in this scope' error

The scope of a variable is always the block it is inside. For example if you do something like

if(...)
{
     int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
     int y = 8; //y is created
} //y leaves scope, since the block ends.

cout << y << endl; //Gives error since y is not defined.

The solution is to define y outside of the if blocks

int y; //y is created

if(...)
{
     y = 5;
} 
else
{
     y = 8;
} 

cout << y << endl; //Ok

In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:

//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
    int y, c;
    int d=date;

    if (month==1||month==2)
    {
         y=((year-1)%100);
         c=(year-1)/100;
    }
    else
    {
         y=year%100;
         c=year/100;
    }
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}

How to submit http form using C#

You can use the HttpWebRequest class to do so.

Example here:

using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Jquery Hide table rows

this might work for you...

$('.trhideclass1').hide();

 

<tr class="trhideclass1">
  <td>Label</td>
  <td>InputFile</td>
</tr>

Extract Data from PDF and Add to Worksheet

Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext.

Pseudocode to extract the text would include:

  1. Using SHELL VBA statement to extract the text from PDF to a temporary file using XPDF
  2. Using sequential file read statements to read the temporary file contents into a string
  3. Pasting the string into Excel

Simplified example below:

    Sub ReadIntoExcel(PDFName As String)
        'Convert PDF to text
        Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"

        'Read in the text file and write to Excel
        Dim TextLine as String
        Dim RowNumber as Integer
        Dim F1 as Integer
        RowNumber = 1
        F1 = Freefile()
        Open "tempfile.txt" for Input as #F1
            While Not EOF(#F1)
                Line Input #F1, TextLine
                ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
                RowNumber = RowNumber + 1
            Wend
        Close #F1
    End Sub

How to create PDF files in Python

It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.

Call js-function using JQuery timer

setInterval is the function you want. That repeats every x miliseconds.

window.setInterval(function() {
    alert('test');
}, 10000);

How do I check if a directory exists? "is_dir", "file_exists" or both?

$save_folder = "some/path/" . date('dmy');

if (!file_exists($save_folder)) {
   mkdir($save_folder, 0777);
}

How do I install PHP cURL on Linux Debian?

Type in console as root:

apt-get update && apt-get install php5-curl

or with sudo:

sudo apt-get update && sudo apt-get install php5-curl

Sorry I missread.

1st, check your DNS config and if you can ping any host at all,

ping google.com
ping zm.archive.ubuntu.com

If it does not work, check /etc/resolv.conf or /etc/network/resolv.conf, if not, change your apt-source to a different one.

/etc/apt/sources.list

Mirrors: http://www.debian.org/mirror/list

You should not use Ubuntu sources on Debian and vice versa.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I'm in VS 2003 and none of these worked for me. What worked was to open the code at the top of the .vb page in the section labeled Web Form Designer Generated Code (the part that says not to edit there) and declare it there, where the system declared all the other controls. Bizzare.

Add image to left of text via css

Try something like:

.create
 { 
  margin: 0px;
  padding-left: 20px;
  background-image: url('yourpic.gif');
    background-repeat: no-repeat;

}

Search and get a line in Python

If you prefer a one-liner:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]

Undefined reference to `sin`

I have the problem anyway with -lm added

gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status

I discovered recently that it does not work if you first specify -lm. The order matters:

gcc mtest.c -o mtest.o -lm

Just link without problems

So you must specify the libraries after.

Changing specific text's color using NSMutableAttributedString in Swift

Swift 2.1 Update:

 let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
 let linkTextWithColor = "click here"

 let range = (text as NSString).rangeOfString(linkTextWithColor)

 let attributedString = NSMutableAttributedString(string:text)
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

 self.helpText.attributedText = attributedString

self.helpText is a UILabel outlet.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

I've read, this is a symbol of Arrow Functions in ES6

this

var a2 = a.map(function(s){ return s.length });

using Arrow Function can be written as

var a3 = a.map( s => s.length );

MDN Docs

How can I use pickle to save a dict?

If you just want to store the dict in a single file, use pickle like that

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
    pickle.dump(a, handle)

with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)

If you want to save and restore multiple dictionaries in multiple files for caching and store more complex data, use anycache. It does all the other stuff you need around pickle

from anycache import anycache

@anycache(cachedir='path/to/files')
def myfunc(hello):
    return {'hello', hello}

Anycache stores the different myfunc results depending on the arguments to different files in cachedir and reloads them.

See the documentation for any further details.

Rails 3.1 and Image Assets

http://railscasts.com/episodes/279-understanding-the-asset-pipeline

This railscast (Rails Tutorial video on asset pipeline) helps a lot to explain the paths in assets pipeline as well. I found it pretty useful, and actually watched it a few times.

The solution I chose is @Lee McAlilly's above, but this railscast helped me to understand why it works. Hope it helps!

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

Get product id and product type in magento?

IN MAGENTO query in the database and fetch the result like. product id, product name and manufracturer with out using the product flat table use the eav catalog_product_entity and its attribute table product_id product_name manufacturer 1 | PRODUCTA | NOKIA 2 | PRODUCTB | SAMSUNG

Find unique rows in numpy.array

Yet another possible solution

np.vstack({tuple(row) for row in a})

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

IIS Express Windows Authentication

If none of the answers helps, you might need to adjust the project properties. Check this other StackOverflow answer on how to do that:

https://stackoverflow.com/a/20857049/56621

Bash Templating: How to build configuration files from templates with Bash?

A longer but more robust version of the accepted answer:

perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\})?;substr($1,0,int(length($1)/2)).($2&&length($1)%2?$2:$ENV{$3||$4});eg' template.txt

This expands all instances of $VAR or ${VAR} to their environment values (or, if they're undefined, the empty string).

It properly escapes backslashes, and accepts a backslash-escaped $ to inhibit substitution (unlike envsubst, which, it turns out, doesn't do this).

So, if your environment is:

FOO=bar
BAZ=kenny
TARGET=backslashes
NOPE=engi

and your template is:

Two ${TARGET} walk into a \\$FOO. \\\\
\\\$FOO says, "Delete C:\\Windows\\System32, it's a virus."
$BAZ replies, "\${NOPE}s."

the result would be:

Two backslashes walk into a \bar. \\
\$FOO says, "Delete C:\Windows\System32, it's a virus."
kenny replies, "${NOPE}s."

If you only want to escape backslashes before $ (you could write "C:\Windows\System32" in a template unchanged), use this slightly-modified version:

perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\});substr($1,0,int(length($1)/2)).(length($1)%2?$2:$ENV{$3||$4});eg' template.txt

How to specify in crontab by what user to run script?

Since you're running Ubuntu, your system crontab is located at /etc/crontab.

As the root user (or using sudo), you can simply edit this file and specify the user that should run this command. Here is the format of entries in the system crontab and how you should enter your command:

# m h dom mon dow user  command
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

Of course the permissions for your php script and your log file should be set so that the www-data user has access to them.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Try this query

SELECT v.VehicleId, v.Name, ll.LocationList
FROM Vehicles v 
LEFT JOIN 
    (SELECT 
     DISTINCT
        VehicleId,
        REPLACE(
            REPLACE(
                REPLACE(
                    (
                        SELECT City as c 
                        FROM Locations x 
                        WHERE x.VehicleID = l.VehicleID FOR XML PATH('')
                    ),    
                    '</c><c>',', '
                 ),
             '<c>',''
            ),
        '</c>', ''
        ) AS LocationList
    FROM Locations l
) ll ON ll.VehicleId = v.VehicleId

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

You should use

this.router.parent.navigate(['/About']);

As well as specifying the route path, you can also specify your route's name:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

Convert string (without any separator) to list

You mean that you want something like:

''.join(n for n in phone_str if n.isdigit())

This uses the fact that strings are iterable. They yield 1 character at a time when you iterate over them.


Regarding your efforts,

This one actually removes all of the digits from the string leaving you with only non-digits.

x = row.translate(None, string.digits)

This one splits the string on runs of whitespace, not after each character:

list = x.split()

The import javax.persistence cannot be resolved

Yes, you will likely need to add another jar or dependency

javax.persistence.* is part of the Java Persistence API (JPA). It is only an API, you can think of it as similar to an interface. There are many implementations of JPA and this answer gives a very good elaboration of each, as well as which to use.

If your javax.persistence.* import cannot be resolved, you will need to provide the jar that implements JPA. You can do that either by manually downloading it (and adding it to your project) or by adding a declaration to a dependency management tool (for eg, Ivy/Maven/Gradle). See here for the EclipseLink implementation (the reference implementation) on Maven repo.

After doing that, your imports should be resolved.

Also see here for what is JPA about. The xml you are referring to could be persistence.xml, which is explained on page 3 of the link.

That being said, you might just be pointing to the wrong target runtime

If i recall correctly, you don't need to provide a JPA implementation if you are deploying it into a JavaEE app server like JBoss. See here "Note that you typically don't need it when you deploy your application in a Java EE 6 application server (like JBoss AS 6 for example).". Try changing your project's target runtime.

If your local project was setup to point to Tomcat while your remote repo assumes a JavaEE server, this could be the case. See here for the difference between Tomcat and JBoss.

Edit: I changed my project to point to GlassFish instead of Tomcat and javax.persistence.* resolved fine without any explicit JPA dependency.

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

grep without showing path/file:line

No need to find. If you are just looking for a pattern within a specific directory, this should suffice:

grep -hn FOO /your/path/*.bar

Where -h is the parameter to hide the filename, as from man grep:

-h, --no-filename

Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

Note that you were using

-H, --with-filename

Print the file name for each match. This is the default when there is more than one file to search.

ArrayList vs List<> in C#

ArrayList are not type safe whereas List<T> are type safe. Simple :).

Which Protocols are used for PING?

The usual command line ping tool uses ICMP Echo, but it's true that other protocols can also be used, and they're useful in debugging different kinds of network problems.

I can remember at least arping (for testing ARP requests) and tcping (which tries to establish a TCP connection and immediately closes it, it can be used to check if traffic reaches a certain port on a host) off the top of my head, but I'm sure there are others aswell.

How to avoid pressing Enter with getchar() for reading a single character only?

getchar() is a standard function that on many platforms requires you to press ENTER to get the input, because the platform buffers input until that key is pressed. Many compilers/platforms support the non-standard getch() that does not care about ENTER (bypasses platform buffering, treats ENTER like just another key).

Retrieving Data from SQL Using pyodbc

In order to receive actual data stored in the table, you should use one of fetch...() functions or use the cursor as an iterator (i.e. "for row in cursor"...). This is described in the documentation:

cursor.execute("select user_id, user_name from users where user_id < 100")
rows = cursor.fetchall()
for row in rows:
    print row.user_id, row.user_name

New og:image size for Facebook share?

I'm using the minimum image size (200 x 200) and getting good results. Take a look:

enter image description here https://developers.facebook.com/tools/debug/og/object?q=origgami.com.br

This squared size is better than rectangles because it is the format that appears on facebook comments. The rectangle format gets cropped.

This size is on facebook documentation

Setting up connection string in ASP.NET to SQL SERVER

If you want to write connection string in Web.config then write under given sting

<connectionStrings>
  <add name="Conn" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

OR

you right in aspx.cs file like

SqlConnection conn = new SqlConnection("Data Source=12.16.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com");

How to use CSS to surround a number with a circle?

HTML EXAMPLE

<h3><span class="numberCircle">1</span> Regiones del Interior</h3>

CODE

    .numberCircle { 

    border-radius:50%;
    width:40px;
    height:40px;
    display:block;
    float:left;
    border:2px solid #000000;
    color:#000000;
    text-align:center;
    margin-right:5px;

}

Git Remote: Error: fatal: protocol error: bad line length character: Unab

I had the same kind of problem after installing GIT on Windows. At first it worked; then, a day later (after a PC reboot), it didn't anymore, and I got this:

$ git pull
fatal: protocol error: bad line length character: git@

The problem was that after the reboot, the automatically started Putty "pageant.exe" didn't have the private key active anymore. When you add a key in pageant, it's not a persistent setting by default. I just had to add the key again, and it worked fine. So, for that case, it's necessary to make pagenant load the key automatically, as discussed here:

https://www.digitalocean.com/community/tutorials/how-to-use-pageant-to-streamline-ssh-key-authentication-with-putty

How to connect SQLite with Java?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;   


public class Connectdatabase {

        Connection con = null;

        public static Connection ConnecrDb(){

            try{
                //String dir = System.getProperty("user.dir");
                Class.forName("org.sqlite.JDBC");
                Connection con = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
                return con;
            }
            catch(ClassNotFoundException | SQLException e){
                JOptionPane.showMessageDialog(null,"Problem with connection of database");
                return null;
            }
        }

    }

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

Select elements by attribute

$("input#A").attr("myattr") == null

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Go to

Tools->Options->Text Editor->C# (or All Languages)->General

and enable Auto List Members and Parameter Information in right hand side pane.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Best data type for storing currency values in a MySQL database

For accounting applications it's very common to store the values as integers (some even go so far as to say it's the only way). To get an idea, take the amount of the transactions (let's suppose $100.23) and multiple by 100, 1000, 10000, etc. to get the accuracy you need. So if you only need to store cents and can safely round up or down, just multiply by 100. In my example, that would make 10023 as the integer to store. You'll save space in the database and comparing two integers is much easier than comparing two floats. My $0.02.

Select columns in PySpark dataframe

The method select accepts a list of column names (string) or expressions (Column) as a parameter. To select columns you can use:

-- column names (strings):

df.select('col_1','col_2','col_3')

-- column objects:

import pyspark.sql.functions as F

df.select(F.col('col_1'), F.col('col_2'), F.col('col_3'))

# or

df.select(df.col_1, df.col_2, df.col_3)

# or

df.select(df['col_1'], df['col_2'], df['col_3'])

-- a list of column names or column objects:

df.select(*['col_1','col_2','col_3'])

#or

df.select(*[F.col('col_1'), F.col('col_2'), F.col('col_3')])

#or 

df.select(*[df.col_1, df.col_2, df.col_3])

The star operator * can be omitted as it's used to keep it consistent with other functions like drop that don't accept a list as a parameter.

Remove CSS class from element with JavaScript (no jQuery)

try:

function removeClassName(elem, name){
    var remClass = elem.className;
    var re = new RegExp('(^| )' + name + '( |$)');
    remClass = remClass.replace(re, '$1');
    remClass = remClass.replace(/ $/, '');
    elem.className = remClass;
}

Static constant string (class member)

In C++11 you can do now:

class A {
 private:
  static constexpr const char* STRING = "some useful string constant";
};

Powershell: Get FQDN Hostname

It can also be retrieved from the registry:

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
   % { $_.'NV HostName', $_.'NV Domain' -join '.' }

How to import a jar in Eclipse

  1. Right Click on the Project.
  2. Click on Build Path.
  3. Click On Configure Build Path.
  4. Under Libraries, Click on Add Jar or Add External Jar.

Better way to convert file sizes in Python

Here it is:

def convert_bytes(size):
   for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
       if size < 1024.0:
           return "%3.1f %s" % (size, x)
       size /= 1024.0

   return size

How to obtain the last path segment of a URI

If you are using Java 8 and you want the last segment in a file path you can do.

Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();

If you have a url such as http://base_path/some_segment/id you can do.

final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);

Create a button programmatically and set a background image

SWIFT 3 Version of Alex Reynolds' Answer

let image = UIImage(named: "name") as UIImage?
let button = UIButton(type: UIButtonType.custom) as UIButton
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: Selector("btnTouched:"), for:.touchUpInside)
        self.view.addSubview(button)

Set initially selected item in Select list in Angular2

I hope it will help someone ! (works on Angular 6)

I had to add lots of select/options dynamically and following worked for me:

<div *ngFor="let option of model.q_options; let ind=index;">

        <select 
          [(ngModel)]="model.q_options[ind].type" 
          [ngModelOptions]="{standalone: true}"
        > 
          <option 
            *ngFor="let object of objects" 
            [ngValue]="object.type" 
            [selected]="object.type === model.q_options[ind].type"
          >{{object.name}}
          </option>
        </select> 

        <div [ngSwitch]="model.q_options[ind].type">
          ( here <div *ngSwitchCase="'text' or 'imagelocal' or etc."> is used to add specific input forms )
        </div>
</div>

and in *.ts

// initial state of the model
// q_options in html = NewOption and its second argument is option type
model = new NewQuestion(1, null, 2, 
  [
    new NewOption(0, 'text', '', 1), 
    new NewOption(1, 'imagelocal', '', 1)
  ]);

// dropdown options
objects = [
    {type: 'text', name: 'text'},
    {type: 'imagelocal', name: 'image - local file'},
    {type: 'imageurl', name: 'image URL'}
   ( and etc.)
];

When user adds one more 'input option' (pls do not confuse 'input option' with select/options - select/options are static here) specific select/option, selected by the user earlier, is preserved on each/all dynamically added 'input option's select/options.

Login to remote site with PHP cURL

View the source of the login page. Look for the form HTML tag. Within that tag is something that will look like action= Use that value as $url, not the URL of the form itself.

Also, while you are there, verify the input boxes are named what you have them listed as.

For example, a basic login form will look similar to:

<form method='post' action='postlogin.php'>
    Email Address: <input type='text' name='email'>
    Password: <input type='password' name='password'>
</form>

Using the above form as an example, change your value of $url to:

$url="http://www.myremotesite.com/postlogin.php";

Verify the values you have listed in $postdata:

$postdata = "email=".$username."&password=".$password;

and it should work just fine.

How can I add raw data body to an axios request?

How about using direct axios API?

axios({
  method: 'post',
  url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
  headers: {}, 
  data: {
    foo: 'bar', // This is the body part
  }
});

Source: axios api

Responsive Images with CSS

Use max-width on the images too. Change:

.erb-image-wrapper img{
    width:100% !important;
    height:100% !important;
    display:block;
}

to...

.erb-image-wrapper img{
    max-width:100% !important;
    max-height:100% !important;
    display:block;
}

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

Object Library Not Registered When Adding Windows Common Controls 6.0

I have been having the same problem. VB6 Win7 64 bit and have come across a very simple solution, so I figured it would be a good idea to share it here in case it helps anyone else.

First I have tried the following with no success:

  • unregistered and re-registering MSCOMCTL, MSCOMCTL2 and the barcode active X controls in every directory I could think of trying (VB98, system 32, sysWOW64, project folder.)

  • Deleting working folder and getting everything again. (through source safe)

  • Copying the OCX files from a machine with no problems and registering those.

  • Installing service pack 6

  • Installing MZ tools - it was worth a try

  • Installing the distributable version of the project.

  • Manually editing the vbp file (after making it writeable) to amend/remove the references and generally fiddling.

  • Un-Installing VB6 and re-Installing (this I thought was a last resort) The problem was occurring on a new project and not just existing ones.

NONE of the above worked but the following did

Open VB6
New project
>Project
    >Components
        Tick the following:
            Microsoft flexigrid control 6.0 (sp6)
            Microsoft MAPI controls 6.0
            Microsoft Masked Edit Control 6.0 (sp3)
            Microsoft Tabbed Dialog Control 6.0 (sp6)
        >Apply

After this I could still not tick the Barcode Active X or the windows common contols 6.0 and windows common controls 2 6.0, but when I clicked apply, the message changed from unregistered, to that it was already in the project.

>exit the components dialog and then load project. 

This time it worked. Tried the components dialog again and the missing three were now ticked. Everything seems fine now.

How to install a specific version of a ruby gem?

You can use the -v or --version flag. For example

gem install bitclock -v '< 0.0.2'

To specify upper AND lower version boundaries you can specify the --version flag twice

gem install bitclock -v '>= 0.0.1' -v '< 0.0.2'

or use the syntax (for example)

gem install bitclock -v '>= 0.0.1, < 0.0.2'

The other way to do it is

gem install bitclock:'>= 0.0.1'

but with the last option it is not possible to specify upper and lower bounderies simultaneously.

[gem 3.0.3 and ruby 2.6.6]

Alternative to a goto statement in Java

Java doesn't have goto, because it makes the code unstructured and unclear to read. However, you can use break and continue as civilized form of goto without its problems.


Jumping forward using break -

ahead: {
    System.out.println("Before break");
    break ahead;
    System.out.println("After Break"); // This won't execute
}
// After a line break ahead, the code flow starts from here, after the ahead block
System.out.println("After ahead");

Output:

Before Break
After ahead

Jumping backward using continue

before: {
    System.out.println("Continue");
    continue before;
}

This will result in an infinite loop as every time the line continue before is executed, the code flow will start again from before.

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

How to fix java.net.SocketException: Broken pipe?

This is caused by:

  • most usually, writing to a connection when the other end has already closed it;
  • less usually, the peer closing the connection without reading all the data that is already pending at his end.

So in both cases you have a poorly defined or implemented application protocol.

There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.

ab load testing

I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.

the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".

the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!

but did anyone think to "localhost" on any apache server for example www.apachefriends.org?

you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".

and then: benchmark it!

bench.php

<?php

for($i=1;$i<50000;$i++){
    print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>

void.php

<?php
?>

on your Desktop you should use a .bat file(in Windows) like this:

bench.bat

"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause

Now if you pay attention closely ...

the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!

here i got :

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/void.php
Document Length:        0 bytes

Concurrency Level:      1
Time taken for tests:   11.219 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2150000 bytes
HTML transferred:       0 bytes
Requests per second:    891.34 [#/sec] (mean)
Time per request:       1.122 [ms] (mean)
Time per request:       1.122 [ms] (mean, across all concurrent requests)
Transfer rate:          187.15 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:     0    1   0.9      1      17
Waiting:        0    1   0.9      1      17
Total:          0    1   0.9      1      17

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      2
  98%      2
  99%      3
 100%     17 (longest request)

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/bench.php
Document Length:        1799964 bytes

Concurrency Level:      1
Time taken for tests:   177.006 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      18001600000 bytes
HTML transferred:       17999640000 bytes
Requests per second:    56.50 [#/sec] (mean)
Time per request:       17.701 [ms] (mean)
Time per request:       17.701 [ms] (mean, across all concurrent requests)
Transfer rate:          99317.00 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:    12   17   3.2     17      90
Waiting:        0    1   1.1      1      26
Total:         13   18   3.2     18      90

Percentage of the requests served within a certain time (ms)
  50%     18
  66%     19
  75%     19
  80%     20
  90%     21
  95%     22
  98%     23
  99%     26
 100%     90 (longest request)

c:\xampp\htdocs\bench>pause
Press any key to continue . . .

90-17= 73 the result i expect !

How to move text up using CSS when nothing is working

used the following snippet and it worked fine..

.smallText .bmv-disclaimer {
   height: 40px;
}

How to update the value stored in Dictionary in C#?

Here is a way to update by an index much like foo[x] = 9 where x is a key and 9 is the value

var views = new Dictionary<string, bool>();

foreach (var g in grantMasks)
{
    string m = g.ToString();
    for (int i = 0; i <= m.Length; i++)
    {
        views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
    }
}

Enable & Disable a Div and its elements in Javascript

If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.

try this.

$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

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

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

How to run only one unit test class using Gradle

In my case, my eclipse java compiler warnings were set too high, and eclipse was not recognizing my class as valid for execution. Updating my compiler settings fixed the problem. You can read more about it here: annotation-nonnull-cannot-be-resolved

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root  
--app.py     <-- file from which app will be run
--models
----user.py      <-- file with "User" model
----order.py    <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from app.py.

This concept is explained better by the answer to this thread posted by @SuperShoot

Hash String via SHA-256 in Java

I suppose you are using a relatively old Java Version without SHA-256. So you must add the BouncyCastle Provider to the already provided 'Security Providers' in your java version.

    // NEEDED if you are using a Java version without SHA-256    
    Security.addProvider(new BouncyCastleProvider());

    // then go as usual 
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "my string...";
    md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
    byte[] digest = md.digest();

Android toolbar center title and custom font

Try

@Override
    public void onBackPressed() {
          if(getTitle().equals(getResources().getString(R.string.app_name))) {
            super.onBackPressed();}
          else {
//set visiblity
           }
}

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How to write inline if statement for print?

Well why don't you simply write:

if b:
    print a
else:
    print 'b is false'

How do I add an element to array in reducer of React native redux?

If you need to insert into a specific position in the array, you can do this:

case ADD_ITEM :
    return { 
        ...state,
        arr: [
            ...state.arr.slice(0, action.pos),
            action.newItem,
            ...state.arr.slice(action.pos),
        ],
    }

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

You have 2 options for this error:

  1. The file you are uploading is too big, which you need to use smaller file.
  2. Increase the upload size in php.ini to

upload_max_filesize = 9M; post_max_size = 9M;

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

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

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

Android Layout Animations from bottom to top and top to bottom on ImageView click

I have solved my issue and now my animation works fine :) if anyone needed just copy my code and xml file and have a happy coding :)

My Activity MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

RelativeLayout rl_footer;
ImageView iv_header;
boolean isBottom = true;
Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl_footer = (RelativeLayout) findViewById(R.id.rl_footer);
    iv_header = (ImageView) findViewById(R.id.iv_up_arrow);
    iv_header.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            iv_header.setImageResource(R.drawable.down_arrow);
            iv_header.setPadding(0, 10, 0, 0); 
            rl_footer.setBackgroundResource(R.drawable.up_manu_bar);
            if (isBottom) {
                SlideToAbove();
                isBottom = false;
            } else {
                iv_header.setImageResource(R.drawable.up_arrow);
                iv_header.setPadding(0, 0, 0, 10);
                rl_footer.setBackgroundResource(R.drawable.down_manu_bar1);
                SlideToDown();
                isBottom = true;
            }

        }
    });

}

public void SlideToAbove() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -5.0f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            // lp.setMargins(0, 0, 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            rl_footer.setLayoutParams(lp);

        }

    });

}

public void SlideToDown() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 5.2f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            lp.setMargins(0, rl_footer.getWidth(), 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rl_footer.setLayoutParams(lp);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

and my Xml activity_main:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/autograph_bg" >

 <RelativeLayout
    android:id="@+id/rl_footer"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/down_manu_bar1" >

    <ImageView
        android:id="@+id/iv_new_file"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:onClick="onNewFileClick"
        android:src="@drawable/file_icon" />

    <TextView
        android:id="@+id/tv_new_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_new_file"
        android:layout_below="@+id/iv_new_file"
        android:text="New"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_insert"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_new_file"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_new_file"
        android:src="@drawable/insert_icon" />

    <TextView
        android:id="@+id/tv_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_insert"
        android:layout_below="@+id/iv_insert"
        android:text="Insert"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_up_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:paddingBottom="10dp"
        android:src="@drawable/up_arrow" />

    <ImageView
        android:id="@+id/iv_down_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/down_arrow"
        android:paddingBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_save"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_insert"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_up_arrow"
        android:src="@drawable/save" />

    <TextView
        android:id="@+id/tv_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_save"
        android:layout_alignParentBottom="true"
        android:text="Save"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_settings"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_save"
        android:layout_marginLeft="27dp"
        android:layout_toRightOf="@+id/tv_save"
        android:paddingTop="2dp"
        android:src="@drawable/icon_settings" />

    <TextView
        android:id="@+id/tv_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="260dp"
        android:text="Settings"
        android:textColor="#ffffff" />
 </RelativeLayout>

 </RelativeLayout>

just create new android project and copy paste my code and have fun! :) also remember in xml i have image view and his background images replace with yout own images thanks..

Transpose/Unzip Function (inverse of zip)?

You could also do

result = ([ a for a,b in original ], [ b for a,b in original ])

It should scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.

(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like zip does.)

If generators instead of actual lists are ok, this would do that:

result = (( a for a,b in original ), ( b for a,b in original ))

The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.

How can I tell if a DOM element is visible in the current viewport?

Update

In modern browsers, you might want to check out the Intersection Observer API which provides the following benefits:

  • Better performance than listening for scroll events
  • Works in cross domain iframes
  • Can tell if an element is obstructing/intersecting another

Intersection Observer is on its way to being a full-fledged standard and is already supported in Chrome 51+, Edge 15+ and Firefox 55+ and is under development for Safari. There's also a polyfill available.


Previous answer

There are some issues with the answer provided by Dan that might make it an unsuitable approach for some situations. Some of these issues are pointed out in his answer near the bottom, that his code will give false positives for elements that are:

  • Hidden by another element in front of the one being tested
  • Outside the visible area of a parent or ancestor element
  • An element or its children hidden by using the CSS clip property

These limitations are demonstrated in the following results of a simple test:

Failed test, using isElementInViewport

The solution: isElementVisible()

Here's a solution to those problems, with the test result below and an explanation of some parts of the code.

function isElementVisible(el) {
    var rect     = el.getBoundingClientRect(),
        vWidth   = window.innerWidth || document.documentElement.clientWidth,
        vHeight  = window.innerHeight || document.documentElement.clientHeight,
        efp      = function (x, y) { return document.elementFromPoint(x, y) };     

    // Return false if it's not in the viewport
    if (rect.right < 0 || rect.bottom < 0 
            || rect.left > vWidth || rect.top > vHeight)
        return false;

    // Return true if any of its four corners are visible
    return (
          el.contains(efp(rect.left,  rect.top))
      ||  el.contains(efp(rect.right, rect.top))
      ||  el.contains(efp(rect.right, rect.bottom))
      ||  el.contains(efp(rect.left,  rect.bottom))
    );
}

Passing test: http://jsfiddle.net/AndyE/cAY8c/

And the result:

Passed test, using isElementVisible

Additional notes

This method is not without its own limitations, however. For instance, an element being tested with a lower z-index than another element at the same location would be identified as hidden even if the element in front doesn't actually hide any part of it. Still, this method has its uses in some cases that Dan's solution doesn't cover.

Both element.getBoundingClientRect() and document.elementFromPoint() are part of the CSSOM Working Draft specification and are supported in at least IE 6 and later and most desktop browsers for a long time (albeit, not perfectly). See Quirksmode on these functions for more information.

contains() is used to see if the element returned by document.elementFromPoint() is a child node of the element we're testing for visibility. It also returns true if the element returned is the same element. This just makes the check more robust. It's supported in all major browsers, Firefox 9.0 being the last of them to add it. For older Firefox support, check this answer's history.

If you want to test more points around the element for visibility-ie, to make sure the element isn't covered by more than, say, 50%-it wouldn't take much to adjust the last part of the answer. However, be aware that it would probably be very slow if you checked every pixel to make sure it was 100% visible.

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

Unit test naming best practices

Kent Beck suggests:

  • One test fixture per 'unit' (class of your program). Test fixtures are classes themselves. The test fixture name should be:

    [name of your 'unit']Tests
    
  • Test cases (the test fixture methods) have names like:

    test[feature being tested]
    

For example, having the following class:

class Person {
    int calculateAge() { ... }

    // other methods and properties
}

A test fixture would be:

class PersonTests {

    testAgeCalculationWithNoBirthDate() { ... }

    // or

    testCalculateAge() { ... }
}

Overlapping Views in Android

Also, take a look at FrameLayout, that's how the Camera's Gallery application implements the Zoom buttons overlay.

Override back button to act like home button

Most of the time you need to create a Service to perform something in the background, and your visible Activity simply controls this Service. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity can finish as usual and the Service will still be running.

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

// 2.0 and above
@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack can be used as a quick alternative on occasion.

NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button.

Fatal error: Cannot use object of type stdClass as array in

Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g

 $getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup'   AND used='0' LIMIT 10");

foreach($getvidids->result() as $key=>$myids)
{

  $vidid[$key] = $myids->videoid;  // better methodology to retrieve and store multiple records in arrays in loop
 }

How to extract text from a PDF file?

I recommend to use pymupdf or pdfminer.six.

Those packages are not maintained:

  • PyPDF2, PyPDF3, PyPDF4
  • pdfminer (without .six)

How to read pure text with pymupdf

There are different options which will give different results, but the most basic one is:

import fitz  # this is pymupdf

with fitz.open("my.pdf") as doc:
    text = ""
    for page in doc:
        text += page.getText()

print(text)

Get user location by IP address

    public static string GetLocationIPAPI(string ipaddress)
    {
        try
        {
            IPDataIPAPI ipInfo = new IPDataIPAPI();
            string strResponse = new WebClient().DownloadString("http://ip-api.com/json/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPAPI>(strResponse);
            if (ipInfo == null || ipInfo.status.ToLower().Trim() == "fail") return "";
            else return ipInfo.city + "; " + ipInfo.regionName + "; " + ipInfo.country + "; " + ipInfo.countryCode;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPINFO
{
    public string ip { get; set; }
    public string city { get; set; }
    public string region { get; set; }
    public string country { get; set; }
    public string loc { get; set; }
    public string postal { get; set; }
    public int org { get; set; }

}

==========================

    public static string GetLocationIPINFO(string ipaddress)
    {            
        try
        {
            IPDataIPINFO ipInfo = new IPDataIPINFO();
            string strResponse = new WebClient().DownloadString("http://ipinfo.io/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPINFO>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region + "; " + ipInfo.country + "; " + ipInfo.postal;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPAPI
{
    public string status { get; set; }
    public string country { get; set; }
    public string countryCode { get; set; }
    public string region { get; set; }
    public string regionName { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public string lat { get; set; }
    public string lon { get; set; }
    public string timezone { get; set; }
    public string isp { get; set; }
    public string org { get; set; }
    public string @as { get; set; }
    public string query { get; set; }
}

==============================

    private static string GetLocationIPSTACK(string ipaddress)
    {
        try
        {
            IPDataIPSTACK ipInfo = new IPDataIPSTACK();
            string strResponse = new WebClient().DownloadString("http://api.ipstack.com/" + ipaddress + "?access_key=XX384X1XX028XX1X66XXX4X04XXXX98X");
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPSTACK>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region_name + "; " + ipInfo.country_name + "; " + ipInfo.zip;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPSTACK
{
    public string ip { get; set; }
    public int city { get; set; }
    public string region_code { get; set; }
    public string region_name { get; set; }
    public string country_code { get; set; }
    public string country_name { get; set; }
    public string zip { get; set; }


}

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Only on Firefox "Loading failed for the <script> with source"

VPNs can sometimes cause this error as well, if they provide some type of auto-blocking. Disabling the VPN worked for my case.

Representing EOF in C code?

The value of EOF can't be confused with any real character.

If a= getchar(), then we must declare a big enough to hold any value that getchar() returns. We can't use char since a must be big enough to hold EOF in addition to characters.

Get the short Git version hash

git log -1 --abbrev-commit

will also do it.

git log --abbrev-commit

will list the log entries with abbreviated SHA-1 checksum.

SELECTING with multiple WHERE conditions on same column

Try to use this alternate query:

SELECT A.CONTACTID 
FROM (SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'VOLUNTEER')A , 
(SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'UPLOADED') B WHERE A.CONTACTID = B.CONTACTID;

simple HTTP server in Java using only Java SE API

I like this question because this is an area where there's continuous innovation and there's always a need to have a light server especially when talking about embedded servers in small(er) devices. I think answers fall into two broad groups.

  1. Thin-server: server-up static content with minimal processing, context or session processing.
  2. Small-server: ostensibly a has many httpD-like server qualities with as small a footprint as you can get away with.

While I might consider HTTP libraries like: Jetty, Apache Http Components, Netty and others to be more like a raw HTTP processing facilities. The labelling is very subjective, and depends on the kinds of thing you've been call-on to deliver for small-sites. I make this distinction in the spirit of the question, particularly the remark about...

  • "...without writing code to manually parse HTTP requests and manually format HTTP responses..."

These raw tools let you do that (as described in other answers). They don't really lend themselves to a ready-set-go style of making a light, embedded or mini-server. A mini-server is something that can give you similar functionality to a full-function web server (like say, Tomcat) without bells and whistles, low volume, good performance 99% of the time. A thin-server seems closer to the original phrasing just a bit more than raw perhaps with a limited subset functionality, enough to make you look good 90% of the time. My idea of raw would be makes me look good 75% - 89% of the time without extra design and coding. I think if/when you reach the level of WAR files, we've left the "small" for bonsi servers that looks like everything a big server does smaller.

Thin-server options

Mini-server options:

  • Spark Java ... Good things are possible with lots of helper constructs like Filters, Templates, etc.
  • MadVoc ... aims to be bonsai and could well be such ;-)

Among the other things to consider, I'd include authentication, validation, internationalisation, using something like FreeMaker or other template tool to render page output. Otherwise managing HTML editing and parameterisation is likely to make working with HTTP look like noughts-n-crosses. Naturally it all depends on how flexible you need to be. If it's a menu-driven FAX machine it can be very simple. The more interactions, the 'thicker' your framework needs to be. Good question, good luck!

Is the NOLOCK (Sql Server hint) bad practice?

Doubt it was a "guru" who'd had any experience in high traffic...

Websites are usually "dirty" by the time the person is viewing the completely loaded page. Consider a form that loads from the database and then saves the data that's edited?? It's idiotic the way people go on about dirty reads being such a no no.

That said, if you have a number of layers building on your selects, you could be building in a dangerous redundancy. If you're dealing in money or status scenarios, then you need not only transactional data read/writes, but a proper concurrency solution (something most "gurus" don't bother with).

On the other hand, if you have an advanced product search for a website (ie something that likely won't be cached and be a little intensive) and you've ever built a site with more than a few concurrent users (phenominal how many "experts" haven't), it is rediculous to bottle neck every other process behind it.

Know what it means and use it when appropriate. Your database will almost always be your main bottle neck these days and being smart about using NOLOCK can save you thousands in infrastructure.

EDIT: It's not just deadlocks it helps with, it's also how much you are going to make everybody else wait until you're finished, or vice versa.

Using NOLOCK Hint in EF4?

How to read data from a zip file without having to unzip the entire file

Zip files have a table of contents. Every zip utility should have the ability to query just the TOC. Or you can use a command line program like 7zip -t to print the table of contents and redirect it to a text file.

Why both no-cache and no-store should be used in HTTP response?

If a caching system correctly implements no-store, then you wouldn't need no-cache. But not all do. Additionally, some browsers implement no-cache like it was no-store. Thus, while not strictly required, it's probably safest to include both.

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

DateTime.TryParse issue with dates of yyyy-dd-MM format

That works:

DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

Multiple aggregate functions in HAVING clause

select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION   
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0

How to delete only the content of file in python

How to delete only the content of file in python

There is several ways of set the logical size of a file to 0, depending how you access that file:

To empty an open file:

def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()

To empty a open file whose file descriptor is known:

def deleteContent(fd):
    os.ftruncate(fd, 0)
    os.lseek(fd, 0, os.SEEK_SET)

To empty a closed file (whose name is known)

def deleteContent(fName):
    with open(fName, "w"):
        pass



I have a temporary file with some content [...] I need to reuse that file

That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile and a context manager to almost transparently create/use/delete your temporary files:

import tempfile

with tempfile.TemporaryFile() as temp:
     # do whatever you want with `temp`

# <- `tempfile` guarantees the file being both closed *and* deleted
#     on exit of the context manager

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

How to compile a c++ program in Linux?

  1. To Compile your C++ code use:-

g++ file_name.cpp -o executable_file_name

(i) -o option is used to show error in the code (ii) if there is no error in the code_file, then it will generate an executable file.

  1. Now execute the generated executable file:

./executable_file_name

Why is json_encode adding backslashes?

I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.

Here is what was happening. If you do:

$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);

The result is:

["{\"test\":\"2\"}","{\"test\":\"four\"}"]

So, what you actually need to do is:

$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);

And this will return

[{"test":"2"},{"test":"four"}]

Count the items from a IEnumerable<T> without iterating?

It may not yield the best performance, but you can use LINQ to count the elements in an IEnumerable:

public int GetEnumerableCount(IEnumerable Enumerable)
{
    return (from object Item in Enumerable
            select Item).Count();
}

How do you check if a JavaScript Object is a DOM Object?

This is from the lovely JavaScript library MooTools:

if (obj.nodeName){
    switch (obj.nodeType){
    case 1: return 'element';
    case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
    }
}

Reading a file character by character in C

The problem here is twofold

  • a) you increment the pointer before you check the value read in, and
  • b) you ignore the fact that fgetc() returns an int instead of a char.

The first is easily fixed:

char *orig = code; // the beginning of the array
// ...
do {
  *code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end

The second problem is more subtle -fgetc returns an int so that the EOF value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF check and probably a regular while loop instead of do / while.

rawQuery(query, selectionArgs)

see below code it may help you.

String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);

or

String q = "SELECT * FROM customer WHERE _id = " + customerDbId  ;
Cursor mCursor = mDb.rawQuery(q, null);

react-router (v4) how to go back?

I am not sure if anyone else ran into this problem or may need to see this. But I spent about 3 hours trying to solve this issue:

I wanted to implement a simple goBack() on the click of a button. I thought I was off to a good start because my App.js was already wrapped in the Router and I was importing { BrowserRouter as Router } from 'react-router-dom'; ... Since the Router element allows me to assess the history object.

ex:

import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
  return (
    <Router>
      <Header />
      <Route path='/' component={Splash} exact />
      <Route path='/home' component={Info} exact />
      <Route path='/timer' component={Timer} exact />
      <Route path='/options' component={Options} exact />
      <Footer />
    </Router>
  );
}
export default App;

BUT the trouble was on my Nav (a child component) module, I had to 'import { withRouter } from 'react-router-dom';' and then force an export with:

export default withRouter(Nav);

ex:

import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
    render() {
        return (
            <div>
                <label htmlFor='back'></label>
                <button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
                <label htmlFor='logOut'></label>
                <button id='logOut' ><a href='./'>Log-Out</a>            
</button>
            </div>
        );
    }
}
export default withRouter(Nav);

in summary, withRouter was created because of a known issue in React where in certain scenarios when inheritance from a router is refused, a forced export is necessary.

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

How to switch databases in psql?

Though not explicitly stated in the question, the purpose is to connect to a specific schema/database.

Another option is to directly connect to the schema. Example:

sudo -u postgres psql -d my_database_name

Source from man psql:

-d dbname
--dbname=dbname
   Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line.

   If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string. See Section 31.1.1, “Connection Strings”, in the
   documentation for more information.

How can I create a marquee effect?

The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.

Also, the accepted answers demo fiddle has a lot of unnecessary styles.

So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.

http://jsfiddle.net/e8ws12pt/

_x000D_
_x000D_
.marquee {_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    padding: 0;_x000D_
    height: 16px;_x000D_
    display: block;_x000D_
}_x000D_
.marquee span {_x000D_
    display: inline-block;_x000D_
    text-indent: 0;_x000D_
    overflow: hidden;_x000D_
    -webkit-transition: 15s;_x000D_
    transition: 15s;_x000D_
    -webkit-animation: marquee 15s linear infinite;_x000D_
    animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
_x000D_
_x000D_

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Accessing Session Using ASP.NET Web API

Going back to basics why not keep it simple and store the Session value in a hidden html value to pass to your API?

Controller

public ActionResult Index()
        {

            Session["Blah"] = 609;

            YourObject yourObject = new YourObject();
            yourObject.SessionValue = int.Parse(Session["Blah"].ToString());

            return View(yourObject);
        }

cshtml

@model YourObject

@{
    var sessionValue = Model.SessionValue;
}

<input type="hidden" value="@sessionValue" id="hBlah" />

Javascript

$(document).ready(function () {

    var sessionValue = $('#hBlah').val();

    alert(sessionValue);

    /* Now call your API with the session variable */}

}

jQuery get the id/value of <li> element after click function

you can get the value of the respective li by using this method after click

HTML:-

<!DOCTYPE html>
<html>
<head>
    <title>show the value of li</title>
    <link rel="stylesheet"  href="pathnameofcss">
</head>
<body>

    <div id="user"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <ul id="pageno">
    <li value="1">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>

    </ul>

    <script src="pathnameofjs" type="text/javascript"></script>
</body>
</html>

JS:-

$("li").click(function ()
{       
var a = $(this).attr("value");

$("#user").html(a);//here the clicked value is showing in the div name user
console.log(a);//here the clicked value is showing in the console
});

CSS:-

ul{
display: flex;
list-style-type:none;
padding: 20px;
}

li{
padding: 20px;
}

Is it possible to use JS to open an HTML select to show its option list?

The solution I present is safe, simple and compatible with Internet Explorer, FireFox and Chrome.

This approach is new and complete. I not found nothing equal to that solution on the internet. Is simple, cross-browser (Internet Explorer, Chrome and Firefox), preserves the layout, use the select itself and is easy to use.

Note: JQuery is required.

HTML CODE

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CustonSelect</title>
<script type="text/javascript" src="./jquery-1.3.2.js"></script>
<script type="text/javascript" src="./CustomSelect.js"></script>
</head>
<div id="testDiv"></div>
<body>
    <table>
        <tr>
            <td>
                <select id="Select0" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select1" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select2" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select3" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="Select4" >
                    <option value="0000">0000</option>
                    <option value="0001">0001</option>
                    <option value="0002">0002</option>
                    <option value="0003">0003</option>
                    <option value="0004">0004</option>
                    <option value="0005">0005</option>
                    <option value="0006">0006</option>
                    <option value="0007">0007</option>
                    <option value="0008">0008</option>
                    <option value="0009">0009</option>
                    <option value="0010">0010</option>
                    <option value="0011">0011</option>
                    <option value="0012">0012</option>
                    <option value="0013">0013</option>
                    <option value="0014">0014</option>
                    <option value="0015">0015</option>
                    <option value="0016">0016</option>
                    <option value="0017">0017</option>
                    <option value="0018">0018</option>
                    <option value="0019">0019</option>
                    <option value="0020">0020</option>
                    <option value="0021">0021</option>
                    <option value="0022">0022</option>
                    <option value="0023">0023</option>
                    <option value="0024">0024</option>
                    <option value="0025">0025</option>
                    <option value="0026">0026</option>
                    <option value="0027">0027</option>
                    <option value="0028">0028</option>
                    <option value="0029">0029</option>
                    <option value="0030">0030</option>
                    <option value="0031">0031</option>
                    <option value="0032">0032</option>
                    <option value="0033">0033</option>
                    <option value="0034">0034</option>
                    <option value="0035">0035</option>
                    <option value="0036">0036</option>
                    <option value="0037">0037</option>
                    <option value="0038">0038</option>
                    <option value="0039">0039</option>
                    <option value="0040">0040</option>
                </select>
            </td>
        </tr>
    </table>
    <input type="button" id="Button0" value="MoveLayout!"/>
</body>
</html>

JAVASCRIPT CODE

var customSelectFields = new Array();


// Note: The list of selects to be modified! By Questor
customSelectFields[0] = "Select0";
customSelectFields[1] = "Select1";
customSelectFields[2] = "Select2";
customSelectFields[3] = "Select3";
customSelectFields[4] = "Select4";

$(document).ready(function()
{


    //Note: To debug! By Questor
    $("#Button0").click(function(event){ AddTestDiv(); });

    StartUpCustomSelect(null);  

});


//Note: To test! By Questor
function AddTestDiv()
{
    $("#testDiv").append("<div style=\"width:100px;height:100px;\"></div>");
}


//Note: Startup selects customization scheme! By Questor
function StartUpCustomSelect(what)
{

    for (i = 0; i < customSelectFields.length; i++)
    {

        $("#" + customSelectFields[i] + "").click(function(event){ UpCustomSelect(this); });
        $("#" + customSelectFields[i] + "").wrap("<div id=\"selectDiv_" + customSelectFields[i] + "\" onmouseover=\"BlockCustomSelectAgain();\" status=\"CLOSED\"></div>").parent().after("<div id=\"coverSelectDiv_" + customSelectFields[i] + "\" onclick=\"UpOrDownCustomSelect(this);\" onmouseover=\"BlockCustomSelectAgain();\"></div>");


        //Note: Avoid breaking the layout when the CSS is modified from "position" to "absolute" on the select! By Questor
        $("#" + customSelectFields[i] + "").parent().css({'width': $("#" + customSelectFields[i] + "")[0].offsetWidth + 'px', 'height': $("#" + customSelectFields[i] + "")[0].offsetHeight + 'px'});

        BlockCustomSelect($("#" + customSelectFields[i] + ""));

    }
}


//Note: Repositions the div that covers the select using the "onmouseover" event so 
//Note: if element on the screen move the div always stand over it (recalculate! By Questor
function BlockCustomSelectAgain(what)
{
    for (i = 0; i < customSelectFields.length; i++)
    {
        if($("#" + customSelectFields[i] + "").parent().attr("status") == "CLOSED")
        {
            BlockCustomSelect($("#" + customSelectFields[i] + ""));
        }
    }
}


//Note: Does not allow the select to be clicked or clickable! By Questor
function BlockCustomSelect(what)
{

    var coverSelectDiv = $(what).parent().next();


    //Note: Ensures the integrity of the div style! By Questor
    $(coverSelectDiv).removeAttr('style');


    //Note: To resolve compatibility issues! By Questor
    var backgroundValue = "";
    var filerValue = "";
    if(navigator.appName == "Microsoft Internet Explorer")
    {
        backgroundValue = 'url(fakeimage)';
        filerValue = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=\'scale\', src=\'fakeimage\' )';
    }


    //Note: To debug! By Questor
    //'border': '5px #000 solid',

    $(coverSelectDiv).css({
        'position': 'absolute', 
        'top': $(what).offset().top + 'px', 
        'left': $(what).offset().left + 'px', 
        'width': $(what)[0].offsetWidth + 'px', 
        'height': $(what)[0].offsetHeight + 'px', 
        'background': backgroundValue,
        '-moz-background-size':'cover',
        '-webkit-background-size':'cover',
        'background-size':'cover',
        'filer': filerValue
    });

}


//Note: Allow the select to be clicked or clickable! By Questor
function ReleaseCustomSelect(what)
{

    var coverSelectDiv = $(what).parent().next();

    $(coverSelectDiv).removeAttr('style');
    $(coverSelectDiv).css({'display': 'none'});

}


//Note: Open the select! By Questor
function DownCustomSelect(what)
{


    //Note: Avoid breaking the layout. Avoid that select events be overwritten by the others! By Questor
    $(what).css({
        'position': 'absolute', 
        'z-index': '100'
    });


    //Note: Open dropdown! By Questor
    $(what).attr("size","10");

    ReleaseCustomSelect(what);


    //Note: Avoids the side-effect of the select loses focus.! By Questor
    $(what).focus();


    //Note: Allows you to select elements using the enter key when the select is on focus! By Questor
    $(what).keyup(function(e){
        if(e.keyCode == 13)
        {
            UpCustomSelect(what);
        }
    });


    //Note: Closes the select when loses focus! By Questor
    $(what).blur(function(e){
        UpCustomSelect(what);
    });

    $(what).parent().attr("status", "OPENED");

}


//Note: Close the select! By Questor
function UpCustomSelect(what)
{

    $(what).css("position","static");


    //Note: Close dropdown! By Questor
    $(what).attr("size","1");

    BlockCustomSelect(what);

    $(what).parent().attr("status", "CLOSED");

}


//Note: Closes or opens the select depending on the current status! By Questor
function UpOrDownCustomSelect(what)
{

    var customizedSelect = $($(what).prev().children()[0]);

    if($(what).prev().attr("status") == "CLOSED")
    {
        DownCustomSelect(customizedSelect);
    }
    else if($(what).prev().attr("status") == "OPENED")
    {
        UpCustomSelect(customizedSelect);
    }

}

How can I get LINQ to return the object which has the max value for a given property?

int max = items.Max(i => i.ID);
var item = items.First(x => x.ID == max);

This assumes there are elements in the items collection of course.

The object 'DF__*' is dependent on column '*' - Changing int to double

MS SQL Studio take care of when you delete the column but if you need to Delete Constraint Programmatically here is simple solution

Here’s a code snippet that’ll drop a column with a default constraint:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = N'__ColumnName__' AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('__TableName__') AND name='__ColumnName__')
EXEC('ALTER TABLE __TableName__ DROP COLUMN __ColumnName__')

Just replace TableName and ColumnName with the appropriate values. You can safely run this even if the column has already been dropped.

Bonus: Here’s the code to drop foreign keys and other types of constraints.

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__')
BEGIN
SELECT @ConstraintName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__'
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
END

Blog

How to set the component size with GridLayout? Is there a better way?

Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.

For example, using GridBagLayout:

import java.awt.*;
import javax.swing.*;

public class LayoutEg1 extends JPanel{
    private static final int ROWS = 10;

    public LayoutEg1() {
        setLayout(new GridBagLayout());
        for (int i = 0; i < ROWS; i++) {
            GridBagConstraints gbc = makeGbc(0, i);
            JLabel label = new JLabel("Row Label " + (i + 1));
            add(label, gbc);

            JPanel panel = new JPanel();
            panel.add(new JCheckBox("check box"));
            panel.add(new JTextField(10));
            panel.add(new JButton("Button"));
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc = makeGbc(1, i);
            add(panel, gbc);
        }
    }

    private GridBagConstraints makeGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = x;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Layout Eg1");
        frame.getContentPane().add(new LayoutEg1());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

C# with MySQL INSERT parameters

Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:

comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;

or:

comm.Parameters.AddWithValue("@person", Myname);

That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.

Hope this helps.

Generate an integer sequence in MySQL

If you were using Oracle, 'pipelined functions' would be the way to go. Unfortunately, MySQL has no such construct.

Depending on the scale of the numbers you want sets of, I see two simple ways to go : you either populate a temporary table with just the numbers you need (possibly using memory tables populated by a stored procedure) for a single query or, up front, you build a big table that counts from 1 to 1,000,000 and select bounded regions of it.

check if a string matches an IP address pattern in python?

Other regex answers in this page will accept an IP with a number over 255.

This regex will avoid this problem:

import re

def validate_ip(ip_str):
    reg = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
    if re.match(reg, ip_str):
        return True
    else:
        return False

Start an Activity with a parameter

I like to do it with a static method in the second activity:

private static final String EXTRA_GAME_ID = "your.package.gameId";

public static void start(Context context, String gameId) {
    Intent intent = new Intent(context, SecondActivity.class);
    intent.putExtra(EXTRA_GAME_ID, gameId);
    context.startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    ... 
    Intent intent = this.getIntent();
    String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}

Then from your first activity (and for anywhere else), you just do:

SecondActivity.start(this, "the.game.id");

Iterating through a range of dates in Python

Use the dateutil library:

from datetime import date
from dateutil.rrule import rrule, DAILY

a = date(2009, 5, 30)
b = date(2009, 6, 9)

for dt in rrule(DAILY, dtstart=a, until=b):
    print dt.strftime("%Y-%m-%d")

This python library has many more advanced features, some very useful, like relative deltas—and is implemented as a single file (module) that's easily included into a project.

How to enable ASP classic in IIS7.5

  • Go to control panel
  • click program features
  • turn windows on and off
  • go to internet services
  • under world wide web services check the asp.net and others

Click ok and your web sites will load properly.

How do I list all the columns in a table?

For MySQL, use:

DESCRIBE name_of_table;

This also works for Oracle as long as you are using SQL*Plus, or Oracle's SQL Developer.

How do I get the classes of all columns in a data frame?

You can use purrr as well, which is similar to apply family functions:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)

PHP mPDF save file as PDF

The Go trough this link state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

 $upload_dir = public_path(); 
             $filename = $upload_dir.'/testing7.pdf'; 
              $mpdf = new \Mpdf\Mpdf();
              //$test = $mpdf->Image($pro_image, 0, 0, 50, 50);

              $html ='<h1> Project Heading </h1>';
              $mail = ' <p> Project Heading </p> ';
              
              $mpdf->autoScriptToLang = true;
              $mpdf->autoLangToFont = true;
              $mpdf->WriteHTML($mail);

              $mpdf->Output($filename,'F'); 
              $mpdf->debug = true;

Example :

 $mpdf->Output($filename,'F');

Example #2

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');

// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

Problems after upgrading to Xcode 10: Build input file cannot be found

I had this happen for building my unit tests. This may have happened because I deleted the example tests.

I removed the Unit test bundle then re-added it as shown in the pictures below and all was well again.

enter image description here

enter image description here

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

How can I see what has changed in a file before committing to git?

You're looking for

git diff --staged

Depending on your exact situation, there are three useful ways to use git diff:

  1. Show differences between index and working tree; that is, changes you haven't staged to commit:
git diff [filename]
  1. Show differences between current commit and index; that is, what you're about to commit (--staged does exactly the same thing, use what you like):
git diff --cached [filename]
  1. Show differences between current commit and working tree:
git diff HEAD [filename]

git diff works recursively on directories, and if no paths are given, it shows all changes.

How to use Jackson to deserialise an array of objects

First create an instance of ObjectReader which is thread-safe.

ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});

Then use it :

List<MyClass> result = objectReader.readValue(inputStream);

Console output in a Qt GUI app?

First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...

Second, qDebug is fancy :)

Third, you can try adding console to your .pro's CONFIG, it might work.

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

This ORA-01461 does not occur only while inserting into a Long column. This error can occur when binding a long string for insert into a VARCHAR2 column and most commonly occurs when there is a multi byte(means single char can take more than one byte space in oracle) character conversion issue.

If the database is UTF-8 then, because of the fact that each character can take up to 3 bytes, conversion of 3 applied to check and so actually limited to use 1333 characters to insert into varchar2(4000).

Another solution would be change the datatype from varchar2(4000) to CLOB.

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

How do I disable right click on my web page?

Yes, you can disable it using html.
Just add oncontextmenu="return false;" on your body or element.
It is very simple and just uses valid HTML, no jQuery or JS.

How to draw vectors (physical 2D/3D vectors) in MATLAB?

            % draw simple vector from pt a to pt b
            % wtr : with respect to
            scale=0;%for drawin  vectors with true scale
            a = [10 20 30];% wrt origine O(0,0,0)
            b = [10 10 20];% wrt origine O(0,0,0)

            starts=a;% a now is the origine of my vector to draw (from a to b) so we made a translation from point O to point  a = to vector a 
            c = b-a;% c is the new coordinates of b wrt origine a 
            ends=c;%
            plot3(a(1),a(2),a(3),'*b')
            hold on
            plot3(b(1),b(2),b(3),'*g')

             quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3),scale);% Use scale = 0 to plot the vectors without the automatic scaling.
            % axis equal
            hold off

Iterating over a numpy array

see nditer

import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
    y += 3

Y == np.array([6, 7, 8, 9])

y = 3 would not work, use y *= 0 and y += 3 instead.

How can I process each letter of text using Javascript?

It is better to use the for...of statement, if the string contains unicode characters, because of the different byte size.

for(var c of "tree ?") { console.log(c); }
//"A".length === 3

How to add days to the current date?

Add Days in Date in SQL

 DECLARE @NEWDOB DATE=null
 
 SET @NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)

Redirecting exec output to a buffer or file

For sending the output to another file (I'm leaving out error checking to focus on the important details):

if (fork() == 0)
{
    // child
    int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    dup2(fd, 1);   // make stdout go to file
    dup2(fd, 2);   // make stderr go to file - you may choose to not do this
                   // or perhaps send stderr to another file

    close(fd);     // fd no longer needed - the dup'ed handles are sufficient

    exec(...);
}

For sending the output to a pipe so you can then read the output into a buffer:

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

What does the "On Error Resume Next" statement do?

It means, when an error happens on the line, it is telling vbscript to continue execution without aborting the script. Sometimes, the On Error follows the Goto label to alter the flow of execution, something like this in a Sub code block, now you know why and how the usage of GOTO can result in spaghetti code:

Sub MySubRoutine()
   On Error Goto ErrorHandler

   REM VB code...

   REM More VB Code...

Exit_MySubRoutine:

   REM Disable the Error Handler!

   On Error Goto 0

   REM Leave....
   Exit Sub

ErrorHandler:

   REM Do something about the Error

   Goto Exit_MySubRoutine
End Sub

jQuery not working with IE 11

For me the issue turned out to be I was using es6's right arrow functions => as opposed to function ().

Replacing => with function () resolved for me.

I had assumed it was a jQuery issue.

How do I use modulus for float/double?

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

From JLS §15.17.3:

The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

Proxy with express.js

I don't have have an express sample, but one with plain http-proxy package. A very strip down version of the proxy I used for my blog.

In short, all nodejs http proxy packages work at the http protocol level, not tcp(socket) level. This is also true for express and all express middleware. None of them can do transparent proxy, nor NAT, which means keeping incoming traffic source IP in the packet sent to backend web server.

However, web server can pickup original IP from http x-forwarded headers and add it into the log.

The xfwd: true in proxyOption enable x-forward header feature for http-proxy.

const url = require('url');
const proxy = require('http-proxy');

proxyConfig = {
    httpPort: 8888,
    proxyOptions: {
        target: {
            host: 'example.com',
            port: 80
        },
        xfwd: true // <--- This is what you are looking for.
    }
};

function startProxy() {

    proxy
        .createServer(proxyConfig.proxyOptions)
        .listen(proxyConfig.httpPort, '0.0.0.0');

}

startProxy();

Reference for X-Forwarded Header: https://en.wikipedia.org/wiki/X-Forwarded-For

Full version of my proxy: https://github.com/J-Siu/ghost-https-nodejs-proxy

How to vertically align a html radio button to it's label?

I know I'd selected the anwer by menuka devinda but looking at the comments below it I concurred and tried to come up with a better solution. I managed to come up with this and in my opinion it's a much more elegant solution:

input[type='radio'], label{   
    vertical-align: baseline;
    padding: 10px;
    margin: 10px;
 }

Thanks to everyone who offered an answer, your answer didn't go unnoticed. If you still got any other ideas feel free to add your own answer to this question.

How to make google spreadsheet refresh itself every 1 minute?

If you are only looking for a refresh rate for the GOOGLEFINANCE function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).

Single-symbol refresh rate (using GoogleClock)

Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.

=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))

For example, with:

  • SYMBOL: GOOG
  • DATA DELAY: 15 (minutes)

then

=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))

Results in a dynamic data-based refresh rate of:

=GoogleClock(15)

Multi-symbol refresh rate (using GoogleClock)

If your sheet contains a number of rows of symbols, you could add a datadelay column for each symbol and use the lowest value, for example:

=GoogleClock(MIN(dataDelayValuesNamedRange))

Where dataDelayValuesNamedRange is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).

Without GoogleClock()

The GoogleClock() function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).

(This part of the answer is based on, and portions copied from, Google Docs Help)

To change how often "some" Google Sheets functions update:

  1. Open a spreadsheet. Click File > Spreadsheet settings.
  2. In the RECALCULATION section, choose a setting from the drop-down menu.
  3. Setting options are:
    • On change
    • On change and every minute
    • On change and every hour
  4. Click SAVE SETTINGS.

NOTE External data functions recalculate at the following intervals:

  • ImportRange: 30 minutes
  • ImportHtml, ImportFeed, ImportData, ImportXml: 1 hour
  • GoogleFinance: 2 minutes

The references in earlier sections to the display and use of the datadelay attribute still apply, as well as the concepts for more efficient coding of sheets.

On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.

[*] in my understanding so far (I am currently testing this)

How to Convert datetime value to yyyymmddhhmmss in SQL server?

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

An example of how to use getopts in bash

POSIX 7 example

It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

And then we can try it out:

$ sh a.sh
Remaining arguments are: 
$ sh a.sh -a
Option -a specified
Remaining arguments are: 
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain

Tested in Ubuntu 17.10, sh is dash 0.5.8.

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

Return content with IHttpActionResult for non-OK response

I had the same problem. I want to create custom result for my api controllers, to call them like return Ok("some text");

Then i did this: 1) Create custom result type with singletone

public sealed class EmptyResult : IHttpActionResult
{
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent) { Content = new StringContent("Empty result") });
    }
}

2) Create custom controller with new method:

public class CustomApiController : ApiController
{
    public IHttpActionResult EmptyResult()
    {
        return new EmptyResult();
    }
}

And then i can call them in my controllers, like this:

public IHttpActionResult SomeMethod()
    {
       return EmptyResult();
    }

How to change the color of progressbar in C# .NET 3.5?

In the designer, you just need to set the ForeColor property to whatever color you'd like. In the case of Red, there's a predefined color for it.

To do it in code (C#) do this:

pgs.ForeColor = Color.Red;

Edit: Oh yeah, also set the Style to continuous. In code, like this:

pgs.Style = System.Windows.Forms.ProgressBarStyle.Continuous;

Another Edit: You'll also need to remove the line that reads Application.EnableVisualStyles() from your Program.cs (or similar). If you can't do this because you want the rest of the application to have visual styles, then I'd suggest painting the control yourself or moving on to WPF since this kind of thing is easy with WPF. You can find a tutorial on owner drawing a progress bar on codeplex

How to check if a String contains only ASCII?

It was possible. Pretty problem.

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class EncodingTest {

    static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII")
            .newEncoder();

    public static void main(String[] args) {

        String testStr = "¤EÀsÆW°ê»Ú®i¶T¤¤¤ß3¼Ó®i¶TÆU2~~KITEC 3/F Rotunda 2";
        String[] strArr = testStr.split("~~", 2);
        int count = 0;
        boolean encodeFlag = false;

        do {
            encodeFlag = asciiEncoderTest(strArr[count]);
            System.out.println(encodeFlag);
            count++;
        } while (count < strArr.length);
    }

    public static boolean asciiEncoderTest(String test) {
        boolean encodeFlag = false;
        try {
            encodeFlag = asciiEncoder.canEncode(new String(test
                    .getBytes("ISO8859_1"), "BIG5"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeFlag;
    }
}

I get exception when using Thread.sleep(x) or wait()

Have a look at this excellent brief post on how to do this properly.

Essentially: catch the InterruptedException. Remember that you must add this catch-block. The post explains this a bit further.

Position Relative vs Absolute?

Absolute will make your element out of your flow layout, and it will be positioned to the closest relative parent (all parents are static by default). That's how you use absolute and relative together most of the time.

You can also use relative alone, but that is very rare case.

I have made an video to explain this.

https://www.youtube.com/watch?v=nGN5CohGVTI

android TextView: setting the background color dynamically doesn't work

you can use android:textColor= " whatever text color u want to give" in xml file where your text view is declared.

How to open link in new tab on html?

Use target="_blank":

<a href="http://www.example.com/" target="_blank" rel="noopener noreferrer">This will open in a new window!</a>

PHP substring extraction. Get the string before the first '/' or the whole string

You can also use this one line solution

list($substring) = explode("/", $string);

What's a good, free serial port monitor for reverse-engineering?

I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.