Programs & Examples On #Semantic web

Representation of database record subjects (a/k/a keys, IDs, entities), predicates (a/k/a columns, attributes), and objects (a/k/a values) as triples, where the first two are always URIs, and the third is either a URI or a literal; enabling humans and machines to more easily share, merge, and evaluate data from heterogeneous origins.

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Nonatomic

Nonatomic will not generate threadsafe routines thru @synthesize accessors. atomic will generate threadsafe accessors so atomic variables are threadsafe (can be accessed from multiple threads without botching of data)

Copy

copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Assign

Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)

Retain

retain is required when the attribute is a pointer to a reference counted object that was allocated on the heap. Allocation should look something like:

NSObject* obj = [[NSObject alloc] init]; // ref counted var

The setter generated by @synthesize will add a reference count to the object when it is copied so the underlying object is not autodestroyed if the original copy goes out of scope.

You will need to release the object when you are finished with it. @propertys using retain will increase the reference count and occupy memory in the autorelease pool.

Strong

strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.

This is a good website to learn about strong and weak for iOS 5. http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1

Weak

weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.

The above link contain both Good information regarding Weak and Strong.

What is the easiest way to initialize a std::vector with hardcoded elements?

A more recent duplicate question has this answer by Viktor Sehr. For me, it is compact, visually appealing (looks like you are 'shoving' the values in), doesn't require c++11 or a third party module, and avoids using an extra (written) variable. Below is how I am using it with a few changes. I may switch to extending the function of vector and/or va_arg in the future intead.


// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
public:
    typedef mkvec<T> my_type;
    my_type& operator<< (const T& val) {
        data_.push_back(val);
        return *this;
    }
    my_type& operator<< (const std::vector<T>& inVector) {
        this->data_.reserve(this->data_.size() + inVector.size());
        this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
        return *this;
    }
    operator std::vector<T>() const {
        return data_;
    }
private:
    std::vector<T> data_;
};

std::vector<int32_t>    vec1;
std::vector<int32_t>    vec2;

vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;  
// vec1 = (5,8,19,79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;  
// vec2 = (1,2,3,5,8,19,79,10,11,12)

How can I add a space in between two outputs?

code:

class Main
{
    public static void main(String[] args)  
    {
        int a=10, b=20;
        System.out.println(a + " " + b);
    }
}

Input: none

Output: 10 20

jquery - disable click

I used .prop('disabled', true) and it worked like a charm, no redefining, simple.

Had to time it out by 125ms as it interfered with the prop from Bootstrap Dropdown.

How do I programmatically click on an element in JavaScript?

I used KooiInc's function listed above but I had to use two different input types one 'button' for IE and one 'submit' for FireFox. I am not exactly sure why but it works.

// HTML

<input type="button" id="btnEmailHidden" style="display:none" />
<input type="submit" id="btnEmailHidden2" style="display:none" />

// in JavaScript

var hiddenBtn = document.getElementById("btnEmailHidden");

if (hiddenBtn.fireEvent) {
    hiddenBtn.fireEvent('onclick');
    hiddenBtn[eType]();
}
else {
    // dispatch for firefox + others
    var evObj = document.createEvent('MouseEvent');
    evObj.initEvent(eType, true, true);
    var hiddenBtn2 = document.getElementById("btnEmailHidden2");
    hiddenBtn2.dispatchEvent(evObj);
}

I have search and tried many suggestions but this is what ended up working. If I had some more time I would have liked to investigate why submit works with FF and button with IE but that would be a luxury right now so on to the next problem.

pthread function from a class

This is a bit old question but a very common issue which many face. Following is a simple and elegant way to handle this by using std::thread

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

class foo
{
    public:
        void bar(int j)
        {
            n = j;
            for (int i = 0; i < 5; ++i) {
                std::cout << "Child thread executing\n";
                ++n;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
        int n = 0;
};

int main()
{
    int n = 5;
    foo f;
    std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    std::cout << "Main Thread running as usual";
    class_thread.join();
    std::cout << "Final value of foo::n is " << f.n << '\n';
}

Above code also takes care of passing argument to the thread function.

Refer std::thread document for more details.

How to debug heap corruption errors?

To really slow things down and perform a lot of runtime checking, try adding the following at the top of your main() or equivalent in Microsoft Visual Studio C++

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF );

Unlink of file Failed. Should I try again?

After none of the above answers seemed to work, running git fetch -p did the job for me.

https://git-scm.com/docs/git-fetch

Bootstrap 4 responsive tables won't take up 100% width

None of these answers are working (date today 9th Dec 2018). The correct resolution here is to add .table-responsive-sm to your table:

<table class='table table-responsive-sm'>
[Your table]
</table>

This applies the responsiveness aspect only to the SM view (mobile). So in mobile view you get the scrolling as desired and in larger views the table is not responsive and thus displayed full width, as desired.

Docs: https://getbootstrap.com/docs/4.0/content/tables/#breakpoint-specific

open the file upload dialogue box onclick the image

Include input type="file" element on your HTML page and on the click event of your button trigger the click event of input type file element using trigger function of jQuery

The code will look like:

<input type="file" id="imgupload" style="display:none"/> 
<button id="OpenImgUpload">Image Upload</button>

And on the button's click event write the jQuery code like :

$('#OpenImgUpload').click(function(){ $('#imgupload').trigger('click'); });

This will open File Upload Dialog box on your button click event..

how to take user input in Array using java?

package userinput;

import java.util.Scanner;

public class USERINPUT {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //allow user  input;
        System.out.println("How many numbers do you want to enter?");
        int num = input.nextInt();

        int array[] = new int[num];

        System.out.println("Enter the " + num + " numbers now.");

        for (int i = 0 ; i < array.length; i++ ) {
           array[i] = input.nextInt();
        }

        //you notice that now the elements have been stored in the array .. array[]

        System.out.println("These are the numbers you have entered.");
        printArray(array);

        input.close();

    }

    //this method prints the elements in an array......
    //if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
    public static void printArray(int arr[]){

        int n = arr.length;

        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }

}

Function to convert timestamp to human date in javascript

To calculate date in timestamp from the given date

//To get the timestamp date from normal date: In format - 1560105000000

//input date can be in format : "2019-06-09T18:30:00.000Z"

this.calculateDateInTimestamp = function (inputDate) {
    var date = new Date(inputDate);
    return date.getTime();
}

output : 1560018600000

SHA1 vs md5 vs SHA256: which to use for a PHP login?

Use SHA256. It is not perfect, as SHA512 would be ideal for a fast hash, but out of the options, its the definite choice. As per any hashing technology, be sure to salt the hash for added security.

As an added note, FRKT, please show me where someone can easily crack a salted SHA256 hash? I am truly very interested to see this.

Important Edit:

Moving forward please use bcrypt as a hardened hash. More information can be found here.


Edit on Salting:

Use a random number, or random byte stream etc. You can use the unique field of the record in your database as the salt too, this way the salt is different per user.

How to run batch file from network share without "UNC path are not supported" message?

My env windows10 2019 lts version and I add this two binray data ,fix this error

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor DisableUNCCheck value 1 Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Command Processor DisableUNCCheck value 1

Find the line number where a specific word appears with "grep"

Use grep -n to get the line number of a match.

I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

sed -n '10,$ { /regex/ { =; p; } }' file

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'

Or you could simply use sed:

sed -n '/regex/=' file

Combining the two sed commands, you get:

sed -n '10,$ { /regex/= }' file

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

When should I use GET or POST method? What's the difference between them?

Get and Post methods have nothing to do with the server technology you are using, it works the same in php, asp.net or ruby. GET and POST are part of HTTP protocol. As mark noted, POST is more secure. POST forms are also not cached by the browser. POST is also used to transfer large quantities of data.

Unable to resolve host "<insert URL here>" No address associated with hostname

Please, check if you have valid internet connection.

Insert array into MySQL database with PHP

Personally I'd json_encode the array (taking into account any escaping etc needed) and bung the entire lot into an appropriately sized text/blob field.

It makes it very easy to store "unstructured" data but a real PITA to search/index on with any grace.

A simple json_decode will "explode" the data back into an array for you.

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

Where can I find Android source code online?

Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.

Contacts is here for example.

Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.

To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.

And others:

How to change the status bar background color and text color on iOS 7?

iTroid23 solution worked for me. I missed the Swift solution. So maybe this is helpful:

1) In my plist I had to add this:

<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>

2) I didn't need to call "setNeedsStatusBarAppearanceUpdate".

3) In swift I had to add this to my UIViewController:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

How to overcome the CORS issue in ReactJS

the simplest way what I found from a tutorial of "TraversyMedia" is that just use https://cors-anywhere.herokuapp.com in 'axios' or 'fetch' api

https://cors-anywhere.herokuapp.com/{type_your_url_here} 

e.g.

axios.get(`https://cors-anywhere.herokuapp.com/https://www.api.com/`)

and in your case edit url as

url: 'https://cors-anywhere.herokuapp.com/https://www.api.com',

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

TL;DR;
Unicode - (nchar, nvarchar, and ntext)
Non-unicode - (char, varchar, and text).

From MSDN

Collations in SQL Server provide sorting rules, case, and accent sensitivity properties for your data. Collations that are used with character data types such as char and varchar dictate the code page and corresponding characters that can be represented for that data type.

Assuming you are using default SQL collation SQL_Latin1_General_CP1_CI_AS then following script should print out all the symbols that you can fit in VARCHAR since it uses one byte to store one character (256 total) if you don't see it on the list printed - you need NVARCHAR.

declare @i int = 0;
while (@i < 256)
begin
print cast(@i as varchar(3)) + '  '+  char(@i)  collate SQL_Latin1_General_CP1_CI_AS 
print cast(@i as varchar(3)) + '  '+ char(@i)  collate Japanese_90_CI_AS  
set @i = @i+1;
end

If you change collation to lets say japanese you will notice that all the weird European letters turned into normal and some symbols into ? marks.

Unicode is a standard for mapping code points to characters. Because it is designed to cover all the characters of all the languages of the world, there is no need for different code pages to handle different sets of characters. If you store character data that reflects multiple languages, always use Unicode data types (nchar, nvarchar, and ntext) instead of the non-Unicode data types (char, varchar, and text).

Otherwise your sorting will go weird.

Can HTML checkboxes be set to readonly?

You could always use a small image that looks like a check box.

CSS: 100% width or height while keeping aspect ratio?

If you only define one dimension on an image the image aspect ratio will always be preserved.

Is the issue that the image is bigger/taller than you prefer?

You could put it inside a DIV that is set to the maximum height/width that you want for the image, and then set overflow:hidden. That would crop anything beyond what you want.

If an image is 100% wide and height:auto and you think it's too tall, that is specifically because the aspect ratio is preserved. You'll need to crop, or to change the aspect ratio.

Please provide some more information about what you're specifically trying to accomplish and I'll try to help more!

--- EDIT BASED ON FEEDBACK ---

Are you familiar with the max-width and max-height properties? You could always set those instead. If you don't set any minimum and you set a max height and width then your image will not be distorted (aspect ratio will be preserved) and it will not be any larger than whichever dimension is longest and hits its max.

Search for string within text column in MySQL

When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:

   $Table_Name    = $wpdb->prefix.'tablename';
   $SearchField = '%'. $YourVariable . '%';   
   $sql_query     = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
 $rows = $wpdb->get_results($sql_query, ARRAY_A);

Is there a color code for transparent in HTML?

All you need is this:

#ffffff00

Here the ffffff is the color and 00 is the transparency

Also, if you want 50% transparent color, then sure you can do... #ffffff80

Where 80 is the hexadecimal equivalent of 50%. Since the scale is 0-255 in RGB Colors, the half would be 255/2 = 128, which when converted to hex becomes 80

And since in transparent we want 0 opacity, we write 00

uncaught syntaxerror unexpected token U JSON

The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined)!

It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.

import web3 from './web3';
import xyz from './build/xyz.json';

const i = new web3.eth.Contract(
  JSON.parse(xyz.interface),
  '0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5'
);

export default i;

which was misspelled as

JSON.parse(xyz.intereface)

which was returning nothing!

How do I read the first line of a file using cat?

There is plenty of good answer to this question. Just gonna drop another one into the basket if you wish to do it with lolcat

lolcat FileName.csv | head -n 1

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

Resize font-size according to div size

Here's a SCSS version of @Patrick's mixin.

$mqIterations: 19;
@mixin fontResize($iterations)
{
  $i: 1;
  @while $i <= $iterations
  {
    @media all and (min-width: 100px * $i) {
      body { font-size:0.2em * $i; }
    }
    $i: $i + 1;
  }
}
@include fontResize($mqIterations);

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome's developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finder or Firebug.

How to create range in Swift?

I created the following extension:

extension String {
    func substring(from from:Int, to:Int) -> String? {
        if from<to && from>=0 && to<self.characters.count {
            let rng = self.startIndex.advancedBy(from)..<self.startIndex.advancedBy(to)
            return self.substringWithRange(rng)
        } else {
            return nil
        }
    }
}

example of use:

print("abcde".substring(from: 1, to: 10)) //nil
print("abcde".substring(from: 2, to: 4))  //Optional("cd")
print("abcde".substring(from: 1, to: 0))  //nil
print("abcde".substring(from: 1, to: 1))  //nil
print("abcde".substring(from: -1, to: 1)) //nil

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

I also think it's absolutely not necessary to start hacking OS X.

I was able to solve it doing a

brew install python

It seems that using the python / pip that comes with new El Capitan has some issues.

adding multiple event listeners to one element

Unless your do_something function actually does something with any given arguments, you can just pass it as the event handler.

var first = document.getElementById('first');
first.addEventListener('touchstart', do_something, false);
first.addEventListener('click', do_something, false);

Getting multiple keys of specified value of a generic Dictionary?

Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had

var greek = new Dictionary<int, string> { { 1, "Alpha" }, { 2, "Alpha" } };

What would you expect to get for greek.WhatDoIPutHere("Alpha")?

Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or IEnumerable<T>)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?

Personally I'd go for an enumerable, like so:

IEnumerable<TKey> KeysFromValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue val)
{
    if (dict == null)
    {
        throw new ArgumentNullException("dict");
    }
    return dict.Keys.Where(k => dict[k] == val);
}

var keys = greek.KeysFromValue("Beta");
int exceptionIfNotExactlyOne = greek.KeysFromValue("Beta").Single();

Generating (pseudo)random alpha-numeric strings

public function randomString($length = 8)
{
    $characters = implode([
        'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
        'abcdefghijklmnoprqstuwvxyz',
        '0123456789',
        //'!@#$%^&*?'
    ]);

    $charactersLength = strlen($characters) - 1;
    $string           = '';

    while ($length) {
        $string .= $characters[mt_rand(0, $charactersLength)];
        --$length;
    }

    return $string;
}

Picking a random element from a set

In C#

        Random random = new Random((int)DateTime.Now.Ticks);

        OrderedDictionary od = new OrderedDictionary();

        od.Add("abc", 1);
        od.Add("def", 2);
        od.Add("ghi", 3);
        od.Add("jkl", 4);


        int randomIndex = random.Next(od.Count);

        Console.WriteLine(od[randomIndex]);

        // Can access via index or key value:
        Console.WriteLine(od[1]);
        Console.WriteLine(od["def"]);

ANTLR: Is there a simple example?

At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4

is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:

  1. parser grammar
  2. lexer grammar
  3. imported LexBasic grammar

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.

Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin

https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr

contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.

Difference between $(this) and event.target?

this is a reference for the DOM element for which the event is being handled (the current target). event.target refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.

You can get a good sense of this by reviewing the jQuery event docs, but in summary:

event.currentTarget

The current DOM element within the event bubbling phase.

event.delegateTarget

The element where the currently-called jQuery event handler was attached.

event.relatedTarget

The other DOM element involved in the event, if any.

event.target

The DOM element that initiated the event.

To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this) or $(evt.target).

The .attr() method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href') or simply evt.target.href will give you what you want.

How unique is UUID?

Here's a testing snippet for you to test it's uniquenes. inspired by @scalabl3's comment

Funny thing is, you could generate 2 in a row that were identical, of course at mind-boggling levels of coincidence, luck and divine intervention, yet despite the unfathomable odds, it's still possible! :D Yes, it won't happen. just saying for the amusement of thinking about that moment when you created a duplicate! Screenshot video! – scalabl3 Oct 20 '15 at 19:11

If you feel lucky, check the checkbox, it only checks the currently generated id's. If you wish a history check, leave it unchecked. Please note, you might run out of ram at some point if you leave it unchecked. I tried to make it cpu friendly so you can abort quickly when needed, just hit the run snippet button again or leave the page.

_x000D_
_x000D_
Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }_x000D_
  Math.trueRandom = (function() {_x000D_
  var crypt = window.crypto || window.msCrypto;_x000D_
_x000D_
  if (crypt && crypt.getRandomValues) {_x000D_
      // if we have a crypto library, use it_x000D_
      var random = function(min, max) {_x000D_
          var rval = 0;_x000D_
          var range = max - min;_x000D_
          if (range < 2) {_x000D_
              return min;_x000D_
          }_x000D_
_x000D_
          var bits_needed = Math.ceil(Math.log2(range));_x000D_
          if (bits_needed > 53) {_x000D_
            throw new Exception("We cannot generate numbers larger than 53 bits.");_x000D_
          }_x000D_
          var bytes_needed = Math.ceil(bits_needed / 8);_x000D_
          var mask = Math.pow(2, bits_needed) - 1;_x000D_
          // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111_x000D_
_x000D_
          // Create byte array and fill with N random numbers_x000D_
          var byteArray = new Uint8Array(bytes_needed);_x000D_
          crypt.getRandomValues(byteArray);_x000D_
_x000D_
          var p = (bytes_needed - 1) * 8;_x000D_
          for(var i = 0; i < bytes_needed; i++ ) {_x000D_
              rval += byteArray[i] * Math.pow(2, p);_x000D_
              p -= 8;_x000D_
          }_x000D_
_x000D_
          // Use & to apply the mask and reduce the number of recursive lookups_x000D_
          rval = rval & mask;_x000D_
_x000D_
          if (rval >= range) {_x000D_
              // Integer out of acceptable range_x000D_
              return random(min, max);_x000D_
          }_x000D_
          // Return an integer that falls within the range_x000D_
          return min + rval;_x000D_
      }_x000D_
      return function() {_x000D_
          var r = random(0, 1000000000) / 1000000000;_x000D_
          return r;_x000D_
      };_x000D_
  } else {_x000D_
      // From http://baagoe.com/en/RandomMusings/javascript/_x000D_
      // Johannes Baagøe <[email protected]>, 2010_x000D_
      function Mash() {_x000D_
          var n = 0xefc8249d;_x000D_
_x000D_
          var mash = function(data) {_x000D_
              data = data.toString();_x000D_
              for (var i = 0; i < data.length; i++) {_x000D_
                  n += data.charCodeAt(i);_x000D_
                  var h = 0.02519603282416938 * n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  h *= n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  n += h * 0x100000000; // 2^32_x000D_
              }_x000D_
              return (n >>> 0) * 2.3283064365386963e-10; // 2^-32_x000D_
          };_x000D_
_x000D_
          mash.version = 'Mash 0.9';_x000D_
          return mash;_x000D_
      }_x000D_
_x000D_
      // From http://baagoe.com/en/RandomMusings/javascript/_x000D_
      function Alea() {_x000D_
          return (function(args) {_x000D_
              // Johannes Baagøe <[email protected]>, 2010_x000D_
              var s0 = 0;_x000D_
              var s1 = 0;_x000D_
              var s2 = 0;_x000D_
              var c = 1;_x000D_
_x000D_
              if (args.length == 0) {_x000D_
                  args = [+new Date()];_x000D_
              }_x000D_
              var mash = Mash();_x000D_
              s0 = mash(' ');_x000D_
              s1 = mash(' ');_x000D_
              s2 = mash(' ');_x000D_
_x000D_
              for (var i = 0; i < args.length; i++) {_x000D_
                  s0 -= mash(args[i]);_x000D_
                  if (s0 < 0) {_x000D_
                      s0 += 1;_x000D_
                  }_x000D_
                  s1 -= mash(args[i]);_x000D_
                  if (s1 < 0) {_x000D_
                      s1 += 1;_x000D_
                  }_x000D_
                  s2 -= mash(args[i]);_x000D_
                  if (s2 < 0) {_x000D_
                      s2 += 1;_x000D_
                  }_x000D_
              }_x000D_
              mash = null;_x000D_
_x000D_
              var random = function() {_x000D_
                  var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32_x000D_
                  s0 = s1;_x000D_
                  s1 = s2;_x000D_
                  return s2 = t - (c = t | 0);_x000D_
              };_x000D_
              random.uint32 = function() {_x000D_
                  return random() * 0x100000000; // 2^32_x000D_
              };_x000D_
              random.fract53 = function() {_x000D_
                  return random() +_x000D_
                      (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53_x000D_
              };_x000D_
              random.version = 'Alea 0.9';_x000D_
              random.args = args;_x000D_
              return random;_x000D_
_x000D_
          }(Array.prototype.slice.call(arguments)));_x000D_
      };_x000D_
      return Alea();_x000D_
  }_x000D_
}());_x000D_
_x000D_
Math.guid = function() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)    {_x000D_
      var r = Math.trueRandom() * 16 | 0,_x000D_
          v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
  });_x000D_
};_x000D_
function logit(item1, item2) {_x000D_
    console.log("Do "+item1+" and "+item2+" equal? "+(item1 == item2 ? "OMG! take a screenshot and you'll be epic on the world of cryptography, buy a lottery ticket now!":"No they do not. shame. no fame")+ ", runs: "+window.numberofRuns);_x000D_
}_x000D_
numberofRuns = 0;_x000D_
function test() {_x000D_
   window.numberofRuns++;_x000D_
   var x = Math.guid();_x000D_
   var y = Math.guid();_x000D_
   var test = x == y || historyTest(x,y);_x000D_
_x000D_
   logit(x,y);_x000D_
   return test;_x000D_
_x000D_
}_x000D_
historyArr = [];_x000D_
historyCount = 0;_x000D_
function historyTest(item1, item2) {_x000D_
    if(window.luckyDog) {_x000D_
       return false;_x000D_
    }_x000D_
    for(var i = historyCount; i > -1; i--) {_x000D_
        logit(item1,window.historyArr[i]);_x000D_
        if(item1 == history[i]) {_x000D_
            _x000D_
            return true;_x000D_
        }_x000D_
        logit(item2,window.historyArr[i]);_x000D_
        if(item2 == history[i]) {_x000D_
            _x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    }_x000D_
    window.historyArr.push(item1);_x000D_
    window.historyArr.push(item2);_x000D_
    window.historyCount+=2;_x000D_
    return false;_x000D_
}_x000D_
luckyDog = false;_x000D_
document.body.onload = function() {_x000D_
document.getElementById('runit').onclick  = function() {_x000D_
window.luckyDog = document.getElementById('lucky').checked;_x000D_
var val = document.getElementById('input').value_x000D_
if(val.trim() == '0') {_x000D_
    var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         if(test) {_x000D_
            window.clearInterval(intervaltimer);_x000D_
         }_x000D_
    },0);_x000D_
}_x000D_
else {_x000D_
   var num = parseInt(val);_x000D_
   if(num > 0) {_x000D_
        var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         num--;_x000D_
         if(num < 0 || test) {_x000D_
    _x000D_
         window.clearInterval(intervaltimer);_x000D_
         }_x000D_
    },0);_x000D_
   }_x000D_
}_x000D_
};_x000D_
};
_x000D_
Please input how often the calulation should run. set to 0 for forever. Check the checkbox if you feel lucky.<BR/>_x000D_
<input type="text" value="0" id="input"><input type="checkbox" id="lucky"><button id="runit">Run</button><BR/>
_x000D_
_x000D_
_x000D_

jQuery rotate/transform

Why not just use, toggleClass on click?

js:

$(this).toggleClass("up");

css:

button.up {
    -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
        -ms-transform: rotate(180deg);
         -o-transform: rotate(180deg);
            transform: rotate(180deg);
               /* IE6–IE9 */
               filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
                 zoom: 1;
    }

you can also add this to the css:

button{
        -webkit-transition: all 500ms ease-in-out;
        -moz-transition: all 500ms ease-in-out;
        -o-transition: all 500ms ease-in-out;
        -ms-transition: all 500ms ease-in-out;
}

which will add the animation.

PS...

to answer your original question:

you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:

<script type="text/javascript">
    $(function() {
     var $elie = $("#bkgimg");
     rotate(0);
     function rotate(degree) {

      // For webkit browsers: e.g. Chrome
    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});


    /* add a condition here for the extremity */ 
    if(degree < 180){
      // Animate rotation with a recursive call
      setTimeout(function() { rotate(++degree); },65);
     }
    }
    });
    </script>

Can Python test the membership of multiple values in a list?

[x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]

The reason I think this is better than the chosen answer is that you really don't need to call the 'all()' function. Empty list evaluates to False in IF statements, non-empty list evaluates to True.

if [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]:
    ...Do something...

Example:

>>> [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
['a', 'b']
>>> [x for x in ['G','F'] if x in ['b', 'a', 'foo', 'bar']]
[]

Unable to create migrations after upgrading to ASP.NET Core 2.0

I was facing the error

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."

This is how my problem was solved. Run the below command while you are in your solution directory

 dotnet ef migrations add InitialMigration --project "Blog.Infrastructure" --startup-project "Blog.Appication"

Here Application is my startup project containing the Startup.cs class & Infrastructure is my project containing the DbContext class.

then run update using the same structure.

dotnet ef database update --project "Blog.Infrastructure" --startup-project "Blog.Application"

jQuery get values of checked checkboxes into array

You need to add .toArray() to the end of your .map() function

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

Demo: http://jsfiddle.net/sZQtL/

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

Checkboxes in web pages – how to make them bigger?

Try this CSS

input[type=checkbox] {width:100px; height:100px;}

Eclipse: Enable autocomplete / content assist

If you would like to use autocomplete all the time without having to worry about hitting Ctrl + Spacebar or your own keyboard shortcut, you can make the following adjustment in the Eclipse preferences to trigger autocomplete simply by typing several different characters:

  1. Eclipse > Preferences > Java > Editor > Content Assist
  2. Auto Activation > Auto activation triggers for Java
  3. Enter all the characters you want to trigger autocomplete, such as the following:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._

Now any time that you type any of these characters, Eclipse will trigger autocomplete suggestions based on the context.

What is an attribute in Java?

A class contains data field descriptions (or properties, fields, data members, attributes), i.e., field types and names, that will be associated with either per-instance or per-class state variables at program run time.

Using Font Awesome icon for bullet points, with a single list item element

@Tama, you may want to check this answer: Using Font Awesome icons as bullets

Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.

In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:

<ul>
  <li>...</li>
  <li>...</li>
  <li>...</li>
</ul>

Thanks.

Laravel 5 How to switch from Production mode

Do not forget to run the command php artisan config:clear after you have made the changes to the .env file. Done this again php artisan env, which will return the correct version.

Flask SQLAlchemy query, specify column names

session.query().with_entities(SomeModel.col1)

is the same as

session.query(SomeModel.col1)

for alias, we can use .label()

session.query(SomeModel.col1.label('some alias name'))

Excel VBA Run-time error '13' Type mismatch

Diogo

Justin has given you some very fine tips :)

You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code

Sheets("Sheet1").Range("A1").Value - 1

I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

Option Explicit

Sub Sample()
  Dim ws As Worksheet
  Dim x As Integer, i As Integer, a As Integer, y As Integer
  Dim name As String
  Dim lastRow As Long
10        On Error GoTo Whoa

20        Application.ScreenUpdating = False

30        name = InputBox("Please insert the name of the sheet")

40        If Len(Trim(name)) = 0 Then Exit Sub

50        Set ws = Sheets(name)

60        With ws
70            If Not IsError(.Range("BE4").Value) Then
80                x = Val(.Range("BE4").Value)
90            Else
100               MsgBox "Please check the value of cell BE4. It seems to have an error"
110               GoTo LetsContinue
120           End If

130           .Range("BF4").Value = x

140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row

150           For i = 5 To lastRow
160               If IsError(.Range("BE" & i)) Then
170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180                   GoTo LetsContinue
190               End If

200               a = 0: y = Val(.Range("BE" & i))
210               If y <> x Then
220                   If y <> 0 Then
230                       If y = 3 Then
240                           a = x
250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x

260                           x = Val(.Range("BE" & i)) - x
270                       End If
280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
290                       x = Val(.Range("BE" & i)) - a
300                   Else
310                       .Range("BF" & i).ClearContents
320                   End If
330               Else
340                   .Range("BF" & i).ClearContents
350               End If
360           Next i
370       End With

LetsContinue:
380       Application.ScreenUpdating = True
390       Exit Sub
Whoa:
400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
         "Error at line     : " & Erl
410       Resume LetsContinue
End Sub

Convert from java.util.date to JodaTime

http://joda-time.sourceforge.net/quickstart.html

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

How to cherry-pick multiple commits

git format-patch --full-index --binary --stdout range... | git am -3

How to export query result to csv in Oracle SQL Developer?

CSV Export does not escape your data. Watch out for strings which end in \ because the resulting \" will look like an escaped " and not a \. Then you have the wrong number of " and your entire row is broken.

How to prevent Browser cache on Angular 2 site?

You can control client cache with HTTP headers. This works in any web framework.

You can set the directives these headers to have fine grained control over how and when to enable|disable cache:

  • Cache-Control
  • Surrogate-Control
  • Expires
  • ETag (very good one)
  • Pragma (if you want to support old browsers)

Good caching is good, but very complex, in all computer systems. Take a look at https://helmetjs.github.io/docs/nocache/#the-headers for more information.

How do I float a div to the center?

if you are using width and height, you should try margin-right: 45%;... it is 100% working for me.. so i can take it to anywhere with percentage!

What is the best way to implement nested dictionaries?

I like the idea of wrapping this in a class and implementing __getitem__ and __setitem__ such that they implemented a simple query language:

>>> d['new jersey/mercer county/plumbers'] = 3
>>> d['new jersey/mercer county/programmers'] = 81
>>> d['new jersey/mercer county/programmers']
81
>>> d['new jersey/mercer country']
<view which implicitly adds 'new jersey/mercer county' to queries/mutations>

If you wanted to get fancy you could also implement something like:

>>> d['*/*/programmers']
<view which would contain 'programmers' entries>

but mostly I think such a thing would be really fun to implement :D

Find and kill a process in one line using bash and regex

if you have pkill,

pkill -f csp_build.py

If you only want to grep against the process name (instead of the full argument list) then leave off -f.

Grid of responsive squares

Now we can easily do this using the aspect-ratio ref property

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

Also like below where we can have a variable number of columns

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

How to prevent robots from automatically filling up a form?

With increasingly sophisticated spam bots and techniques like automated browsers, it will become harder to determine the source of spam. But whether posted by software, a human, or both, spam is spam because of its content. I think the best solution is to run the posted content through an anti-spam API like Cleantalk or Akismet. It's relatively cheap and effective and doesn't hassle the user. You can check form submission times and the other traditional checks for less sophisticated bots before hitting the API.

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

how to get right offset of an element? - jQuery

Maybe I'm misunderstanding your question, but the offset is supposed to give you two variables: a horizontal and a vertical. This defines the position of the element. So what you're looking for is:

$("#whatever").offset().left

and

$("#whatever").offset().top

If you need to know where the right boundary of your element is, then you should use:

$("#whatever").offset().left + $("#whatever").outerWidth()

PowerShell Connect to FTP server and get files

Remote pick directory path should be the exact path on the ftp server you are tryng to access.. here is the script to download files from the server.. you can add or modify with SSLMode..

#ftp server 
$ftp = "ftp://example.com/" 
$user = "XX" 
$pass = "XXX"
$SetType = "bin"  
$remotePickupDir = Get-ChildItem 'c:\test' -recurse
$webclient = New-Object System.Net.WebClient 

$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  
foreach($item in $remotePickupDir){ 
    $uri = New-Object System.Uri($ftp+$item.Name) 
    #$webclient.UploadFile($uri,$item.FullName)
    $webclient.DownloadFile($uri,$item.FullName)
}

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Simply remove the server in Eclipse and add tomcat server again. than shutdown the tomcat in tomcat/bin/shutdown.bat file and start the server in eclipse.

What is path of JDK on Mac ?

The location has changed from Java 6 (provided by Apple) to Java 7 and onwards (provided by Oracle). The best generic way to find this out is to run

/usr/libexec/java_home

This is the natively supported way to find out both the path to the default Java installation as well as all alternative ones present.

If you check out its help text (java_home -h), you'll see that you can use this command to reliably start a Java program on OS X (java_home --exec ...), with the ability to explicitly specify the desired Java version and architecture, or even request the user to install it if missing.

A more pedestrian approach, but one which will help you trace specifically which Java installation the command java resolves into, goes like this:

  1. run

    which java
    
  2. if that gives you something like /usr/bin/java, which is a symbolic link to the real location, run

    ls -l `which java`
    

    On my system, this outputs

    /usr/bin/java -> /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java
    

    and therefrom you can read the Java home directory;

  3. if usr/bin/java points to another symbolic link, recursively apply the same approach with

    ls -l <whatever the /usr/bin/java symlink points to>
    

An important variation is the setup you get if you start by installing Apple's Java and later install Oracle's. In that case Step 2 above will give you

/usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Commands/java

and that particular java binary is a stub which will resolve the actual java command to call by consulting the JAVA_HOME environment variable and, if it's not set or doesn't point to a Java home directory, will fall back to calling java_home. It is important to have this in mind when debugging your setup.

What are these attributes: `aria-labelledby` and `aria-hidden`

aria-hidden="true" will hide decorative items like glyphicon icons from screen readers, which doesn't have meaningful pronunciation so as not to cause confusions. It's a nice thing do as matter of good practice.

Laravel: Auth::user()->id trying to get a property of a non-object

Check your route for the function in which you are using Auth::user(), For getting Auth::user() data the function should be inside web middleware Route::group(['middleware' => 'web'], function () {}); .

How do I convert a decimal to an int in C#?

System.Decimal implements the IConvertable interface, which has a ToInt32() member.

Does calling System.Decimal.ToInt32() work for you?

Box-Shadow on the left side of the element only

You probably need more blur and a little less spread.

box-shadow: -10px 0px 10px 1px #aaaaaa;

Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.

How to check that a string is parseable to a double?

Something like below should suffice :-

String decimalPattern = "([0-9]*)\\.([0-9]*)";  
String number="20.00";  
boolean match = Pattern.matches(decimalPattern, number);
System.out.println(match); //if true then decimal else not  

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

You need to restart VirtualBox service you can do it with this:

sudo /Library/StartupItems/VirtualBox/VirtualBox restart

If in this path is empty you can use:

sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart

After I use Parallels I always need to do it.

Jquery .on('scroll') not firing the event while scrolling

Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?

Then you can use:

$('#ulId').on('scroll',function(){ console.log('Event Fired'); })

obviously replacing ulId with whatever the actual id of the scrollable div is.

Then set css display: block; on the #ulId (or containing div) upon load?

How do I test if a string is empty in Objective-C?

if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

Hidden features of Windows batch files

For loops with numeric counters (outputs 1 through 10):

for /l %i in (1,1,10) do echo %i

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

After further reading, and confirmation from Linus G Thiel above, I found I simply had to,

  • Downgrade to Node.js 0.6.12
  • And either,
    • Install Mocha as global
    • Add ./node_modules/.bin to my PATH

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

HTML.ActionLink vs Url.Action in ASP.NET Razor

You can easily present Html.ActionLink as a button by using the appropriate CSS style. For example:

@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })

Get attribute name value of <input>

For the below line, Initially faced problem with out giving single code that 'currnetRowAppName'value is not taking space with string. So, after that giving single code '"+row.applicationName+"', its taking space also.

Example:

<button class='btn btn-primary btn-xs appDelete' type='button' currnetRowAppName='"+row.applicationName+"' id="+row.id+ >

var viewAppNAME = $(this).attr("currnetRowAppName");
alert(viewAppNAME)

This is working fine.

Convert List<String> to List<Integer> directly

Why don't you use stream to convert List of Strings to List of integers? like below

List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
            "50", "60", "70"));
List<Integer> integerList = stringList.stream()
            .map(Integer::valueOf).collect(Collectors.toList());

complete operation could be something like this

String s = "AttributeGet:1,16,10106,10111";
List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
    Arrays.asList(s.replace("AttributeGet:", "").split(","))
    .stream().map(Integer::valueOf).collect(Collectors.toList())
    : new ArrayList<Integer>();

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

How to programmatically empty browser cache?

You can now use Cache.delete()

Example:

let id = "your-cache-id";
// you can find the id by going to 
// application>storage>cache storage 
// (minus the page url at the end)
// in your chrome developer console 

caches.open(id)
.then(cache => cache.keys()
  .then(keys => {
    for (let key of keys) {
      cache.delete(key)
    }
  }));

Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.

Get the year from specified date php

You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there

$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
     if(strlen($parts[$i]) == 4)
     {
          $year = $parts[$i];
          break;
      }
  }

Can I set background image and opacity in the same property?

You can use CSS psuedo selector ::after to achieve this. Here is a working demo.

enter image description here

_x000D_
_x000D_
.bg-container{_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  border: 1px solid #000;_x000D_
  position: relative;_x000D_
}_x000D_
.bg-container .content{_x000D_
  position: absolute;_x000D_
  z-index:999;_x000D_
  text-align: center;_x000D_
  width: 100%;_x000D_
}_x000D_
.bg-container::after{_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index:-99;_x000D_
  background-image: url(https://i.stack.imgur.com/Hp53k.jpg);_x000D_
  background-size: cover;_x000D_
  opacity: 0.4;_x000D_
}
_x000D_
<div class="bg-container">_x000D_
   <div class="content">_x000D_
     <h1>Background Opacity 0.4</h1>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to disable or enable viewpager swiping in android

If you want to extend it just because you need Not-Swipeable behaviour, you dont need to do it. ViewPager2 provides nice property called : isUserInputEnabled

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

Where are Docker images stored on the host machine?

I couldn't resolve the question with Docker version 18.09 on macos using the above answers and tried again.

The only actual solution for me was using this docker-compose.yml configuration:

version: '3.7'
...
  services:
    demo-service:
      volumes:
        - data-volume:/var/tmp/container-volume

volumes:
  data-volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /tmp/host-volume

After launching with docker-compose up I finally had /tmp/host-volume from macos shared as writeable volume from within the container:

> docker exec -it 1234 /bin/bash
bash-4.4$ df
Filesystem           1K-blocks      Used Available Use% Mounted on
...
osxfs                488347692 464780044  21836472  96% /var/tmp/container-volume

Hope this helps others too.

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

What does OpenCV's cvWaitKey( ) function do?

waits milliseconds to check if the key is pressed, if pressed in that interval return its ascii value, otherwise it still -1

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

you could use the following for different locales

private void localeDecimalInput(final EditText editText){

    DecimalFormat decFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
    DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
    final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());

    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(editable.toString().contains(defaultSeperator))
                editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
            else
                editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
        }
    });
}

How to change color of Android ListView separator line?

For a single color line use:

list.setDivider(new ColorDrawable(0x99F10529));   //0xAARRGGBB
list.setDividerHeight(1);

It's important that DividerHeight is set after the divider, else you won't get anything.

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

Vue template or render function not defined yet I am using neither?

Make sure you import the .vue extension explicitly like so:

import myComponent from './my/component/my-component.vue';

If you don't add the .vue and you have a .ts file with the same name in that directory, for example, if you're separating the js/ts from the template and linking it like this inside of my-component.vue:

<script lang="ts" src="./my-component.ts"></script>

... then the import will bring in the .ts by default and so there really is no template or render function defined because it didn't import the .vue template.

When you tell it to use .vue in the import, then it finds your template right away.

Setting background-image using jQuery CSS property

The problem I was having, is that I kept adding a semi-colon ; at the end of the url() value, which prevented the code from working.

? NOT WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');

? WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');

Notice the omitted semi-colon ; at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.

Excel - match data from one range to another and get the value from the cell to the right of the matched data

I have added the following on my excel sheet

=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)

Still doesn't seem to work. I get an #N/A
BUT

=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)

Works

How can I do a case insensitive string comparison?

I'd like to write an extension method for EqualsIgnoreCase

public static class StringExtensions
{
    public static bool? EqualsIgnoreCase(this string strA, string strB)
    {
        return strA?.Equals(strB, StringComparison.CurrentCultureIgnoreCase);
    }
}

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

I solve this problem with a "using" block

using (SqlConnection conn = new SqlConnection(connectionString))

    {

       // stuff to do with data base
    }

    // or if you are using entity framework 
    using (DataBaseEntity data = new DataBaseEntity)
{

    }

Here is where I get the idea https://social.msdn.microsoft.com/Forums/sqlserver/es-ES/b4b350ba-b0d5-464d-8656-8c117d55b2af/problema-al-modificar-en-entity-framework?forum=vcses is in spanish (look for the second answer)

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The === operator is called a strict comparison operator, it does differ from the == operator.

Lets take 2 vars a and b.

For "a == b" to evaluate to true a and b need to be the same value.

In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.

Take the following example

var a = 1;
var b = "1";

if (a == b) //evaluates to true as a and b are both 1
{
    alert("a == b");
}

if (a === b) //evaluates to false as a is not the same type as b
{
    alert("a === b");
}

In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.

In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.

How to get old Value with onchange() event in text box

Maybe you can store the previous value of the textbox into a hidden textbox. Then you can get the first value from hidden and the last value from textbox itself. An alternative related to this, at onfocus event of your textbox set the value of your textbox to an hidden field and at onchange event read the previous value.

What's the difference between a temp table and table variable in SQL Server?

Differences between Temporary Tables (##temp/#temp) and Table Variables (@table) are as:

  1. Table variable (@table) is created in the memory. Whereas, a Temporary table (##temp/#temp) is created in the tempdb database. However, if there is a memory pressure the pages belonging to a table variable may be pushed to tempdb.

  2. Table variables cannot be involved in transactions, logging or locking. This makes @table faster then #temp. So table variable is faster then temporary table.

  3. Temporary table allows Schema modifications unlike Table variables.

  4. Temporary tables are visible in the created routine and also in the child routines. Whereas, Table variables are only visible in the created routine.

  5. Temporary tables are allowed CREATE INDEXes whereas, Table variables aren’t allowed CREATE INDEX instead they can have index by using Primary Key or Unique Constraint.

What is "Advanced" SQL?

Performance tuning, creating indices, stored procedures, etc.

"Advanced" means something different to everyone. I'd imagine this type of thing means something different to every job-poster.

Table is marked as crashed and should be repaired

Connect to your server via SSH

then connect to your mysql console

and

USE user_base
REPAIR TABLE TABLE;

-OR-

If there are a lot of broken tables in current database:

mysqlcheck -uUSER -pPASSWORD  --repair --extended user_base

If there are a lot of broken tables in a lot of databases:

mysqlcheck -uUSER -pPASSWORD  --repair --extended -A

Yes or No confirm box using jQuery

_x000D_
_x000D_
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
  $('<div></div>').appendTo('body')_x000D_
    .html('<div><h6>' + message + '?</h6></div>')_x000D_
    .dialog({_x000D_
      modal: true,_x000D_
      title: 'Delete message',_x000D_
      zIndex: 10000,_x000D_
      autoOpen: true,_x000D_
      width: 'auto',_x000D_
      resizable: false,_x000D_
      buttons: {_x000D_
        Yes: function() {_x000D_
          // $(obj).removeAttr('onclick');                                _x000D_
          // $(obj).parents('.Parent').remove();_x000D_
_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        },_x000D_
        No: function() {_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        }_x000D_
      },_x000D_
      close: function(event, ui) {_x000D_
        $(this).remove();_x000D_
      }_x000D_
    });_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
_x000D_
_x000D_

git clone: Authentication failed for <URL>

Rather than escape my password I left it out and was prompted for it, but only when I included the domain name before my username:

git clone https://some-dom-name\[email protected]/tfs/...

Reset MySQL root password using ALTER USER statement after install on Mac

If you started mysql using mysql -u root -p

Try ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

Source: http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

Local file access with JavaScript

There is a (commercial) product, "localFS" which can be used to read and write entire file-system on client computer.

Small Windows app must be installed and tiny .js file included in your page.

As a security feature, file-system access can be limited to one folder and protected with a secret-key.

https://www.fathsoft.com/localfs

Laravel 5.4 create model, controller and migration in single artisan command

You don't need to add --resource flag just type the following and laravel will create the whole desired resources

 php artisan make:controller TodoController --model=todo

How do I move an existing Git submodule within a Git repository?

The trick seems to be understanding that the .git directory for submodules are now kept in the master repository, under .git/modules, and each submodule has a .git file that points to it. This is the procedure you need now:

  • Move the submodule to its new home.
  • Edit the .git file in the submodule's working directory, and modify the path it contains so that it points to the right directory in the master repository's .git/modules directory.
  • Enter the master repository's .git/modules directory, and find the directory corresponding to your submodule.
  • Edit the config file, updating the worktree path so that it points to the new location of the submodule's working directory.
  • Edit the .gitmodules file in the root of the master repository, updating the path to the working directory of the submodule.
  • git add -u
  • git add <parent-of-new-submodule-directory> (It's important that you add the parent, and not the submodule directory itself.)

A few notes:

  • The [submodule "submodule-name"] lines in .gitmodules and .git/config must match each other, but don't correspond to anything else.
  • The submodule working directory and .git directory must correctly point to each other.
  • The .gitmodules and .git/config files should be synchronised.

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

How can I declare a Boolean parameter in SQL statement?

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

How to add double quotes to a string that is inside a variable?

If you want to add double quotes to a string that contains dynamic values also. For the same in place of CodeId[i] and CodeName[i] you can put your dynamic values.

data = "Test ID=" + "\"" + CodeId[i] + "\"" + " Name=" + "\"" + CodeName[i] + "\"" + " Type=\"Test\";

Random Number Between 2 Double Numbers

Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:

public static class RandomExtensions
{
    public static double NextDouble(
        this Random random,
        double minValue,
        double maxValue)
    {
        return random.NextDouble() * (maxValue - minValue) + minValue;
    }
}

Now you can call it as if it were a method on the Random class:

Random random = new Random();
double value = random.NextDouble(1.23, 5.34);

Note that you should not create lots of new Random objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance of Random and re-use it.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

  • I've been facing the same issue for days. I did installed OLEDB drivers for 64 bit, tried out 32 bit also which are available at microsoft website.
  • I tried to reinstall office 64bit version also somehow it didn't work. Tried Allowing 32bit application in IIS pool true.
  • Tried Changing project environment to X86, AnyMachine, Mixed. And almost tried all the patch that i could find on internet. But all solution disappointed me.
  • Although i finally came to know that the provider which we were downloading was latest and was not working with it either.
  • I uninstalled it and installed oledb drivers 14.0.7015.1000 .I dont have the link for it as i got it from company resources , you might have to google it but it works. I came on this DOWNLOAD LINK of microsoft and it worked too... however it is version 14.0.6119.5000 but it worked.

Automatically running a batch file as an administrator

CMD Itself does not have a function to run files as admin, but powershell does, and that powershell function can be exectuted through CMD with a certain command. Write it in command prompt to run the file you specified as admin.

powershell -command start-process -file yourfilename -verb runas

Hope it helped!

How to use SVN, Branch? Tag? Trunk?

I asked myself the same questions when we came to implement Subversion here -- about 20 developers spread across 4 - 6 projects. I didn't find any one good source with ''the answer''. Here are some parts of how our answer has developed over the last 3 years:

-- commit as often as is useful; our rule of thumb is commit whenever you have done sufficient work that it would be a problem having to re-do it if the modifications got lost; sometimes I commit every 15 minutes or so, other times it might be days (yes, sometimes it takes me a day to write 1 line of code)

-- we use branches, as one of your earlier answers suggested, for different development paths; right now for one of our programs we have 3 active branches: 1 for the main development, 1 for the as-yet-unfinished effort to parallelise the program, and 1 for the effort to revise it to use XML input and output files;

-- we scarcely use tags, though we think we ought to use them to identify releases to production;

Think of development proceeding along a single path. At some time or state of development marketing decide to release the first version of the product, so you plant a flag in the path labelled '1' (or '1.0' or what have you). At some other time some bright spark decides to parallelise the program, but decides that that will take weeks and that people want to keep going down the main path in the meantime. So you build a fork in the path and different people wander off down the different forks.

The flags in the road are called 'tags' ,and the forks in the road are where 'branches' divide. Occasionally, also, branches come back together.

-- we put all material necessary to build an executable (or system) into the repository; That means at least source code and make file (or project files for Visual Studio). But when we have icons and config files and all that other stuff, that goes into the repository. Some documentation finds its way into the repo; certainly any documentation such as help files which might be integral to the program does, and it's a useful place to put developer documentation.

We even put Windows executables for our production releases in there, to provide a single location for people looking for software -- our Linux releases go to a server so don't need to be stored.

-- we don't require that the repository at all times be capable of delivering a latest version which builds and executes; some projects work that way, some don't; the decision rests with the project manager and depends on many factors but I think it breaks down when making major changes to a program.

Generate sha256 with OpenSSL and C++

Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>

bool computeHash(const std::string& unhashed, std::string& hashed)
{
    bool success = false;

    EVP_MD_CTX* context = EVP_MD_CTX_new();

    if(context != NULL)
    {
        if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
        {
            if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
            {
                unsigned char hash[EVP_MAX_MD_SIZE];
                unsigned int lengthOfHash = 0;

                if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
                {
                    std::stringstream ss;
                    for(unsigned int i = 0; i < lengthOfHash; ++i)
                    {
                        ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
                    }

                    hashed = ss.str();
                    success = true;
                }
            }
        }

        EVP_MD_CTX_free(context);
    }

    return success;
}

int main(int, char**)
{
    std::string pw1 = "password1", pw1hashed;
    std::string pw2 = "password2", pw2hashed;
    std::string pw3 = "password3", pw3hashed;
    std::string pw4 = "password4", pw4hashed;

    hashPassword(pw1, pw1hashed);
    hashPassword(pw2, pw2hashed);
    hashPassword(pw3, pw3hashed);
    hashPassword(pw4, pw4hashed);

    std::cout << pw1hashed << std::endl;
    std::cout << pw2hashed << std::endl;
    std::cout << pw3hashed << std::endl;
    std::cout << pw4hashed << std::endl;

    return 0;
}

The advantage of this higher level interface is that you simply need to swap out the EVP_sha256() call with another digest's function, e.g. EVP_sha512(), to use a different digest. So it adds some flexibility.

How do you comment an MS-access Query?

It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.

Curly braces in string in PHP

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

Smooth scroll without the use of jQuery

With using the following smooth scrolling is working fine:

_x000D_
_x000D_
html {_x000D_
  scroll-behavior: smooth;_x000D_
}
_x000D_
_x000D_
_x000D_

TypeError: got multiple values for argument

I was brought here for a reason not explicitly mentioned in the answers so far, so to save others the trouble:

The error also occurs if the function arguments have changed order - for the same reason as in the accepted answer: the positional arguments clash with the keyword arguments.

In my case it was because the argument order of the Pandas set_axis function changed between 0.20 and 0.22:

0.20: DataFrame.set_axis(axis, labels)
0.22: DataFrame.set_axis(labels, axis=0, inplace=None)

Using the commonly found examples for set_axis results in this confusing error, since when you call:

df.set_axis(['a', 'b', 'c'], axis=1)

prior to 0.22, ['a', 'b', 'c'] is assigned to axis because it's the first argument, and then the positional argument provides "multiple values".

How to transfer paid android apps from one google account to another google account

You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.

What is the purpose of the HTML "no-js" class?

This is not only applicable in Modernizer. I see some site implement like below to check whether it has javascript support or not.

<body class="no-js">
    <script>document.body.classList.remove('no-js');</script>
    ...
</body>

If javascript support is there, then it will remove no-js class. Otherwise no-js will remain in the body tag. Then they control the styles in the css when no javascript support.

.no-js .some-class-name {

}

Set "Homepage" in Asp.Net MVC

I tried the answer but it didn't worked for me. This is what i ended up doing:

Create a new controller DefaultController. In index action, i wrote one line redirect:

return Redirect("~/Default.aspx")

In RouteConfig.cs, change controller="Default" for the route.

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
        );

Tomcat: LifecycleException when deploying

I had this problem, where it just would not deploy on Tomcat , then i removed all @webServlet Annotations from all my servlet code and it deployed successfully.

Javascript Cookie with no expiration date

You can make a cookie never end by setting it to whatever date plus one more than the current year like this :

var d = new Date();    
document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";

python: how to check if a line is an empty line

line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

<ng-container> vs <template>

The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:

<template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

If 'currentHero' is truthy this will be rendered as

<hero-detail> [...] </hero-detail>

But what if you want an conditional output like this:

<h1>Title</h1><br>
<p>text</p>

.. and you don't want the output be wrapped in a container.

You could write the de-sugared version directly like so:

<template [ngIf]="showContent">
  <h1>Title</h1>
  <p>text</p><br>
</template>

And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)

For that reason a different notation was created, like so:

<ng-container *ngIf="showContent"><br>
  <h1>Title</h1><br>
  <p>text</p><br>
</ng-container>

Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.

drag drop files into standard html file input

The following works in Chrome and FF, but i've yet to find a solution that covers IE10+ as well:

_x000D_
_x000D_
// dragover and dragenter events need to have 'preventDefault' called_x000D_
// in order for the 'drop' event to register. _x000D_
// See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets_x000D_
dropContainer.ondragover = dropContainer.ondragenter = function(evt) {_x000D_
  evt.preventDefault();_x000D_
};_x000D_
_x000D_
dropContainer.ondrop = function(evt) {_x000D_
  // pretty simple -- but not for IE :(_x000D_
  fileInput.files = evt.dataTransfer.files;_x000D_
_x000D_
  // If you want to use some of the dropped files_x000D_
  const dT = new DataTransfer();_x000D_
  dT.items.add(evt.dataTransfer.files[0]);_x000D_
  dT.items.add(evt.dataTransfer.files[3]);_x000D_
  fileInput.files = dT.files;_x000D_
_x000D_
  evt.preventDefault();_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div id="dropContainer" style="border:1px solid black;height:100px;">_x000D_
   Drop Here_x000D_
</div>_x000D_
  Should update here:_x000D_
  <input type="file" id="fileInput" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You'll probably want to use addEventListener or jQuery (etc.) to register your evt handlers - this is just for brevity's sake.

What is the symbol for whitespace in C?

#include <stdio.h>
main()
{
int c,sp,tb,nl;
sp = 0;
tb = 0;
nl = 0;
while((c = getchar()) != EOF)
{
   switch( c )
{
   case ' ':
        ++sp;
     printf("space:%d\n", sp);
     break;
   case  '\t':
        ++tb;
     printf("tab:%d\n", tb);
     break;
   case '\n':
        ++nl;
     printf("new line:%d\n", nl);
     break;
  }
 }
}

builtins.TypeError: must be str, not bytes

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

How do I put hint in a asp:textbox

Just write like this:

<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox>

PHP: Limit foreach() statement?

You can either use

break;

or

foreach() if ($tmp++ < 2) {
}

(the second solution is even worse)

Check the current number of connections to MongoDb

In OS X, too see the connections directly on the network interface, just do:

$ lsof -n -i4TCP:27017

mongod     2191 inanc    7u  IPv4 0xab6d9f844e21142f  0t0  TCP 127.0.0.1:27017 (LISTEN)
mongod     2191 inanc   33u  IPv4 0xab6d9f84604cd757  0t0  TCP 127.0.0.1:27017->127.0.0.1:56078 (ESTABLISHED)
stores.te 18704 inanc    6u  IPv4 0xab6d9f84604d404f  0t0  TCP 127.0.0.1:56078->127.0.0.1:27017 (ESTABLISHED)
  • No need to use grep etc, just use the lsof's arguments.

  • Too see the connections on MongoDb's CLI, see @milan's answer (which I just edited).

Passing an array using an HTML form hidden element

If you want to post an array you must use another notation:

foreach ($postvalue as $value){
<input type="hidden" name="result[]" value="$value.">
}

in this way you have three input fields with the name result[] and when posted $_POST['result'] will be an array

Two versions of python on linux. how to make 2.7 the default

All OS comes with a default version of python and it resides in /usr/bin. All scripts that come with the OS (e.g. yum) point this version of python residing in /usr/bin. When you want to install a new version of python you do not want to break the existing scripts which may not work with new version of python.

The right way of doing this is to install the python as an alternate version.

e.g.
wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 
tar xf Python-2.7.3.tar.bz2
cd Python-2.7.3
./configure --prefix=/usr/local/
make && make altinstall

Now by doing this the existing scripts like yum still work with /usr/bin/python. and your default python version would be the one installed in /usr/local/bin. i.e. when you type python you would get 2.7.3

This happens because. $PATH variable has /usr/local/bin before usr/bin.

/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

If python2.7 still does not take effect as the default python version you would need to do

export PATH="/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"

How do I clear a C++ array?

std::fill(a.begin(),a.end(),0);

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

Error in Process.Start() -- The system cannot find the file specified

You can use the folowing to get the full path to your program like this:

Environment.CurrentDirectory

How to use MySQL DECIMAL?

MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.

To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED.

You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.


Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:

"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*

As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.

Npm install cannot find module 'semver'

I'm facing the same issue here.

If this occurs right after you run brew install yarn try running yarn global add npm and voilà - fixed!

Key Listeners in python?

It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into curses. If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with termios, which unfortunately appears to be poorly documented in Python. Neither of these options are that simple, though, unfortunately. Additionally, they do not work under Windows; if you need them to work under Windows, you'll have to use PDCurses as a replacement for curses or pywin32 rather than termios.


I was able to get this working decently. It prints out the hexadecimal representation of keys you type. As I said in the comments of your question, arrows are tricky; I think you'll agree.

#!/usr/bin/env python
import sys
import termios
import contextlib


@contextlib.contextmanager
def raw_mode(file):
    old_attrs = termios.tcgetattr(file.fileno())
    new_attrs = old_attrs[:]
    new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
    try:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
        yield
    finally:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)


def main():
    print 'exit with ^C or ^D'
    with raw_mode(sys.stdin):
        try:
            while True:
                ch = sys.stdin.read(1)
                if not ch or ch == chr(4):
                    break
                print '%02x' % ord(ch),
        except (KeyboardInterrupt, EOFError):
            pass


if __name__ == '__main__':
    main()

jQuery date formatting

Here's a really basic function I just made that doesn't require any external plugins:

$.date = function(dateObject) {
    var d = new Date(dateObject);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }
    var date = day + "/" + month + "/" + year;

    return date;
};

Use:

$.date(yourDateObject);

Result:

dd/mm/yyyy

Get folder name from full file path

I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:

s.Substring(s.LastIndexOf(@"\"));

How to access the GET parameters after "?" in Express?

const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')

const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
  usersNdJobs()
    .then((users) => {
      res.render('users', { users })
    })
    .catch(console.error)
})

app.get('/api/company/users', (req, res) => {
  const companyname = req.query.companyName
  console.log(companyname)
  userByJob(companyname)
    .then((users) => {
      res.render('job', { users })
    }).catch(console.error)
})

app.post('/api/users/add', (req, res) => {
  const userName = req.body.userName
  const jobName = req.body.jobName
  console.log("user name = "+userName+", job name : "+jobName)
  addUser(userName, jobName)
    .then((result) => {
      res.status(200).json(result)
    })
    .catch((error) => {
      res.status(404).json({ 'message': error.toString() })
    })
})
app.post('/users/add', (request, response) => {
  const { userName, job } = request.body
  addTeam(userName, job)
  .then((user) => {
    response.status(200).json({
      "userName": user.name,
      "city": user.job
    })
  .catch((err) => {
    request.status(400).json({"message": err})
  })
})

app.post('/api/user/company/add', (req, res) => {
  const userName = req.body.userName
  const companyName = req.body.companyName
  console.log(userName, companyName)
  addUserToCompany(userName, companyName)
  .then((result) => {
    res.json(result)
  })
  .catch(console.error)
})

app.get('/api/company/user', (req, res) => {
 const companyname = req.query.companyName
 console.log(companyname)
 userByJob(companyname)
 .then((users) => {
   res.render('jobs', { users })
 })
})

app.listen(3000, () =>
  console.log('Example app listening on port 3000!')
)

What is the best way to tell if a character is a letter or number in Java without using regexes?

// check if ch is a letter
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    // ...

// check if ch is a digit
if (ch >= '0' && ch <= '9')
    // ...

// check if ch is a whitespace
if ((ch == ' ') || (ch =='\n') || (ch == '\t'))
    // ...

Source: https://docs.oracle.com/javase/tutorial/i18n/text/charintro.html

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

The solution needs to add these headers to the server response.

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'

If you have access to the server, you can add them and this will solve your problem

OR

You can try concatentaing this in front of the url:

https://cors-anywhere.herokuapp.com/

How to Refresh a Component in Angular

Other way to refresh (hard way) a page in angular 2 like this it's look like f5

import { Location } from '@angular/common';

constructor(private location: Location) {}

pageRefresh() {
   location.reload();
}

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

cannot make a static reference to the non-static field

you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.

Account account = new Account(1122, 20000, 4.5);

    double sB = Account.withdraw(account.getBalance(), 2500);
    double eB = Account.deposit(sB, 3000);
    System.out.println("Balance is " + eB);
    System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
    account.setDateCreated(new Date());
    System.out.println("The account was created " + account.getDateCreated());

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Call to undefined method mysqli_stmt::get_result

for those searching for an alternative to $result = $stmt->get_result() I've made this function which allows you to mimic the $result->fetch_assoc() but using directly the stmt object:

function fetchAssocStatement($stmt)
{
    if($stmt->num_rows>0)
    {
        $result = array();
        $md = $stmt->result_metadata();
        $params = array();
        while($field = $md->fetch_field()) {
            $params[] = &$result[$field->name];
        }
        call_user_func_array(array($stmt, 'bind_result'), $params);
        if($stmt->fetch())
            return $result;
    }

    return null;
}

as you can see it creates an array and fetches it with the row data, since it uses $stmt->fetch() internally, you can call it just as you would call mysqli_result::fetch_assoc (just be sure that the $stmt object is open and result is stored):

//mysqliConnection is your mysqli connection object
if($stmt = $mysqli_connection->prepare($query))
{
    $stmt->execute();
    $stmt->store_result();

    while($assoc_array = fetchAssocStatement($stmt))
    {
        //do your magic
    }

    $stmt->close();
}

How can I get customer details from an order in WooCommerce?

Having tried $customer = new WC_Customer(); and global $woocommerce; $customer = $woocommerce->customer; I was still getting empty address data even when I logged in as a non-admin user.

My solution was as follows:

function mwe_get_formatted_shipping_name_and_address($user_id) {

    $address = '';
    $address .= get_user_meta( $user_id, 'shipping_first_name', true );
    $address .= ' ';
    $address .= get_user_meta( $user_id, 'shipping_last_name', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_company', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_address_1', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_address_2', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_city', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_state', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_postcode', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_country', true );

    return $address;
}

...and this code works regardless of whether you are logged in as admin or not.

Get bottom and right position of an element

// Returns bottom offset value + or - from viewport top
function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom }

// Returns right offset value
function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right }

var bottom = offsetBottom('#logo');
var right = offsetRight('#logo');

This will find the distance from the top and left of your viewport to your element's exact edge and nothing beyond that. So say your logo was 350px and it had a left margin of 50px, variable 'right' will hold a value of 400 because that's the actual distance in pixels it took to get to the edge of your element, no matter if you have more padding or margin to the right of it.

If your box-sizing CSS property is set to border-box it will continue to work just as if it were set as the default content-box.

R object identification

str(x)

It's all you need to remember for 99% of cases.

Move SQL data from one table to another

Yes it is. First INSERT + SELECT and then DELETE orginals.

INSERT INTO Table2 (UserName,Password)
SELECT UserName,Password FROM Table1 WHERE UserName='X' AND Password='X'

then delete orginals

DELETE FROM Table1 WHERE UserName='X' AND Password='X'

you may want to preserve UserID or someother primary key, then you can use IDENTITY INSERT to preserve the key.

see more on SET IDENTITY_INSERT on MSDN

How do you implement a circular buffer in C?

@Adam Rosenfield's solution, although correct, could be implemented with a more lightweight circular_buffer structure that does not invlove count and capacity.

The structure could only hold the following 4 pointers:

  • buffer: Points to the start of the buffer in memory.
  • buffer_end: Points to the end of the buffer in memory.
  • head: Points to the end of stored data.
  • tail: Points to the start of stored data.

We could keep the sz attribute to allow the parametrisation of the unit of storage.

Both the count and the capacity values should be derive-able using the above pointers.

Capacity

capacity is straight forward, as it can be derived by dividing the distance between the buffer_end pointer and the buffer pointer by the unit of storage sz (snippet below is pseudocode):

capacity = (buffer_end - buffer) / sz

Count

For count though, things get a bit more complicated. For example, there is no way to determine whether the buffer is empty or full, in the scenario of head and tail pointing to the same location.

To tackle that, the buffer should allocate memory for an additional element. For example, if the desired capacity of our circular buffer is 10 * sz, then we need to allocate 11 * sz.

Capacity formula will then become (snippet below is pseudocode):

capacity_bytes = buffer_end - buffer - sz
capacity = capacity_bytes / sz

This extra element semantic allows us to construct conditions that evaluate whether the buffer is empty or full.

Empty state conditions

In order for the buffer to be empty, the head pointer points to the same location as the tail pointer:

head == tail

If the above evaluates to true, the buffer is empty.

Full state conditions

In order for the buffer to be full, the head pointer should be 1 element behind the tail pointer. Thus, the space needed to cover in order to jump from the head location to the tail location should be equal to 1 * sz.

if tail is larger that head:

tail - head == sz

If the above evaluates to true, the buffer is full.

if head is larger that tail:

  1. buffer_end - head returns the space to jump from the head to the end of the buffer.
  2. tail - buffer returns the space needed to jump from the start of the buffer to the `tail.
  3. Adding the above 2 should equal to the space needed to jump from the head to the tail
  4. The space derived in step 3, shold not be more than 1 * sz
(buffer_end - head) + (tail - buffer) == sz
=> buffer_end - buffer - head + tail == sz
=> buffer_end - buffer - sz == head - tail
=> head - tail == buffer_end - buffer - sz
=> head - tail == capacity_bytes

If the above evaluates to true, the buffer is full.

In practice

Modifying @Adam Rosenfield's to use the above circular_buffer structure:

#include <string.h>

#define CB_SUCCESS 0        /* CB operation was successful */
#define CB_MEMORY_ERROR 1   /* Failed to allocate memory */
#define CB_OVERFLOW_ERROR 2 /* CB is full. Cannot push more items. */
#define CB_EMPTY_ERROR 3    /* CB is empty. Cannot pop more items. */

typedef struct circular_buffer {
  void *buffer;
  void *buffer_end;
  size_t sz;
  void *head;
  void *tail;
} circular_buffer;

int cb_init(circular_buffer *cb, size_t capacity, size_t sz) {
  const int incremented_capacity = capacity + 1; // Add extra element to evaluate count
  cb->buffer = malloc(incremented_capacity * sz);
  if (cb->buffer == NULL)
    return CB_MEMORY_ERROR;
  cb->buffer_end = (char *)cb->buffer + incremented_capacity * sz;
  cb->sz = sz;
  cb->head = cb->buffer;
  cb->tail = cb->buffer;
  return CB_SUCCESS;
}

int cb_free(circular_buffer *cb) {
  free(cb->buffer);
  return CB_SUCCESS;
}

const int _cb_length(circular_buffer *cb) {
  return (char *)cb->buffer_end - (char *)cb->buffer;
}

int cb_push_back(circular_buffer *cb, const void *item) {
  const int buffer_length = _cb_length(cb);
  const int capacity_length = buffer_length - cb->sz;

  if ((char *)cb->tail - (char *)cb->head == cb->sz ||
      (char *)cb->head - (char *)cb->tail == capacity_length)
    return CB_OVERFLOW_ERROR;

  memcpy(cb->head, item, cb->sz);

  cb->head = (char*)cb->head + cb->sz;
  if(cb->head == cb->buffer_end)
    cb->head = cb->buffer;

  return CB_SUCCESS;
}

int cb_pop_front(circular_buffer *cb, void *item) {
  if (cb->head == cb->tail)
    return CB_EMPTY_ERROR;

  memcpy(item, cb->tail, cb->sz);

  cb->tail = (char*)cb->tail + cb->sz;
  if(cb->tail == cb->buffer_end)
    cb->tail = cb->buffer;

  return CB_SUCCESS;
}

Android: How do bluetooth UUIDs work?

The UUID is used for uniquely identifying information. It identifies a particular service provided by a Bluetooth device. The standard defines a basic BASE_UUID: 00000000-0000-1000-8000-00805F9B34FB.

Devices such as healthcare sensors can provide a service, substituting the first eight digits with a predefined code. For example, a device that offers an RFCOMM connection uses the short code: 0x0003

So, an Android phone can connect to a device and then use the Service Discovery Protocol (SDP) to find out what services it provides (UUID).

In many cases, you don't need to use these fixed UUIDs. In the case your are creating a chat application, for example, one Android phone interacts with another Android phone that uses the same application and hence the same UUID.

So, you can set an arbitrary UUID for your application using, for example, one of the many random UUID generators on the web (for example).

format a number with commas and decimals in C# (asp.net MVC3)

Maybe you simply want the standard format string "N", as in

number.ToString("N")

It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).

If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").

Edit: The sizes of the groups between the commas are governed by the

CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes

array, given that you don't specify a special format provider.

Five equal columns in twitter bootstrap

var cols = $(".container .item").length;
if (cols == 5){
    $('div.item').removeClass('col-md-2..etc').addClass('col-md-3').css('width', '20%');
 }

Jquery and Done! Framework!

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

'uint32_t' does not name a type

I had tha same problem trying to compile a lib I download from the internet. In my case, there was already a #include <cstdint> in the code. I solved it adding a:

using std::uint32_t;

String or binary data would be truncated. The statement has been terminated

SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12 introduced trace flag 460 in order to return the details of truncation warnings. You can enable it at the query level or at the server level.

Query level

INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO

Server Level

DBCC TRACEON(460, -1);
GO

From SQL Server 2019 you can enable it at database level:

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

The old output message is:

Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.

The new output message is:

Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.

In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

seek() function?

When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek() operation moves that pointer to some other part of the file so you can read or write at that place.

So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20) to move to where you want to start reading, then continue with reading the file.

Or say you want to read every 10th byte, you could write a loop that does seek(9, 1) (moves 9 bytes forward relative to the current positions), read(1) (reads one byte), repeat.

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

How to create a DB for MongoDB container on start up?

The official mongo image has merged a PR to include the functionality to databases and admin users at startup.

The database initialisation will run scripts in /docker-entrypoint-initdb.d/ when there is nothing populated in the /data/db directory.

Database Initialisation

The mongo container image provides the /docker-entrypoint-initdb.d/ path to deploy custom .js or .sh setup scripts that will be run once on database initialisation. .js scripts will be run against test by default or MONGO_INITDB_DATABASE if defined in the environment.

COPY mysetup.sh /docker-entrypoint-initdb.d/

or

COPY mysetup.js /docker-entrypoint-initdb.d/

A simple initialisation mongo shell javascript file that demonstrates setting up the container collection with data, logging and how to exit with an error (for result checking).

let error = true

let res = [
  db.container.drop(),
  db.container.createIndex({ myfield: 1 }, { unique: true }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]

printjson(res)

if (error) {
  print('Error, exiting')
  quit(1)
}

Admin User Setup

The environment variables to control "root" user setup are

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

Example

docker run -d \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  mongod

or Dockerfile

FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password

You don't need to use --auth on the command line as the docker entrypoint.sh script adds this in when it detects the environment variables exist.

Appending a byte[] to the end of another byte[]

I wrote the following procedure for concatenation of several array:

  static public byte[] concat(byte[]... bufs) {
    if (bufs.length == 0)
        return null;
    if (bufs.length == 1)
        return bufs[0];
    for (int i = 0; i < bufs.length - 1; i++) {
        byte[] res = Arrays.copyOf(bufs[i], bufs[i].length+bufs[i + 1].length);
        System.arraycopy(bufs[i + 1], 0, res, bufs[i].length, bufs[i + 1].length);
        bufs[i + 1] = res;
    }
    return bufs[bufs.length - 1];
}

It uses Arrays.copyOf

Are there inline functions in java?

Java does not provide a way to manually suggest that a method should be inlined. As @notnoop says in the comments, the inlining is typically done by the JVM at execution time.

Getting a count of rows in a datatable that meet certain criteria

int numberOfRecords = 0;

numberOfRecords = dtFoo.Select().Length;

MessageBox.Show(numberOfRecords.ToString());

The view didn't return an HttpResponse object. It returned None instead

if qs.count()==1:
        print('cart id exists')
        if ....

else:    
        return render(request,"carts/home.html",{})

Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.

above code can be changed to

if qs.count()==1:
        print('cart id exists')
        if ....

else:   

return render(request,"carts/home.html",{})

This may solve such issues

Match all elements having class name starting with a specific string

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

Bootstrap 3 breakpoints and media queries

You should be able to use those breakpoints if you use http://lesscss.org/ to build your CSS.

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) {  }

/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) {  }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) {  }

From https://getbootstrap.com/docs/3.4/css/#grid-media-queries

In fact @screen-sm-min is a variable than is replaced by the value specified in _variable when building with Less. If you don't use Less, you can replace this variable by the value:

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {  }

/* Medium devices (desktops, 992px and up) */
@media (min-width: 992px) {  }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {  }

Bootstrap 3 officially supports Sass: https://github.com/twbs/bootstrap-sass. If you are using Sass (and you should) the syntax is a bit different.

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: $screen-sm-min) { }

/* Medium devices (desktops, 992px and up) */
@media (min-width: $screen-md-min) {  }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: $screen-lg-min) {  }

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Remove HTML tags from string including &nbsp in C#

var noHtml = Regex.Replace(inputHTML, @"<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;", string.Empty).Trim();

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

How can I get a random number in Kotlin?

Another way of implementing s1m0nw1's answer would be to access it through a variable. Not that its any more efficient but it saves you from having to type ().

val ClosedRange<Int>.random: Int
    get() = Random().nextInt((endInclusive + 1) - start) +  start 

And now it can be accessed as such

(1..10).random

How do you add a timed delay to a C++ program?

In Win32:

#include<windows.h>
Sleep(milliseconds);

In Unix:

#include<unistd.h>
unsigned int microsecond = 1000000;
usleep(3 * microsecond);//sleeps for 3 second

sleep() only takes a number of seconds which is often too long.

Select arrow style change

You can use this. Its Tested code

    select {
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right !important;
    appearance: none !important;
    background-size: 25px 25px !important;
    background-position: 99% 50% !important;
}

Replace multiple strings with multiple other strings

I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did

str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};


function replaceAll (str, mapObj) {

    var arr = Object.keys(mapObj),
        re;

    $.each(arr, function (key, value) {
        re = new RegExp(value, "g");
        str = str.replace(re, function (matched) {
            return mapObj[value];
        });
    });

    return str;

}
replaceAll(str, mapObj)

returns "blah blah 234433 blah blah"

This way it will match the key in the mapObj and not the matched word'

How to get the selected value from drop down list in jsp?

Direct value should work just fine:

var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

VBA - Select columns using numbers?

You can use resize like this:

For n = 1 To 5
    Columns(n).Resize(, 5).Select
    '~~> rest of your code
Next

In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.

justify-content property isn't working

justify-content only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content will do nothing.

Some examples where it would have an effect:

  • if your flex items are all inflexible (flex: none or flex: 0 0 auto), and smaller than the container.

  • if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width on each of the flexible items.

In both of those cases, justify-content would be in charge of distributing the excess space.

In your example, though, you have flex items that have flex: 1 or flex: 6 with no max-width limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content to do anything with.

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

Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

  1. First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)

  2. Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..

How to append a char to a std::string?

I found a simple way... I needed to tack a char on to a string that was being built on the fly. I needed a char list; because I was giving the user a choice and using that choice in a switch() statement.

I simply added another std::string Slist; and set the new string equal to the character, "list" - a, b, c or whatever the end user chooses like this:

char list;
std::string cmd, state[], Slist;
Slist = list; //set this string to the chosen char;
cmd = Slist + state[x] + "whatever";
system(cmd.c_str());

Complexity may be cool but simplicity is cooler. IMHO

How do I use the nohup command without getting nohup.out?

Have you tried redirecting all three I/O streams:

nohup ./yourprogram > foo.out 2> foo.err < /dev/null &

Are there such things as variables within an Excel formula?

You could store intermediate values in a cell or column (which you could hide if you choose)

C1: = VLOOKUP(A1, B:B, 1, 0)
D1: = IF(C1 > 10, C1 - 10, C1)

Create table using Javascript

Here is an example of drawing a table using raphael.js. We can draw tables directly to the canvas of the browser using Raphael.js Raphael.js is a javascript library designed specifically for artists and graphic designers.

<!DOCTYPE html>
<html>

    <head>
    </head>
    <body>
        <div id='panel'></div>
    </body>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>    
paper = new Raphael(0,0,500,500);// width:500px, height:500px

var x = 100;
var y = 50;
var height = 50
var width = 100;

WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)
{
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;
}


function WriteTableRow(x,y,width,height,paper,TDdata)
{ // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.

    var TD = TDdata.split(",");
    for (j=0;j<TD.length;j++)
    {
        var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});// draw outline
        paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
        x = x + width;
    }
}

</script>

</html>

Please check the preview image: https://i.stack.imgur.com/RAFhH.png

Copy multiple files with Ansible

Or you can use with_items:

- copy:
    src: "{{ item }}"
    dest: /etc/fooapp/
    owner: root
    mode: 600
  with_items:
    - dest_dir

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

Sending email with gmail smtp with codeigniter email library

It can be this:

If you are using cpanel for your website smtp restrictions are problem and cause this error. SMTP Restrictions

Error while sending an email with CodeIgniter

Making an iframe responsive

I present to you The Incredible Singing Cat solution =)

.wrapper {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    height: 0;
}
.wrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

jsFiddle: http://jsfiddle.net/omarjuvera/8zkunqxy/2/
As you move the window bar, you'll see iframe to responsively resize


Alternatively, you may also use the intrinsic ratio technique - This is just an alternate option of the same solution above (tomato, tomato)

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
} 

.iframe-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  border: 0;
  width: 100%;
  height: 100%;
}

How do I add comments to package.json for npm install?

You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:

"dependencies": {
  "grunt": "...",
  "grunt-cli": "...",

  "api-easy": "# Here is the pull request: https://github.com/...",
  "api-easy": "git://..."

  "grunt-vows": "...",
  "vows": "..."
}

However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.

The recommened hack is to use "//" keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//" keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.

Update: One annoying disadvantage of the duplicated key hack is that npm install --save silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.

The "//" hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save, too.

Maven: Failed to read artifact descriptor

I had this problem in eclipse, mvn -U clean install didn't work but right clicking the project and selecting Maven->Update Project fixed it.

C++ pass an array by reference

Arrays can only be passed by reference, actually:

void foo(double (&bar)[10])
{
}

This prevents you from doing things like:

double arr[20];
foo(arr); // won't compile

To be able to pass an arbitrary size array to foo, make it a template and capture the size of the array at compile time:

template<typename T, size_t N>
void foo(T (&bar)[N])
{
    // use N here
}

You should seriously consider using std::vector, or if you have a compiler that supports c++11, std::array.