Programs & Examples On #Zebra printers

Zebra printers are generally thermal bar code label and receipt printers which can understand ZPL, EPL, CPCL, or KPL languages

Send raw ZPL to Zebra printer via USB

Found amazing simple solution - working for Chrome (Windows, not tested on Mac)

Zebra ZP 450

  1. Go here Zebra Generic Text
  2. Go precisely by the manual
  3. No COM1 or any other ports needed - USB is enough
  4. When done (named the printer ZTEXT), does not matter if it won't print a test page
  5. Turn of Spooling and enable direct printing in Printer Preferences - 1 note here 1 printer is ZP450 CPT and other ZP450 only - on the other one I do not even need to turn off spooling and it worked.
  6. Go to Chrome and printing ZPL from there with Chrome Print Dialog Box by selecting the ZTEXT printer (Generic / Text) Printer (Do not choose Windows Dialog Box) - we needed this for Chrome to be working

.NET code to send ZPL to Zebra printers

This way you will be able to send ZPL to a printer no matter how it is connected (LPT, USB, Network Share...)

Create the RawPrinterHelper class (from the Microsoft article on How to send raw data to a printer by using Visual C# .NET):

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class RawPrinterHelper
{
    // Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)] public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)] public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level,  [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32    dwError = 0, dwWritten = 0;
        IntPtr    hPrinter = new IntPtr(0);
        DOCINFOA    di = new DOCINFOA();
        bool    bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
        {
            // Start a document.
            if( StartDocPrinter(hPrinter, 1, di) )
            {
                // Start a page.
                if( StartPagePrinter(hPrinter) )
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if( bSuccess == false )
        {
                dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }

    public static bool SendFileToPrinter( string szPrinterName, string szFileName )
    {
        // Open the file.
        FileStream fs = new FileStream(szFileName, FileMode.Open);
        // Create a BinaryReader on the file.
        BinaryReader br = new BinaryReader(fs);
        // Dim an array of bytes big enough to hold the file's contents.
        Byte []bytes = new Byte[fs.Length];
        bool bSuccess = false;
        // Your unmanaged pointer.
        IntPtr pUnmanagedBytes = new IntPtr(0);
        int nLength;

        nLength = Convert.ToInt32(fs.Length);
        // Read the contents of the file into the array.
        bytes = br.ReadBytes( nLength );
        // Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
        // Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
        // Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
        // Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes);
        return bSuccess;
    }
    public static bool SendStringToPrinter( string szPrinterName, string szString )
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString);
        // Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount);
        Marshal.FreeCoTaskMem(pBytes);
        return true;
    }
}

Call the print method:

private void BtnPrint_Click(object sender, System.EventArgs e)
{
    string s = "^XA^LH30,30\n^FO20,10^ADN,90,50^AD^FDHello World^FS\n^XZ";

    PrintDialog pd  = new PrintDialog();
    pd.PrinterSettings = new PrinterSettings();
    if(DialogResult.OK == pd.ShowDialog(this))
    {
        RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
    }
}

There are 2 gotchas I've come across that happen when you're sending txt files with ZPL codes to the printer:

  1. The file has to end with a new line character
  2. Encoding has to be set to Encoding.Default when reading ANSI txt files with special characters

    public static bool SendTextFileToPrinter(string szFileName, string printerName)
    {
        var sb = new StringBuilder();
    
        using (var sr = new StreamReader(szFileName, Encoding.Default))
        {
            while (!sr.EndOfStream)
            {
                sb.AppendLine(sr.ReadLine());
            }
        }
    
        return RawPrinterHelper.SendStringToPrinter(printerName, sb.ToString());
    }
    

How to access full source of old commit in BitBucket?

I understand you want to download an older version via the BitBucket web interface without using a Mercurial/Git client.

Check this related question. On the comments, someone says that there is no way to do that. Fortunately, that's not entirely true.

By navigating on BitBucket project pages, I found no link to download an arbitrary version. There are links to download specific tags, in the format:

https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz

But by tweaking a bit the url above, changing the tag name by the commit hash, like:

https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz

You can actually download a specific version.

As mentioned by Rakka Rage in a comment, replacing .tar.gz by .zip works too.

Sleeping in a batch file

This was tested on Windows XP SP3 and Windows 7 and uses CScript. I put in some safe guards to avoid del "" prompting. (/q would be dangerous)

Wait one second:

sleepOrDelayExecution 1000

Wait 500 ms and then run stuff after:

sleepOrDelayExecution 500 dir \ /s

sleepOrDelayExecution.bat:

@echo off
if "%1" == "" goto end
if NOT %1 GTR 0 goto end
setlocal
set sleepfn="%temp%\sleep%random%.vbs"
echo WScript.Sleep(%1) >%sleepfn%
if NOT %sleepfn% == "" if NOT EXIST %sleepfn% goto end
cscript %sleepfn% >nul
if NOT %sleepfn% == "" if EXIST %sleepfn% del %sleepfn%
for /f "usebackq tokens=1*" %%i in (`echo %*`) DO @ set params=%%j
%params%
:end

Circle drawing with SVG's arc path

I know it's a bit late in the game, but I remembered this question from when it was new and I had a similar dillemma, and I accidently found the "right" solution, if anyone is still looking for one:

<path 
    d="
    M cx cy
    m -r, 0
    a r,r 0 1,0 (r * 2),0
    a r,r 0 1,0 -(r * 2),0
    "
/>

In other words, this:

<circle cx="100" cy="100" r="75" />

can be achieved as a path with this:

  <path 
        d="
        M 100, 100
        m -75, 0
        a 75,75 0 1,0 150,0
        a 75,75 0 1,0 -150,0
        "
  />

The trick is to have two arcs, the second one picking up where the first left off and using the negative diameter to get back to the original arc start point.

The reason it can't be done as a full circle in one arc (and I'm just speculating) is because you would be telling it to draw an arc from itself (let's say 150,150) to itself (150,150), which it renders as "oh, I'm already there, no arc necessary!".

The benefits of the solution I'm offering are:

  1. it's easy to translate from a circle directly to a path, and
  2. there is no overlap in the two arc lines (which may cause issues if you are using markers or patterns, etc). It's a clean continuous line, albeit drawn in two pieces.

None of this would matter if they would just allow textpaths to accept shapes. But I think they are avoiding that solution since shape elements like circle don't technically have a "start" point.

jsfiddle demo: http://jsfiddle.net/crazytonyi/mNt2g/

Update:

If you are using the path for a textPath reference and you are wanting the text to render on the outer edge of the arc, you would use the exact same method but change the sweep-flag from 0 to 1 so that it treats the outside of the path as the surface instead of the inside (think of 1,0 as someone sitting at the center and drawing a circle around themselves, while 1,1 as someone walking around the center at radius distance and dragging their chalk beside them, if that's any help). Here is the code as above but with the change:

<path 
    d="
    M cx cy
    m -r, 0
    a r,r 0 1,1 (r * 2),0
    a r,r 0 1,1 -(r * 2),0
    "
/>

How can I "disable" zoom on a mobile web page?

please try adding this meta-tag and style

<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>


<style>
body{
        touch-action: manipulation;
    }
</style>

Why doesn't file_get_contents work?

If it is a local file, you have to wrap it in htmlspecialchars like so:

    $myfile = htmlspecialchars(file_get_contents($file_name));

Then it works

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

php how to go one level up on dirname(__FILE__)

If you happen to have php 7.0+ you could use levels.

dirname( __FILE__, 2 ) with the second parameter you can define the amount of levels you want to go back.

http://php.net/manual/en/function.dirname.php

Display exact matches only with grep

try this:

grep -P '^(tomcat!?)' tst1.txt

It will search for specific word in txt file. Here we are trying to search word tomcat

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

Unable to allocate array with shape and data type

I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the pagefile size, as it was a Memory overcommitment problem for me too.

Windows 8

  1. On the Keyboard Press the WindowsKey + X then click System in the popup menu
  2. Tap or click Advanced system settings. You might be asked for an admin password or to confirm your choice
  3. On the Advanced tab, under Performance, tap or click Settings.
  4. Tap or click the Advanced tab, and then, under Virtual memory, tap or click Change
  5. Clear the Automatically manage paging file size for all drives check box.
  6. Under Drive [Volume Label], tap or click the drive that contains the paging file you want to change
  7. Tap or click Custom size, enter a new size in megabytes in the initial size (MB) or Maximum size (MB) box, tap or click Set, and then tap or click OK
  8. Reboot your system

Windows 10

  1. Press the Windows key
  2. Type SystemPropertiesAdvanced
  3. Click Run as administrator
  4. Under Performance, click Settings
  5. Select the Advanced tab
  6. Select Change...
  7. Uncheck Automatically managing paging file size for all drives
  8. Then select Custom size and fill in the appropriate size
  9. Press Set then press OK then exit from the Virtual Memory, Performance Options, and System Properties Dialog
  10. Reboot your system

Note: I did not have the enough memory on my system for the ~282GB in this example but for my particular case this worked.

EDIT

From here the suggested recommendations for page file size:

There is a formula for calculating the correct pagefile size. Initial size is one and a half (1.5) x the amount of total system memory. Maximum size is three (3) x the initial size. So let's say you have 4 GB (1 GB = 1,024 MB x 4 = 4,096 MB) of memory. The initial size would be 1.5 x 4,096 = 6,144 MB and the maximum size would be 3 x 6,144 = 18,432 MB.

Some things to keep in mind from here:

However, this does not take into consideration other important factors and system settings that may be unique to your computer. Again, let Windows choose what to use instead of relying on some arbitrary formula that worked on a different computer.

Also:

Increasing page file size may help prevent instabilities and crashing in Windows. However, a hard drive read/write times are much slower than what they would be if the data were in your computer memory. Having a larger page file is going to add extra work for your hard drive, causing everything else to run slower. Page file size should only be increased when encountering out-of-memory errors, and only as a temporary fix. A better solution is to adding more memory to the computer.

HTML input fields does not get focus when clicked

In my case it was Bootstrap popup in opened state. Text input was in another calendar popup on top of Bootstrap one, input got its focus back after removing tabindex="-1" attribute from Bootstrap modal.

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

Cannot find pkg-config error

Try

Calling another different view from the controller using ASP.NET MVC 4

Also, you can just set the ViewName:

return View("ViewName");

Full controller example:

public ActionResult SomeAction() {
    if (condition)
    {
        return View("CustomView");
    }else{
        return View();
    }
}

This works on MVC 5.

Most concise way to convert a Set<T> to a List<T>

Considering that we have Set<String> stringSet we can use following:

Plain Java

List<String> strList = new ArrayList<>(stringSet);

Guava

List<String> strList = Lists.newArrayList(stringSet);

Apache Commons

List<String> strList = new ArrayList<>();
CollectionUtils.addAll(strList, stringSet);

Java 10 (Unmodifiable List)

List<String> strList = List.copyOf(stringSet);
List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());

Java 8 (Modifiable Lists)

import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());

As per the doc for the method toList()

There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

So if we need a specific implementation e.g. ArrayList we can get it this way:

List<String> stringList2 = stringSet.stream().
                              collect(toCollection(ArrayList::new));

Java 8 (Unmodifiable Lists)

We can make use of Collections::unmodifiableList method and wrap the list returned in previous examples. We can also write our own custom method as:

class ImmutableCollector {
    public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
            return Collector.of( supplier, List::add, (left, right) -> {
                        left.addAll(right);
                        return left;
                    }, Collections::unmodifiableList);
        }
}

And then use it as:

List<String> stringList3 = stringSet.stream()
             .collect(ImmutableCollector.toImmutableList(ArrayList::new)); 

Another possibility is to make use of collectingAndThen method which allows some final transformation to be done before returning result:

    List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
      toCollection(ArrayList::new),Collections::unmodifiableList));

One point to note is that the method Collections::unmodifiableList returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList returns truly immutable list in Java 10.

RESTful Authentication via Spring

We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:

Set up the security context like so:

<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

CustomAuthenticationEntryPoint:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:

public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start. Happy coding. :)

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

Trying to get property of non-object - Laravel 5

Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).

C++ Vector of pointers

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new, fill the object in with the data, and then push the address of the data onto the vector (probably not the best design, but most likely what's intended anyway).

Insert a line break in mailto body

<a href="mailto:[email protected]?subject=Request&body=Hi,%0DName:[your name] %0DGood day " target="_blank"></a>

Try adding %0D to break the line. This will definitely work.

Above code will display the following:

Hi,
Name:[your name] 
Good day

How do I find the index of a character within a string in C?

What about:

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

copying to e to preserve the original string, I suppose if you don't care you could just operate over *string

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!

An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.

See this example:

const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);

console.log(timeZoneRelatedDate.toLocaleDateString(
    'ja-JP', 
    {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }
).replace(/\//gi,'-'));

// RESULT: "2020-01-14"

console.log(timeZoneRelatedDate.toISOString());

// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)

console.log(timeZoneRelatedDate.toISOString().slice(0,10));

// RESULT: "2020-01-13"

Clear screen in shell

import curses
stdscr = curses.initscr()
stdscr.clear()

Display open transactions in MySQL

How can I display these open transactions and commit or cancel them?

There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).

You display threads using

SHOW FULL PROCESSLIST  

See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html

It will not help you, because you cannot commit a transaction from a broken connection.

What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html

4.5.1.6.3. Disabling mysql Auto-Reconnect

If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.

This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:

Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

How to diagnose and fix this
To check for auto-reconnection:

If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.

Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.

How to tell if browser/tab is active

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isTabActive;

window.onfocus = function () { 
  isTabActive = true; 
}; 

window.onblur = function () { 
  isTabActive = false; 
}; 

// test
setInterval(function () { 
  console.log(window.isTabActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Android Room - simple select query - Cannot access database on the main thread

You can allow database access on the main thread but only for debugging purpose, you shouldn't do this on production.

Here is the reason.

Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.

From Now() to Current_timestamp in Postgresql

Here is an example ...

select * from tablename where to_char(added_time, 'YYYY-MM-DD')  = to_char( now(), 'YYYY-MM-DD' )

added_time is a column name which I converted to char for match

What is meant by Ems? (Android TextView)

em is the typography unit of font width. one em in a 16-point typeface is 16 points

Make EditText ReadOnly

As android:editable="" is deprecated,

Setting

  • android:clickable="false"
  • android:focusable="false"
  • android:inputType="none"
  • android:cursorVisible="false"

will make it "read-only".

However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:

  • myEditText.setOnLongClickListener { true }

suffices.

Parser Error when deploy ASP.NET application

I've solve the issue. The solution is to not making virtual dir manualy and then copy app files here, but use 'Add Application...' option. Here is post that helped me http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/7ad2acb0-42ca-4ee8-9161-681689b60dda/

How to align an indented line in a span that wraps into multiple lines?

Also you can try to use

display:inline-block;

if you would like the span element to align horizontally.

Incase you would like to align span elements vertically, just use

 display:block;

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

Parsing JSON from XmlHttpRequest.responseJSON

You can simply set xhr.responseType = 'json';

_x000D_
_x000D_
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
  if (this.status == 200) {_x000D_
    console.log('response', this.response); // JSON response  _x000D_
  }_x000D_
};_x000D_
xhr.send();_x000D_
  
_x000D_
_x000D_
_x000D_

Documentation for responseType

Deleting Row in SQLite in Android

Try the below code-

mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
int rowDeleted = mSQLiteDatabase.delete(TABLE_NAME,id + " =?",
                    new String[] {String.valueOf(id)});
mSQLiteDatabase.close();//This is very important once database operation is done.
if(rowDeleted != 0){
    //delete success.
} else {
    //delete failed.
}

How do I fix twitter-bootstrap on IE?

If you are using responsive layout, try including this js on your code: https://github.com/scottjehl/Respond

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1

1) Make sure .Net core SDK installed on your machine. Download .NET!

2) set PATH environment variables as below Path

Android - Set text to TextView

As you have given static text

err.setText("Escriba su mensaje y luego seleccione el canal.");

It will not change , it will remain same.

Example for Dynamic Text for textview is :

MainActivity.java
package com.example.dynamictextview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    int count = 0;
    Button clickMeBtn;
    TextView dynamicText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        clickMeBtn = (Button) findViewById(R.id.button_click);
        dynamicText = (TextView) findViewById(R.id.textview);

        clickMeBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                count++;
                dynamicText.setText("dynamic text example : " + count);

            }
        });

    }

}

For activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dynamictextview.MainActivity" >

    <Button 
        android:id="@+id/button_click"
       android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click me"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:layout_below="@id/button_click"
        android:layout_centerHorizontal="true"
        android:textSize="25sp"
        android:layout_marginTop="20dp"
        />

</RelativeLayout>

how to convert string to numerical values in mongodb

Three things need to care for:

  1. parseInt() will store double data type in mongodb. Please use new NumberInt(string).
  2. in Mongo shell command for bulk usage, yield won't work. Please DO NOT add 'yield'.
  3. If you already change string to double by parseInt(). It looks like you have no way to change the type to int directly. The solution is a little bit wired: change double to string first and then change back to int by new NumberInt().

What does the servlet <load-on-startup> value signify

It indicates that the servlet won't be started until a request tries to access it.

If load-on-startup is greater than or equal to zero then when the container starts it will start that servlet in ascending order of the load on startup value you put there (ie 0, 1 then 2 then 5 then 10 and so on).

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

Rails Root directory path?

In addition to all the other correct answers, since Rails.root is a Pathname object, this won't work:

Rails.root + '/app/assets/...'

You could use something like join

Rails.root.join('app', 'assets')

If you want a string use this:

Rails.root.join('app', 'assets').to_s

Git: Cannot see new remote branch

You can checkout remote branch /n git fetch && git checkout remotebranch

How to extract a string using JavaScript Regex?

You need to use the m flag:

multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

Also put the * in the right place:

"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^    ^
//-----------------------------------------------------------------------|

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.

How do I dump the data of some SQLite3 tables?

This version works well with newlines inside inserts:

sqlite3 database.sqlite3 .dump | grep -v '^CREATE'

In practice excludes all the lines starting with CREATE which is less likely to contain newlines

Typescript: Type 'string | undefined' is not assignable to type 'string'

You can use the NonNullable Utility Type:

Example

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

Docs.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Get the time difference between two datetimes

If we want only hh:mm:ss, we can use a function like that:

//param: duration in milliseconds
MillisecondsToTime: function(duration) {
    var seconds = parseInt((duration/1000)%60)
        , minutes = parseInt((duration/(1000*60))%60)
        , hours = parseInt((duration/(1000*60*60))%24)
        , days  = parseInt(duration/(1000*60*60*24));

    var hoursDays = parseInt(days*24);
    hours += hoursDays;
    hours = (hours < 10) ? "0" + hours : hours;
    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;
    return hours + ":" + minutes + ":" + seconds;
}

How to generate access token using refresh token through google drive API?

Using ASP.Net Post call, this worked for me.

StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");                        
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
                    var values = new Dictionary<string, string>
                    {
                        { "client_id", <Your Client Id> },
                        { "client_secret", <Your Client Secret> },
                        { "refresh_token", <Your Saved Refresh Token> },
                        { "grant_type", "refresh_token"}
                    };

                    var content = new FormUrlEncodedContent(values);
                    var response = await client.PostAsync(getNewToken.ToString(), content);

Responding with a JSON object in Node.js (converting object/array to JSON string)

Using res.json with Express:

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

Alternatively:

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}

AngularJS: factory $http.get JSON file

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:

<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!--  Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>

This is your javascript file that contains the JSON data

// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
     "Title": "Star Wars",
     "Year": "1983",
     "Rated": "N/A",
     "Released": "01 May 1983",
     "Runtime": "N/A",
     "Genre": "Action, Adventure, Sci-Fi",
     "Director": "N/A",
     "Writer": "N/A",
     "Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
     "Plot": "N/A",
     "Language": "English",
     "Country": "USA",
     "Awards": "N/A",
     "Poster": "N/A",
     "Metascore": "N/A",
     "imdbRating": "7.9",
     "imdbVotes": "342",
     "imdbID": "tt0251413",
     "Type": "game",
     "Response": "True"
};

Finally, work with the JSON data anywhere in your code

// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;

Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.

// extract from karma.conf.js
files: [
     'json-data/JSONSearchResultHardcodedData.js',
     'json-data/JSONFindByIdResults.js'
     ...
]

Hope this helps.

++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733

UPDATE

An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.

// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
      return {
         "Title": "Bri Squared",
         "Year": "2011",
         "Rated": "N/A",
         "Released": "N/A",
         "Runtime": "N/A",
         "Genre": "Comedy",
         "Director": "Joy Gohring",
         "Writer": "Briana Lane",
         "Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
         "Plot": "N/A",
         "Language": "English",
         "Country": "USA",
         "Awards": "N/A",
         "Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
         "Metascore": "N/A",
         "imdbRating": "8.2",
         "imdbVotes": "5",
         "imdbID": "tt1937109",
         "Type": "movie",
         "Response": "True"
   }
}

Decimal separator comma (',') with numberDecimal inputType in EditText

Simple solution, make a custom control. (this is made in Xamarin android but should port easily to java)

public class EditTextDecimalNumber:EditText
{
    readonly string _numberFormatDecimalSeparator;

    public EditTextDecimalNumber(Context context, IAttributeSet attrs) : base(context, attrs)
    {
        InputType = InputTypes.NumberFlagDecimal;
        TextChanged += EditTextDecimalNumber_TextChanged;
        _numberFormatDecimalSeparator = System.Threading.Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator;

        KeyListener = DigitsKeyListener.GetInstance($"0123456789{_numberFormatDecimalSeparator}");
    }

    private void EditTextDecimalNumber_TextChanged(object sender, TextChangedEventArgs e)
    {
        int noOfOccurence = this.Text.Count(x => x.ToString() == _numberFormatDecimalSeparator);
        if (noOfOccurence >=2)
        {
            int lastIndexOf = this.Text.LastIndexOf(_numberFormatDecimalSeparator,StringComparison.CurrentCulture);
            if (lastIndexOf!=-1)
            {
                this.Text = this.Text.Substring(0, lastIndexOf);
                this.SetSelection(this.Text.Length);
            }

        }
    }
}

How to use class from other files in C# with visual studio?

According to your explanation you haven't included your Class2.cs in your project. You have just created the required Class file but haven't included that in the project.

The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.

Do the following to overcome this,

Simply Right click on your project then -> [Add] - > [Existing Item...] : Select Class2.cs and press OK

Problem should be solved now.

Furthermore, when adding new classes use this procedure,

Right click on project -> [Add] -> Select Required Item (ex - A class, Form etc.)

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

How can I install Visual Studio Code extensions offline?

If you are looking for a scripted solution:

  1. Get binary download URL: you can use an API, but be warned that there is no documentation for it. This API can return an URL to download .vsix files (see example below)
  2. Download the binary
  3. Carefully unzip the binary into ~/.vscode/extensions/: you need to modify unzipped directory name, remove one file and move/rename another one.

For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.

POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json

{
    "filters": [
        {
        "criteria": [
            {
                "filterType": 8,
                "value": "Microsoft.VisualStudio.Code",
            },
            {
                "filterType": 7,
                "value": "ms-python.python",
            }
        ],
        "pageNumber": 1,
        "pageSize": 10,
        "sortBy": 0,
        "sortOrder": 0,
        }
    ],
    "assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
    "flags": 514,
}

Explanations to the above example:

  • "filterType": 8 - FilterType.Target more FilterTypes
  • "filterType": 7 - FilterType.ExtensionName more FilterTypes
  • "flags": 514 - 0x2 | 0x200 - Flags.IncludeFiles | Flags.IncludeLatestVersionOnly - more Flags
    • to get flag decimal value you can run python -c "print(0x2|0x200)"
  • "assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"] - to get only link to .vsix file more AssetTypes

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

if ($_SERVER['REQUEST_METHOD'] == 'POST') is the correct way, you can send a post request without any post data.

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

this worked for me

// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.LoginPath = new PathString("/auth/login");
            options.AccessDeniedPath = new PathString("/auth/denied");
        });

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this:

Display display   = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width  = displaySize.x;
int height = displaySize.y;

How to copy a file to a remote server in Python using SCP or SSH?

fabric could be used to upload files vis ssh:

#!/usr/bin/env python
from fabric.api import execute, put
from fabric.network import disconnect_all

if __name__=="__main__":
    import sys
    # specify hostname to connect to and the remote/local paths
    srcdir, remote_dirname, hostname = sys.argv[1:]
    try:
        s = execute(put, srcdir, remote_dirname, host=hostname)
        print(repr(s))
    finally:
        disconnect_all()

APT command line interface-like yes/no input?

As a programming noob, I found a bunch of the above answers overly complex, especially if the goal is to have a simple function that you can pass various yes/no questions to, forcing the user to select yes or no. After scouring this page and several others, and borrowing all of the various good ideas, I ended up with the following:

def yes_no(question_to_be_answered):
    while True:
        choice = input(question_to_be_answered).lower()
        if choice[:1] == 'y': 
            return True
        elif choice[:1] == 'n':
            return False
        else:
            print("Please respond with 'Yes' or 'No'\n")

#See it in Practice below 

musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
    print('and getting caught in the rain')
elif musical_taste == False:
    print('You clearly have no taste in music')

Why do I need an IoC container as opposed to straightforward DI code?

In the .NET world AOP isn't too popular, so for DI a framework is your only real option, whether you write one yourself or use another framework.

If you used AOP you can inject when you compile your application, which is more common in Java.

There are many benefits to DI, such as reduced coupling so unit testing is easier, but how will you implement it? Do you want to use reflection to do it yourself?

HTML -- two tables side by side

You can place your tables in a div and add style to your table "float: left"

<div>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

or simply use css:

div>table {
  float: left
}

How can I set size of a button?

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible

JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));

for(int i=0 ; i<16 ; i++){
    JButton btn = new JButton(String.valueOf(i));
    btn.setPreferredSize(new Dimension(40, 40));
    panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.

Edit

I've modified the provided code and I believe it now conforms to what is desired:

JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
    for (int j=1; j<=4; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 100));
        firstPanel.add(btn);
    }
}

JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
    for (int j=1; j<=13; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        secondPanel.add(btn);
    }
}

mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);

frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);

Basically I now set the preferred size of the panels and a minimum size for the frame.

How to document Python code using Doxygen

Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.

For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.

Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

How can I merge two commits into one if I already started rebase?

Let me suggest you an easier approach,

Instead of divind into GIT's deep consepts and bothering with the editor's crab, you could do the following;

Lets suppose you created a branch named bug1 from master. Made 2 commits to bug1. You only modified 2 files with these changes.

Copy these two files into a text editor. Checkout master. Paste the files. Commit.

That simple.

How do I run Python code from Sublime Text 2?

You can use SublimeREPL (you need to have Package Control installed first).

What is the purpose of mvnw and mvnw.cmd files?

The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.

mvnw: it's an executable Unix shell script used in place of a fully installed Maven

mvnw.cmd: it's for Windows environment


Use Cases

The wrapper should work with different operating systems such as:

  • Linux
  • OSX
  • Windows
  • Solaris

After that, we can run our goals like this for the Unix system:

./mvnw clean install

And the following command for Batch:

./mvnw.cmd clean install

If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.


Maven Wrapper plugin

Maven Wrapper plugin to make auto installation in a simple Spring Boot project.

First, we need to go in the main folder of the project and run this command:

mvn -N io.takari:maven:wrapper

We can also specify the version of Maven:

mvn -N io.takari:maven:wrapper -Dmaven=3.5.2

The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.


Source 1 (further reading): https://www.baeldung.com/maven-wrapper

How do I programmatically force an onchange event on an input?

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly

Javascript: 'window' is not defined

Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

Check if a variable is of function type

An other simply way:

var fn = function () {}
if (fn.constructor === Function) {
  // true
} else {
  // false
}

How do I start a process from C#?

As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...

using System.Diagnostics;
...
Process.Start("process.exe");

The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.

using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.

This method allows far more control than I've mentioned.

git still shows files as modified after adding to .gitignore

Your .gitignore is working, but it still tracks the files because they were already in the index.

To stop this you have to do : git rm -r --cached .idea/

When you commit the .idea/ directory will be removed from your git repository and the following commits will ignore the .idea/ directory.

PS: You could use .idea/ instead of .idea/* to ignore a directory. You can find more info about the patterns on the .gitignore man page.


Helpful quote from the git-rm man page

--cached
    Use this option to unstage and remove paths only from the index. 
    Working tree files, whether modified or not, will be left alone.

Does delete on a pointer to a subclass call the base class destructor?

If you have a usual pointer (A*) then the destructor will not be called (and memory for A instance will not be freed either) unless you do delete explicitly in B's destructor. If you want automatic destruction look at smart pointers like auto_ptr.

get launchable activity name of package from adb

#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'

sample:

getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI

Where to change the value of lower_case_table_names=2 on windows xampp

If you have the file my-default.ini rename it to my.ini

Log4j: How to configure simplest possible file logging?

I have one generic log4j.xml file for you:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="default.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/mylogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="another.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/anotherlogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <logger name="com.yourcompany.SomeClass" additivity="false">
        <level value="debug" />
        <appender-ref ref="another.file" />
    </logger>

    <root>
        <priority value="info" />
        <appender-ref ref="default.console" />
        <appender-ref ref="default.file" />
    </root>
</log4j:configuration>

with one console, two file appender and one logger poiting to the second file appender instead of the first.

EDIT

In one of the older projects I have found a simple log4j.properties file:

# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.

# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with 
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless 
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

For the description of all the layout arguments look here: log4j PatternLayout arguments

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

Reading Excel files from C#

I just used ExcelLibrary to load an .xls spreadsheet into a DataSet. Worked great for me.

CodeIgniter: "Unable to load the requested class"

In Windows, capitalization in paths doesn't matter. In Linux it does.

When you autoload, use "Foo" not "foo".

I believe that will do the trick.

I think it works when you take it out of autoloading because codeigniter is smart enough to figure out the capitalization in the path and classes are case independent in php.

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

Change size of text in text input tag?

In your CSS stylesheet, try adding:

input[type="text"] {
    font-size:25px;
}

See this jsFiddle example

List<Map<String, String>> vs List<? extends Map<String, String>>

Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)

I have a method that's meant to accept a Set of A objects that I originally wrote with this signature:

void myMethod(Set<A> set)

But it want to actually call it with Sets of subclasses of A. But this is not allowed! (The reason for that is, myMethod could add objects to set that are of type A, but not of the subtype that set's objects are declared to be at the caller's site. So this could break the type system if it were possible.)

Now here come generics to the rescue, because it works as intended if I use this method signature instead:

<T extends A> void myMethod(Set<T> set)

or shorter, if you don't need to use the actual type in the method body:

void myMethod(Set<? extends A> set)

This way, set's type becomes a collection of objects of the actual subtype of A, so it becomes possible to use this with subclasses without endangering the type system.

Artisan migrate could not find driver

In your php.ini configuration file simply uncomment the extension:

;extension=pdo_mysql

(You can find your php.ini file in the php folder where your server is installed.)

make this to

extension=pdo_mysql

now you need to configure your .env file in find DB_DATABASE= write in that database name which you used than migrate like if i used my database and database name is "abc" than i need to write there DB_DATABASE=abc and save that .env file and run command again

php artisan migrate

so after run than you got some msg like as:

php artisan migrate
Migration table created successfully.

How to stop mysqld

For Windows, you can run this command directly if mysql/bin is in your path.

mysqladmin -u root -p shutdown

setTimeout / clearTimeout problems

You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

Efficient way to rotate a list in python

Just some notes on timing:

If you're starting with a list, l.append(l.pop(0)) is the fastest method you can use. This can be shown with time complexity alone:

  • deque.rotate is O(k) (k=number of elements)
  • list to deque conversion is O(n)
  • list.append and list.pop are both O(1)

So if you are starting with deque objects, you can deque.rotate() at the cost of O(k). But, if the starting point is a list, the time complexity of using deque.rotate() is O(n). l.append(l.pop(0) is faster at O(1).

Just for the sake of illustration, here are some sample timings on 1M iterations:

Methods which require type conversion:

  • deque.rotate with deque object: 0.12380790710449219 seconds (fastest)
  • deque.rotate with type conversion: 6.853878974914551 seconds
  • np.roll with nparray: 6.0491721630096436 seconds
  • np.roll with type conversion: 27.558452129364014 seconds

List methods mentioned here:

  • l.append(l.pop(0)): 0.32483696937561035 seconds (fastest)
  • "shiftInPlace": 4.819645881652832 seconds
  • ...

Timing code used is below.


collections.deque

Showing that creating deques from lists is O(n):

from collections import deque
import big_o

def create_deque_from_list(l):
     return deque(l)

best, others = big_o.big_o(create_deque_from_list, lambda n: big_o.datagen.integers(n, -100, 100))
print best

# --> Linear: time = -2.6E-05 + 1.8E-08*n

If you need to create deque objects:

1M iterations @ 6.853878974914551 seconds

setup_deque_rotate_with_create_deque = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
"""

test_deque_rotate_with_create_deque = """
dl = deque(l)
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_with_create_deque, setup_deque_rotate_with_create_deque)

If you already have deque objects:

1M iterations @ 0.12380790710449219 seconds

setup_deque_rotate_alone = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
dl = deque(l)
"""

test_deque_rotate_alone= """
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_alone, setup_deque_rotate_alone)

np.roll

If you need to create nparrays

1M iterations @ 27.558452129364014 seconds

setup_np_roll_with_create_npa = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
"""

test_np_roll_with_create_npa = """
np.roll(l,-1) # implicit conversion of l to np.nparray
"""

If you already have nparrays:

1M iterations @ 6.0491721630096436 seconds

setup_np_roll_alone = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
npa = np.array(l)
"""

test_roll_alone = """
np.roll(npa,-1)
"""
timeit.timeit(test_roll_alone, setup_np_roll_alone)

"Shift in place"

Requires no type conversion

1M iterations @ 4.819645881652832 seconds

setup_shift_in_place="""
import random
l = [random.random() for i in range(1000)]
def shiftInPlace(l, n):
    n = n % len(l)
    head = l[:n]
    l[:n] = []
    l.extend(head)
    return l
"""

test_shift_in_place="""
shiftInPlace(l,-1)
"""

timeit.timeit(test_shift_in_place, setup_shift_in_place)

l.append(l.pop(0))

Requires no type conversion

1M iterations @ 0.32483696937561035

setup_append_pop="""
import random
l = [random.random() for i in range(1000)]
"""

test_append_pop="""
l.append(l.pop(0))
"""
timeit.timeit(test_append_pop, setup_append_pop)

How to use View.OnTouchListener instead of onClick

for use sample touch listener just you need this code

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    ClipData data = ClipData.newPlainText("", "");
    View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
    view.startDrag(data, shadowBuilder, null, 0);

    return true;
}

How to convert a string to ASCII

Use Convert.ToInt32() for conversion. You can have a look at How to convert string to ASCII value in C# and ASCII values.

Finding elements not in a list

In the case where item and z are sorted iterators, we can reduce the complexity from O(n^2) to O(n+m) by doing this

def iexclude(sorted_iterator, exclude_sorted_iterator):
    next_val = next(exclude_sorted_iterator)
    for item in sorted_iterator:
        try:
            while next_val < item:
                next_val = next(exclude_sorted_iterator)
                continue
            if item == next_val:
                continue
        except StopIteration:
            pass
        yield item

If the two are iterators, we also have the opportunity to reduce the memory footprint not storing z (exclude_sorted_iterator) as a list.

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

How to get the path of running java program

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }

How can I output leading zeros in Ruby?

filenames = '000'.upto('100').map { |index| "file_#{index}" }

Outputs

[file_000, file_001, file_002, file_003, ..., file_098, file_099, file_100]

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

How can I use Python to get the system hostname?

You will probably load the os module anyway, so another suggestion would be:

import os
myhost = os.uname()[1]

curl_init() function not working

Just adding my answer for the case where there are multiple versions of PHP installed in your system, and you are sure that you have already installed the php-curl package, and yet Apache is still giving you the same error.

curl_init() undefined even if php-curl is enabled in Php 7.

sed one-liner to convert all uppercase to lowercase?

Here are many solutions :

To upercaser with perl, tr, sed and awk

perl -ne 'print uc'
perl -npe '$_=uc'
perl -npe 'tr/[a-z]/[A-Z]/'
perl -npe 'tr/a-z/A-Z/'
tr '[a-z]' '[A-Z]'
sed y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
sed 's/\([a-z]\)/\U\1/g'
sed 's/.*/\U&/'
awk '{print toupper($0)}'

To lowercase with perl, tr, sed and awk

perl -ne 'print lc'
perl -npe '$_=lc'
perl -npe 'tr/[A-Z]/[a-z]/'
perl -npe 'tr/A-Z/a-z/'
tr '[A-Z]' '[a-z]'
sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
sed 's/\([A-Z]\)/\L\1/g'
sed 's/.*/\L&/'
awk '{print tolower($0)}'

Complicated bash to lowercase :

while read v;do v=${v//A/a};v=${v//B/b};v=${v//C/c};v=${v//D/d};v=${v//E/e};v=${v//F/f};v=${v//G/g};v=${v//H/h};v=${v//I/i};v=${v//J/j};v=${v//K/k};v=${v//L/l};v=${v//M/m};v=${v//N/n};v=${v//O/o};v=${v//P/p};v=${v//Q/q};v=${v//R/r};v=${v//S/s};v=${v//T/t};v=${v//U/u};v=${v//V/v};v=${v//W/w};v=${v//X/x};v=${v//Y/y};v=${v//Z/z};echo "$v";done

Complicated bash to uppercase :

while read v;do v=${v//a/A};v=${v//b/B};v=${v//c/C};v=${v//d/D};v=${v//e/E};v=${v//f/F};v=${v//g/G};v=${v//h/H};v=${v//i/I};v=${v//j/J};v=${v//k/K};v=${v//l/L};v=${v//m/M};v=${v//n/N};v=${v//o/O};v=${v//p/P};v=${v//q/Q};v=${v//r/R};v=${v//s/S};v=${v//t/T};v=${v//u/U};v=${v//v/V};v=${v//w/W};v=${v//x/X};v=${v//y/Y};v=${v//z/Z};echo "$v";done

Simple bash to lowercase :

while read v;do echo "${v,,}"; done

Simple bash to uppercase :

while read v;do echo "${v^^}"; done

Note that ${v,} and ${v^} only change the first letter.

You should use it that way :

(while read v;do echo "${v,,}"; done) < input_file.txt > output_file.txt

extracting days from a numpy.timedelta64 value

You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.

>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23

Or, as @PhillipCloud suggested, just days.astype(int) since the timedelta is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

You can find more about it here.

How set background drawable programmatically in Android

If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..

Xcode is not currently available from the Software Update server

Had the same issue and was getting the same error. When i ran xcode-select -p, it gave output as /Library/Developer/CommandLineTools. So that means xcode was already installed in my system. Then i ran steps as given on this answer. After which any command which required xcode ran successfully.

Static Classes In Java

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

public class Outer {
   static class Nested_Demo {
      public void my_method() {
          System.out.println("This is my nested class");
      }
   }
public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}

Using a dispatch_once singleton model in Swift

My way of implementation in Swift...

ConfigurationManager.swift

import Foundation

    let ConfigurationManagerSharedInstance = ConfigurationManager()
 class ConfigurationManager : NSObject {
    var globalDic: NSMutableDictionary = NSMutableDictionary()

class var sharedInstance:ConfigurationManager {
    return ConfigurationManagerSharedInstance

}

init() {

    super.init()

    println ("Config Init been Initiated, this will be called only onece irrespective of many calls")   

}

Access the globalDic from any screen of the application by the below.

Read:

 println(ConfigurationManager.sharedInstance.globalDic)  

Write:

 ConfigurationManager.sharedInstance.globalDic = tmpDic // tmpDict is any value that to be shared among the application

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

How to tell which row number is clicked in a table?

In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:

<table id="elitable" border="1" cellspacing="0" width="100%">
  <tr>
 <td>100</td><td>AAA</td><td>aaa</td>
  </tr>
  <tr>
<td>200</td><td>BBB</td><td>bbb</td>
   </tr>
   <tr>
<td>300</td><td>CCC</td><td>ccc</td>
  </tr>
</table>


    <script>
    $(function(){
        $("#elitable tr").click(function(){
        alert (this.rowIndex);
        });
    });
    </script>

DEMO

Adding machineKey to web.config on web-farm sites

If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.

  1. Open IIS manager.
  2. If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
  3. Double-click the Machine Key icon in ASP.NET settings in the middle pane:
  4. MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
  5. Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.

Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…

How to document a method with parameter(s)?

Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.

One example:

Parameters
----------
x : type
    Description of parameter `x`.

Text file in VBA: Open/Find Replace/SaveAs/Close File

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

Anchor links in Angularjs?

I had the same problem, but this worked for me:

<a ng-href="javascript:void(0);#tagId"></a>

convert a char* to std::string

Most answers talks about constructing std::string.

If already constructed, just use assignment operator.

std::string oString;
char* pStr;

... // Here allocate and get character string (e.g. using fgets as you mentioned)

oString = pStr; // This is it! It copies contents from pStr to oString

How do I programmatically "restart" an Android app?

Try using FLAG_ACTIVITY_CLEAR_TASK

Adjust list style image position?

solution with fontawesome

#polyNedir ul li { position:relative;padding-left:20px }
#polyNedir ul li:after{font-family:fontawesome;content:'\f111';position:absolute;left:0px;top:3px;color:#fff;font-size:10px;}

CSS3 Box Shadow on Top, Left, and Right Only

The following code did it for me to make a shadow inset of the right side:

-moz-box-shadow: inset -10px 0px 10px -10px #000;
-webkit-box-shadow: inset -10px 0px 10px -10px #000;
box-shadow: inset -10px 0px 10px -10px #000;

Hope it will help!!!!

jQuery text() and newlines

You can use html instead of text and replace each occurrence of \n with <br>. You will have to correctly escape your text though.

x = x.replace(/&/g, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

[ :Unexpected operator in shell programming

you have to use bash instead or rewrite your script using standard sh

sh -c 'test "$choose" = "y" -o "$choose" = "Y"'

Where does MAMP keep its php.ini?

After going through all the solutions here, the easiest way to find the loaded php.ini file is to go into phpinfo on the loaded MAMP webpage, which will show you the loaded php.ini file.

This will also confirm if the parameters you change, like max_file_size, have updated correctly.

How can I replace a regex substring match in Javascript?

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);

Or if you're sure there won't be any other digits in the string:

var str   = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);

Trust Store vs Key Store - creating with keytool

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

A long bigger than Long.MAX_VALUE

If triangle.lborderA is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.

However, if triangle.lborderA is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300) does return true.

  public static boolean isBiggerThanMaxLong(double in){
    return in > Long.MAX_VALUE;
  }

Python os.path.join on Windows

The proposed solutions are interesting and offer a good reference, however they are only partially satisfying. It is ok to manually add the separator when you have a single specific case or you know the format of the input string, but there can be cases where you want to do it programmatically on generic inputs.

With a bit of experimenting, I believe the criteria is that the path delimiter is not added if the first segment is a drive letter, meaning a single letter followed by a colon, no matter if it corresponds to a real unit.

For example:

import os
testval = ['c:','c:\\','d:','j:','jr:','data:']

for t in testval:
    print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value:  c: , join to "folder" c:folder
test value:  c:\ , join to "folder" c:\folder
test value:  d: , join to "folder" d:folder
test value:  j: , join to "folder" j:folder
test value:  jr: , join to "folder" jr:\folder
test value:  data: , join to "folder" data:\folder

A convenient way to test for the criteria and apply a path correction can be to use os.path.splitdrive comparing the first returned element to the test value, like t+os.path.sep if os.path.splitdrive(t)[0]==t else t.

Test:

for t in testval:
    corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
    print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c:    corrected: c:\  join corrected-> c:\folder
original: c:\   corrected: c:\  join corrected-> c:\folder
original: d:    corrected: d:\  join corrected-> d:\folder
original: j:    corrected: j:\  join corrected-> j:\folder
original: jr:   corrected: jr:  join corrected-> jr:\folder
original: data: corrected: data:  join corrected-> data:\folder

it can be probably be improved to be more robust for trailing spaces, and I have tested it only on windows, but I hope it gives an idea. See also Os.path : can you explain this behavior? for interesting details on systems other then windows.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

Is there a way to specify a default property value in Spring XML?

Spring 3 supports ${my.server.port:defaultValue} syntax.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I had this problem with my datasource in WildFly and Tomcat, connecting to a Oracle 10g.

I found that under certain conditions the statement wasn't closed even when the statement.close() was invoked. The problem was with the Oracle Driver we were using: ojdbc7.jar. This driver is intended for Oracle 12c and 11g, and it seems has some issues when is used with Oracle 10g, so I downgrade to ojdbc5.jar and now everything is running fine.

Remove All Event Listeners of Specific Type

Remove all listeners in element by one js line:

element.parentNode.innerHTML += '';

Use YAML with variables

Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...

# fooz.yml
  foo:
    bar: <%= $ENV[:some_var] %>

No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.

If you can use the template like that or the << >> or the {{ }} styles depending on your reader, after that you just ...

In another yml file ...

# boo.yml

development:
  fooz: foo

Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

With Eclipse and Windows:

you have to copy 2 files - xxxPROJECTxxx.properties - log4j.properties here : C:\Eclipse\CONTENER\TOMCAT\apache-tomcat-7\lib

Changing default shell in Linux

You should have a 'skeleton' somewhere in /etc, probably /etc/skeleton, or check the default settings, probably /etc/default or something. Those are scripts that define standard environment variables getting set during a login.

If it is just for your own account: check the (hidden) file ~/.profile and ~/.login. Or generate them, if they don't exist. These are also evaluated by the login process.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

REPLACE INTO table(column_list) VALUES(value_list);

is a shorter form of

INSERT OR REPLACE INTO table(column_list) VALUES(value_list);

For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.

REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.


This is a work around.. not checked the speed..

INSERT OR IGNORE INTO table (column_list) VALUES(value_list);

followed by

UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'

This method allows a replace to occur without causing a trigger.

Best algorithm for detecting cycles in a directed graph

According to Lemma 22.11 of Cormen et al., Introduction to Algorithms (CLRS):

A directed graph G is acyclic if and only if a depth-first search of G yields no back edges.

This has been mentioned in several answers; here I'll also provide a code example based on chapter 22 of CLRS. The example graph is illustrated below.

enter image description here

CLRS' pseudo-code for depth-first search reads:

enter image description here

In the example in CLRS Figure 22.4, the graph consists of two DFS trees: one consisting of nodes u, v, x, and y, and the other of nodes w and z. Each tree contains one back edge: one from x to v and another from z to z (a self-loop).

The key realization is that a back edge is encountered when, in the DFS-VISIT function, while iterating over the neighbors v of u, a node is encountered with the GRAY color.

The following Python code is an adaptation of CLRS' pseudocode with an if clause added which detects cycles:

import collections


class Graph(object):
    def __init__(self, edges):
        self.edges = edges
        self.adj = Graph._build_adjacency_list(edges)

    @staticmethod
    def _build_adjacency_list(edges):
        adj = collections.defaultdict(list)
        for edge in edges:
            adj[edge[0]].append(edge[1])
        return adj


def dfs(G):
    discovered = set()
    finished = set()

    for u in G.adj:
        if u not in discovered and u not in finished:
            discovered, finished = dfs_visit(G, u, discovered, finished)


def dfs_visit(G, u, discovered, finished):
    discovered.add(u)

    for v in G.adj[u]:
        # Detect cycles
        if v in discovered:
            print(f"Cycle detected: found a back edge from {u} to {v}.")

        # Recurse into DFS tree
        if v not in finished:
            dfs_visit(G, v, discovered, finished)

    discovered.remove(u)
    finished.add(u)

    return discovered, finished


if __name__ == "__main__":
    G = Graph([
        ('u', 'v'),
        ('u', 'x'),
        ('v', 'y'),
        ('w', 'y'),
        ('w', 'z'),
        ('x', 'v'),
        ('y', 'x'),
        ('z', 'z')])

    dfs(G)

Note that in this example, the time in CLRS' pseudocode is not captured because we're only interested in detecting cycles. There is also some boilerplate code for building the adjacency list representation of a graph from a list of edges.

When this script is executed, it prints the following output:

Cycle detected: found a back edge from x to v.
Cycle detected: found a back edge from z to z.

These are exactly the back edges in the example in CLRS Figure 22.4.

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

I also face that problem Finally, i solved it

<meta property="og:image" itemprop="image" content="http://yourdomain.com/yourfolder/imagename.png" />

My image property

  1. Dimension : 300X200
  2. Size : < 300KB
  3. URL: http://yourdomain.com/yourfolder/imagename.png

Make sure in image name there is no space, if you have two words then use underscore sign

how to convert date to a format `mm/dd/yyyy`

Use CONVERT with the Value specifier of 101, whilst casting your data to date:

CONVERT(VARCHAR(10), CAST(Created_TS AS DATE), 101)

How to replace multiple white spaces with one white space

Here is the Solution i work with. Without RegEx and String.Split.

public static string TrimWhiteSpace(this string Value)
{
    StringBuilder sbOut = new StringBuilder();
    if (!string.IsNullOrEmpty(Value))
    {
        bool IsWhiteSpace = false;
        for (int i = 0; i < Value.Length; i++)
        {
            if (char.IsWhiteSpace(Value[i])) //Comparion with WhiteSpace
            {
                if (!IsWhiteSpace) //Comparison with previous Char
                {
                    sbOut.Append(Value[i]);
                    IsWhiteSpace = true;
                }
            }
            else
            {
                IsWhiteSpace = false;
                sbOut.Append(Value[i]);
            }
        }
    }
    return sbOut.ToString();
}

so you can:

string cleanedString = dirtyString.TrimWhiteSpace();

Java default constructor

I hope you got your answer regarding which is default constructor. But I am giving below statements to correct the comments given.

  • Java does not initialize any local variable to any default value. So if you are creating an Object of a class it will call default constructor and provide default values to Object.

  • Default constructor provides the default values to the object like 0, null etc. depending on the type.

Please refer below link for more details.

https://www.javatpoint.com/constructor

What's the better (cleaner) way to ignore output in PowerShell?

Personally, I use ... | Out-Null because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null and [void] .... $null = ... is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null and ... > $null come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null), compared to putting $null = or [void] before the expression to determine what happens after executing it.

Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help command or your favorite search engine to try to find out what Out-Null does. You get a useful result immediately, right? Now try to do the same with [void] and $null =. Not so easy, is it?

Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void], $null =, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*

* I am presuming that Out-Null is clear and well-known, which I don't know to be $true. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

How to redirect both stdout and stderr to a file

If you want to log to the same file:

command1 >> log_file 2>&1

If you want different files:

command1 >> log_file 2>> err_file

How to resolve cURL Error (7): couldn't connect to host?

In PHP, If your network under proxy. You should set the proxy URL and port

curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number

This is solves my problem

append multiple values for one key in a dictionary

You can use setdefault.

for line in list:  
    d.setdefault(year, []).append(value)

This works because setdefault returns the list as well as setting it on the dictionary, and because a list is mutable, appending to the version returned by setdefault is the same as appending it to the version inside the dictionary itself. If that makes any sense.

Breaking up long strings on multiple lines in Ruby without stripping newlines

Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.

class Subscription
  def warning_message
    <<~HEREDOC
      Subscription expiring soon!
      Your free trial will expire in #{days_until_expiration} days.
      Please update your billing information.
    HEREDOC
  end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be removed from each line of the content.

How do I format XML in Notepad++?

You can't, granted you don't have access to install plugins. But you probably have or can get Eclipse (Visual Studio can do this too).

Ctrl + N (new file) ? (choose XML file) ? (paste your XML content) ? Ctrl + Shift + K (format)

If you want to format JSON NotePad++ can do this by default with Ctrl + Alt + m

Changing background color of text box input not working when empty

on body tag's onLoad try setting it like

document.getElementById("subEmail").style.backgroundColor = "yellow";

and after that on change of that input field check if some value is there, or paint it yellow like

function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
    inputVal.style.backgroundColor = "yellow";
            }
    }

How can I get (query string) parameters from the URL in Next.js?

url prop is deprecated as of Next.js version 6: https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md

To get the query parameters, use getInitialProps:

For stateless components

import Link from 'next/link'
const About = ({query}) => (
  <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)

About.getInitialProps = ({query}) => {
  return {query}
}

export default About;

For regular components

class About extends React.Component {

  static getInitialProps({query}) {
    return {query}
  }

  render() {
    console.log(this.props.query) // The query is available in the props object
    return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>

  }
}

The query object will be like: url.com?a=1&b=2&c=3 becomes: {a:1, b:2, c:3}

Convert number to varchar in SQL with formatting

Correción: 3-LEN

declare @t  TINYINT 
set @t =233
SELECT ISNULL(REPLICATE('0',3-LEN(@t)),'') + CAST(@t AS VARCHAR) 

In Python, how do you convert seconds since epoch to a `datetime` object?

For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro's answer):

from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00

Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(...) anyway to get the offset.

If you don't want to go all the way to microseconds you can choose a different unit with the isoformat() method.

lambda expression for exists within list

I would look at the Join operator:

from r in list join i in listofIds on r.Id equals i select r

I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.

Edit: Extension method syntax for completeness (now that I've figured it out):

var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);

Why is the Android emulator so slow? How can we speed up the Android emulator?

Update

You can now enable the Quick Boot option for Android Emulator. That will save emulator state, and it will start the emulator quickly on the next boot.

Click on Emulator edit button, then click Show Advanced Setting. Then enable Quick Boot like below screenshot.

Quick boot

Android Development Tools (ADT) 9.0.0 (or later) has a feature that allows you to save state of the AVD (emulator), and you can start your emulator instantly. You have to enable this feature while creating a new AVD or you can just create it later by editing the AVD.

Also I have increased the Device RAM Size to 1024 which results in a very fast emulator.

Refer to the given below screenshots for more information.

Creating a new AVD with the save snapshot feature.

Android emulator with save snapshot feature.

Launching the emulator from the snapshot.

Launching the emulator from the snapshot.

And for speeding up your emulator you can refer to Speed up your Android Emulator!:

Using ssd hard drive has too much impact and I recommend to use more suitable ram (8 or higher)

Copy files without overwrite

Here it is in batch file form:

@echo off
set source=%1
set dest=%2
for %%f in (%source%\*) do if not exist "%dest%\%%~nxf" copy "%%f" "%dest%\%%~nxf"

How to add target="_blank" to JavaScript window.location?

window.location sets the URL of your current window. To open a new window, you need to use window.open. This should work:

function ToKey(){
    var key = document.tokey.key.value.toLowerCase();
    if (key == "smk") {
        window.open('http://www.smkproduction.eu5.org', '_blank');
    } else {
        alert("Kodi nuk është valid!");
    }
}

Classes cannot be accessed from outside package

Let me guess

Your initial declaration of class PUBLICClass was not public, then you made it `Public', can you try to clean and rebuild your project ?

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

with pattern.findall(row) as f:

You are using the with statement. It requires an object with __enter__ and __exit__ methods. But pattern.findall returns a list, with tries to store the __exit__ method, but it can't find it, and raises an error. Just use

f = pattern.findall(row)

instead.

How to trigger a file download when clicking an HTML button or JavaScript

If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:

<div onClick=(()=>{downloadjs(url, filename)})/>

*it's jsx/react syntax, but can be used in pure html

Note: Edited to fix layout issue above

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Resizing a button

Another alternative is that you are allowed to have multiple classes in a tag. Consider:

 <div class="button big">This is a big button</div>
 <div class="button small">This is a small button</div>

And the CSS:

 .button {
     /* all your common button styles */
 }

 .big {
     height: 60px;
     width: 100px;
 }
 .small {
     height: 40px;
     width: 70px;
 }

and so on.

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Finding which process was killed by Linux OOM killer

Try this out:

grep -i 'killed process' /var/log/messages

TypeError: 'int' object is not callable

As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

Insert php variable in a href

echo '<a href="' . $folder_path . '">Link text</a>';

Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.

EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?

Better way to right align text in HTML Table

A number of years ago (in the IE only days) I was using the <col align="right"> tag, but I just tested it and and it seems to be an IE only feature:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Test</title>
</head>
<body>
    <table width="100%" border="1">
        <col align="left" />
        <col align="left" />
        <col align="right" />
        <tr>
            <th>ISBN</th>
            <th>Title</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>3476896</td>
            <td>My first HTML</td>
            <td>$53</td>
        </tr>
    </table>
</body>
</html>

The snippet is taken from www.w3schools.com. Of course, it should not be used (unless for some reason you really target the IE rendering engine only), but I thought it would be interesting to mention it.

Edit:

Overall, I don't understand the reasoning behing abandoning this tag. It would appear to be very useful (at least for manual HTML publishing).

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

Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.

What is the difference between T(n) and O(n)?

f(n) belongs to O(n) if exists positive k as f(n)<=k*n

f(n) belongs to T(n) if exists positive k1, k2 as k1*n<=f(n)<=k2*n

Wikipedia article on Big O Notation

How to evaluate a math expression given in string form?

A Java class that can evaluate mathematical expressions:

package test;

public class Calculator {

    public static Double calculate(String expression){
        if (expression == null || expression.length() == 0) {
            return null;
        }
        return calc(expression.replace(" ", ""));
    }
    public static Double calc(String expression) {

        if (expression.startsWith("(") && expression.endsWith(")")) {
            return calc(expression.substring(1, expression.length() - 1));
        }
        String[] containerArr = new String[]{expression};
        double leftVal = getNextOperand(containerArr);
        expression = containerArr[0];
        if (expression.length() == 0) {
            return leftVal;
        }
        char operator = expression.charAt(0);
        expression = expression.substring(1);

        while (operator == '*' || operator == '/') {
            containerArr[0] = expression;
            double rightVal = getNextOperand(containerArr);
            expression = containerArr[0];
            if (operator == '*') {
                leftVal = leftVal * rightVal;
            } else {
                leftVal = leftVal / rightVal;
            }
            if (expression.length() > 0) {
                operator = expression.charAt(0);
                expression = expression.substring(1);
            } else {
                return leftVal;
            }
        }
        if (operator == '+') {
            return leftVal + calc(expression);
        } else {
            return leftVal - calc(expression);
        }

    }

    private static double getNextOperand(String[] exp){
        double res;
        if (exp[0].startsWith("(")) {
            int open = 1;
            int i = 1;
            while (open != 0) {
                if (exp[0].charAt(i) == '(') {
                    open++;
                } else if (exp[0].charAt(i) == ')') {
                    open--;
                }
                i++;
            }
            res = calc(exp[0].substring(1, i - 1));
            exp[0] = exp[0].substring(i);
        } else {
            int i = 1;
            if (exp[0].charAt(0) == '-') {
                i++;
            }
            while (exp[0].length() > i && isNumber((int) exp[0].charAt(i))) {
                i++;
            }
            res = Double.parseDouble(exp[0].substring(0, i));
            exp[0] = exp[0].substring(i);
        }
        return res;
    }


    private static boolean isNumber(int c) {
        int zero = (int) '0';
        int nine = (int) '9';
        return (c >= zero && c <= nine) || c =='.';
    }

    public static void main(String[] args) {
        System.out.println(calculate("(((( -6 )))) * 9 * -1"));
        System.out.println(calc("(-5.2+-5*-5*((5/4+2)))"));

    }

}

What does --net=host option in Docker command really do?

  1. you can create your own new network like --net="anyname"
  2. this is done to isolate the services from different container.
  3. suppose the same service are running in different containers, but the port mapping remains same, the first container starts well , but the same service from second container will fail. so to avoid this, either change the port mappings or create a network.

Jquery UI Datepicker not displaying

Seems to happen with some themes (cupertino/theme.css) in my case.

And the problem is the .ui-helper-hidden-accessible class which have clip property, like previous users said.

Just Overwrite it and it will be fine

$(document).ready(function() {
    $("#datePicker").datepicker({ dateFormat: "yy-m-d" });
    $('#ui-datepicker-div').css('clip', 'auto');
});

Simple way to convert datarow array to datatable

You could use System.Linq like this:

if (dataRows != null && dataRows.Length > 0)
{
   dataTable = dataRows.AsEnumerable().CopyToDataTable();
}

Difference between one-to-many and many-to-one relationship

One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).

The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:

  1. Multiplicity (ER term: cardinality)
    • One-to-one relationships: Example Husband and Wife
    • One-to-Many relationships: Example Mother and Children
    • Many-to-Many relationships: Example Student and Subject
  2. Directionality : Not affect on mapping but makes difference on how we can access data.
    • Uni-directional relationships: A relationship field or property that refers to the other entity.
    • Bi-directional relationships: Each entity has a relationship field or property that refers to the other entity.

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

How to revert a "git rm -r ."?

If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html

git prune -n
git cat-file -p <blob #>

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

checking if number entered is a digit in jquery

Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:

/^\d+$/.match(value)
Number(value) == value

How to correct indentation in IntelliJ

Just select the code and

  • on Windows do Ctrl + Alt + L

  • on Linux do Ctrl + Windows Key + Alt + L

  • on Mac do CMD + Option + L

XML Error: There are multiple root elements

If you're in charge (or have any control over the web service), get them to add a unique root element!

If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.

Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

Generate JSON string from NSDictionary in iOS

Apple added a JSON parser and serializer in iOS 5.0 and Mac OS X 10.7. See NSJSONSerialization.

To generate a JSON string from a NSDictionary or NSArray, you do not need to import any third party framework anymore.

Here is how to do it:

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput 
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

How to add a "confirm delete" option in ASP.Net Gridview?

This should do it.

I found it here: http://forums.asp.net/p/1331581/2678206.aspx

<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
        <asp:ImageButton ID="DeleteButton" runat="server" ImageUrl="~/site/img/icons/cross.png"
                    CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this event?');"
                    AlternateText="Delete" />               
    </ItemTemplate>
</asp:TemplateField>  

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

Reading CSV file and storing values into an array

My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace. Below is a sample code:

using Microsoft.VisualBasic.FileIO;

var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
 csvParser.CommentTokens = new string[] { "#" };
 csvParser.SetDelimiters(new string[] { "," });
 csvParser.HasFieldsEnclosedInQuotes = true;

 // Skip the row with the column names
 csvParser.ReadLine();

 while (!csvParser.EndOfData)
 {
  // Read current line fields, pointer moves to the next line.
  string[] fields = csvParser.ReadFields();
  string Name = fields[0];
  string Address = fields[1];
 }
}

Remember to add reference to Microsoft.VisualBasic

More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html

How to sort a list of lists by a specific index of the inner list?

More easy to understand (What is Lambda actually doing):

ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
def thirdItem(ls):
    #return the third item of the list
    return ls[2]
#Sort according to what the thirdItem function return 
ls2.sort(key=thirdItem)

Transparent background on winforms?

The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

What are OLTP and OLAP. What is the difference between them?

OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.

Store JSON object in data attribute in HTML jQuery

The trick for me was to add double quotes around keys and values. If you use a PHP function like json_encode will give you a JSON encoded string and an idea how to properly encode yours.

jQuery('#elm-id').data('datakey') will return an object of the string, if the string is properly encoded as json.

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

  1. "{test: 1}" (test does not have double quotes around it).
  2. "{'test': 1}" ('test' is using single quotes instead of double quotes).
  3. "'test'" ('test' is using single quotes instead of double quotes).
  4. ".1" (a number must start with a digit; "0.1" would be valid).
  5. "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
  6. "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n

makefile:4: *** missing separator. Stop

You should always write command after a Tab and not white space.

This applies to gcc line (line #4) in your case. You need to insert tab before gcc.

Also replace \rm -fr ll with rm -fr ll. Insert tabs before this command too.

Maven artifact and groupId naming

However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.

com means this project belongs to a company, and org means this project belongs to a social organization. These are alright, but for those strange domain like xxx.tv, xxx.uk, xxx.cn, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.

Text vertical alignment in WPF TextBlock

A Textblock itself can't do vertical alignment

The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.

<Border BorderBrush="{x:Null}" Height="50">
    <TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>

Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable

jQuery `.is(":visible")` not working in Chrome

Internet Explorer, Chrome, Firefox...

Cross Browser function "isVisible()"

//check if exist and is visible
function isVisible(id) {
    var element = $('#' + id);
    if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
        return true;
    } else {
        return false;
    }
}

Full example:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script type="text/javascript">
            //check if exist and is visible
            function isVisible(id) {
                var element = $('#' + id);
                if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
                    return true;
                } else {
                    return false;
                }
            }

            function check(id) {
                if (isVisible(id)) {
                    alert('visible: true');
                } else {
                    alert('visible: false');
                }
                return false;
            }
        </script>

        <style type="text/css">
            #fullname{
                display: none;
            }
            #vote{
                visibility: hidden;
            }
        </style>
        <title>Full example: isVisible function</title>
    </head>
    <body>
        <div id="hello-world">
            Hello World!
        </div>
        <div id="fullname">
            Fernando Mosquera Catarecha
        </div>
        <div id="vote">
            rate it!
        </div>
        <a href="#" onclick="check('hello-world');">Check isVisible('hello-world')</a><br /><br />
        <a href="#" onclick="check('fullname');">Check isVisible('fullname')</a><br /><br />
        <a href="#" onclick="check('vote');">Check isVisible('vote')</a>
    </body>
</html>

Regards,

Fernando

Run chrome in fullscreen mode on Windows

Running chrome.exe --start-fullscreen --app=https://google.com will not get you Chrome in fullscreen, but in kiosk mode.

However, running chrome --start-fullscreen --app=https://google.com (notice : it's chrome instead of chrome.exe) worked in my case.

INSERT with SELECT

Yes, absolutely, but check your syntax.

INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM   courses
WHERE  cid = 2

You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm