Programs & Examples On #Zabbix

Zabbix is a free, open-source monitoring tool for diverse IT components,such as networks, servers, VM and cloud services.Zabbix provides metrics,such as network utilization,CPU load and disk usage consumption.The software monitors operations on Linux, HP-UX, Mac OS X, Solaris and Windows via agents installed on machines with a centralised server It includes enterprise class features that can scale to support monitoring on thousands of servers.

Zabbix server is not running: the information displayed may not be current

To solve the problem zabbix server is not running you have to :

First - Check that all of the database parameters in zabbix.conf.php ( /etc/zabbix/web/zabbix.conf.php) and zabbix_server.conf ( /etc/zabbix/zabbix_server.conf) to be the same. Including:
• DBHost
• DBName
• DBUser
• DBPassword

Second- Change SElinux parameters:

#setsebool -P httpd_can_network_connect on
#setsebool -P httpd_can_connect_zabbix 1
#setsebool -P zabbix_can_network 1

After all, restart all services:

#service zabbix-server restart
#service httpd restart

worth a try.

How do you UrlEncode without using System.Web?

System.Uri.EscapeUriString() can be problematic with certain characters, for me it was a number / pound '#' sign in the string.

If that is an issue for you, try:

System.Uri.EscapeDataString() //Works excellent with individual values

Here is a SO question answer that explains the difference:

What's the difference between EscapeUriString and EscapeDataString?

and recommends to use Uri.EscapeDataString() in any aspect.

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Android SeekBar setOnSeekBarChangeListener

All answers are correct, but you need to convert a long big fat number into a timer first:

    public String toTimer(long milliseconds){
    String finalTimerString = "";
    String secondsString;
    // Convert total duration into time
    int hours = (int)( milliseconds / (1000*60*60));
    int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
    int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
    // Add hours if there
    if(hours > 0){
        finalTimerString = hours + ":";
    }
    // Prepending 0 to seconds if it is one digit
    if(seconds < 10){
        secondsString = "0" + seconds;
    }else{
        secondsString = "" + seconds;}
    finalTimerString = finalTimerString + minutes + ":" + secondsString;
    // return timer string
    return finalTimerString;
}

And this is how you use it:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));        
}

Git Bash: Could not open a connection to your authentication agent

I checked all the solutions on this post and the post that @kenorb referenced above, and I did not find any solution that worked for me.

I am using Git 1.9.5 Preview on Windows 7 with the following configuration: - Run Git from the Windows Command Prompt - Checkout Windows-style, commit Unix-style line endings

I used the 'Git Bash' console for everything... And all was well until I tried to install the SSH keys. GitHub's documentation says to do the following (don't run these commands until you finish reading the post):

Ensure ssh-agent is enabled:

If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background
ssh-agent -s
# Agent pid 59566
If you are using another terminal prompt, such as msysgit, turn on ssh-agent:
# start the ssh-agent in the background
eval $(ssh-agent -s)
# Agent pid 59566

Now of course I missed the fact that you were supposed to do one or the other. So, I ran these commands multiple times because the later ssh-add command was failing, so I returned to this step, and continued to retry over and over.

This results in 1 Windows 'ssh-agent' process being created every single time you run these commands (notice the new PID every time you enter those commands?)

So, Ctrl+Alt+Del and hit End Process to stop each 'ssh-agent.exe' process.

Now that all the messed up stuff from the failed attempts is cleaned up, I will tell you how to get it working...

In 'Git Bash':

Start the 'ssh-agent.exe' process

eval $(ssh-agent -s)

And install the SSH keys

ssh-add "C:\Users\MyName\.ssh\id_rsa"

* Adjust the path above with your username, and make sure that the location of the* /.ssh directory is in the correct place. I think you choose this location during the Git installation? Maybe not...

The part I was doing wrong before I figured this out was I was not using quotes around the 'ssh-add' location. The above is how it needs to be entered on Windows.

How can I check whether a option already exist in select by JQuery

Does not work, you have to do this:

if ( $("#your_select_id option[value='enter_value_here']").length == 0 ){
  alert("option doesn't exist!");
}

How to show full column content in a Spark Dataframe?

The following answer applies to a Spark Streaming application.

By setting the "truncate" option to false, you can tell the output sink to display the full column.

val query = out.writeStream
          .outputMode(OutputMode.Update())
          .format("console")
          .option("truncate", false)
          .trigger(Trigger.ProcessingTime("5 seconds"))
          .start()

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

send mail from linux terminal in one line

You can also use sendmail:

/usr/sbin/sendmail [email protected] < /file/to/send

Checking if sys.argv[x] is defined

You can simply append the value of argv[1] to argv and then check if argv[1] doesn't equal the string you inputted Example:

from sys import argv
argv.append('SomeString')
if argv[1]!="SomeString":
            print(argv[1])

How can I change image source on click with jQuery?

It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :

$(function() {
 $('.menulink').click(function(){
   $("#bg").attr('src',"img/picture1.jpg");
   return false;
 });
});

Interesting question on the differences between prevent default and return false.

In this case, return false will work just fine because the event doesn't need to be propagated.

Authentication versus Authorization

Authentication is the process of ascertaining that somebody really is who they claim to be.

Authorization refers to rules that determine who is allowed to do what. E.g. Adam may be authorized to create and delete databases, while Usama is only authorised to read.

The two concepts are completely orthogonal and independent, but both are central to security design, and the failure to get either one correct opens up the avenue to compromise.

In terms of web apps, very crudely speaking, authentication is when you check login credentials to see if you recognize a user as logged in, and authorization is when you look up in your access control whether you allow the user to view, edit, delete or create content.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

Dynamically Add Variable Name Value Pairs to JSON Object

You can achieve this using Lodash _.assign function.

_x000D_
_x000D_
var ipID = {};_x000D_
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});_x000D_
console.log(ipID);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

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

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Best practices to test protected methods with PHPUnit

You can indeed use __call() in a generic fashion to access protected methods. To be able to test this class

class Example {
    protected function getMessage() {
        return 'hello';
    }
}

you create a subclass in ExampleTest.php:

class ExampleExposed extends Example {
    public function __call($method, array $args = array()) {
        if (!method_exists($this, $method))
            throw new BadMethodCallException("method '$method' does not exist");
        return call_user_func_array(array($this, $method), $args);
    }
}

Note that the __call() method does not reference the class in any way so you can copy the above for each class with protected methods you want to test and just change the class declaration. You may be able to place this function in a common base class, but I haven't tried it.

Now the test case itself only differs in where you construct the object to be tested, swapping in ExampleExposed for Example.

class ExampleTest extends PHPUnit_Framework_TestCase {
    function testGetMessage() {
        $fixture = new ExampleExposed();
        self::assertEquals('hello', $fixture->getMessage());
    }
}

I believe PHP 5.3 allows you to use reflection to change the accessibility of methods directly, but I assume you'd have to do so for each method individually.

WPF popup window

You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:

MyWindow popup = new MyWindow();
popup.ShowDialog();

You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null), you can set the window's DialogResult property before closing it and then check for it (it is the value returned by ShowDialog()).

C# ASP.NET Single Sign-On Implementation

There are multiple options to implement SSO for a .NET application.

Check out the following tutorials online:

Basics of Single Sign on, July 2012

http://www.codeproject.com/Articles/429166/Basics-of-Single-Sign-on-SSO

GaryMcAllisterOnline: ASP.NET MVC 4, ADFS 2.0 and 3rd party STS integration (IdentityServer2), Jan 2013

http://garymcallisteronline.blogspot.com/2013/01/aspnet-mvc-4-adfs-20-and-3rd-party-sts.html

The first one uses ASP.NET Web Forms, while the second one uses ASP.NET MVC4.

If your requirements allow you to use a third-party solution, also consider OpenID. There's an open source library called DotNetOpenAuth.

For further information, read MSDN blog post Integrate OpenAuth/OpenID with your existing ASP.NET application using Universal Providers.

Hope this helps!

How to read the last row with SQL Server

This is how you get the last record and update a field in Access DB.

UPDATE compalints SET tkt = addzone &'-'& customer_code &'-'& sn where sn in (select max(sn) from compalints )

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

How to identify all stored procedures referring a particular table

SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%TableNameOrWhatever%'

BTW -- here is a handy resource for this type of question: Querying the SQL Server System Catalog FAQ

When is assembly faster than C?

Here is a real world example: Fixed point multiplies on old compilers.

These don't only come handy on devices without floating point, they shine when it comes to precision as they give you 32 bits of precision with a predictable error (float only has 23 bit and it's harder to predict precision loss). i.e. uniform absolute precision over the entire range, instead of close-to-uniform relative precision (float).


Modern compilers optimize this fixed-point example nicely, so for more modern examples that still need compiler-specific code, see


C doesn't have a full-multiplication operator (2N-bit result from N-bit inputs). The usual way to express it in C is to cast the inputs to the wider type and hope the compiler recognizes that the upper bits of the inputs aren't interesting:

// on a 32-bit machine, int can hold 32-bit fixed-point integers.
int inline FixedPointMul (int a, int b)
{
  long long a_long = a; // cast to 64 bit.

  long long product = a_long * b; // perform multiplication

  return (int) (product >> 16);  // shift by the fixed point bias
}

The problem with this code is that we do something that can't be directly expressed in the C-language. We want to multiply two 32 bit numbers and get a 64 bit result of which we return the middle 32 bit. However, in C this multiply does not exist. All you can do is to promote the integers to 64 bit and do a 64*64 = 64 multiply.

x86 (and ARM, MIPS and others) can however do the multiply in a single instruction. Some compilers used to ignore this fact and generate code that calls a runtime library function to do the multiply. The shift by 16 is also often done by a library routine (also the x86 can do such shifts).

So we're left with one or two library calls just for a multiply. This has serious consequences. Not only is the shift slower, registers must be preserved across the function calls and it does not help inlining and code-unrolling either.

If you rewrite the same code in (inline) assembler you can gain a significant speed boost.

In addition to this: using ASM is not the best way to solve the problem. Most compilers allow you to use some assembler instructions in intrinsic form if you can't express them in C. The VS.NET2008 compiler for example exposes the 32*32=64 bit mul as __emul and the 64 bit shift as __ll_rshift.

Using intrinsics you can rewrite the function in a way that the C-compiler has a chance to understand what's going on. This allows the code to be inlined, register allocated, common subexpression elimination and constant propagation can be done as well. You'll get a huge performance improvement over the hand-written assembler code that way.

For reference: The end-result for the fixed-point mul for the VS.NET compiler is:

int inline FixedPointMul (int a, int b)
{
    return (int) __ll_rshift(__emul(a,b),16);
}

The performance difference of fixed point divides is even bigger. I had improvements up to factor 10 for division heavy fixed point code by writing a couple of asm-lines.


Using Visual C++ 2013 gives the same assembly code for both ways.

gcc4.1 from 2007 also optimizes the pure C version nicely. (The Godbolt compiler explorer doesn't have any earlier versions of gcc installed, but presumably even older GCC versions could do this without intrinsics.)

See source + asm for x86 (32-bit) and ARM on the Godbolt compiler explorer. (Unfortunately it doesn't have any compilers old enough to produce bad code from the simple pure C version.)


Modern CPUs can do things C doesn't have operators for at all, like popcnt or bit-scan to find the first or last set bit. (POSIX has a ffs() function, but its semantics don't match x86 bsf / bsr. See https://en.wikipedia.org/wiki/Find_first_set).

Some compilers can sometimes recognize a loop that counts the number of set bits in an integer and compile it to a popcnt instruction (if enabled at compile time), but it's much more reliable to use __builtin_popcnt in GNU C, or on x86 if you're only targeting hardware with SSE4.2: _mm_popcnt_u32 from <immintrin.h>.

Or in C++, assign to a std::bitset<32> and use .count(). (This is a case where the language has found a way to portably expose an optimized implementation of popcount through the standard library, in a way that will always compile to something correct, and can take advantage of whatever the target supports.) See also https://en.wikipedia.org/wiki/Hamming_weight#Language_support.

Similarly, ntohl can compile to bswap (x86 32-bit byte swap for endian conversion) on some C implementations that have it.


Another major area for intrinsics or hand-written asm is manual vectorization with SIMD instructions. Compilers are not bad with simple loops like dst[i] += src[i] * 10.0;, but often do badly or don't auto-vectorize at all when things get more complicated. For example, you're unlikely to get anything like How to implement atoi using SIMD? generated automatically by the compiler from scalar code.

Best way to store passwords in MYSQL database

best to use crypt for password storing in DB

example code :

$crypted_pass = crypt($password);

//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
   echo("hello user!")
}

documentation :

http://www.php.net/manual/en/function.crypt.php

How to create a function in a cshtml template?

In ASP.NET Core Razor Pages, you can combine C# and HTML in the function:

@model PagerModel
@{
}

@functions 
{
    void PagerNumber(int pageNumber, int currentPage)
    {
        if (pageNumber == currentPage)
        {
            <span class="page-number-current">@pageNumber</span>
        }
        else
        {
            <a class="page-number-other" href="/table/@pageNumber">@pageNumber</a>
        }
    }
}

<p>@PagerNumber(1,2) @PagerNumber(2,2) @PagerNumber(3,2)</p>

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

FlutterError: Unable to load asset

This is issue has almost driven me nut in the past. To buttress what others have said, after making sure that all the indentations on the yaml file has been corrected and the problem persist, run a 'flutter clean' command at the terminal in Android studio. As at flutter 1.9, this should fix the issue.

How to validate phone numbers using regex

Do a replace on formatting characters, then check the remaining for phone validity. In PHP,

 $replace = array( ' ', '-', '/', '(', ')', ',', '.' ); //etc; as needed
 preg_match( '/1?[0-9]{10}((ext|x)[0-9]{1,4})?/i', str_replace( $replace, '', $phone_num );

Breaking a complex regexp like this can be just as effective, but much more simple.

What is the use of ByteBuffer in Java?

The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:

  • Absolute and relative get and put methods that read and write single bytes;

  • Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;

  • Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;

  • Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;

  • Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and

  • Methods for compacting, duplicating, and slicing a byte buffer.

Example code : Putting Bytes into a buffer.

    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10

    // Use the absolute put(int, byte).
    // This method does not affect the position.
    bbuf.put(0, (byte)0xFF); // position=0

    // Set the position
    bbuf.position(5);

    // Use the relative put(byte)
    bbuf.put((byte)0xFF);

    // Get the new position
    int pos = bbuf.position(); // 6

    // Get remaining byte count
    int rem = bbuf.remaining(); // 4

    // Set the limit
    bbuf.limit(7); // remaining=1

    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

How to exclude particular class name in CSS selector?

One way is to use the multiple class selector (no space as that is the descendant selector):

_x000D_
_x000D_
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
   background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design  reMode_hover">_x000D_
    <span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
 class="reMode_design  reMode_hover reMode_selected">_x000D_
    <span>Design</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

Does "display:none" prevent an image from loading?

Yes it will render faster, slightly, only because it doesn't have to render the image and is one less element to sort on the screen.

If you don't want it loaded, leave a DIV empty where you can load html into it later containing an <img> tag.

Try using firebug or wireshark as I've mentioned before and you'll see that the files DO get transferred even if display:none is present.

Opera is the only browser which will not load the image if the display is set to none. Opera has now moved to webkit and will render all images even if their display is set to none.

Here is a testing page that will prove it:

http://www.quirksmode.org/css/displayimg.html

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

Yes/No message box using QMessageBox

You would use QMessageBox::question for that.

Example in a hypothetical widget's slot:

#include <QApplication>
#include <QMessageBox>
#include <QDebug>

// ...

void MyWidget::someSlot() {
  QMessageBox::StandardButton reply;
  reply = QMessageBox::question(this, "Test", "Quit?",
                                QMessageBox::Yes|QMessageBox::No);
  if (reply == QMessageBox::Yes) {
    qDebug() << "Yes was clicked";
    QApplication::quit();
  } else {
    qDebug() << "Yes was *not* clicked";
  }
}

Should work on Qt 4 and 5, requires QT += widgets on Qt 5, and CONFIG += console on Win32 to see qDebug() output.

See the StandardButton enum to get a list of buttons you can use; the function returns the button that was clicked. You can set a default button with an extra argument (Qt "chooses a suitable default automatically" if you don't or specify QMessageBox::NoButton).

Verifying that a string contains only letters in C#

Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.

Returning a stream from File.OpenRead()

You forgot to seek:

str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);

C++ deprecated conversion from string constant to 'char*'

A reason for this problem (which is even harder to detect than the issue with char* str = "some string" - which others have explained) is when you are using constexpr.

constexpr char* str = "some string";

It seems that it would behave similar to const char* str, and so would not cause a warning, as it occurs before char*, but it instead behaves as char* const str.

Details

Constant pointer, and pointer to a constant. The difference between const char* str, and char* const str can be explained as follows.

  1. const char* str : Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
    1. str++ ; : VALID. We are modifying the pointer, and not the data being pointed to.
    2. *str = 'a'; : INVALID. We are trying to modify the data being pointed to.
  2. char* const str : Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
    1. str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
    2. *str = 'a'; : VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5];.
  3. const char* const str : Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
    1. str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
    2. *str = 'a'; : INVALID. We are trying to modify the data pointed by this pointer, which is also constant.

In my case the issue was that I was expecting constexpr char* str to behave as const char* str, and not char* const str, since visually it seems closer to the former.

Also, the warning generated for constexpr char* str = "some string" is slightly different from char* str = "some string".

  1. Compiler warning for constexpr char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *const'
  2. Compiler warning for char* str = "some string": ISO C++11 does not allow conversion from string literal to 'char *'.

Tip

You can use C gibberish ? English converter to convert C declarations to easily understandable English statements, and vice versa. This is a C only tool, and thus wont support things (like constexpr) which are exclusive to C++.

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

How to get a URL parameter in Express?

This will work if your route looks like this: localhost:8888/p?tagid=1234

var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234

Otherwise use the following code if your route looks like this: localhost:8888/p/1234

var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234

MVC razor form with multiple different submit buttons?

The cleanest solution I've found is as follows:

This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.

In your view:

@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
    if (isOnDli)
    {
        <button name="removeDli" value="@result.WeNo">Remove From DLI</button>
    }
    else
    {
        <button name="performDli" value="@result.WeNo">Perform DLI</button>
    }
}

Then in your action:

    public ActionResult DliAction(string removeDli, string performDli)
    {
        if (string.IsNullOrEmpty(performDli))
        {
            ...
        }
        else if (string.IsNullOrEmpty(removeDli))
        {
            ...
        }

        return View();
    }

This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:

In your view:

@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{

        <button name="weNo" value="@result.WeNo">Process This WeNo</button>

        <button name="weNo" value="@result.WeNo">Process A Different WeNo This Item</button>
}

Then in your action:

    public ActionResult DliAction(string weNo)
    {
        // Process the weNo...

        return View();
    }

How to get the IP address of the server on which my C# application is running on?

Maybe by external IP you can consider (if you are in a Web server context) using this

Request.ServerVariables["LOCAL_ADDR"];

I was asking the same question as you and I found it in this stackoverflow article.

It worked for me.

Oracle error : ORA-00905: Missing keyword

Unless there is a single row in the ASSIGNMENT table and ASSIGNMENT_20081120 is a local PL/SQL variable of type ASSIGNMENT%ROWTYPE, this is not what you want.

Assuming you are trying to create a new table and copy the existing data to that new table

CREATE TABLE assignment_20081120
AS
SELECT *
  FROM assignment

how to check the jdk version used to compile a .class file

You're looking for this on the command line (for a class called MyClass):

On Unix/Linux:

javap -verbose MyClass | grep "major"

On Windows:

javap -verbose MyClass | findstr "major"

You want the major version from the results. Here are some example values:

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51
  • Java 8 uses major version 52
  • Java 9 uses major version 53
  • Java 10 uses major version 54
  • Java 11 uses major version 55

Use jquery to set value of div tag

if your value is a pure text (like 'test') you could use the text() method as well. like this:

$('div.total-title').text('test');

anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:

$(document).ready(
    function() {
        $('div.total-title').text('test');
    }
);

this way the script executes after the HTML of the div is parsed by the browser.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

Your ORDRELINJE table is linked with ORDER table using a foreign key constraint constraint Ordrelinje_fk foreign key(Ordre) references Ordre(OrdreID) according to which Ordre int NOT NULL, column of table ORDRELINJE must match any Ordre int NOT NULL, column of ORDER table.

Now what is happening here is, when you are inserting new row into ORDRELINJE table, according to fk constraint Ordrelinje_fk it is checking ORDER table if the OrdreID is present or not and as it is not matching with any OrderId, Compiler is complaining for foreign key violation. This is the reason you are getting this error.

Foreign key is the primary key of the other table which you use in any table to link between both. This key is bound by the foreign key constraint which you specify while creating the table. Any operation on the data must not violate this constraint. Violation of this constraint may result in errors like this.

Hope I made it clear.

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

Create web service proxy in Visual Studio from a WSDL file

save the file on your disk and then use the following as URL:

file://your_path/your_file.wsdl

How to sort two lists (which reference each other) in the exact same way

You can sort indexes using values as keys:

indexes = range(len(list1))
indexes.sort(key=list1.__getitem__)

To get sorted lists given sorted indexes:

sorted_list1 = map(list1.__getitem__, indexes)
sorted_list2 = map(list2.__getitem__, indexes)

In your case you shouldn't have list1, list2 but rather a single list of pairs:

data = [(3, 'three'), (2, 'two'), (4, 'four'), (1, 'one'), (1, 'one2')]

It is easy to create; it is easy to sort in Python:

data.sort() # sort using a pair as a key

Sort by the first value only:

data.sort(key=lambda pair: pair[0])

How to turn on front flash light programmatically in Android?

You can also use the following code to turn off the flash.

Camera.Parameters params = mCamera.getParameters()
p.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);

show more/Less text with just HTML and JavaScript

Hope this Code you are looking for HTML:

            <div class="showmore">
                <div class="shorten_txt">
                    <h4> #@item.Title</h4>
                    <p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
                </div>
            </div>

SCRIPT:

    var showChar = 100;
    var ellipsestext = "[...]";
    $('.showmore').each(function () {
        $(this).find('.shorten_txt p').addClass('more_p').hide();
        $(this).find('.shorten_txt p:first').removeClass('more_p').show();
        $(this).find('.shorten_txt ul').addClass('more_p').hide();
        //you can do this above with every other element
        var teaser = $(this).find('.shorten_txt p:first').html();
        var con_length = parseInt(teaser.length);
        var c = teaser.substr(0, showChar);
        var h = teaser.substr(showChar, con_length - showChar);
        var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
        '</span></span><span class="morecontent_txt">' + h
        + '</span>';
        if (con_length > showChar) {
            $(this).find(".shorten_txt p:first").html(html);
            $(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
        }
    });
    $(".showmore").click(function () {
        if ($(this).hasClass("less")) {
            $(this).removeClass("less");
        } else {
            $(this).addClass("less");
        }
        $(this).find('.shorten_txt p:first span.moreelipses').toggle();
        $(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
        $(this).find('.shorten_txt .more_p').toggle();
        return false;
    });

Responsive width Facebook Page Plugin

The accepted answer works for me only the first time that page is loaded, but after the browser is resized or I change from landscape to portrait in mobile devices the Facebook Plugin (version 3.2) doesn't adapt to my container. The solution for me was just check the Adapt to plugin container width, and add a listener to know when the page is resized then I remove the facebook iframe and load it again.

window.addEventListener('resize', this.resize);
resize = () => {
    document.querySelector('.fb-page').classList.remove('fb_iframe_widget');
    document.querySelector('.fb-page').classList.remove('fb_iframe_widget_fluid');
    FB.XFBML.parse();
};

By the way, I added a timeout to avoid multiple refreshing while the user is resizing the page, but it's optional

var FB_UPDATE_TIMEOUT = null;

window.addEventListener('resize', this.resize);
resize = () => {
    if(FB_UPDATE_TIMEOUT === null) {
        FB_UPDATE_TIMEOUT = window.setTimeout(function() {
            FB_UPDATE_TIMEOUT = null;
            document.querySelector('.fb-page').classList.remove('fb_iframe_widget');
            document.querySelector('.fb-page').classList.remove('fb_iframe_widget_fluid');
            FB.XFBML.parse();
        }, 100);
    }
};

Demo

SQLite3 database or disk is full / the database disk image is malformed

while using Google App Engine, i had this problem. For some reason i did following since then Google App Engine was never starting.

$ echo '' > /tmp/appengine.apprtc.root/*.db

To fix it i required to do manually:

$ sqlite3 datastore.db
sqlite> begin immediate;
<press CTRL+Z>
$ cp datastore.db logs.db

And then run the Google App Engine with flag:

$ dev_appserver.py --clear_datastore --clear_search_index

after that it finally worked.

How to secure phpMyAdmin

Another solution is to use the config file without any settings. The first time you might have to include your mysql root login/password so it can install all its stuff but then remove it.

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['host'] = 'localhost';

$cfg['Servers'][$i]['connect_type'] = 'tcp';

$cfg['Servers'][$i]['compress'] = false;

$cfg['Servers'][$i]['extension'] = 'mysql';

Leaving it like that without any apache/lighhtpd aliases will just present to you a log in screen. enter image description here

You can log in with root but it is advised to create other users and only allow root for local access. Also remember to use string passwords, even if short but with a capital, and number of special character. for example !34sy2rmbr! aka "easy 2 remember"

-EDIT: A good password now a days is actually something like words that make no grammatical sense but you can remember because they funny. Or use keepass to generate strong randoms an have easy access to them

How do you execute an arbitrary native command from a string?

Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).

http://connect.microsoft.com/PowerShell/feedback/details/376207/

They suggest using --% as a way to force PowerShell to stop trying to interpret the text to the right.

For example:

MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj

How to change screen resolution of Raspberry Pi

As other comments here pointed out, you'll need to uncomment disable_overscan=1 in /boot/config.txt

if you are using NOOBS (this is what im using), you'll find in the end of the file a set of default settings that has disable_overscan=0 attribute. you'll need to change its value to 1, and re-boot.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

Because the second element is null after you clear the list.

Use:

String s = myList.get(0);

And remember, index 0 is the first element.

The role of #ifdef and #ifndef

The code looks strange because the printf are not in any function blocks.

Aborting a stash pop in Git

I solved this in a somewhat different way. Here's what happened.

First, I popped on the wrong branch and got conflicts. The stash remained intact but the index was in conflict resolution, blocking many commands.

A simple git reset HEAD aborted the conflict resolution and left the uncommitted (and UNWANTED) changes.

Several git co <filename> reverted the index to the initial state. Finally, I switched branch with git co <branch-name> and run a new git stash pop, which resolved without conflicts.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

nginx missing sites-available directory

If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available and /etc/nginx/sites-enabled, do the following:

  1. Locate your nginx.conf file. Likely at /etc/nginx/nginx.conf
  2. Find the http block.
  3. Somewhere in the http block, write include /etc/nginx/conf.d/*.conf; This tells nginx to pull in any files in the conf.d directory that end in .conf. (I know: it's weird that a directory can have a . in it.)
  4. Create the conf.d directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data.
  5. Move or copy your separate config files (just like you have in /etc/nginx/sites-available) into the directory conf.d.
  6. Reload or restart nginx.
  7. Eat an ice cream cone.

Any .conf files that you put into the conf.d directory from here on out will become active as long as you reload/restart nginx after.

Note: You can use the conf.d and sites-enabled + sites-available method concurrently if you wish. I like to test on my dev box using conf.d. Feels faster than symlinking and unsymlinking.

ADB Shell Input Events

Also, if you want to send embedded spaces with the input command, use %s

adb shell input text 'this%sis%san%sexample'   

will yield

this is an example

being input.

% itself does not need escaping - only the special %s pair is treated specially. This leads of course to the obvious question of how to enter the literal string %s, which you would have to do with two separate commands.

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

How to get POST data in WebAPI?

Is there a way to handle form post data in a Web Api controller?

The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:

public void Post(NameValueCollection formData)
{
  var value = formData["key"];
}

What is the most robust way to force a UIView to redraw?

I had a problem with a big delay between calling setNeedsDisplay and drawRect: (5 seconds). It turned out I called setNeedsDisplay in a different thread than the main thread. After moving this call to the main thread the delay went away.

Hope this is of some help.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I am running VS 2012, and SQL Server 2008 R2 SP2, Developer Edition. I ended up having to install items from the Microsoft® SQL Server® 2012 Feature Pack. I think that the install instructions noted that these items work for SQL Server 2005 through 2012. I don't know what the exact requirements are to fix this error, but I installed the three items, and the error stopped appearing.

Microsoft® SQL Server® 2012 Feature Pack Items

  • Microsoft® SQL Server® 2012 Shared Management Objects : x86 , x64
  • Microsoft® System CLR Types for Microsoft® SQL Server® 2012 : x86 , x64
  • Microsoft® SQL Server® 2012 Native Client : x86 , x64

Based on threads elsewhere, you may not end up needing the last item or two. Good luck!

How do I get out of 'screen' without typing 'exit'?

In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.

Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".

How do I hide javascript code in a webpage?

It's possible. But it's viewable anyway.

You can make this tool for yourself:

_x000D_
_x000D_
const btn = document.querySelector('.btn');
btn.onclick = textRead;
const copy = document.querySelector('.copy');
copy.onclick = Copy;
const file = document.querySelector('.file');
file.type = 'file';
const pre = document.querySelector('.pre');

var pretxt = pre;

if (pre.innerHTML == "") {
    copy.hidden = true;
}

function textRead() {
    let file = document.querySelector('.file').files[0];
    let read = new FileReader();
    read.addEventListener('load', function(e) {
        let data = e.target.result;
        pre.textContent = data;
    });
    read.readAsDataURL(file);
    copy.hidden = false;
}

function Copy() {
    var text = pre;
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.addRange(range);
    document.execCommand('copy');
    selection.removeAllRanges();
}
_x000D_
<input class="file" />
<br>
<button class="btn">Read File</button>
<pre class="pre"></pre>
<button class="copy">Copy</button>
_x000D_
_x000D_
_x000D_

How to use this tool?

  1. Create a JavaScript file.
  2. Go in the tool and choose your JavaScript file.
  3. Copy result.
  4. Paste the result in Notepad.
  5. Remove data:text/javascript;base64,.
  6. Paste eval(atob('Notepad Text')) to your code and change Notepad Text to your Notepad text result.

How to view this hidden code?

  1. Copy the hidden code and paste it in Notepad.
  2. Copy a string that after eval and atob.
  3. Paste data:text/javascript;base64,String and change String to your copied string.

Hiding table data using <div style="display:none">

you should add style="display:none" in any of <tr> that you want to hide.

Solutions for INSERT OR UPDATE on SQL Server

Doing an if exists ... else ... involves doing two requests minimum (one to check, one to take action). The following approach requires only one where the record exists, two if an insert is required:

DECLARE @RowExists bit
SET @RowExists = 0
UPDATE MyTable SET DataField1 = 'xxx', @RowExists = 1 WHERE Key = 123
IF @RowExists = 0
  INSERT INTO MyTable (Key, DataField1) VALUES (123, 'xxx')

Xampp localhost/dashboard

Wanna a list of folder in xampp?

Just delete or change the file index.php to index.txt. And you will get the list just typing url: localhost.

Browser screenshot

Oracle: Import CSV file

An alternative solution is using an external table: http://www.orafaq.com/node/848

Use this when you have to do this import very often and very fast.

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

I am assuming that you need the JDK itself. If so you can accomplish this with:

sudo add-apt-repository ppa:sun-java-community-team/sun-java6

sudo apt-get update

sudo apt-get install sun-java6-jdk

You don't really need to go around editing sources or anything along those lines.

Removing viewcontrollers from navigation stack

Swift 5, Xcode 11.3

I found this approach simple by specifying which view controller(s) you want to remove from the navigation stack.

extension UINavigationController {

    func removeViewController(_ controller: UIViewController.Type) {
        if let viewController = viewControllers.first(where: { $0.isKind(of: controller.self) }) {
            viewController.removeFromParent()
        }
    }
}

Example use:

navigationController.removeViewController(YourViewController.self)

Silent installation of a MSI package

The proper way to install an MSI silently is via the msiexec.exe command line as follows:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging
 /QN = run completely silently
 /i = run install sequence 

There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

Bulk Insert to Oracle using .NET

I'm loading 50,000 records in 15 or so seconds using Array Binding in ODP.NET

It works by repeatedly invoking a stored procedure you specify (and in which you can do updates/inserts/deletes), but it passes the multiple parameter values from .NET to the database in bulk.

Instead of specifying a single value for each parameter to the stored procedure you specify an array of values for each parameter.

Oracle passes the parameter arrays from .NET to the database in one go, and then repeatedly invokes the stored procedure you specify using the parameter values you specified.

http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html

/Damian

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

How do I launch a program from command line without opening a new cmd window?

You can use the call command...

Type: call /?

Usage: call [drive:][path]filename [batch-parameters]

For example call "Example File/Input File/My Program.bat" [This is also capable with calling files that have a .exe, .cmd, .txt, etc.

NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!

Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...

Interface defining a constructor signature?

Beginning with C# 8.0, an interface member may declare a body. This is called a default implementation. Members with bodies permit the interface to provide a "default" implementation for classes and structs that don't provide an overriding implementation. In addition, beginning with C# 8.0, an interface may include:

Constants Operators Static constructor. Nested types Static fields, methods, properties, indexers, and events Member declarations using the explicit interface implementation syntax. Explicit access modifiers (the default access is public).

How to append rows in a pandas dataframe in a for loop?

Suppose your data looks like this:

import pandas as pd
import numpy as np

np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
    data = dict(zip(np.random.choice(10, replace=False, size=5),
                    np.random.randint(10, size=5)))
    data = pd.DataFrame(data.items())
    data = data.transpose()
    data.columns = data.iloc[0]
    data = data.drop(data.index[[0]])
    df = df.append(data)
print('{}\n'.format(df))
# 0   0   1   2   3   4   5   6   7   8   9
# 1   6 NaN NaN   8   5 NaN NaN   7   0 NaN
# 1 NaN   9   6 NaN   2 NaN   1 NaN NaN   2
# 1 NaN   2   2   1   2 NaN   1 NaN NaN NaN
# 1   6 NaN   6 NaN   4   4   0 NaN NaN NaN
# 1 NaN   9 NaN   9 NaN   7   1   9 NaN NaN

Then it could be replaced with

np.random.seed(2015)
data = []
for i in range(5):
    data.append(dict(zip(np.random.choice(10, replace=False, size=5),
                         np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)

In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data) once at the end, outside the loop.

Each call to df.append requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.

SQL Server: Importing database from .mdf?

Apart from steps mentioned in posted answers by @daniele3004 above, I had to open SSMS as Administrator otherwise it was showing Primary file is read only error.

Go to Start Menu , navigate to SSMS link , right click on the SSMS link , select Run As Administrator. Then perform the above steps.

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

using href links inside <option> tag

Use a real dropdown menu instead: a list (ul, li) and links. Never misuse form elements as links.

Readers with screen readers usually scan through a automagically generated list of links – the’ll miss these important information. Many keyboard navigation systems (e.g. JAWS, Opera) offer different keyboard shortcuts for links and form elements.

If you still cannot drop the idea of a select don’t use the onchange handler at least. This is a real pain for keyboard users, it makes your third item nearly inaccessible.

Node.js – events js 72 throw er unhandled 'error' event

Close nodejs app running in another shell. Restart the terminal and run the program again.


Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port and run the app.

To find the PID of the application that is using port:8000

$ fuser 8000/tcp
8000/tcp:            16708

Here PID is 16708 Now kill the process using the kill [PID] command

$ kill 16708

TortoiseSVN icons not showing up under Windows 7

I found that if you install the 32bit version first it some how mucks up the 64bit version. On reinstalling windows 7 i just installed the 64bit version and it seems to work fine now.

Write lines of text to a file in R

You could do that in a single statement

cat("hello","world",file="output.txt",sep="\n",append=TRUE)

Material UI and Grid system

Below is made by purely MUI Grid system,

MUI - Grid Layout

With the code below,

// MuiGrid.js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
    backgroundColor: "#b5b5b5",
    margin: "10px"
  }
}));

export default function FullWidthGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container spacing={0}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>xs=12</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

↓ CodeSandbox ↓

Edit MUI-Grid system

Select Last Row in the Table

Use Model::where('user_id', $user_id)->latest()->get()->first(); it will return only one record, if not find, it will return null. Hope this will help.

combining two data frames of different lengths

Just my 2 cents. This code combines two matrices or data.frames into one. If one data structure have lower number of rows then missing rows will be added with NA values.

combine.df <- function(x, y) {
    rows.x <- nrow(x)
    rows.y <- nrow(y)
    if (rows.x > rows.y) {
        diff <- rows.x - rows.y
        df.na <- matrix(NA, diff, ncol(y))
        colnames(df.na) <- colnames(y)
        cbind(x, rbind(y, df.na))
    } else {
        diff <- rows.y - rows.x
        df.na <- matrix(NA, diff, ncol(x))
        colnames(df.na) <- colnames(x)
        cbind(rbind(x, df.na), y)
    }
}

df1 <- data.frame(1:10, row.names = 1:10)
df2 <- data.frame(1:5, row.names = 10:14)
combine.df(df1, df2)

ImageButton in Android

android:background="@drawable/eye"

works automatically.

android:src="@drawable/eye"

was what I used with all the problems of resizing the image the the width and height of the button...

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

Why maven? What are the benefits?

Maven can provide benefits for your build process by employing standard conventions and practices to accelerate your development cycle while at the same time helping you achieve a higher rate of success. For a more detailed look at how Maven can help you with your development process please refer to The Benefits of Using Maven.

How Does Modulus Divison Work

modulus division is simply this : divide two numbers and return the remainder only

27 / 16 = 1 with 11 left over, therefore 27 % 16 = 11

ditto 43 / 16 = 2 with 11 left over so 43 % 16 = 11 too

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer 4.0.1.14 surely does support connections to PostgreSQL.

Edit:

If you have different user name and database name, one should specify in hostname: hostname/database? (do not forget ?) or hostname:port/database?.

(thanks to @kinkajou and @Kloe2378231; more details on https://stackoverflow.com/a/28671213/565525).

How to Lock the data in a cell in excel using vba

Sub LockCells()

Range("A1:A1").Select

Selection.Locked = True

Selection.FormulaHidden = False

ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

End Sub

How to get the size of a file in MB (Megabytes)?

     String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
     File file = new File(FILE_NAME);

    if((file.length()) <= (1048576)) {      
        System.out.println("file size is less than 1 mb");
        }else {
            System.out.println("file size is More  than 1 mb");             
        }

Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb

Reorder / reset auto increment primary key

You can remove the primary key auto increment functionality of that column, then every time you update that column run a query before hand that will count all the rows in the table, then run a loop that iterates through that row count inserting each value into the respective row, and finally run a query inserting a new row with the value of that column being the total row count plus one. This will work flawlessly and is the most absolute solution to someone trying to accomplish what you are. Here is an example of code you may use for the function:

$table_row_count = mysql_result(mysql_query("SELECT COUNT(`field_1`) FROM `table`"), 0);
$viewsrowsdata = mysql_query("
    SELECT `rank`, `field1`, `field2`, `field3`, `field4`
        FROM (SELECT (@rank:=@rank+1) as `rank`, `field1`, `field2`, `field3`, `field4`
            FROM (SELECT * FROM `views`) a
            CROSS JOIN (SELECT @rank:=0) b
            ORDER BY rank ASC) c
");
while ($row = mysql_fetch_assoc($viewsrowsdata)) {
    $data[] = $row;
}
foreach ($data as $row) {
    $new_field_1 = (int)$row['rank'];
    $old_field_1 = (int)$row['field1'];
    mysql_query("UPDATE `table` SET `field_1` = $new_field_1 WHERE `field_1` = $old_field_1");
}
mysql_query("INSERT INTO `table` (`field1`, `field2`, `field3`, `field4`) VALUES ('$table_row_count' + 1, '$field_2_value', 'field_3_value', 'field_4_value')");

Here I created an associative array which I had appended on a rank column with the query within a select query, which gave each row a rank value starting with 1. I then iterated through the associative array.

Another option would have been to get the row count, run a basic select query, get the associative array and iterate it through the same way but with an added variable that updates through each iteration. This is less flexible but will accomplish the same thing.

$table_row_count = mysql_result(mysql_query("SELECT COUNT(`field_1`) FROM `table`"), 0);
$viewsrowsdata = mysql_query("SELECT * FROM `table`");
$updated_key = 0;
while ($row = mysql_fetch_assoc($viewsrowsdata)) {
    $data[] = $row;
}
foreach ($data as $row) {
    $updated_key = $updated_key + 1;
    mysql_query("UPDATE `table` SET `field_1` = '$updated_key' WHERE `field_1` = '$row['field_1']'");
}
mysql_query("INSERT INTO `table` (`field1`, `field2`, `field3`, `field4`) VALUES ('$table_row_count' + 1, '$field_2_value', 'field_3_value', 'field_4_value')");

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Here is a bare bones version:

Let's say that you have a date in Cell A1 in the format you described. For example: 19760210.

Then this formula will give you the date you want:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).

On my system (Excel 2010) it works with strings or floats.

jQuery: serialize() form and other parameters

I fix the problem with under statement ; send data with url same GET methode

$.ajax({
    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

I had the same error and I solved it by importing HttpModule in app.module.ts

import { HttpModule } from '@angular/http';

and then in the imports[] array:

HttpModule

How to see top processes sorted by actual memory usage?

How to total up used memory by process name:

Sometimes even looking at the biggest single processes there is still a lot of used memory unaccounted for. To check if there are a lot of the same smaller processes using the memory you can use a command like the following which uses awk to sum up the total memory used by processes of the same name:

ps -e -orss=,args= |awk '{print $1 " " $2 }'| awk '{tot[$2]+=$1;count[$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n

e.g. output

9344 docker 1
9948 nginx: 4
22500 /usr/sbin/NetworkManager 1
24704 sleep 69
26436 /usr/sbin/sshd 15
34828 -bash 19
39268 sshd: 10
58384 /bin/su 28
59876 /bin/ksh 29
73408 /usr/bin/python 2
78176 /usr/bin/dockerd 1
134396 /bin/sh 84
5407132 bin/naughty_small_proc 1432
28061916 /usr/local/jdk/bin/java 7

Expression must have class type

a is a pointer. You need to use->, not .

Distinct() with lambda?

All solutions I've seen here rely on selecting an already comparable field. If one needs to compare in a different way, though, this solution here seems to work generally, for something like:

somedoubles.Distinct(new LambdaComparer<double>((x, y) => Math.Abs(x - y) < double.Epsilon)).Count()

How to establish ssh key pair when "Host key verification failed"

Step1:$Bhargava.ssh#

ssh-keygen -R 199.95.30.220

step2:$Bhargava.ssh #

ssh-copy-id [email protected]

          Enter the the password.........

step3: Bhargava .ssh #

ssh [email protected]

Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-68-generic x86_64) * Documentation: https://help.ubuntu.com/ Ubuntu 14.04.3 LTS server : 228839 ip : 199.95.30.220 hostname : qt.example.com System information as of Thu Mar 24 02:13:43 EDT 2016 System load: 0.67 Processes: 321 Usage of /home: 5.1% of 497.80GB Users logged in: 0 Memory usage: 53% IP address for eth0: 199.95.30.220 Swap usage: 16% IP address for docker0: 172.17.0.1 Graph this data and manage this system at: https://landscape.canonical.com/ Last login: Wed Mar 23 02:07:29 2016 from 103.200.41.50

hostname@qt:~$

How to use Google App Engine with my own naked domain (not subdomain)?

Google does offer naked domain redirection.

  • Login to your google apps account and select "manage this domain"
  • Navigate to Domain settings
  • Within Domain Setings, navigate to Domain names
  • There's a link that says "change the A record". Clicking that will give you the destination IPs for the A records you need to create.

Android TextView Justify Text

UPDATED

We have created a simple class for this. There are currently two methods to achieve what you are looking for. Both require NO WEBVIEW and SUPPORTS SPANNABLES.

LIBRARY: https://github.com/bluejamesbond/TextJustify-Android

SUPPORTS: Android 2.0 to 5.X

SETUP

// Please visit Github for latest setup instructions.

SCREENSHOT

Comparison.png

How to delete an SVN project from SVN repository

In the case where you simply want to delete a project from the head revision, so that it no longer shows up in your repo when you run svn list file:///path/to/repo/ just run:

svn delete file:///path/to/repo/project 

However, if you need to delete all record of it in the repo, use another method.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can parse the string using Html Agility pack and get the InnerText.

    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)");
    string result = htmlDoc.DocumentNode.InnerText;

Applying a single font to an entire website with CSS

*{font-family:Algerian;}

this html worked for me. Added to canvas settings in wordpress.

Looks cool - thanks !

Set environment variables from file of key/value pairs

Modified from @Dan Kowalczyk

I put this in ~/.bashrc.

set -a
. ./.env >/dev/null 2>&1
set +a

Cross-compatible very well with Oh-my-Zsh's dotenv plugin. (There is Oh-my-bash, but it doesn't have dotenv plugin.)

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

I know the question doesn't state SQL Server express, but its worth pointing out that the SQL Server Express editions don't come with the profiler (very annoying), and I suspect that they also don't come with the query analyzer.

npm start error with create-react-app

I might be very late to answer this question but this is what has worked for me and it might help someone to get back on the development track!

nvm install v12.0 // You may need to install nvm, if not already done
rm -rd node_modules/
npm cache clean --force
npm install

Cheers!!

Named placeholders in string formatting

Based on the answer I created MapBuilder class:

public class MapBuilder {

    public static Map<String, Object> build(Object... data) {
        Map<String, Object> result = new LinkedHashMap<>();

        if (data.length % 2 != 0) {
            throw new IllegalArgumentException("Odd number of arguments");
        }

        String key = null;
        Integer step = -1;

        for (Object value : data) {
            step++;
            switch (step % 2) {
                case 0:
                    if (value == null) {
                        throw new IllegalArgumentException("Null key value");
                    }
                    key = (String) value;
                    continue;
                case 1:
                    result.put(key, value);
                    break;
            }
        }

        return result;
    }

}

then I created class StringFormat for String formatting:

public final class StringFormat {

    public static String format(String format, Object... args) {
        Map<String, Object> values = MapBuilder.build(args);

        for (Map.Entry<String, Object> entry : values.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            format = format.replace("$" + key, value.toString());
        }

        return format;
    }

}

which you could use like that:

String bookingDate = StringFormat.format("From $startDate to $endDate"), 
        "$startDate", formattedStartDate, 
        "$endDate", formattedEndDate
);

Replace console output in Python

Added a little bit more functionality to the example of Aravind Voggu:

def progressBar(name, value, endvalue, bar_length = 50, width = 20):
        percent = float(value) / endvalue
        arrow = '-' * int(round(percent*bar_length) - 1) + '>'
        spaces = ' ' * (bar_length - len(arrow))
        sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
                         name, width, arrow + spaces, int(round(percent*100))))
        sys.stdout.flush()
        if value == endvalue:     
             sys.stdout.write('\n\n')

Now you are able to generate multiple progressbars without replacing the previous one.

I've also added name as a value with a fixed width.

For two loops and two times the use of progressBar() the result will look like:

progress bar animation

How to get the CPU Usage in C#?

After spending some time reading over a couple different threads that seemed pretty complicated I came up with this. I needed it for an 8 core machine where I wanted to monitor SQL server. For the code below then I passed in "sqlservr" as appName.

private static void RunTest(string appName)
{
    bool done = false;
    PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
    PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
    while (!done)
    {
        float t = total_cpu.NextValue();
        float p = process_cpu.NextValue();
        Console.WriteLine(String.Format("_Total = {0}  App = {1} {2}%\n", t, p, p / t * 100));
        System.Threading.Thread.Sleep(1000);
    }
}

It seems to correctly measure the % of CPU being used by SQL on my 8 core server.

Renew Provisioning Profile

Unfortunately renewing does not seem to work in my case. My Ad Hoc Distribution Profile is about to expire in 5 days. I got warnings about that on the iPhone and the Xcode Organizer shows a warning sign next to it as well.

In Apple's provisioning portal it was marked as inactive and there was a button to reactivate it. But still with the same expiry date, 5 days from now. Next, I added two more iPhones to it, yet, the changed profile still expires 5 days from now.

Finally, I deleted the profile in the provisioning portal and created a new one from scratch, using a different name, yet this new one still expires on April 13th, 5 days from now!

That is really frustrating! So I guess I have to wait until after it expires and create a new one then.

In case you are wondering if my developer subscription runs out, it is not. I just renewed it in February.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

How to indent a few lines in Markdown markup?

I would use &emsp; is a lot cleaner in my opinion.

How do I compute derivative using Numpy?

You have four options

  1. Finite Differences
  2. Automatic Derivatives
  3. Symbolic Differentiation
  4. Compute derivatives by hand.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2·x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]

Intellij Cannot resolve symbol on import

I faced a similar issue, Mike's comment helped me move in the direction to solve it.
Though the required library was a part of the module in my project too, it needed a change of scope. In the module dependency, I changed the scope to "Compile" rather than "Test" and it works fine for me now.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

For me that issue was due to a bad cast between two activities. I recently moved this method from Activity1 to another 2. Doing so, the refactor left this explicit cast as it was before. So instead of doing

((Activity1) mainActivity).hideDialog();

I was supposed to do

((Activity2) mainActivity).hideDialog();

Note: But this error did not happen on android 8.0 I'm not yet sure why.

*** Hope it helps.

Strip first and last character from C string

To "remove" the 1st character point to the second character:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */

To remove the last character replace it with a '\0'.

p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Try this ...

import sys
buffer = []
while True:
    userinput = sys.stdin.readline().rstrip('\n')
    if userinput == 'quit':
        break
    else:
        buffer.append(userinput)

2D array values C++

The proper way to initialize a multidimensional array in C or C++ is

int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};

You can use this same trick to initialize even higher-dimensional arrays if you want.

Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!

How can I exclude directories from grep -R?

Many correct answers have been given here, but I'm adding this one to emphasize one point which caused some rushed attempts to fail before: exclude-dir takes a pattern, not a path to a directory.

Say your search is:

grep -r myobject

And you notice that your output is cluttered with results from the src/other/objects-folder. This command will not give you the intended result:

grep -r myobject --exclude-dir=src/other/objects-folder

And you may wonder why exclude-dir isn't working! To actually exclude results from the objects-folder, simply do this:

grep -r myobject --exclude-dir=objects-folder

In other words, just use the folder name, not the path. Obvious once you know it.

From the man page:

--exclude-dir=GLOB
Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB.

How to pass a form input value into a JavaScript function

There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.

HTML:

<form>
    <input type="text" id="formValueId" name="valueId"/>
    <input type="button" id="myButton" />
</form>

JavaScript:

$(document).ready(function() {
    $('#myButton').click(function() {
      foo($('#formValueId').val());
    });
});

How to pass props to {this.props.children}

If you have multiple children you want to pass props to, you can do it this way, using the React.Children.map:

render() {
    let updatedChildren = React.Children.map(this.props.children,
        (child) => {
            return React.cloneElement(child, { newProp: newProp });
        });

    return (
        <div>
            { updatedChildren }
        </div>
    );
}

If your component is having just one child, there's no need for mapping, you can just cloneElement straight away:

render() {
    return (
        <div>
            {
                React.cloneElement(this.props.children, {
                    newProp: newProp
                })
            }
        </div>
    );
}

Node/Express file upload

const http          = require('http');
const fs            = require('fs');

// https://www.npmjs.com/package/formidable
const formidable    = require('formidable');

// https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js
const path          = require('path');

router.post('/upload', (req, res) => {
    console.log(req.files);

    let oldpath = req.files.fileUploaded.path;

    // https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js       
    let newpath = path.resolve( `./${req.files.fileUploaded.name}` );

    // copy
    // https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean
    fs.copyFile( oldpath, newpath, (err) => {

        if (err) throw err;

        // delete
        fs.unlink( oldpath, (err) => {

            if (err) throw err;

            console.log('Success uploaded")
        } );                

    } );

});

How to get date, month, year in jQuery UI datepicker?

You can use method getDate():

$('#calendar').datepicker({
    dateFormat: 'yy-m-d',
    inline: true,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate'),
            day  = date.getDate(),  
            month = date.getMonth() + 1,              
            year =  date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

FIDDLE

How to open a link in new tab (chrome) using Selenium WebDriver?

The original poster is asking on how to open a link on a new tab. So this is how I have done it in C#.

        IWebDriver driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("https://microsoft.com");
        IWebElement eventlink = driver.FindElement(By.Id("uhfLogo"));
        Actions action = new Actions(driver);
        action.KeyDown(Keys.Control).MoveToElement(eventlink).Click().Perform(); 

This actually performs a Control+Click on the selected element in order to open the link in a new tab.

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

How to set text color to a text view programmatically

Use,..

Color.parseColor("#bdbdbd");

like,

mTextView.setTextColor(Color.parseColor("#bdbdbd"));

Or if you have defined color code in resource's color.xml file than

(From API >= 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>));

(For API < 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>));

Split a String into an array in Swift?

let fullName : String = "Steve.Jobs"
let fullNameArr : [String] = fullName.components(separatedBy: ".")

var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

How to implement a ViewPager with different Fragments / Layouts

Create new instances in your fragments and do like so in your Activity

 private class SlidePagerAdapter extends FragmentStatePagerAdapter {
    public SlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){
            case 0:
                return Fragment1.newInstance();
            case 1:
                return Fragment2.newInstance();
            case 2:
                return Fragment3.newInstance();
            case 3:
                return Fragment4.newInstance();


            default: break;

        }
        return null;
    }

Set transparent background using ImageMagick and commandline prompt

I had the same problem. In which i have to remove white background from jpg/png image format using ImageMagick.

What worked for me was:

1) Convert image format to png: convert input.jpg input.png

2) convert input.png -fuzz 2% -transparent white output.png

cartesian product in pandas

Minimal code needed for this one. Create a common 'key' to cartesian merge the two:

df1['key'] = 0
df2['key'] = 0

df_cartesian = df1.merge(df2, how='outer')

Show special characters in Unix while using 'less' Command

less will look in its environment to see if there is a variable named LESS

You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less from the comand line, it will find the LESS.

Try adding this

export LESS="-CQaix4"

This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less, just tap the 'h' key and nose around, or run less --help.

Edit:

I looked at the help, and noticed there is also an -r option

-r  -R  ....  --raw-control-chars  --RAW-CONTROL-CHARS
                Output "raw" control characters.

I agree that cat may be the most exact match to your stated needs.

cat -vet file | less

Will add '$' at end of each line and convert tab char to visual '^I'.

cat --help
   (edited)
    -e                       equivalent to -vE
    -E, --show-ends          display $ at end of each line
    -t                       equivalent to -vT
    -T, --show-tabs          display TAB characters as ^I
    -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB

I hope this helps.

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

Simple but usefull way:

$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
        return $query;

Get specific object by id from array of objects in AngularJS

Using ES6 solution

For those still reading this answer, if you are using ES6 the find method was added in arrays. So assuming the same collection, the solution'd be:

const foo = { "results": [
    {
        "id": 12,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] };
foo.results.find(item => item.id === 2)

I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.

Angular solution (old solution)

I aimed to solve this problem by doing the following:

$filter('filter')(foo.results, {id: 1})[0];

A use case example:

app.controller('FooCtrl', ['$filter', function($filter) {
    var foo = { "results": [
        {
            "id": 12,
            "name": "Test"
        },
        {
            "id": 2,
            "name": "Beispiel"
        },
        {
            "id": 3,
            "name": "Sample"
        }
    ] };

    // We filter the array by id, the result is an array
    // so we select the element 0

    single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];

    // If you want to see the result, just check the log
    console.log(single_object);
}]);

Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview

How to show current time in JavaScript in the format HH:MM:SS?

You can do this in Javascript.

var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());

At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.

Check this in JSFiddle

Updates:
For prefixed 0's try

var time = new Date();
console.log(
    ("0" + time.getHours()).slice(-2)   + ":" + 
    ("0" + time.getMinutes()).slice(-2) + ":" + 
    ("0" + time.getSeconds()).slice(-2));

WRONGTYPE Operation against a key holding the wrong kind of value php

This error means that the value indexed by the key "l_messages" is not of type hash, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.

How to check if a column exists before adding it to an existing table in PL/SQL?

All the metadata about the columns in Oracle Database is accessible using one of the following views.

user_tab_cols; -- For all tables owned by the user

all_tab_cols ; -- For all tables accessible to the user

dba_tab_cols; -- For all tables in the Database.

So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..

DECLARE
  v_column_exists number := 0;  
BEGIN
  Select count(*) into v_column_exists
    from user_tab_cols
    where upper(column_name) = 'ADD_TMS'
      and upper(table_name) = 'EMP';
      --and owner = 'SCOTT --*might be required if you are using all/dba views

  if (v_column_exists = 0) then
      execute immediate 'alter table emp add (ADD_TMS date)';
  end if;
end;
/

If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..

If you have file1.sql

alter table t1 add col1 date;
alter table t1 add col2 date;
alter table t1 add col3 date;

And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Passing command line arguments to R CMD BATCH

Here's another way to process command line args, using R CMD BATCH. My approach, which builds on an earlier answer here, lets you specify arguments at the command line and, in your R script, give some or all of them default values.

Here's an R file, which I name test.R:

defaults <- list(a=1, b=c(1,1,1)) ## default values of any arguments we might pass

## parse each command arg, loading it into global environment
for (arg in commandArgs(TRUE))
  eval(parse(text=arg))

## if any variable named in defaults doesn't exist, then create it
## with value from defaults
for (nm in names(defaults))
  assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]))[[1]])

print(a)
print(b)

At the command line, if I type

R CMD BATCH --no-save --no-restore '--args a=2 b=c(2,5,6)' test.R

then within R we'll have a = 2 and b = c(2,5,6). But I could, say, omit b, and add in another argument c:

R CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.R

Then in R we'll have a = 2, b = c(1,1,1) (the default), and c = "hello".

Finally, for convenience we can wrap the R code in a function, as long as we're careful about the environment:

## defaults should be either NULL or a named list
parseCommandArgs <- function(defaults=NULL, envir=globalenv()) {
  for (arg in commandArgs(TRUE))
    eval(parse(text=arg), envir=envir)

  for (nm in names(defaults))
    assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]), envir=envir)[[1]], pos=envir)
}

## example usage:
parseCommandArgs(list(a=1, b=c(1,1,1)))

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

public void Each<T>(IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
        action(item);
}

... and call it thusly:

Each(myList, i => Console.WriteLine(i));

How to show MessageBox on asp.net?

MessageBox doesn't exist in ASP.NET. If you need functionality in the browser, like showing a message box, then you need to opt for javascript. ASP.NET provides you with means to inject javascript which gets rendered and executed when the html sent to the browser's loaded and displayed. You can use the following code in the Page_Load for example:

Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
{
    String cstext = "alert('Hello World');";
    cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}

This sample's taken from MSDN.

How do I post button value to PHP?

Keep in mind that what you're getting in a POST on the server-side is a key-value pair. You have values, but where is your key? In this case, you'll want to set the name attribute of the buttons so that there's a key by which to access the value.

Additionally, in keeping with conventions, you'll want to change the type of these inputs (buttons) to submit so that they post their values to the form properly.

Also, what is your onclick doing?

Core dumped, but core file is not in the current directory?

With the launch of systemd, there's another scenario aswell. By default systemd will store core dumps in its journal, being accessible with the systemd-coredumpctl command. Defined in the core_pattern-file:

$ cat /proc/sys/kernel/core_pattern 
|/usr/lib/systemd/systemd-coredump %p %u %g %s %t %e

This behaviour can be disabled with a simple "hack":

$ ln -s /dev/null /etc/sysctl.d/50-coredump.conf
$ sysctl -w kernel.core_pattern=core      # or just reboot

As always, the size of core dumps has to be equal or higher than the size of the core that is being dumped, as done by for example ulimit -c unlimited.

How can I delete an item from an array in VB.NET?

Seems like this sounds more complicated than it is...

    Dim myArray As String() = TextBox1.Lines
    'First we count how many null elements there are...
    Dim Counter As Integer = 0
    For x = 0 To myArray.Count - 1
        If Len(myArray(x)) < 1 Then
            Counter += 1
        End If
    Next
    'Then we dimension an array to be the size of the last array
    'minus the amount of nulls found...
    Dim tempArr(myArray.Count - Counter) As String

    'Indexing starts at zero, so let's set the stage for that...
    Counter = -1

    For x = 0 To myArray.Count - 1
        'Set the conditions for the new array as in
        'It .contains("word"), has no value, length is less than 1, ect.
        If Len(myArray(x)) > 1 Then
            Counter += 1
            'So if a value is present, we move that value over to
            'the new array.
            tempArr(Counter) = myArray(x)
        End If
    Next

Now you can assign tempArr back to the original or what ever you need done with it as in...

TextBox1.Lines = tempArr (You now have a textbox void of blank lines)

Insert line break in wrapped cell via code

You could also use vbCrLf which corresponds to Chr(13) & Chr(10).

AWS EFS vs EBS vs S3 (differences & when to use?)

EBS is simple - block level storage which can be attached to an instance from same AZ, and can survive irrespective of instance life.

However, interesting difference is between EFS and S3, and to identify proper use cases for it.

Cost: EFS is approximately 10 times costly than S3.

Usecases:

  • Whenever we have thousands of instances who needs to process file simultaneously EFS is recommended over S3.
  • Also note that S3 is object based storage while EFS is file based it implies that whenever we have requirement that files are updated continuously (refreshed) we should use EFS.
  • S3 is eventually consistent while EFS is strong consistent. In case you can't afford eventual consistency, you should use EFS

How to clear or stop timeInterval in angularjs?

    $scope.toggleRightDelayed = function(){
        var myInterval = $interval(function(){
            $scope.toggleRight();
        },1000,1)
        .then(function(){
            $interval.cancel(myInterval);
        });
    };

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.

class NormalizeData:

    def __init__(self, element):
        self.element = element

    def execute(self):
        if isinstance(self.element, dict):
            self.__iterate()
        else:
            return

    def __iterate(self):
        for key in self.element:
            if isinstance(self.element[key], <ClassName>):
                self.element[key] = str(self.element[key])

            node = NormalizeData(self.element[key])
            node.execute()

Get Application Directory

For current Android application package:

public String getDataDir(Context context) throws Exception {
    return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
}

For any package:

public String getAnyDataDir(Context context, String packageName) throws Exception {
    return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.dataDir;
}

Add a tooltip to a div

Here's a nice jQuery Tooltip:

https://jqueryui.com/tooltip/

To implement this, just follow these steps:

  1. Add this code in your <head></head> tags:

    <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>    
    <script type="text/javascript">
    $("[title]").tooltip();
    </script> 
    <style type="text/css"> 
    
    /* tooltip styling. by default the element to be styled is .tooltip  */
    .tooltip {
        display:none;
        background:transparent url(https://dl.dropboxusercontent.com/u/25819920/tooltip/black_arrow.png);
        font-size:12px;
        height:70px;
        width:160px;
        padding:25px;
        color:#fff;
    }
    </style> 
    
  2. On the HTML elements that you want to have the tooltip, just add a title attribute to it. Whatever text is in the title attribute will be in the tooltip.

Note: When JavaScript is disabled, it will fallback to the default browser/operating system tooltip.

How to capture a JFrame's close button click event?

Try this:

setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

It will work.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

EDIT 2

After three months we can say: no more official Google Apps in Genymotion and CyanogenMod-like method is only way to get Google Apps. However, you can still use the previous project of the Genymotion team: AndroVM (download mirror).


EDIT

Google apps will be removed from Genymotion in November. You can find more information on the Genymotion Google Plus page.


Choose virtual device with Google Apps:

Done:

How to hide TabPage from TabControl

+1 for microsoft :-) .
I managed to do it this way:
(it assumes you have a Next button that displays the next TabPage - tabSteps is the name of the Tab control)
At start up, save all the tabpages in a proper list.
When user presses Next button, remove all the TabPages in the tab control, then add that with the proper index:

int step = -1;
List<TabPage> savedTabPages;

private void FMain_Load(object sender, EventArgs e) {
    // save all tabpages in the list
    savedTabPages = new List<TabPage>();
    foreach (TabPage tp in tabSteps.TabPages) {
        savedTabPages.Add(tp);
    }
    SelectNextStep();
}

private void SelectNextStep() {
    step++;
    // remove all tabs
    for (int i = tabSteps.TabPages.Count - 1; i >= 0 ; i--) {
            tabSteps.TabPages.Remove(tabSteps.TabPages[i]);
    }

    // add required tab
    tabSteps.TabPages.Add(savedTabPages[step]);
}

private void btnNext_Click(object sender, EventArgs e) {
    SelectNextStep();
}

Update

public class TabControlHelper {
    private TabControl tc;
    private List<TabPage> pages;
    public TabControlHelper(TabControl tabControl) {
        tc = tabControl;
        pages = new List<TabPage>();
        foreach (TabPage p in tc.TabPages) {
            pages.Add(p);
        }
    }

    public void HideAllPages() {
        foreach(TabPage p in pages) {
            tc.TabPages.Remove(p);
        }
    }

    public void ShowAllPages() {
        foreach (TabPage p in pages) {
            tc.TabPages.Add(p);
        }
    }

    public void HidePage(TabPage tp) {
        tc.TabPages.Remove(tp);
    }        

    public void ShowPage(TabPage tp) {
        tc.TabPages.Add(tp);
    }
}  

My Routes are Returning a 404, How can I Fix Them?

If you're using Vagrant though Homestead, it's possible there was an error mounting the shared folder. It looks like Vagrant takes your files from that folder and swaps out the files that are actually on the host machine on boot, so if there was an error, you're essentially trying to access your Laravel installation from when you first made it (which is why you're only getting "home"- that was generated during installation).

You can easily check this by sshing into your vm and checking the routes/web.php file to see if it's actually your file. If it isn't, exit out and vagrant halt, vagrant up, and look for errors on boot.

What is a wrapper class?

I currently used a wrapper class for my project and the main benefits I get (just a single benefit to widen the topic explanation):

Exception handling: My main class ,that another class wraps, has methods that are throwing exceptions if occurs any, so I created a wrapper class that handles the exceptions and logs them immediately. So, in my main scope, there is no exception handling. I just call a method and do something.

Easy Usage: I can easily initiate the object. Normally initiating phase is constructed of a lot of steps.

Code Readability: When another programmer opens my code, the code will seem very clear and easy to manipulate.

Hiding the Details: If you are generating a class that another programmer is going to use, then you can wrap the details like "error handling, exception handling, logging messages and etc..." so that the programmer will not be have to handle the chaos, just simply uses the methods.

Is it not possible to define multiple constructors in Python?

Jack M. is right. Do it this way:

>>> class City:
...     def __init__(self, city=None):
...         self.city = city
...     def __repr__(self):
...         if self.city:  return self.city
...         return ''
...
>>> c = City('Berlin')
>>> print c
Berlin
>>> c = City()
>>> print c

>>>

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

How do I validate a date in this format (yyyy-mm-dd) using jquery?

Just use Date constructor to compare with string input:

_x000D_
_x000D_
function isDate(str) {_x000D_
  return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
_x000D_
_x000D_

Edited: Responding to one of the comments

Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal

_x000D_
_x000D_
function pad(n) {_x000D_
  return (10 > n ? ('0' + n) : (n));_x000D_
}_x000D_
_x000D_
function isDate(str) {_x000D_
  if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {_x000D_
    return false;_x000D_
  }_x000D_
  var dt = new Date(str.replace(/\-/g, '/'));_x000D_
  return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
_x000D_
_x000D_

How to find a number in a string using JavaScript?

// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

output will be 15

If You want to learn more about regex here are some links:

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

Rename Excel Sheet with VBA Macro

Suggest you add handling to test if any of the sheets to be renamed already exist:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub

DevTools failed to load SourceMap: Could not load content for chrome-extension

I resolved this by clearing App Data.

Cypress documentation admits that App Data can get corrupted:

Cypress maintains some local application data in order to save user preferences and more quickly start up. Sometimes this data can become corrupted. You may fix an issue you have by clearing this app data.

  1. Open Cypress via cypress open
  2. Go to File -> View App Data
  3. This will take you to the directory in your file system where your App Data is stored. If you cannot open Cypress, search your file system for a directory named cy whose content should look something like this:

       production
            all.log
            browsers
            bundles
            cache
            projects
            proxy
            state.json

  1. Delete everything in the cy folder
  2. Close Cypress and open it up again

Source: https://docs.cypress.io/guides/references/troubleshooting.html#To-clear-App-Data

How to combine date from one field with time from another field - MS SQL Server

Another way is to use CONCATand CAST, be aware, that you need to use DATETIME2(x) to make it work. You can set x to anything between 0-7 7 meaning no precision loss.

DECLARE @date date = '2018-03-12'
DECLARE @time time = '07:00:00.0000000'
SELECT CAST(CONCAT(@date, ' ', @time) AS DATETIME2(7))

Returns 2018-03-12 07:00:00.0000000

Tested on SQL Server 14

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Java: get all variable names in a class

As mentioned by few users, below code can help find all the fields in a given class.

TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
    String name=method.getName();
    if(name.startsWith("get"))
    {
        System.out.println(name.substring(3));
    }else if(name.startsWith("is"))
    {
        System.out.println(name.substring(2));
    }
}

However a more interesting approach is below:

With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)

TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();

Map<String,Object> props = m.convertValue(testObject, Map.class);

for(Map.Entry<String, Object> entry : props.entrySet()){
    if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
}

How to test the `Mosquitto` server?

In separate terminal windows do the following:

  1. Start the broker:

    mosquitto
    
  2. Start the command line subscriber:

    mosquitto_sub -v -t 'test/topic'
    
  3. Publish test message with the command line publisher:

    mosquitto_pub -t 'test/topic' -m 'helloWorld'
    

As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:

test/topic helloWorld

How to convert a List<String> into a comma separated string without iterating List explicitly

import com.google.common.base.Joiner;

Joiner.on(",").join(ids);

or you can use StringUtils:

   public static String join(Object[] array,
                              char separator)

   public static String join(Iterable<?> iterator,
                              char separator)

Joins the elements of the provided array/iterable into a single String containing the provided list of elements.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

Repeat a task with a time delay?

Timer works fine. Here, I use Timer to search text after 1.5s and update UI. Hope that helps.

private Timer _timer = new Timer();

_timer.schedule(new TimerTask() {
    @Override
    public void run() {
        // use runOnUiThread(Runnable action)
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                search();
            }
        });
    }
}, timeInterval);

React Error: Target Container is not a DOM Element

Also make sure id set in index.html is same as the one you referring to in index.js

index.html:

<body> 
    <div id="root"></div>
    <script src="/bundle.js"></script>
</body>

index.js:

ReactDOM.render(<App/>,document.getElementById('root'));

How to convert a Date to a formatted string in VB.net?

You can use the ToString overload. Have a look at this page for more info

So just Use myDate.ToString("yyyy-MM-dd HH:mm:ss")

or something equivalent

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

Populating a ComboBox using C#

Define a class

public class Language
{
     public string Name { get; set; }
     public string Value { get; set; }
}

then...

//Build a list
var dataSource = new List<Language>();
dataSource.Add(new Language() { Name = "blah", Value = "blah" });
dataSource.Add(new Language() { Name = "blah", Value = "blah" });
dataSource.Add(new Language() { Name = "blah", Value = "blah" });

//Setup data binding
this.comboBox1.DataSource = dataSource;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Value";

// make it readonly
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

How to open html file?

Use codecs.open with the encoding parameter.

import codecs
f = codecs.open("test.html", 'r', 'utf-8')

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

make image( not background img) in div repeat?

Not with CSS you can't. You need to use JS. A quick example copying the img to the background:

var $el = document.getElementById( 'rightflower' )
  , $img = $el.getElementsByTagName( 'img' )[0]
  , src  = $img.src

$el.innerHTML = "";
$el.style.background = "url( " + src + " ) repeat-y;"

Or you can actually repeat the image, but how many times?

var $el = document.getElementById( 'rightflower' )
  , str = ""
  , imgHTML = $el.innerHTML
  , i, i2;
for( i=0,i2=10; i<i2; i++ ){
    str += imgHTML;
}
$el.innerHTML = str;

How to write to an existing excel file without overwriting data (using pandas)?

Starting in pandas 0.24 you can simplify this with the mode keyword argument of ExcelWriter:

import pandas as pd

with pd.ExcelWriter('the_file.xlsx', engine='openpyxl', mode='a') as writer: 
     data_filtered.to_excel(writer) 

Detecting when a div's height changes using jQuery

Pretty basic but works:

function dynamicHeight() {
    var height = jQuery('').height();
    jQuery('.edito-wrapper').css('height', editoHeight);
}
editoHeightSize();

jQuery(window).resize(function () {
    editoHeightSize();
});

Oracle database: How to read a BLOB?

If you're interested to get the plaintext (body part) from a BLOB, you could use the CTX_DOC package.

For example, the CTX_DOC.FILTER procedure can "generate either a plain text or a HTML version of a document". Be aware that CTX_DOC.FILTER requires an index on the BLOB column. If you don't want that, you could use the CTX_DOC.POLICY_FILTER procedure instead, which doesn't require an index.

What to gitignore from the .idea folder?

For a couple of years I was a supporter of using a specific .gitignore for IntelliJ with this suggested configuration.

Not anymore.

IntelliJ is updated quite frequently, internal config file specs change more often than I would like and JetBrains flagship excels at auto-configuring itself based on maven/gradle/etc build files.

So my suggestion would be to leave all editor config files out of project and have users configure editor to their liking. Things like code styling can and should be configured at build level; say using Google Code Style or CheckStyle directly on Maven/Gradle/sbt/etc.

This ensures consistency and leaves editor files out of source code that, in my personal opinion, is where they should be.

How can I reverse a list in Python?

You can also use the bitwise complement of the array index to step through the array in reverse:

>>> array = [0, 10, 20, 40]
>>> [array[~i] for i, _ in enumerate(array)]
[40, 20, 10, 0]

Whatever you do, don't do it this way ;)

Find package name for Android apps to use Intent to launch Market app from web

It depends where exactly you want to get the information from. You have a bunch of options:

  • If you have a copy of the .apk, it's just a case of opening it as a zip file and looking at the AndroidManifest.xml file. The top level <manifest> element will have a package attribute.
  • If you have the app installed on a device and can connect using adb, you can launch adb shell and execute pm list packages -f, which shows the package name for each installed apk.
  • If you just want to manually find a couple of package names, you can search for the app on http://www.cyrket.com/m/android/, and the package name is shown in the URL
  • You can also do it progmatically from an Android app using the PackageManager

Once you've got the package name, you simply link to market://search?q=pname:<package_name> or http://market.android.com/search?q=pname:<package_name>. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Javascript Iframe innerHTML

You can get html out of an iframe using this code iframe = document.getElementById('frame'); innerHtml = iframe.contentDocument.documentElement.innerHTML

javascript remove "disabled" attribute from html input

Best answer is just removeAttribute

element.removeAttribute("disabled");

Hide/Show Action Bar Option Menu Item for different fragments

MenuItem Import = menu.findItem(R.id.Import);
  Import.setVisible(false)

How to find MySQL process list and to kill those processes?

You can do something like this to check if any mysql process is running or not:

ps aux | grep mysqld
ps aux | grep mysql

Then if it is running you can killall by using(depending on what all processes are running currently):

killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe    

what is trailing whitespace and how can I handle this?

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.

WebView and HTML5 <video>

I had a similar problem. I had HTML files and videos in the assets-folder of my app.

Therefore the videos were located inside of the APK. Because the APK is really a ZIP-file, the WebView was not able to read the video-files.

Copying all HTML- and video-files onto the SD-Card worked for me.

How can I get the UUID of my Android phone in an application?

Add

  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Method

String getUUID(){
    TelephonyManager teleManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    String tmSerial = teleManager.getSimSerialNumber();
    String tmDeviceId = teleManager.getDeviceId();
    String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
    if (tmSerial  == null) tmSerial   = "1";
    if (tmDeviceId== null) tmDeviceId = "1";
    if (androidId == null) androidId  = "1";
    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDeviceId.hashCode() << 32) | tmSerial.hashCode());
    String uniqueId = deviceUuid.toString();
    return uniqueId;
}