Programs & Examples On #Ccavenue

Ccavenue is a very popular payment gateway system in India. It provides money transaction in Indian Rupees (INR)

Hidden Features of Xcode

When you use code completion on a method and it has multiple arguments, using CTRL + / to move to the next argument you need to fill in.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Close all browsers and tabs to ensure that the ActiveX control is not reside in memory. Open a fresh IE9 browser. Select Tools->Manage Add-ons. Change the drop down to "All add-ons" since the default only shows ones that are loaded.

Now select the add-on you wish to remove. There will be a link displayed on the lower left that says "More information". Click it.

This opens a further dialog that allows you to safely un-install the ActiveX control.

If you follow the direction of manually running the 'regsvr32' to remove the OCX it is not sufficient. ActiveX controls are wrapped up as signed CAB files and they extract to multiple DLLs and OCXs potentially. You wish to use IE to safely and correctly unregister every COM DLL and OCX.

There you have it! The problem is that in IE 9 it is somewhat hidden since you have to click the "More information" whereas IE8 you could do it from the same UI.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:

=A1=A50

If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

Change onClick attribute with javascript

You are not actually changing the function.

onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.

Another problem is your variable color seems out of nowhere.

Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)

How can I get nth element from a list?

I'm not saying that there's anything wrong with your question or the answer given, but maybe you'd like to know about the wonderful tool that is Hoogle to save yourself time in the future: With Hoogle, you can search for standard library functions that match a given signature. So, not knowing anything about !!, in your case you might search for "something that takes an Int and a list of whatevers and returns a single such whatever", namely

Int -> [a] -> a

Lo and behold, with !! as the first result (although the type signature actually has the two arguments in reverse compared to what we searched for). Neat, huh?

Also, if your code relies on indexing (instead of consuming from the front of the list), lists may in fact not be the proper data structure. For O(1) index-based access there are more efficient alternatives, such as arrays or vectors.

Associating enums with strings in C#

I like to use properties in a class instead of methods, since they look more enum-like.

Here's a example for a Logger:

public class LogCategory
{
    private LogCategory(string value) { Value = value; }

    public string Value { get; set; }

    public static LogCategory Trace   { get { return new LogCategory("Trace"); } }
    public static LogCategory Debug   { get { return new LogCategory("Debug"); } }
    public static LogCategory Info    { get { return new LogCategory("Info"); } }
    public static LogCategory Warning { get { return new LogCategory("Warning"); } }
    public static LogCategory Error   { get { return new LogCategory("Error"); } }
}

Pass in type-safe string values as a parameter:

public static void Write(string message, LogCategory logCategory)
{
    var log = new LogEntry { Message = message };
    Logger.Write(log, logCategory.Value);
}

Usage:

Logger.Write("This is almost like an enum.", LogCategory.Info);

CSS media queries: max-width OR max-height

There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:

@media only screen 
and (min-width : 415px){
    /* Styles */
}

@media only screen 
and (min-width : 769px){
    /* Styles */
}

@media only screen 
and (min-width : 992px){
    /* Styles */
}

But if you are writing media queries for smaller device first, then it would be something like:

@media only screen 
and (max-width : 991px){
    /* Styles */
}

@media only screen 
and (max-width : 768px){
    /* Styles */
}

@media only screen 
and (max-width : 414px){
    /* Styles */
}

Align HTML input fields by :

I have just given width to Label and input type were aligned automatically.

_x000D_
_x000D_
input[type="text"] {_x000D_
    width:100px;_x000D_
 height:30px;_x000D_
 border-radius:5px;_x000D_
 background-color: lightblue;_x000D_
 margin-left:2px;_x000D_
  position:relative;_x000D_
}_x000D_
_x000D_
label{_x000D_
position:relative;_x000D_
width:300px;_x000D_
border:2px dotted black;_x000D_
margin:20px;_x000D_
padding:5px;_x000D_
font-family:AR CENA;_x000D_
font-size:20px;_x000D_
_x000D_
}
_x000D_
<label>First Name:</label><input type="text" name="fname"><br>_x000D_
<label>Last Name:</label><input type="text" name="lname"><br>
_x000D_
_x000D_
_x000D_

Is this a good way to clone an object in ES6?

This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.

For deep cloning you'll need a different solution.

const clone = {...original} to shallow clone

const newobj = {...original, prop: newOne} to immutably add another prop to the original and store as a new object.

How to enter quotes in a Java string?

In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.

If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:

String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";

Or, if you want to do it with one String variable, it would be:

String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";

Of course, this actually replaces the original ROM, since Java Strings are immutable.

If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.

setting multiple column using one update

Just add parameters, split by comma:

UPDATE tablename SET column1 = "value1", column2 = "value2" ....

See also: mySQL manual on UPDATE

EnterKey to press button in VBA Userform

Here you can simply use:

SendKeys "{ENTER}" at the end of code linked to the Username field.

And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.

Storing money in a decimal column - what precision and scale?

When handling money in MySQL, use DECIMAL(13,2) if you know the precision of your money values or use DOUBLE if you just want a quick good-enough approximate value. So if your application needs to handle money values up to a trillion dollars (or euros or pounds), then this should work:

DECIMAL(13, 2)

Or, if you need to comply with GAAP then use:

DECIMAL(13, 4)

Uncaught TypeError: Cannot read property 'appendChild' of null

add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=

How to reload/refresh an element(image) in jQuery

Based on @kasper Taeymans' answer.

If u simply need reload image (not replace it's src with smth new), try:

_x000D_
_x000D_
$(function() {_x000D_
  var img = $('#img');_x000D_
_x000D_
  var refreshImg = function(img) {_x000D_
    // the core of answer is 2 lines below_x000D_
    var dummy = '?dummy=';_x000D_
    img.attr('src', img.attr('src').split(dummy)[0] + dummy + (new Date()).getTime());_x000D_
_x000D_
    // remove call on production_x000D_
    updateImgVisualizer();_x000D_
  };_x000D_
_x000D_
_x000D_
  // for display current img url in input_x000D_
  // for sandbox only!_x000D_
  var updateImgVisualizer = function() {_x000D_
    $('#img-url').val(img.attr('src'));_x000D_
  };_x000D_
_x000D_
  // bind img reload on btn click_x000D_
  $('.img-reloader').click(function() {_x000D_
    refreshImg(img);_x000D_
  });_x000D_
_x000D_
  // remove call on production_x000D_
  updateImgVisualizer();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<img id="img" src="http://dummyimage.com/628x150/">_x000D_
_x000D_
_x000D_
<p>_x000D_
  <label>_x000D_
    Current url of img:_x000D_
    <input id="img-url" type="text" readonly style="width:500px">_x000D_
  </label>_x000D_
</p>_x000D_
_x000D_
<p>_x000D_
  <button class="img-reloader">Refresh</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Could not find module FindOpenCV.cmake ( Error in configuration process)

find / -name "OpenCVConfig.cmake"

export OpenCV_DIR=/path/found/above

firestore: PERMISSION_DENIED: Missing or insufficient permissions

Your rules should be like this for this case however the message says that it is not the suggested way, but if you do this you can do inserts with no permission error

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

When is std::weak_ptr useful?

weak_ptr is also good to check the correct deletion of an object - especially in unit tests. Typical use case might look like this:

std::weak_ptr<X> weak_x{ shared_x };
shared_x.reset();
BOOST_CHECK(weak_x.lock());
... //do something that should remove all other copies of shared_x and hence destroy x
BOOST_CHECK(!weak_x.lock());

repaint() in Java

If you added JComponent to already visible Container, then you have call

frame.getContentPane().validate();
frame.getContentPane().repaint();

for example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(460, 500);
        frame.setTitle("Circles generator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              frame.setVisible(true);
           }
        });

        String input = JOptionPane.showInputDialog("Enter n:");
        CustomComponents0 component = new CustomComponents0();
        frame.add(component);
        frame.getContentPane().validate();
        frame.getContentPane().repaint();
    }

    static class CustomComponents0 extends JLabel {

        private static final long serialVersionUID = 1L;

        @Override
        public Dimension getMinimumSize() {
            return new Dimension(200, 100);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }

        @Override
        public void paintComponent(Graphics g) {
            int margin = 10;
            Dimension dim = getSize();
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
        }
    }
}

prevent property from being serialized in web API

Almost same as greatbear302's answer, but i create ContractResolver per request.

1) Create a custom ContractResolver

public class MyJsonContractResolver : DefaultContractResolver
{
    public List<Tuple<string, string>> ExcludeProperties { get; set; }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if (ExcludeProperties?.FirstOrDefault(
            s => s.Item2 == member.Name && s.Item1 == member.DeclaringType.Name) != null)
        {
            property.ShouldSerialize = instance => { return false; };
        }

        return property;
    }
}

2) Use custom contract resolver in action

public async Task<IActionResult> Sites()
{
    var items = await db.Sites.GetManyAsync();

    return Json(items.ToList(), new JsonSerializerSettings
    {
        ContractResolver = new MyJsonContractResolver()
        {
            ExcludeProperties = new List<Tuple<string, string>>
            {
                Tuple.Create("Site", "Name"),
                Tuple.Create("<TypeName>", "<MemberName>"),
            }
        }
    });
}

Edit:

It didn't work as expected(isolate resolver per request). I'll use anonymous objects.

public async Task<IActionResult> Sites()
{
    var items = await db.Sites.GetManyAsync();

    return Json(items.Select(s => new
    {
        s.ID,
        s.DisplayName,
        s.Url,
        UrlAlias = s.Url,
        NestedItems = s.NestedItems.Select(ni => new
        {
            ni.Name,
            ni.OrdeIndex,
            ni.Enabled,
        }),
    }));
}

time delayed redirect?

You can easily create timed redirections with JavaScript. But I suggest you to use location.replace('url') instead of location.href. It prevents to browser to push the site into the history. I found this JavaScript redirect tool. I think you could use this.

Example code (with 5 secs delay):

<!-- Pleace this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="5;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.com/";
    var delay = "5000";
    window.onload = function ()
    {
        setTimeout(GoToURL, delay);
    }
    function GoToURL()
    {
        if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
        {
            var referLink = document.createElement("a");
            referLink.href = url;
            document.body.appendChild(referLink);
            referLink.click();
        }
        else { window.location.replace(url); } // All other browsers
    }
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

CSS position:fixed inside a positioned element

The current selected solution appears to have misunderstood the problem.

The trick is to neither use absolute nor fixed positioning. Instead, have the close button outside of the div with its position set to relative and a left float so that it is immediately right of the div. Next, set a negative left margin and a positive z index so that it appears above the div.

Here's an example:

#close
    {
        position: relative;
        float: left;
        margin-top: 50vh;
        margin-left: -100px;
        z-index: 2;
    }

#dialog
    {
        height: 100vh;
        width: 100vw;
        position: relative;
        overflow: scroll;
        float: left;
    }

<body> 
    <div id="dialog">
    ****
    </div>

    <div id="close"> </div>
</body>

How to convert Moment.js date to users local timezone?

Use utcOffset function.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

RegEx for valid international mobile phone number

After stripping all characters except '+' and digits from your input, this should do it:

^\+[1-9]{1}[0-9]{3,14}$

If you want to be more exact with the country codes see this question on List of phone number country codes

However, I would try to be not too strict with my validation. Users get very frustrated if they are told their valid numbers are not acceptable.

Validate email with a regex in jQuery

function mailValidation(val) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!expr.test(val)) {
        $('#errEmail').text('Please enter valid email.');
    }
    else {
        $('#errEmail').hide();
    }
}

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

How can I pretty-print JSON using Go?

Here's what I use. If it fails to pretty print the JSON it just returns the original string. Useful for printing HTTP responses that should contain JSON.

import (
    "encoding/json"
    "bytes"
)

func jsonPrettyPrint(in string) string {
    var out bytes.Buffer
    err := json.Indent(&out, []byte(in), "", "\t")
    if err != nil {
        return in
    }
    return out.String()
}

ORA-12154 could not resolve the connect identifier specified

I had the same issue. In my case I was using a web service which was build using AnyCPU settings. Since the WCF was using 32 bit Oracle data access components therefore it was raising the same error when I tried to call it from a console client. So when I compiled the WCF service using the x86 based setting the client was able to successfully get data from the web service.

If you compile as "Any CPU" and run on an x64 platform, then you won't be able to load 32-bit dlls (which in our case were the Oracle Data Access components), because our app wasn't started in WOW64 (Windows32 on Windows 64). So in order to allow the 32 bit dependency of Oracle Data Access components I compilee the web service with Platform target of x86 and that solved it for me

As an alternative if you have 64bit ODAC drivers installed on the machine that also caused the problem to go away.

How to easily duplicate a Windows Form in Visual Studio?

I usually copy the files in windows explorer, open them up in Notepad/Wordpad and just change the one mention of the class name at the top. Include those files in your project, and you'll be good to go.

Get index of a key in json

What you are after are numerical indexes in the way classic arrays work, however there is no such thing with json object/associative arrays.

"key1", "key2" themeselves are the indexes and there is no numerical index associated with them. If you want to have such functionality you have to assiciate them yourself.

Accessing the web page's HTTP Headers in JavaScript

I think the question went in the wrong way, If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header. Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..

Git will not init/sync/update new submodules

I had this same problem - it turned out that the .gitmodules file was committed, but the actual submodule commit (i.e. the record of the submodule's commit ID) wasn't.

Adding it manually seemed to do the trick - e.g.:

git submodule add http://github.com/sciyoshi/pyfacebook.git external/pyfacebook

(Even without removing anything from .git/config or .gitmodules.)

Then commit it to record the ID properly.

Adding some further comments to this working answer: If the git submodule init or git submodule update does'nt work, then as described above git submodule add url should do the trick. One can cross check this by

 git config --list

and one should get an entry of the submodule you want to pull in the result of the git config --list command. If there is an entry of your submodule in the config result, then now the usual git submodule update --init should pull your submodule. To test this step, you can manually rename the submodule and then updating the submodule.

 mv yourmodulename yourmodulename-temp
 git submodule update --init

To find out if you have local changes in the submodule, it can be seen via git status -u ( if you want to see changes in the submodule ) or git status --ignore-submodules ( if you dont want to see the changes in the submodule ).

Difference between modes a, a+, w, w+, and r+ in built-in open function?

Same info, just in table form

                  | r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
write after seek  |     +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

where meanings are: (just to avoid any misinterpretation)

  • read - reading from file is allowed
  • write - writing to file is allowed

  • create - file is created if it does not exist yet

  • trunctate - during opening of the file it is made empty (all content of the file is erased)

  • position at start - after file is opened, initial position is set to the start of the file

  • position at end - after file is opened, initial position is set to the end of the file

Note: a and a+ always append to the end of file - ignores any seek movements.
BTW. interesting behavior at least on my win7 / python2.7, for new file opened in a+ mode:
write('aa'); seek(0, 0); read(1); write('b') - second write is ignored
write('aa'); seek(0, 0); read(2); write('b') - second write raises IOError

JQuery, Spring MVC @RequestBody and JSON - making it work together

In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

Following yet again on the use of a custom aggregate function of string concatenation: you need to remember that the select statement will place rows in any order, so you will need to do a sub select in the from statement with an order by clause, and then an outer select with a group by clause to aggregate the strings, thus:

SELECT custom_aggregate(MY.special_strings)
FROM (SELECT special_strings, grouping_column 
        FROM a_table 
        ORDER BY ordering_column) MY
GROUP BY MY.grouping_column

iPhone - Get Position of UIView within entire UIWindow

In Swift:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

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

<span> elements are inline elements, as such layout properties such as width or margin don't work. You can fix that by either changing the <span> to a block element (such as <div>), or by using padding instead.

Note that making a span element a block element by adding display: block; is redundant, as a span is by definition a otherwise style-less inline element whereas div is an otherwise style-less block element. So the correct solution is to use a div instead of a block-span.

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

See for the protocols HTTPS and HTTP

Sometimes if you are using mixed protocols [this happens mostly with JSONP callbacks ] you can end up in this ERROR.

Make sure both the web-page and the resource page have the same HTTP protocols.

How do I select a MySQL database through CLI?

Switch to a database.

mysql> use [db name];

MySQL Commands

How to remove outliers from a dataset

Use outline = FALSE as an option when you do the boxplot (read the help!).

> m <- c(rnorm(10),5,10)
> bp <- boxplot(m, outline = FALSE)

enter image description here

Read Content from Files which are inside Zip file

As of Java 7, the NIO Api provides a better and more generic way of accessing the contents of Zip or Jar files. Actually, it is now a unified API which allows you to treat Zip files exactly like normal files.

In order to extract all of the files contained inside of a zip file in this API, you'd do this:

In Java 8:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystems.newFileSystem(fromZip, Collections.emptyMap())
            .getRootDirectories()
            .forEach(root -> {
                // in a full implementation, you'd have to
                // handle directories 
                Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
            });
}

In java 7:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());

    for(Path root : zipFs.getRootDirectories()) {
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                    throws IOException {
                // You can do anything you want with the path here
                Files.copy(file, toDirectory);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                    throws IOException {
                // In a full implementation, you'd need to create each 
                // sub-directory of the destination directory before 
                // copying files into it
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

Link to reload current page

One way using JavaScript:

<a href="javascript:window.location.reload(true)">Reload</a>

ValueError: max() arg is an empty sequence

I realized that I was iterating over a list of lists where some of them were empty. I fixed this by adding this preprocessing step:

tfidfLsNew = [x for x in tfidfLs if x != []]

the len() of the original was 3105, and the len() of the latter was 3101, implying that four of my lists were completely empty. After this preprocess my max() min() etc. were functioning again.

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

if Linux users still have the same error, probably they have used "sudo" for adding android platform.. a quick solution for this here, or you have installed cordova using sudo, also there is a solution for this problem here.

Hope this help!

Get all LI elements in array

If you want all the li tags in an array even when they are in different ul tags then you can simply do

var lis = document.getElementByTagName('li'); 

and if you want to get particular div tag li's then:

var lis = document.getElementById('divID').getElementByTagName('li'); 

else if you want to search a ul first and then its li tags then you can do:

var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
    var lis=uls[i].getElementsByTagName('li');
    for(var j=0;j<lis.length;j++){
        console.log(lis[j].innerHTML);
    }
}

Split string with delimiters in C

My approach is to scan the string and let the pointers point to every character after the deliminators(and the first character), at the same time assign the appearances of deliminator in string to '\0'.
First make a copy of original string(since it's constant), then get the number of splits by scan it pass it to pointer parameter len. After that, point the first result pointer to the copy string pointer, then scan the copy string: once encounter a deliminator, assign it to '\0' thus the previous result string is terminated, and point the next result string pointer to the next character pointer.

char** split(char* a_str, const char a_delim, int* len){
    char* s = (char*)malloc(sizeof(char) * strlen(a_str));
    strcpy(s, a_str);
    char* tmp = a_str;
    int count = 0;
    while (*tmp != '\0'){
        if (*tmp == a_delim) count += 1;
        tmp += 1;
    }
    *len = count;
    char** results = (char**)malloc(count * sizeof(char*));
    results[0] = s;
    int i = 1;
    while (*s!='\0'){
        if (*s == a_delim){
            *s = '\0';
            s += 1;
            results[i++] = s;
        }
        else s += 1;
    }
    return results;
}

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

In my case, I needed to replace this:

@Html.ActionLink("Return license", "Licenses_Revoke", "Licenses", new { id = userLicense.Id }, null)

With this:

<a href="#" onclick="returnLicense(event)">Return license</a>

<script type="text/javascript">
    function returnLicense(e) {
        e.preventDefault();

        $.post('@Url.Action("Licenses_Revoke", "Licenses", new { id = Model.Customer.AspNetUser.UserLicenses.First().Id })', getAntiForgery())
            .done(function (res) {
                window.location.reload();
            });
    }
</script>

Even if I don't understand why. Suggestions are welcome!

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Full examples of using pySerial package

I have not used pyserial but based on the API documentation at https://pyserial.readthedocs.io/en/latest/shortintro.html it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whatever you are dealing with.

Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.

In Linux, how to tell how much memory processes are using?

Why all these complicated answers with various shell scripts? Use htop, it automatically changes the sizes and you can select which info you want shown and it works in the terminal, so it does not require a desktop. Example: htop -d8

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Open Android Studio and under the Tools you will find the AVD manager. Click on it and ensure that you have a valid virtual device with the SDK downloaded (click "download" in the Actions column if shown). Then ensure that the correct virtual device is selected on the toolbar.

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I wanted to merge two branches so that all the contents in old_branch to be updated with the contents from new_branch

For me this worked like a charm:

$ git checkout new_branch
$ git merge -m 'merge message' -s ours origin/old_branch
$ git checkout old_branch
$ git merge new_branch
$ git push origin old_branch

Windows batch: formatted date into variable

You can get the current date in a locale-agnostic way using

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x

Then you can extract the individual parts using substrings:

set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%

Another way, where you get variables that contain the individual parts, would be:

for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%

Much nicer than fiddling with substrings, at the expense of polluting your variable namespace.

If you need UTC instead of local time, the command is more or less the same:

for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%

Browser detection

I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.

Or use these libs to determine the browser type if you really must.

Also see Browser & version in prototype library?

adding css file with jquery

Try doing it the other way around.

$('<link rel="stylesheet" href="css/style2.css" type="text/css" />').appendTo('head');

Postman - How to see request with headers and body data with variables substituted

Even though they are separate windows but the request you send from Postman, it's details should be available in network tab of developer tools. Just make sure you are not sending any other http traffic during that time, just for clarity.

WebAPI Multiple Put/Post parameters

Natively WebAPI doesn't support binding of multiple POST parameters. As Colin points out there are a number of limitations that are outlined in my blog post he references.

There's a workaround by creating a custom parameter binder. The code to do this is ugly and convoluted, but I've posted code along with a detailed explanation on my blog, ready to be plugged into a project here:

Passing multiple simple POST Values to ASP.NET Web API

Access cell value of datatable

string abc= dt.Rows[0]["column name"].ToString();

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

What is the default value for Guid?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000".

new Guid()

default(Guid)

Guid.Empty

How to disable sort in DataGridView?

foreach (DataGridViewColumn column in dataGridView.Columns)
{
    column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

How do I insert an image in an activity with android studio?

I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

enter image description here


Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

enter image description here

It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

enter image description here

Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/homepage"
        tools:layout_editor_absoluteX="55dp"
        tools:layout_editor_absoluteY="130dp" />

You need to give image location using

app:srcCompat="@drawable/imagename"

react-native :app:installDebug FAILED

on my android device, the problem was about the previous build versions of the application that I had installed on my phone before. the following steps solved my problem:

  1. removing any previous build of the application, including debugging version and signed apk version

  2. on the root directory of your project, run (on windows):

    cd android

    .\gradlew clean

    cd ..

    npm cache clean --force

  3. reboot your android device

hope this help you too.

How to do an Integer.parseInt() for a decimal number?

String s="0.01";
int i = Double.valueOf(s).intValue();

C++ calling base class constructors

The short answer for this is, "because that's what the C++ standard specifies".

Note that you can always specify a constructor that's different from the default, like so:

class Shape  {

  Shape()  {...} //default constructor
  Shape(int h, int w) {....} //some custom constructor


};

class Rectangle : public Shape {
  Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call

}

The default constructor of the base class is called only if you don't specify which one to call.

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

Get the Highlighted/Selected text

Yes you can do it with simple JavaScript snippet:

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

Splitting strings in PHP and get last part

As per this post:

end((explode('-', $string)));

which won't cause E_STRICT warning in PHP 5 (PHP magic). Although the warning will be issued in PHP 7, so adding @ in front of it can be used as a workaround.

How to resolve Unneccessary Stubbing exception

If you're using this style instead:

@Rule
public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

replace it with:

@Rule
public MockitoRule rule = MockitoJUnit.rule().silent();

How to rename a class and its corresponding file in Eclipse?

Just rename the class in the source code. Eclipse will point out an error by underlining the class name with a red squiggly line. Hover on that line with your mouse pointer and eclipse will give you the option to rename compilation unit. Click on that.

How to beautifully update a JPA entity in Spring Data?

I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.

  1. Use RepositoryExtendJPA.save(entity).
    Example:
    List<Person> person = this.PersonRepository.findById(0) person.setName("Neo"); This.PersonReository.save(person);
    this block code updated new name for record which has id = 0;
  2. Use @Transactional from javax or spring framework.
    Let put @Transactional upon your class or specified function, both are ok.
    I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.

How to fade changing background image

This was the only reasonable thing I found to fade a background image.

<div id="foo">
  <!-- some content here -->
</div>

Your CSS; now enhanced with CSS3 transition.

#foo {
  background-image: url(a.jpg);
  transition: background 1s linear;
}

Now swap out the background

document.getElementById("foo").style.backgroundImage = "url(b.jpg)";

Voilà, it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.

Adding files to a GitHub repository

You can use Git GUI on Windows, see instructions:

  1. Open the Git Gui (After installing the Git on your computer).

enter image description here

  1. Clone your repository to your local hard drive:

enter image description here

  1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

enter image description here

  1. You will notice the scanned files:

enter image description here

  1. Click on "Stage Changed":

enter image description here

  1. Approve and click "Commit":

enter image description here

  1. Click on "Push":

enter image description here

  1. Click on "Push":

enter image description here

  1. Wait for the files to upload to git:

enter image description here

enter image description here

Python: pandas merge multiple dataframes

functools.reduce and pd.concat are good solutions but in term of execution time pd.concat is the best.

from functools import reduce
import pandas as pd

dfs = [df1, df2, df3, ...]
nan_value = 0

# solution 1 (fast)
result_1 = pd.concat(dfs, join='outer', axis=1).fillna(nan_value)

# solution 2
result_2 = reduce(lambda df_left,df_right: pd.merge(df_left, df_right, 
                                              left_index=True, right_index=True, 
                                              how='outer'), 
                  dfs).fillna(nan_value)

What is the difference between map and flatMap and a good use case for each?

map returns RDD of equal number of elements while flatMap may not.

An example use case for flatMap Filter out missing or incorrect data.

An example use case for map Use in wide variety of cases where is the number of elements of input and output are the same.

number.csv

1
2
3
-
4
-
5

map.py adds all numbers in add.csv.

from operator import *

def f(row):
  try:
    return float(row)
  except Exception:
    return 0

rdd = sc.textFile('a.csv').map(f)

print(rdd.count())      # 7
print(rdd.reduce(add))  # 15.0

flatMap.py uses flatMap to filtered out missing data before addition. Less numbers are added compared to the previous version.

from operator import *

def f(row):
  try:
    return [float(row)]
  except Exception:
    return []

rdd = sc.textFile('a.csv').flatMap(f)

print(rdd.count())      # 5
print(rdd.reduce(add))  # 15.0

What is the most efficient way of finding all the factors of a number in Python?

I've tried most of these wonderful answers with timeit to compare their efficiency versus my simple function and yet I constantly see mine outperform those listed here. I figured I'd share it and see what you all think.

def factors(n):
    results = set()
    for i in xrange(1, int(math.sqrt(n)) + 1):
        if n % i == 0:
            results.add(i)
            results.add(int(n/i))
    return results

As it's written you'll have to import math to test, but replacing math.sqrt(n) with n**.5 should work just as well. I don't bother wasting time checking for duplicates because duplicates can't exist in a set regardless.

Retrieving a property of a JSON object by index?

Simple solution, just one line..

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

obj = Object.values(obj);

obj[1]....

Equivalent of Oracle's RowID in SQL Server

You can get the ROWID by using the methods given below :

1.Create a new table with auto increment field in it

2.Use Row_Number analytical function to get the sequence based on your requirement.I would prefer this because it helps in situations where you are you want the row_id on ascending or descending manner of a specific field or combination of fields

Sample:Row_Number() Over(Partition by Deptno order by sal desc)

Above sample will give you the sequence number based on highest salary of each department.Partition by is optional and you can remove it according to your requirements

How do I convert a factor into date format?

You can try lubridate package which makes life much easier

library(lubridate)

mdy_hms(mydate)

The above will change the date format to POSIXct

A sample working example:

> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt" 

For case with factor use as.character

data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

Hadoop cluster setup - java.net.ConnectException: Connection refused

Check your firewall setting and set

  <property>
  <name>fs.default.name</name>
  <value>hdfs://MachineName:9000</value>
  </property>

replace localhost to machine name

Cannot implicitly convert type 'int?' to 'int'.

You can change the last line to following (assuming you want to return 0 when there is nothing in db):

return OrdersPerHour == null ? 0 : OrdersPerHour.Value;

How to validate a date?

var isDate_ = function(input) {
        var status = false;
        if (!input || input.length <= 0) {
          status = false;
        } else {
          var result = new Date(input);
          if (result == 'Invalid Date') {
            status = false;
          } else {
            status = true;
          }
        }
        return status;
      }

this function returns bool value of whether the input given is a valid date or not. ex:

if(isDate_(var_date)) {
  // statements if the date is valid
} else {
  // statements if not valid
}

Problems with jQuery getJSON using local files in Chrome

You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.

long long int vs. long int vs. int64_t in C++

Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like

template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64

Showing empty view when ListView is empty

Activity code, its important to extend ListActivity.

package com.example.mylistactivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import com.example.mylistactivity.R;

// It's important to extend ListActivity rather than Activity
public class MyListActivity extends ListActivity {

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

        // shows list view
        String[] values = new String[] { "foo", "bar" };

        // shows empty view
        values = new String[] { };

        setListAdapter(new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                values));
    }
}

Layout xml, the id in both views are important.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- the android:id is important -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

    <!-- the android:id is important -->
    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="i am empty"/>
</LinearLayout>

MongoDB "root" user

Mongodb user management:

roles list:

read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase

create user:

db.createUser(user, writeConcern)

db.createUser({ user: "user",
  pwd: "pass",
  roles: [
    { role: "read", db: "database" } 
  ]
})

update user:

db.updateUser("user",{
  roles: [
    { role: "readWrite", db: "database" } 
  ]
})

drop user:

db.removeUser("user")

or

db.dropUser("user")

view users:

db.getUsers();

more information: https://docs.mongodb.com/manual/reference/security/#read

A fast way to delete all rows of a datatable at once

If you are running your code against a sqlserver database then
use this command

string sqlTrunc = "TRUNCATE TABLE " + yourTableName
SqlCommand cmd = new SqlCommand(sqlTrunc, conn);
cmd.ExecuteNonQuery();

this will be the fastest method and will delete everything from your table and reset the identity counter to zero.

The TRUNCATE keyword is supported also by other RDBMS.

5 years later:
Looking back at this answer I need to add something. The answer above is good only if you are absolutely sure about the source of the value in the yourTableName variable. This means that you shouldn't get this value from your user because he can type anything and this leads to Sql Injection problems well described in this famous comic strip. Always present your user a choice between hard coded names (tables or other symbolic values) using a non editable UI.

How to insert a new key value pair in array in php?

Try this:

foreach($array as $k => $obj) { 
    $obj->{'newKey'} = "value"; 
}

Bootstrap button drop-down inside responsive table not visible because of scroll

Simply Use This

.table-responsive {
    overflow: inherit;
}

It works on Chrome, but not IE10 or Edge because inherit property is not supported

How do I change file permissions in Ubuntu

Add -R for recursive:

sudo chmod -R 666 /var/www

List all sequences in a Postgres db 8.1 with SQL

Assuming exec() function declared in this post https://stackoverflow.com/a/46721603/653539 , sequences together with their last values can be fetched using single query:

select s.sequence_schema, s.sequence_name,
  (select * from exec('select last_value from ' || s.sequence_schema || '.' || s.sequence_name) as e(lv bigint)) last_value
from information_schema.sequences s

Bootstrap 4, how to make a col have a height of 100%?

I have tried over a half-dozen solutions suggested on Stack Overflow, and the only thing that worked for me was this:

<div class="row" style="display: flex; flex-wrap: wrap">
    <div class="col-md-6">
        Column A
    </div>
    <div class="col-md-6">
        Column B
    </div>
</div>

I got the solution from https://codepen.io/ondrejsvestka/pen/gWPpPo

Note that it seems to affect the column margins. I had to apply adjustments to those.

Single line sftp from terminal

To UPLOAD a single file, you will need to create a bash script. Something like the following should work on OS X if you have sshpass installed.

Usage:

sftpx <password> <user@hostname> <localfile> <remotefile>

Put this script somewhere in your path and call it sftpx:

#!/bin/bash

export RND=`cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32`
export TMPDIR=/tmp/$RND
export FILENAME=$(basename "$4")
export DSTDIR=$(dirname "$4")

mkdir $TMPDIR
cp "$3" $TMPDIR/$FILENAME

export SSHPASS=$1
sshpass -e sftp -oBatchMode=no -b - $2 << !
   lcd $TMPDIR
   cd $DSTDIR
   put $FILENAME
   bye
!

rm $TMPDIR/$FILENAME
rmdir $TMPDIR

Adding items in a Listbox with multiple columns

select propety

Row Source Type => Value List

Code :

ListbName.ColumnCount=2

ListbName.AddItem "value column1;value column2"

How to count duplicate rows in pandas dataframe?

None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:

# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})

# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]

Remove URL parameters without refreshing page

a simple way to do this, works on any page, requires HTML 5

// get the string following the ?
var query = window.location.search.substring(1)

// is there anything there ?
if(query.length) {
   // are the new history methods available ?
   if(window.history != undefined && window.history.pushState != undefined) {
        // if pushstate exists, add a new state to the history, this changes the url without reloading the page

        window.history.pushState({}, document.title, window.location.pathname);
   }
}

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

Where can I find error log files?

This is a preferable answer in most use cases, because it allows you to decouple execution of the software from direct knowledge of the server platform, which keeps your code much more portable. If you are doing a lot of cron/cgi, this may not help directly, but it can be set into a config at web runtime that the cron/cgi scripts pull from to keep the log location consistent in that case.


You can get the current log file assigned natively to php on any platform at runtime by using:

ini_get('error_log');

This returns the value distributed directly to the php binary by the webserver, which is what you want in 90% of use cases (with the glaring exception being cgi). Cgi will often log to this same location as the http webserver client, but not always.

You will also want to check that it is writeable before committing anything to it to avoid errors. The conf file that defines it's location (typically either apache.conf globally or vhosts.conf on a per-domain basis), but the conf does not ensure that file permissions allow write access at runtime.

how to refresh my datagridview after I add new data

You can use a binding source to bind to with your datagridview. Set your class or list of data. Set a bindingsource.datasource equal to that. Set the datasource of your datagridview to your bindingsource.

How do I convert a float number to a whole number in JavaScript?

If look into native Math object in JavaScript, you get the whole bunch of functions to work on numbers and values, etc...

Basically what you want to do is quite simple and native in JavaScript...

Imagine you have the number below:

const myValue = 56.4534931;

and now if you want to round it down to the nearest number, just simply do:

const rounded = Math.floor(myValue);

and you get:

56

If you want to round it up to the nearest number, just do:

const roundedUp = Math.ceil(myValue);

and you get:

57

Also Math.round just round it to higher or lower number depends on which one is closer to the flot number.

Also you can use of ~~ behind the float number, that will convert a float to a whole number.

You can use it like ~~myValue...

What is web.xml file and what are all things can I do with it?

What is web.xml file and what all things can I do with it ?

The /WEB-INF/web.xml file is the Web Application Deployment Descriptor of your application. This file is an XML document that defines everything about your application that a server needs to know (except the context path, which is assigned by the Application Deployer and Administrator when the application is deployed): servlets and other components like filters or listeners, initialization parameters, container-managed security constraints, resources, welcome pages, etc.

Note that reference you mentioned is pretty old (Java EE 1.4), there have been few changes in Java EE 5 and even more in Java EE 6 (which makes the web.xml "optional" and introduces Web Fragments).

Is there any configuration parameter which should be avoided like plague?

No.

Any parameters related to performance or memory usage?

No, such things are not configured at the application level but at the container level.

Security related risk due to common mis-configuration ?

Well, if you want to use container-managed security constraints and fail at configuring them properly, resources won't obviously be properly protected. Apart from that, the biggest security risks come from the code you'll deploy IMO.

Maven command to determine which settings.xml file Maven is using

You can use the maven help plugin to tell you the contents of your user and global settings files.

mvn help:effective-settings

will ask maven to spit out the combined global and user settings.

Running a simple shell script as a cronjob

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don´t want GUI´s you may use:

crontab -e

If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don´t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don´t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

(HTML) Download a PDF file instead of opening them in browser when clicked

This is only possible with setting a http response header by the server side code. Namely;

Content-Disposition: attachment; filename=fname.ext

Java Reflection: How to get the name of a variable?

see this example :

PersonneTest pt=new PersonneTest();
System.out.println(pt.getClass().getDeclaredFields().length);
Field[]x=pt.getClass().getDeclaredFields();
System.out.println(x[1].getName());

Is there a shortcut to make a block comment in Xcode?

Cmd + Shift + 7 will comment the selected lines.

How to mount a host directory in a Docker container

You can also do this with Portainer web application for a different visual experience.

First pull the Portainer image:

docker pull portainer/portainer

Then create a volume for Portainer:

docker volume create portainer_data

Also create a Portainer container:

docker run -d -p 8000:8000 -p 9000:9000 --name=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

You will be able to access the web app with your browser at this URL: "http://localhost:9000". At the first login, you will be prompted to set your Portainer admin credentials.

In the web app, follow these menus and buttons: (Container > Add container > Fill settings > Deploy Container)

I had trouble to create a "mount" volume with Portainer and I realized I had to click "bind" when creating my container's volume. Below is an illustration of the volume binding settings that worked for my container creation with a mounted volume binded to the host.

volume binding settings

P.S.: I'm using Docker 19.035 and Portainer 1.23.1

nvarchar(max) still being truncated

Results to text only allows a maximum of 8192 characters.

Screenshot

I use this approach

DECLARE @Query NVARCHAR(max);

set @Query = REPLICATE('A',4000)
set @Query = @Query + REPLICATE('B',4000)
set @Query = @Query + REPLICATE('C',4000)
set @Query = @Query + REPLICATE('D',4000)

select LEN(@Query)

SELECT @Query /*Won't contain any "D"s*/
SELECT @Query as [processing-instruction(x)] FOR XML PATH /*Not truncated*/

Android Closing Activity Programmatically

you can use finishAffinity(); to close all the activity..

Find if variable is divisible by 2

You don't need jQuery. Just use JavaScript's Modulo operator.

How to create a temporary directory?

The following snippet will safely create a temporary directory (-d) and store its name into the TMPDIR. (An example use of TMPDIR variable is shown later in the code where it's used for storing original files that will be possibly modified.)

The first trap line executes exit 1 command when any of the specified signals is received. The second trap line removes (cleans up) the $TMPDIR on program's exit (both normal and abnormal). We initialize these traps after we check that mkdir -d succeeded to avoid accidentally executing the exit trap with $TMPDIR in an unknown state.

#!/bin/bash

# Create a temporary directory and store its name in a variable ...
TMPDIR=$(mktemp -d)

# Bail out if the temp directory wasn't created successfully.
if [ ! -e $TMPDIR ]; then
    >&2 echo "Failed to create temp directory"
    exit 1
fi

# Make sure it gets removed even if the script exits abnormally.
trap "exit 1"           HUP INT PIPE QUIT TERM
trap 'rm -rf "$TMPDIR"' EXIT

# Example use of TMPDIR:
for f in *.csv; do
    cp "$f" "$TMPDIR"
    # remove duplicate lines but keep order
    perl -ne 'print if ++$k{$_}==1' "$TMPDIR/$f" > "$f"
done

Eclipse projects not showing up after placing project files in workspace/projects

Or you could try:

  1. Go to File -> Switch Workspace
  2. Select your workspace (if shown)

CSS Circle with border

Try this:

.circle {
    height: 20px;
    width: 20px;
    padding: 5px;
    text-align: center; 
    border-radius: 50%;
    display: inline-block;
    color:#fff;
    font-size:1.1em;
    font-weight:600;
    background-color: rgba(0,0,0,0.1);
    border: 1px solid rgba(0,0,0,0.2);
}

How to check if two words are anagrams

I saw that no one has used the "hashcode" approach to find out the anagrams. I found my approach little different than the approaches discussed above hence thought of sharing it. I wrote the below code to find the anagrams which works in O(n).

/**
 * This class performs the logic of finding anagrams
 * @author ripudam
 *
 */
public class AnagramTest {

    public static boolean isAnagram(final String word1, final String word2) {

            if (word1 == null || word2 == null || word1.length() != word2.length()) {
                 return false;
            }

            if (word1.equals(word2)) {
                return true;
            }

            final AnagramWrapper word1Obj = new AnagramWrapper(word1);
            final AnagramWrapper word2Obj = new AnagramWrapper(word2);

            if (word1Obj.equals(word2Obj)) {
                return true;
            }

            return false;
        }

        /*
         * Inner class to wrap the string received for anagram check to find the
         * hash
         */
        static class AnagramWrapper {
            String word;

            public AnagramWrapper(final String word) {
                this.word = word;
            }

            @Override
            public boolean equals(final Object obj) {

                return hashCode() == obj.hashCode();
            }

            @Override
            public int hashCode() {
                final char[] array = word.toCharArray();
                int hashcode = 0;
                for (final char c : array) {
                    hashcode = hashcode + (c * c);
                }
                return hashcode;
            }
         }
    }

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

You can use the xmp element, see What was the <XMP> tag used for?. It has been in HTML since the beginning and is supported by all browsers. Specifications frown upon it, but HTML5 CR still describes it and requires browsers to support it (though it also tells authors not to use it, but it cannot really prevent you).

Everything inside xmp is taken as such, no markup (tags or character references) is recognized there, except, for apparent reason, the end tag of the element itself, </xmp>.

Otherwise xmp is rendered like pre.

When using “real XHTML”, i.e. XHTML served with an XML media type (which is rare), the special parsing rules do not apply, so xmp is treated like pre. But in “real XHTML”, you can use a CDATA section, which implies similar parsing rules. It has no special formatting, so you would probably want to wrap it inside a pre element:

<pre><![CDATA[
This is a demo, tags like <p> will
appear literally.
]]></pre>

I don’t see how you could combine xmp and CDATA section to achieve so-called polyglot markup

What does "export" do in shell programming?

Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

Non-exported variables are only visible from the current process (the shell).

From the bash man page:

export [-fn] [name[=word]] ...
export -p

The supplied names are marked for automatic export to the environment of subsequently executed commands.

If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

The -n option causes the export property to be removed from each name.

If a variable name is followed by =word, the value of the variable is set to word.

export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

Adding content to a linear layout dynamically?

In your onCreate(), write the following

LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);

view1, view2 and view3 are your TextViews. They're easily created programmatically.

What USB driver should we use for the Nexus 5?

Are you sure it's a driver problem? A device that isn't detected probably has a hardware or firmware problem. If it isn't detected, you won't hear the USB device detected chime. It might not be serious, e.g. some "USB" cables are really only charging cables. Try a USB cable that you know works for data, e.g. the one that came with the phone or one you use for connecting an external hard drive.

How to disable keypad popup when on edittext?

People have suggested many great solutions here, but I used this simple technique with my EditText (nothing in java and AnroidManifest.xml is required). Just set your focusable and focusableInTouchMode to false directly on EditText.

 <EditText
        android:id="@+id/text_pin"
        android:layout_width="136dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:textAlignment="center"
        android:inputType="numberPassword"
        android:password="true"
        android:textSize="24dp"
        android:focusable="false"
        android:focusableInTouchMode="false"/>

My intent here is to use this edit box in App lock activity where I am asking user to input the PIN and I want to show my custom PIN pad. Tested with minSdk=8 and maxSdk=23 on Android Studio 2.1

enter image description here

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

find files by extension, *.html under a folder in nodejs

i like using the glob package:

const glob = require('glob');

glob(__dirname + '/**/*.html', {}, (err, files)=>{
  console.log(files)
})

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.

http://chromedriver.storage.googleapis.com/index.html?path=2.24/

It is working for me in Win7 64 bit.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

How to convert int to float in C?

You are doing integer arithmetic, so there the result is correct. Try

percentage=((double)number/total)*100;

BTW the %f expects a double not a float. By pure luck that is converted here, so it works out well. But generally you'd mostly use double as floating point type in C nowadays.

Save string to the NSUserDefaults?

Here Swift updated:

let userID = "BOB"  

Declare userDefaults:

let defaults = UserDefaults.standard
defaults.setValue(userID, forKey: "userID")

And get it:

let userID = defaults.object(forKey: "userID")

Change bootstrap navbar background color and font color

I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #000; /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
        a:hover, .navbar-default .navbar-nav > .active > a:focus {
    color: white; /*BACKGROUND color for active*/
    background-color: #030033;
}

.navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
    color: #262626;
    text-decoration: none;
    background-color: #66CCFF; /*change color of links in drop down here*/
}

.nav > li > a:hover,
.nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
}

.navbar-default .navbar-nav > li > a {
    color: white; /*Change active text color here*/
}

How to browse localhost on Android device?

For the mac user:

I have worked on this problem for one afternoon until I realized the Xampp I used was not the real "Xampp" It was Xampp VM which runs itself based on a Linux virtual machine. That made it not running on localhost, instead, another IP. I installed the real Xampp and run my local server on localhost and then just access it with the IP of my mac.

Hope this will help someone.

Portable way to check if directory exists [Windows/Linux, C]

You can use the GTK glib to abstract from OS stuff.

glib provides a g_dir_open() function which should do the trick.

How to print time in format: 2009-08-10 18:17:54.811

You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.

struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);

how to display employee names starting with a and then b in sql

select * 
from stores 
where name like 'a%' or 
name like 'b%' 
order by name

Get gateway ip address in android

I'm using cyanogenmod 7.2 on android 2.3.4, then just open terminal emulator and type:

$ ip addr show
$ ip route show

Separators for Navigation

The other solution are OK, but there is no need to add separator at the very last if using :after or at the very beginning if using :before.

SO:

case :after

.link:after {
  content: '|';
  padding: 0 1rem;
}

.link:last-child:after {
  content: '';
}

case :before

.link:before {
  content: '|';
  padding: 0 1rem;
}

.link:first-child:before {
  content: '';
}

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

Not sure you resolved this issue or not, but this is how I do it and it works on Android:

  1. Use openssl to merge client's cert(cert must be signed by a CA that accepted by server) and private key into a PCKS12 format key pair: openssl pkcs12 -export -in clientcert.pem -inkey clientkey.pem -out client.p12
  2. You may need patch your JRE to umlimited strength encryption depends on your key strength: copy the jar files fromJCE 5.0 unlimited strength Jurisdiction Policy FIles and override those in your JRE (eg.C:\Program Files\Java\jre6\lib\security)
  3. Use Portecle tool mentioned above and create a new keystore with BKS format
  4. Import PCKS12 key pair generated in step 1 and save it as BKS keystore. This keystore works with Android client authentication.
  5. If you need to do certificate chain, you can use this IBM tool:KeyMan to merge client's PCKS12 key pair with CA cert. But it only generate JKS keystore, so you again need Protecle to convert it to BKS format.

nginx 502 bad gateway

I had the same problem while setting up an Ubuntu server. Turns out I was having the problem due to incorrect permissions on socket file.

If you are having the problem due to a permission problem, you can uncomment the following lines from: /etc/php5/fpm/pool.d/www.conf

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

Alternatively, although I wouldn't recommend, you can give read and write permissions to all groups by using the following command.

sudo chmod go+rw /var/run/php5-fpm.sock

HTTP status code for update and delete?

Since the question delves into if DELETE "should" return 200 vs 204 it is worth considering that some people recommend returning an entity with links so the preference is for 200.

"Instead of returning 204 (No Content), the API should be helpful and suggest places to go. In this example I think one obvious link to provide is to" 'somewhere.com/container/' (minus 'resource') "- the container from which the client just deleted a resource. Perhaps the client wishes to delete more resources, so that would be a helpful link."

http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/

If a client encounters a 204 response, it can either give up, go to the entry point of the API, or go back to the previous resource it visited. Neither option is particularly good.

Personally I would not say 204 is wrong (neither does the author; he says "annoying") because good caching at the client side has many benefits. Best is to be consistent either way.

Best way to Bulk Insert from a C# DataTable

string connectionString= ServerName + DatabaseName + SecurityType;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
    connection.Open();
    bulkCopy.DestinationTableName = "TableName";
    try {
        bulkCopy.WriteToServer(dataTableName);
    } catch (Exception e) {
        Console.Write(e.Message);
    }
}

Please note that the structure of the database table and the table name should be the same or it will throw an exception.

What is the difference between a process and a thread?

First, let's look at the theoretical aspect. You need to understand what a process is conceptually to understand the difference between a process and a thread and what's shared between them.

We have the following in section 2.2.2 The Classical Thread Model of Modern Operating Systems 3e by Tanenbaum:

The process model is based on two independent concepts: resource grouping and execution. Sometimes it is use­ful to separate them; this is where threads come in....

He continues:

One way of looking at a process is that it is a way to group related resources together. A process has an address space containing program text and data, as well as other resources. These resource may include open files, child processes, pending alarms, signal handlers, accounting information, and more. By putting them together in the form of a process, they can be managed more easily. The other concept a process has is a thread of execution, usually shortened to just thread. The thread has a program counter that keeps track of which instruc­tion to execute next. It has registers, which hold its current working variables. It has a stack, which contains the execution history, with one frame for each proce­dure called but not yet returned from. Although a thread must execute in some process, the thread and its process are different concepts and can be treated sepa­rately. Processes are used to group resources together; threads are the entities scheduled for execution on the CPU.

Further down he provides the following table:

Per process items             | Per thread items
------------------------------|-----------------
Address space                 | Program counter
Global variables              | Registers
Open files                    | Stack
Child processes               | State
Pending alarms                |
Signals and signal handlers   |
Accounting information        |

Let's deal with the hardware multithreading issue. Classically, a CPU would support a single thread of execution, maintaining the thread's state via a single program counter (PC), and set of registers. But what happens when there's a cache miss? It takes a long time to fetch data from main memory, and while that's happening the CPU is just sitting there idle. So someone had the idea to basically have two sets of thread state (PC + registers) so that another thread (maybe in the same process, maybe in a different process) can get work done while the other thread is waiting on main memory. There are multiple names and implementations of this concept, such as Hyper-threading and simultaneous multithreading (SMT for short).

Now let's look at the software side. There are basically three ways that threads can be implemented on the software side.

  1. User space threads
  2. Kernel threads
  3. A combination of the two

All you need to implement threads is the ability to save the CPU state and maintain multiple stacks, which can in many cases be done in user space. The advantage of user space threads is super fast thread switching since you don't have to trap into the kernel and the ability to schedule your threads the way you like. The biggest drawback is the inability to do blocking I/O (which would block the entire process and all its user threads), which is one of the big reasons we use threads in the first place. Blocking I/O using threads greatly simplifies program design in many cases.

Kernel threads have the advantage of being able to use blocking I/O, in addition to leaving all the scheduling issues to the OS. But each thread switch requires trapping into the kernel which is potentially relatively slow. However, if you're switching threads because of blocked I/O this isn't really an issue since the I/O operation probably trapped you into the kernel already anyway.

Another approach is to combine the two, with multiple kernel threads each having multiple user threads.

So getting back to your question of terminology, you can see that a process and a thread of execution are two different concepts and your choice of which term to use depends on what you're talking about. Regarding the term "light weight process", I don't personally see the point in it since it doesn't really convey what's going on as well as the term "thread of execution".

Download a file by jQuery.Ajax

The HTML Code:-

'<button type="button" id="GetFile">Get File!</button>'


The jQuery Code:-

'$('#GetFile').on('click', function () {
    $.ajax({
        url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/172905/test.pdf',
        method: 'GET',
        xhrFields: {
            responseType: 'blob'
        },
        success: function (data) {
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(data);
            a.href = url;
            a.download = 'myfile.pdf';
            document.body.append(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        }
    });
});'

req.body empty on posts

I had the same problem a few minutes ago, I tried everything possible in the above answers but any of them worked.

The only thing I did, was upgrade Node JS version, I didn't know that upgrading could affect in something, but it did.

I have installed Node JS version 10.15.0 (latest version), I returned to 8.11.3 and everything is now working. Maybe body-parser module should take a fix on this.

html select only one checkbox in a group

With plain old javascript.

<html>
<head>
</head>
<body>
<input type="checkbox" name="group1[]" id="groupname1" onClick="toggle(1,'groupname')"/>
<input type="checkbox" name="group1[]" id="groupname2" onClick="toggle(2,'groupname')"  />
<input type="checkbox" name="group1[]" id="groupname3" onClick="toggle(3,'groupname')" />

<input type="checkbox" name="group2[]" id="diffGroupname1" onClick="toggle(1,'diffGroupname')"/>
<input type="checkbox" name="group2[]" id="diffGroupname2" onClick="toggle(2,'diffGroupname')"  />
<input type="checkbox" name="group2[]" id="diffGroupname3" onClick="toggle(3,'diffGroupname')" />
<script>
function toggle(which,group){
var counter=1;
var checkbox=document.getElementById(group+counter);
while(checkbox){
if(counter==which){

}else{
checkbox.checked=false;
}
counter++;
checkbox=document.getElementById(group+counter);
}
}
</script>
</body>
</html>

edit: also possible

<html>
<head>
</head>
<body>
<input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')"/>
<input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')"  />
<input type="checkbox" name="group1[]" class="groupname" onClick="toggle(this,'groupname')" />

<input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')"/>
<input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')"  />
<input type="checkbox" name="group2[]" class="diffGroupname" onClick="toggle(this,'diffGroupname')" />
<script>
function toggle(which,theClass){
var checkbox=document.getElementsByClassName(theClass);
for(var i=0;i<checkbox.length;i++){
if(checkbox[i]==which){

}else{
checkbox[i].checked=false;
}
}
}
</script>
</body>
</html>

HTML5 Video tag not working in Safari , iPhone and iPad

If your videos are protected by a session-based login system, Safari will fail to load them. This is because Safari makes an initial request for the video, then hands the task over to QuickTime, which makes another request. Since Safari holds the session info, it will pass the authentication, but QuickTime will not.

You can see this if you view your server access log ... first the request from Safari, then the request from QuickTime. Other browsers just make a single request from the browser itself.

If this is your problem, you might have to rework the video access to use temporary tokens or a limited time access from the original request. I'll update this answer if I find a more direct solution.

jquery toggle slide from left to right and back

Hide #categories initially

#categories {
    display: none;
}

and then, using JQuery UI, animate the Menu slowly

var duration = 'slow';

$('#cat_icon').click(function () {
    $('#cat_icon').hide(duration, function() {
        $('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

You can use any time in milliseconds as well

var duration = 2000;

If you want to hide on class='panel_item' too, select both panel_title and panel_item

$('.panel_title,.panel_item').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

Sorry for digging up such an old thread, but there is a major error in the following reasoning:

RAII moves the responsibility of exception safety from the user of the object to the designer (and implementer) of the object. I would argue this is the correct place as you then only need to get exception safety correct once (in the design/implementation). By using finally you need to get exception safety correct every time you use an object.

More often than not, you have to deal with dynamically allocated objects, dynamic numbers of objects etc. Within the try-block, some code might create many objects (how many is determined at runtime) and store pointers to them in a list. Now, this is not an exotic scenario, but very common. In this case, you'd want to write stuff like

void DoStuff(vector<string> input)
{
  list<Foo*> myList;

  try
  {    
    for (int i = 0; i < input.size(); ++i)
    {
      Foo* tmp = new Foo(input[i]);
      if (!tmp)
        throw;

      myList.push_back(tmp);
    }

    DoSomeStuff(myList);
  }
  finally
  {
    while (!myList.empty())
    {
      delete myList.back();
      myList.pop_back();
    }
  }
}

Of course the list itself will be destroyed when going out of scope, but that wouldn't clean up the temporary objects you have created.

Instead, you have to go the ugly route:

void DoStuff(vector<string> input)
{
  list<Foo*> myList;

  try
  {    
    for (int i = 0; i < input.size(); ++i)
    {
      Foo* tmp = new Foo(input[i]);
      if (!tmp)
        throw;

      myList.push_back(tmp);
    }

    DoSomeStuff(myList);
  }
  catch(...)
  {
  }

  while (!myList.empty())
  {
    delete myList.back();
    myList.pop_back();
  }
}

Also: why is it that even managed lanuages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?

Hint: there's more you can do with "finally" than just memory deallocation.

How to check if click event is already bound - JQuery

Here's my version:

Utils.eventBoundToFunction = function (element, eventType, fCallback) {
    if (!element || !element.data('events') || !element.data('events')[eventType] || !fCallback) {
        return false;
    }

    for (runner in element.data('events')[eventType]) {
        if (element.data('events')[eventType][runner].handler == fCallback) {
            return true;
        }

    }

    return false;
};

Usage:

Utils.eventBoundToFunction(okButton, 'click', handleOkButtonFunction)

Pandas: sum DataFrame rows for given columns

If you have just a few columns to sum, you can write:

df['e'] = df['a'] + df['b'] + df['d']

This creates new column e with the values:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

For longer lists of columns, EdChum's answer is preferred.

JQuery: detect change in input field

Use $.on() to bind your chosen event to the input, don't use the shortcuts like $.keydown() etc because as of jQuery 1.7 $.on() is the preferred method to attach event handlers (see here: http://api.jquery.com/on/ and http://api.jquery.com/bind/).

$.keydown() is just a shortcut to $.bind('keydown'), and $.bind() is what $.on() replaces (among others).

To answer your question, as far as I'm aware, unless you need to fire an event on keydown specifically, the change event should do the trick for you.

$('element').on('change', function(){
    console.log('change');
});

To respond to the below comment, the javascript change event is documented here: https://developer.mozilla.org/en-US/docs/Web/Events/change

And here is a working example of the change event working on an input element, using jQuery: http://jsfiddle.net/p1m4xh08/

Ways to circumvent the same-origin policy

AnyOrigin didn't function well with some https sites, so I just wrote an open source alternative called whateverorigin.org that seems to work well with https.

Code on github.

Bootstrap select dropdown list placeholder

Use hidden:

<select>
    <option hidden >Display but don't show in list</option>
    <option> text 1 </option>
    <option> text 2 </option>
    <option> text 3 </option>
</select>

How to cast List<Object> to List<MyClass>

List<Object[]> testNovedads = crudService.createNativeQuery(
            "SELECT ID_NOVEDAD_PK, OBSERVACIONES, ID_SOLICITUD_PAGO_FK FROM DBSEGUIMIENTO.SC_NOVEDADES WHERE ID_NOVEDAD_PK < 2000");

Convertir<TestNovedad> convertir = new Convertir<TestNovedad>();
Collection<TestNovedad> novedads = convertir.toList(testNovedads, TestNovedad.class);
for (TestNovedad testNovedad : novedads) {
    System.out.println(testNovedad.toString());
}

public Collection<T> toList(List<Object[]> objects, Class<T> type) {
    Gson gson = new Gson();
    JSONObject jsonObject = new JSONObject();
    Collection<T> collection = new ArrayList<>();
    Field[] fields = TestNovedad.class.getDeclaredFields();
    for (Object[] object : objects) {
        int pos = 0;
        for (Field field : fields) {
            jsonObject.put(field.getName(), object[pos++]);
        }
        collection.add(gson.fromJson(jsonObject.toString(), type));
    }
    return collection;
}

How to place a div on the right side with absolute position

I'm assuming that your container element is probably position:relative;. This is will mean that the dialog box will be positioned accordingly to the container, not the page.

Can you change the markup to this?

<html>
<body>
    <!-- Need to place this div at the top right of the page-->
        <div class="ajax-message">
            <div class="row">
                <div class="span9">
                    <div class="alert">
                        <a class="close icon icon-remove"></a>
                        <div class="message-content">
                            Some message goes here
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <div class="container">
        <!-- Page contents starts here. These are dynamic-->
        <div class="row">
            <div class="span12 inner-col">
                <h2>Documents</h2>
            </div>
        </div>
    </div>
</body>
</html>

With the dialog box outside the main container then you can use absolute positioning relative to the page.

Firebug-like debugger for Google Chrome

If you are using Chromium on Ubuntu using the nightly ppa, then you should have the chromium-browser-inspector

Java String to SHA1

This is my solution of converting string to sha1. It works well in my Android app:

private static String encryptPassword(String password)
{
    String sha1 = "";
    try
    {
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(password.getBytes("UTF-8"));
        sha1 = byteToHex(crypt.digest());
    }
    catch(NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
    catch(UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    return sha1;
}

private static String byteToHex(final byte[] hash)
{
    Formatter formatter = new Formatter();
    for (byte b : hash)
    {
        formatter.format("%02x", b);
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}

How to check if a socket is connected/disconnected in C#?

Following the advice from NibblyPig and zendar, I came up with the code below, which works on every test I made. I ended up needing both the ping, and the poll. The ping will let me know if the cable has been disconnected, or the physical layer otherwise disrupted (router powered off, etc). But sometimes after reconnect I get a RST, the ping is ok, but the tcp state is not.

#region CHECKS THE SOCKET'S HEALTH
    if (_tcpClient.Client.Connected)
    {
            //Do a ping test to see if the server is reachable
            try
            {
                Ping pingTest = new Ping()
                PingReply reply = pingTest.Send(ServeripAddress);
                if (reply.Status != IPStatus.Success) ConnectionState = false;
            } catch (PingException) { ConnectionState = false; }

            //See if the tcp state is ok
            if (_tcpClient.Client.Poll(5000, SelectMode.SelectRead) && (_tcpClient.Client.Available == 0))
            {
                ConnectionState = false;
            }
        }
    }
    else { ConnectionState = false; }
#endregion

List of installed gems?

Gem::Specification.map {|a| a.name}

However, if your app uses Bundler it will return only list of dependent local gems. To get all installed:

def all_installed_gems
   Gem::Specification.all = nil    
   all = Gem::Specification.map{|a| a.name}  
   Gem::Specification.reset
   all
end

Where are SQL Server connection attempts logged?

If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.

Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.

If you want to audit a client application name along with each failed login, you can use an Extended Events session.

To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

'negative' pattern matching in python

See it in action:

matchObj = re.search("^(?!OK|\\.).*", item)

Don't forget to put .* after negative look-ahead, otherwise you couldn't get any match ;-)

The type or namespace name 'DbContext' could not be found

I am using Visual Studio 2010 express and adding a reference to C:\Program Files\Microsoft ADO.NET Entity Framework 4.1\Binaries\EntityFramework.dll solved the problem.

AngularJS: Can't I set a variable value on ng-click?

If you are using latest versions of Angular (2/5/6) :

In your component.ts

//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

How to execute only one test spec with angular-cli

This worked for me in every case:

ng test --include='**/dealer.service.spec.ts'

However, I usually got "TypeError: Cannot read property 'ngModule' of null" for this:

ng test --main src/app/services/dealer.service.spec.ts

Version of @angular/cli 10.0.4

How do I use the conditional operator (? :) in Ruby?

The code condition ? statement_A : statement_B is equivalent to

if condition == true
  statement_A
else
  statement_B
end

Produce a random number in a range using C#

Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.

public static class RandomExtensionMethods
{
    public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
    {
        return random.NextDouble() * (maxNumber - minNumber) + minNumber;
    }
}

Usage (make sure to import the namespace that contain the RandomExtensionMethods class):

var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);

phpMyAdmin allow remote users

My setup was a little different using XAMPP. in httpd-xampp.conf I had to make the following change.

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

change to

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    #makes it so I can config the database from anywhere
    #change the line below
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

I need to state that I'm brand new at this so I'm just hacking around but this is how I got it working.

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String? = "Bertie"

Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea of what they are. Compare the optional above to creating a normal String:

var name: String = "Bertie" // No "?" after String

From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.

Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.

You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ?-clicking on it. Here's the important part of the definition:

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

Optional is just an enum which can be one of two cases: .none or .some. If it's .some, there's an associated value which, in the example above, would be the String "Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String, it's Optional, or more precisely Optional<String>.

Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.

Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.


How to create optionals

To create an optional, append a ? after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?.

var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)

// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}

Using optionals

You can compare an optional to nil to see if it has a value:

var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
    print("There is a name")
}
if name == nil { // Could also use an "else"
    print("Name has no value")
}

This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none.


Only optionals can be nil

If you try to set a non-optional variable to nil, you'll get an error.

var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'

Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil and when the image is retrieved, the optional gets a value.

Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.


To use an optional, you "unwrap" it

An optional String cannot be used in place of an actual String. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil, it causes a runtime crash. Before unwrapping you should be sure there's a value.

var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: \(unwrappedName)")

name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.

Checking and using an optional

Because you should always check for nil before unwrapping and using an optional, this is a common pattern:

var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
    let unwrappedMealPreference: String = mealPreference!
    print("Meal: \(unwrappedMealPreference)") // or do something useful
}

In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".

var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
    print("Meal: \(unwrappedMealPreference)") 
}

This creates a temporary constant (or variable if you replace let with var) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope

var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
    print("Meal: \(mealPreference)") // separate from the other mealPreference
}

Here's some code to demonstrate that a different variable is used:

var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
    print("Meal: \(mealPreference)") // mealPreference is a String, not a String?
    mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: \(mealPreference)") // Prints "Meal: Optional("Vegetarian")"

Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription to silence it:

print("\(mealPreference.debugDescription)")

What are optionals for?

Optionals have two use cases:

  1. Things that can fail (I was expecting something but I got nothing)
  2. Things that are nothing now but might be something later (and vice-versa)

Some concrete examples:

  • A property which can be there or not there, like middleName or spouse in a Person class
  • A method which can return a value or nothing, like searching for a match in an array
  • A method which can return either a result or get an error and return nothing, like trying to read a file's contents (which normally returns the file's data) but the file doesn't exist
  • Delegate properties, which don't always have to be set and are generally set after initialization
  • For weak properties in classes. The thing they point to can be set to nil at any time
  • A large resource that might have to be released to reclaim memory
  • When you need a way to know when a value has been set (data not yet loaded > the data) instead of using a separate dataLoaded Boolean

Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound which is really NSIntegerMax, kCLLocationCoordinate2DInvalid to represent an invalid coordinate, -1 or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil as a parameter, this has to be documented. In Objective-C, nil was a pointer just as all objects were defined as pointers, but nil pointed to a specific (zero) address. In Swift, nil is a literal which means the absence of a certain type.


Comparing to nil

You used to be able to use any optional as a Boolean:

let leatherTrim: CarExtras? = nil
if leatherTrim {
    price = price + 1000
}

In more recent versions of Swift you have to use leatherTrim != nil. Why is this? The problem is that a Boolean can be wrapped in an optional. If you have Boolean like this:

var ambiguous: Boolean? = false

it has two kinds of "false", one where there is no value and one where it has a value but the value is false. Swift hates ambiguity so now you must always check an optional against nil.

You might wonder what the point of an optional Boolean is? As with other optionals the .none state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"


Swift tricks

Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;

var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }

None of these lines should compile.

  • The first line sets an optional String using a String literal, two different types. Even if this was a String the types are different
  • The second line sets an optional String to nil, two different types
  • The third line compares an optional string to nil, two different types

I'll go through some of the implementation details of optionals that allow these lines to work.


Creating an optional

Using ? to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:

var name: Optional<String> = Optional("Bob")

This calls Optional's first initializer, public init(_ some: Wrapped), which infers the optional's associated type from the type used within the parentheses.

The even longer way of creating and setting an optional:

var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("\(serialNumber.debugDescription)")

Setting an optional to nil

You can create an optional with no initial value, or create one with the initial value of nil (both have the same outcome).

var name: String?
var name: String? = nil

Allowing optionals to equal nil is enabled by the protocol ExpressibleByNilLiteral (previously named NilLiteralConvertible). The optional is created with Optional's second initializer, public init(nilLiteral: ()). The docs say that you shouldn't use ExpressibleByNilLiteral for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:

class Clint: ExpressibleByNilLiteral {
    var name: String?
    required init(nilLiteral: ()) {
        name = "The Man with No Name"
    }
}

let clint: Clint = nil // Would normally give an error
print("\(clint.name)")

The same protocol allows you to set an already-created optional to nil. Although it's not recommended, you can use the nil literal initializer directly:

var name: Optional<String> = Optional(nilLiteral: ())

Comparing an optional to nil

Optionals define two special "==" and "!=" operators, which you can see in the Optional definition. The first == allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.

// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
    print("tuxedoRequired is nil")
}

The second == operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable (the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none. Note the distinction between comparing to the nil literal.

Furthermore, it allows you to compare any Equatable type to an optional wrapping that type:

let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
    print("It's a match!") // Prints "It's a match!"
}

Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {)

I said there are two == operators, but there's actually a third which allow you to put nil on the left-hand side of the comparison

if nil == name { ... }

Naming Optionals

There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.


The official definition

From "The Basics" in the Swift Programming Language:

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.


To finish, here's a poem from 1899 about optionals:

Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away

Antigonish


More resources:

How to print object array in JavaScript?

You can just use the following syntax and the object will be fully shown in the console:

console.log('object evt: %O', object);

I use Chrome browser don't know if this is adaptable for other browsers.

Throw keyword in function's signature

Jalf already linked to it, but the GOTW puts it quite nicely why exception specifications are not as useful as one might hope:

int Gunc() throw();    // will throw nothing (?)
int Hunc() throw(A,B); // can only throw A or B (?)

Are the comments correct? Not quite. Gunc() may indeed throw something, and Hunc() may well throw something other than A or B! The compiler just guarantees to beat them senseless if they do… oh, and to beat your program senseless too, most of the time.

That's just what it comes down to, you probably just will end up with a call to terminate() and your program dying a quick but painful death.

The GOTWs conclusion is:

So here’s what seems to be the best advice we as a community have learned as of today:

  • Moral #1: Never write an exception specification.
  • Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.

Vue.js redirection to another page

To stay in line with your original request:

window.location.href = 'some_url'

You can do something like this:

<div @click="this.window.location='some_url'">
</div>

Note that this does not take advantage of using Vue's router, but if you want to "make a redirection in Vue.js similar to the vanilla javascript", this would work.

How to call a JavaScript function within an HTML body

Try wrapping the createtable(); statement in a <script> tag:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>

        </tr>
        <script>createtable();</script>
</table>

I would avoid using document.write() and use the DOM if I were you though.

Necessary to add link tag for favicon.ico?

<link rel="icon" type="image/x-icon" href="http://example.com/favicon.ico" />
<link rel="icon" type="image/png" href="http://example.com/favicon.png" />
<link rel="icon" type="image/gif" href="http://example.com/favicon.gif" />
<link rel="icon" type="image/jpeg" href="http://example.com/favicon.jpeg" />
<link rel="icon" type="image/webp" href="http://example.com/favicon.webp" />

It all depends on which format of image you like to use!
if you have an icon of your website, it will be much better for UX!

demo

show logo in the browser tab

enter image description here

Axios get access to response header fields

Faced same problem in asp.net core Hope this helps

public static class CorsConfig
{
    public static void AddCorsConfig(this IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder
                .WithExposedHeaders("X-Pagination")
                );
        });
    }
}

JavaScript closure inside loops – simple practical example

The main issue with the code shown by the OP is that i is never read until the second loop. To demonstrate, imagine seeing an error inside of the code

funcs[i] = function() {            // and store them in funcs
    throw new Error("test");
    console.log("My value: " + i); // each should log its value.
};

The error actually does not occur until funcs[someIndex] is executed (). Using this same logic, it should be apparent that the value of i is also not collected until this point either. Once the original loop finishes, i++ brings i to the value of 3 which results in the condition i < 3 failing and the loop ending. At this point, i is 3 and so when funcs[someIndex]() is used, and i is evaluated, it is 3 - every time.

To get past this, you must evaluate i as it is encountered. Note that this has already happened in the form of funcs[i] (where there are 3 unique indexes). There are several ways to capture this value. One is to pass it in as a parameter to a function which is shown in several ways already here.

Another option is to construct a function object which will be able to close over the variable. That can be accomplished thusly

jsFiddle Demo

funcs[i] = new function() {   
    var closedVariable = i;
    return function(){
        console.log("My value: " + closedVariable); 
    };
};

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

How can I parse a time string containing milliseconds in it with python?

DNS answer above is actually incorrect. The SO is asking about milliseconds but the answer is for microseconds. Unfortunately, Python`s doesn't have a directive for milliseconds, just microseconds (see doc), but you can workaround it by appending three zeros at the end of the string and parsing the string as microseconds, something like:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

where time_str is formatted like 30/03/09 16:31:32.123.

Hope this helps.

Sending a file over TCP sockets in Python

Remove below code

s.send("Hello server!")

because your sending s.send("Hello server!") to server, so your output file is somewhat more in size.

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Is there a way to make a DIV unselectable?

The following CSS code works almost modern browser:

.unselectable {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

For IE, you must use JS or insert attribute in html tag.

<div id="foo" unselectable="on" class="unselectable">...</div>

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

set column width of a gridview in asp.net

This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.

    <asp:TemplateField   HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
    <asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate> 
 <EditItemTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate> 
<FooterTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>

How to enable mod_rewrite for Apache 2.2

Old thread, just want to put that don't set AllowOverride to all instead use specific mod you want to use,

AllowOverride mod_rewrite mod_mime

And this line should be un-commented

LoadModule rewrite_module modules/mod_rewrite.so

Refrences

how to drop database in sqlite?

You can drop tables by issuing an SQL Command as you would normally. If you want to drop the whole database you'll have to delete the file. You can delete the file located under

data/data/com.your.app.name/database/[databasefilename]

you can do this from the eclipse view called "FileBrowser" out of the "Android" Category for example. Or directly on your emulator or phone.

How do I programmatically "restart" an Android app?

My solution doesn't restart the process/application. It only lets the app "restart" the home activity (and dismiss all other activities). It looks like a restart to users, but the process is the same. I think in some cases people want to achieve this effect, so I just leave it here FYI.

public void restart(){
    Intent intent = new Intent(this, YourHomeActivity.class);
    this.startActivity(intent);
    this.finishAffinity();
}

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

The solution is to set the default value in your .elem. But this annimation work fine with -moz but not yet implement in -webkit

Look at the fiddle I updated from yours : http://jsfiddle.net/DoubleYo/4Vz63/1648/

It works fine with Firefox but not with Chrome

_x000D_
_x000D_
.elem{_x000D_
    position: absolute;_x000D_
    top: 40px;_x000D_
    left: 40px;_x000D_
    width: 0; _x000D_
    height: 0;_x000D_
    border-style: solid;_x000D_
    border-width: 75px;_x000D_
    border-color: red blue green orange;_x000D_
    transition-property: transform;_x000D_
    transition-duration: 1s;_x000D_
}_x000D_
.elem:hover {_x000D_
    animation-name: rotate; _x000D_
    animation-duration: 2s; _x000D_
    animation-iteration-count: infinite;_x000D_
    animation-timing-function: linear;_x000D_
}_x000D_
_x000D_
@keyframes rotate {_x000D_
    from {transform: rotate(0deg);}_x000D_
    to {transform: rotate(360deg);}_x000D_
}
_x000D_
<div class="elem"></div>
_x000D_
_x000D_
_x000D_

How do I grab an INI value within a shell script?

If using sections, this will do the job :

Example raw output :

$ ./settings
[section]
SETTING_ONE=this is setting one
SETTING_TWO=This is the second setting
ANOTHER_SETTING=This is another setting

Regexp parsing :

$ ./settings | sed -n -E "/^\[.*\]/{s/\[(.*)\]/\1/;h;n;};/^[a-zA-Z]/{s/#.*//;G;s/([^ ]*) *= *(.*)\n(.*)/\3_\1='\2'/;p;}"
section_SETTING_ONE='this is setting one'
section_SETTING_TWO='This is the second setting'
section_ANOTHER_SETTING='This is another setting'

Now all together :

$ eval "$(./settings | sed -n -E "/^\[.*\]/{s/\[(.*)\]/\1/;h;n;};/^[a-zA-Z]/{s/#.*//;G;s/([^ ]*) *= *(.*)\n(.*)/\3_\1='\2'/;p;}")"
$ echo $section_SETTING_TWO
This is the second setting

How do I create a message box with "Yes", "No" choices and a DialogResult?

Use:

MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
    // Do something
}
else if (m == m.No)
{
    // Do something else
}

MessageBoxResult is used on Windows Phone instead of DialogResult...

PDO Prepared Inserts multiple rows in single query

This worked for me

$sql = 'INSERT INTO table(pk_pk1,pk_pk2,date,pk_3) VALUES '; 
$qPart = array_fill(0, count($array), "(?, ?,UTC_TIMESTAMP(),?)");
$sql .= implode(",", $qPart);
$stmt =    DB::prepare('base', $sql);
$i = 1;
foreach ($array as $value) { 
  $stmt->bindValue($i++, $value);
  $stmt->bindValue($i++, $pk_pk1);
  $stmt->bindValue($i++, $pk_pk2); 
  $stmt->bindValue($i++, $pk_pk3); 
} 
$stmt->execute();