Programs & Examples On #Appfabric beta 2

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Testing done with express + node + ionic running in differente ports.

Localhost:8100

Localhost:5000

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests

app.all('*', function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "*");
       res.header("Access-Control-Allow-Headers", "X-Requested-With");
       res.header('Access-Control-Allow-Headers', 'Content-Type');
       next();
});

Python json.loads shows ValueError: Extra data

If you want to solve it in a two-liner you can do it like this:

with open('data.json') as f:
    data = [json.loads(line) for line in f]

Is a GUID unique 100% of the time?

Is a GUID unique 100% of the time?

Not guaranteed, since there are several ways of generating one. However, you can try to calculate the chance of creating two GUIDs that are identical and you get the idea: a GUID has 128 bits, hence, there are 2128 distinct GUIDs – much more than there are stars in the known universe. Read the wikipedia article for more details.

Check if Variable is Empty - Angular 2

if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}

How to jump back to NERDTree from file in tab?

In more recent versions of NERDTree you can use the command :NERDTreeFocus, which will move focus to the NERDTree window.

Execute a command line binary with Node.js

If you don't mind a dependency and want to use promises, child-process-promise works:

installation

npm install child-process-promise --save

exec Usage

var exec = require('child-process-promise').exec;

exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

spawn usage

var spawn = require('child-process-promise').spawn;

var promise = spawn('echo', ['hello']);

var childProcess = promise.childProcess;

console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});

promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

Setting up and using Meld as your git difftool and mergetool

While the other answer is correct, here's the fastest way to just go ahead and configure Meld as your visual diff tool. Just copy/paste this:

git config --global diff.tool meld
git config --global difftool.prompt false

Now run git difftool in a directory and Meld will be launched for each different file.

Side note: Meld is surprisingly slow at comparing CSV files, and no Linux diff tool I've found is faster than this Windows tool called Compare It! (last updated in 2010).

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Using Felipe Leusin's answer for years, after a recent update of core libraries and of Json.Net, I ran into a System.MissingMethodException:SupportedMediaTypes. The solution in my case, hopefully helpful to others experiencing the same unexpected exception, is to install System.Net.Http. NuGet apparently removes it in some circumstances. After a manual installation, the issue was resolved.

Convert hex to binary

import binascii
hexa_input = input('Enter hex String to convert to Binary: ')
pad_bits=len(hexa_input)*4
Integer_output=int(hexa_input,16)
Binary_output= bin(Integer_output)[2:]. zfill(pad_bits)
print(Binary_output)
"""zfill(x) i.e. x no of 0 s to be padded left - Integers will overwrite 0 s
starting from right side but remaining 0 s will display till quantity x
[y:] where y is no of output chars which need to destroy starting from left"""

Checking for directory and file write permissions in .NET

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

DISABLE the Horizontal Scroll

I know it's too late, but there is an approach in javascript that can help you detect witch html element is causing the horizontal overflow -> scrollbar to appear

Here is a link to the post on CSS Tricks

var docWidth = document.documentElement.offsetWidth;
[].forEach.call(
  document.querySelectorAll('*'),
  function(el) {
    if (el.offsetWidth > docWidth) {
      console.log(el);
    }
  }
);

it Might return something like this:

<div class="div-with-extra-width">...</div>

then you just remove the extra width from the div or set it's max-width:100%

Hope this helps!

It fixed the problem for me :]

How to prune local tracking branches that do not exist on remote anymore

If using Windows and Powershell, you can use the following to delete all local branches that have been merged into the branch currently checked out:

git branch --merged | ? {$_[0] -ne '*'} | % {$_.trim()} | % {git branch -d $_}

Explanation

  • Lists the current branch and the branches that have been merged into it
  • Filters out the current branch
  • Cleans up any leading or trailing spaces from the git output for each remaining branch name
  • Deletes the merged local branches

It's worth running git branch --merged by itself first just to make sure it's only going to remove what you expect it to.

(Ported/automated from http://railsware.com/blog/2014/08/11/git-housekeeping-tutorial-clean-up-outdated-branches-in-local-and-remote-repositories/.)

What are XAND and XOR

Guys, don´t scare the crap out of others (hey! just kidding), but it´s really all a question of equivalences and synonyms:

firstly:

"XAND" doesn´t exist logically, neither does "XNAND", however "XAND" is normally thought-up by a studious but confused initiating logic student.(wow!). It com from the thought that, if there´s a XOR(exclusive OR) it´s logical to exist a "XAND"("exclusive" AND). The rational suggestion would be an "IAND"("inclusive" AND), which isn´t used or recognised as well. So:

 XNOR <=> !XOR <=> EQV

And all this just discribes a unique operator, called the equivalency operator(<=>, EQV) so:

A  |  B  | A <=> B | A XAND B | A XNOR B | A !XOR B | ((NOT(A) AND B)AND(A AND NOT(B)))
---------------------------------------------------------------------------------------
T  |  T  |    T    |     T    |     T    |     T    |                T    
T  |  F  |    F    |     F    |     F    |     F    |                F    
F  |  T  |    F    |     F    |     F    |     F    |                F    
F  |  F  |    T    |     T    |     T    |     T    |                T    

And just a closing comment: The 'X' prefix is only possible if and only if the base operator isn´t unary. So, XNOR <=> NOT XOR <=/=> X NOR.

Peace.

Align a div to center

The usual technique for this is margin:auto

However, old IE doesn't grok this so one usually adds text-align: center to an outer containing element. You wouldn't think that would work but the same IE's that ignore auto also incorrectly apply the text align center to block level inner elements so things work out.

And this doesn't actually do a real float.

How to Install Sublime Text 3 using Homebrew

I did not have brew cask installed so I had to install it first,so these were the steps I followed:

brew install caskroom/cask/brew-cask
brew tap caskroom/versions
brew cask install sublime-text

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I inspired myself from @maxisam's answer and created my own sort function and I'd though I'd share it (cuz I'm bored).

Situation I want to filter through an array of cars. The selected properties to filter are name, year, price and km. The property price and km are numbers (hence the use of .toString). I also want to control for uppercase letters (hence .toLowerCase). Also I want to be able to split up my filter query into different words (e.g. given the filter 2006 Acura, it finds matches 2006 with the year and Acura with the name).

Function I pass to filter

        var attrs = [car.name.toLowerCase(), car.year, car.price.toString(), car.km.toString()],
            filters = $scope.tableOpts.filter.toLowerCase().split(' '),
            isStringInArray = function (string, array){
                for (var j=0;j<array.length;j++){
                    if (array[j].indexOf(string)!==-1){return true;}
                }
                return false;
            };

        for (var i=0;i<filters.length;i++){
            if (!isStringInArray(filters[i], attrs)){return false;}
        }
        return true;
    };

How to read a string one letter at a time in python

A couple of things for ya:

The loading would be "better" like this:

with file('morsecodes.txt', 'rt') as f:
   for line in f:
      line = line.strip()
      if len(line) > 0:
         # do your stuff to parse the file

That way you don't need to close, and you don't need to manually load each line, etc., etc.

for letter in userInput:
   if ValidateLetter(letter):  # you need to define this
      code = GetMorseCode(letter)  # from my other answer
      # do whatever you want

How to identify numpy types in python?

To get the type, use the builtin type function. With the in operator, you can test if the type is a numpy type by checking if it contains the string numpy;

In [1]: import numpy as np

In [2]: a = np.array([1, 2, 3])

In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>

In [4]: 'numpy' in str(type(a))
Out[4]: True

(This example was run in IPython, by the way. Very handy for interactive use and quick tests.)

What is a wrapper class?

It might also be valuable to note that in some environments, much of what wrapper classes might do is being replaced by aspects.

EDIT:

In general a wrapper is going to expand on what the wrappee does, without being concerned about the implementation of the wrappee, otherwise there's no point of wrapping versus extending the wrapped class. A typical example is to add timing information or logging functionality around some other service interface, as opposed to adding it to every implementation of that interface.

This then ends up being a typical example for Aspect programming. Rather than going through an interface function by function and adding boilerplate logging, in aspect programming you define a pointcut, which is a kind of regular expression for methods, and then declare methods that you want to have executed before, after or around all methods matching the pointcut. Its probably fair to say that aspect programming is a kind of use of the Decorator pattern, which wrapper classes can also be used for, but that both technologies have other uses.

Is it possible to simulate key press events programmatically?

What you can do is programmatically trigger keyevent listeners by firing keyevents. It makes sense to allow this from a sandboxed security-perspective. Using this ability, you can then apply a typical observer-pattern. You could call this method "simulating".

Below is an example of how to accomplish this in the W3C DOM standard along with jQuery:

function triggerClick() {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var cb = document.querySelector('input[type=submit][name=btnK]'); 
  var canceled = !cb.dispatchEvent(event);
  if (canceled) {
    // preventDefault was called and the event cancelled
  } else {
    // insert your event-logic here...
  }
}

This example is adapted from: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

In jQuery:

jQuery('input[type=submit][name=btnK]')
  .trigger({
    type: 'keypress',
    which: character.charCodeAt(0 /*the key to trigger*/)      
   });

But as of recently, there is no [DOM] way to actually trigger keyevents leaving the browser-sandbox. And all major browser vendors will adhere to that security concept.

As for plugins such as Adobe Flash - which are based on the NPAPI-, and permit bypassing the sandbox: these are phasing-out ; Firefox.

Detailed Explanation:

You cannot and you must not for security reasons (as Pekka already pointed out). You will always require a user interaction in between. Additionally imagine the chance of the browser vendors getting sued by users, as various programmatic keyboard events will have led to spoofing attacks.

See this post for alternatives and more details. There is always the flash based copy-and-paste. Here is an elegant example. At the same time it is a testimony why the web is moving away from plugin vendors.

There is a similar security mindset applied in case of the opt-in CORS policy to access remote content programmatically.

The answer is:
There is no way to programmatically trigger input keys in the sandboxed browser environment under normal circumstances.

Bottomline: I am not saying it will not be possible in the future, under special browser-modes and/or privileges towards the end-goal of gaming, or similar user-experiences. However prior to entering such modes, the user will be asked for permissions and risks, similar to the Fullscreen API model.

Useful: In the context of KeyCodes, this tool and keycode mapping will come in handy.

Disclosure: The answer is based on the answer here.

Difference between Java SE/EE/ME?

As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:

The Java Programming Language Platforms

There are four platforms of the Java programming language:

  • Java Platform, Standard Edition (Java SE)

  • Java Platform, Enterprise Edition (Java EE)

  • Java Platform, Micro Edition (Java ME)

  • JavaFX

All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

Best approach to remove time part of datetime in SQL Server

I really like:

[date] = CONVERT(VARCHAR(10), GETDATE(), 120)

The 120 format code will coerce the date into the ISO 8601 standard:

'YYYY-MM-DD' or '2017-01-09'

Super easy to use in dplyr (R) and pandas (Python)!

How do I create a user account for basic authentication?

If you create a user with the advanced user management (from command line: netplwiz), then modify the group, remove users, and add iis_users. They will be able to authenticate to your web page, but not the computer.

%Like% Query in spring JpaRepository

You can also implement the like queries using Spring Data JPA supported keyword "Containing".

List<Registration> findByPlaceContaining(String place);

How to add link to flash banner

@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.

movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
  var url:String = "http://site";
  var request:URLRequest = new URLRequest(url);
  try {
    navigateToURL(request, '_blank');
  } catch (e:Error) {
    trace("Error occurred!");
  }
}

source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/

POST JSON to API using Rails and HTTParty

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}

Invalid date in safari

How about hijack Date with fix-date? No dependencies, min + gzip = 280 B

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

URL to load resources from the classpath in Java

From Java 9+ and up, you can define a new URLStreamHandlerProvider. The URL class uses the service loader framework to load it at run time.

Create a provider:

package org.example;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.spi.URLStreamHandlerProvider;

public class ClasspathURLStreamHandlerProvider extends URLStreamHandlerProvider {

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        if ("classpath".equals(protocol)) {
            return new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u) throws IOException {
                    return ClassLoader.getSystemClassLoader().getResource(u.getPath()).openConnection();
                }
            };
        }
        return null;
    }

}

Create a file called java.net.spi.URLStreamHandlerProvider in the META-INF/services directory with the contents:

org.example.ClasspathURLStreamHandlerProvider

Now the URL class will use the provider when it sees something like:

URL url = new URL("classpath:myfile.txt");

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

If you don't want to recompile (as Visual Leak Detector requires) I would recommend WinDbg, which is both powerful and fast (though it's not as easy to use as one could desire).

On the other hand, if you don't want to mess with WinDbg, you can take a look at UMDH, which is also developed by Microsoft and it's easier to learn.

Take a look at these links in order to learn more about WinDbg, memory leaks and memory management in general:

How can I delete multiple lines in vi?

it is dxd, not ddx

if you want to delete 5 lines, cursor to the beginning of the first line to delete and d5d

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

Can I have onScrollListener for a ScrollView?

Here's a derived HorizontalScrollView I wrote to handle notifications about scrolling and scroll ending. It properly handles when a user has stopped actively scrolling and when it fully decelerates after a user lets go:

public class ObservableHorizontalScrollView extends HorizontalScrollView {
    public interface OnScrollListener {
        public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
        public void onEndScroll(ObservableHorizontalScrollView scrollView);
    }

    private boolean mIsScrolling;
    private boolean mIsTouching;
    private Runnable mScrollingRunnable;
    private OnScrollListener mOnScrollListener;

    public ObservableHorizontalScrollView(Context context) {
        this(context, null, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();

        if (action == MotionEvent.ACTION_MOVE) {
            mIsTouching = true;
            mIsScrolling = true;
        } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            if (mIsTouching && !mIsScrolling) {
                if (mOnScrollListener != null) {
                    mOnScrollListener.onEndScroll(this);
                }
            }

            mIsTouching = false;
        }

        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);

        if (Math.abs(oldX - x) > 0) {
            if (mScrollingRunnable != null) {
                removeCallbacks(mScrollingRunnable);
            }

            mScrollingRunnable = new Runnable() {
                public void run() {
                    if (mIsScrolling && !mIsTouching) {
                        if (mOnScrollListener != null) {
                            mOnScrollListener.onEndScroll(ObservableHorizontalScrollView.this);
                        }
                    }

                    mIsScrolling = false;
                    mScrollingRunnable = null;
                }
            };

            postDelayed(mScrollingRunnable, 200);
        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollChanged(this, x, y, oldX, oldY);
        }
    }

    public OnScrollListener getOnScrollListener() {
        return mOnScrollListener;
    }

    public void setOnScrollListener(OnScrollListener mOnEndScrollListener) {
        this.mOnScrollListener = mOnEndScrollListener;
    }

}

Get Locale Short Date Format using javascript

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

The Intl.DateTimeFormat object is a constructor for objects that enable language sensitive date and time formatting.

var date = new Date(2014, 11, 31, 12, 30, 0);

var formatter = new Intl.DateTimeFormat("ru");
console.log( formatter.format(date) ); // 31.12.2014

var formatter = new Intl.DateTimeFormat("en-US");

console.log(formatter.format(date)); // 12/31/2014

format of your current zone :

console.log(new Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale).
format(new Date()))

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Return list from async/await method

Works for me:

List<Item> list = Task.Run(() => manager.GetList()).Result;

in this way it is not necessary to mark the method with async in the call.

How to watch for form changes in Angular

Expanding on Mark's suggestions...

Method 3

Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.

export class App implements DoCheck {
  person = { first: "Sally", last: "Jones" };
  oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning

  ngDoCheck() {
    // Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
    for (let prop in this.person) {
      if (this.oldPerson[prop] !==  this.person[prop]) {
        console.log(`person.${prop} changed: ${this.person[prop]}`);
        this.oldPerson[prop] = this.person[prop];
      }
    }
  }

Try in Plunker

Compute a confidence interval from sample data

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module:

from statistics import NormalDist

def confidence_interval(data, confidence=0.95):
  dist = NormalDist.from_samples(data)
  z = NormalDist().inv_cdf((1 + confidence) / 2.)
  h = dist.stdev * z / ((len(data) - 1) ** .5)
  return dist.mean - h, dist.mean + h

This:

  • Creates a NormalDist object from the data sample (NormalDist.from_samples(data), which gives us access to the sample's mean and standard deviation via NormalDist.mean and NormalDist.stdev.

  • Compute the Z-score based on the standard normal distribution (represented by NormalDist()) for the given confidence using the inverse of the cumulative distribution function (inv_cdf).

  • Produces the confidence interval based on the sample's standard deviation and mean.


This assumes the sample size is big enough (let's say more than ~100 points) in order to use the standard normal distribution rather than the student's t distribution to compute the z value.

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How can I give the Intellij compiler more heap space?

I like to share a revelation that I had. When you build a project, Intellij Idea runs a java process that resides in its core(ex: C:\Program Files\JetBrains\IntelliJ IDEA 2020.3\jbr\bin). The "build process heap size", as mentioned by many others, changes the heap size of this java process. However, the main java process is triggered later by the Idea's java process, hence have different VM arguments. I noticed that the max heap size of this process is 1/3 of the Idea's java process, while min heap is the half of max(1/6). To round up:

When you set 9g heap on "build process heap size" the actual heap size for the compiler is max 3g and min 1,5g. And no need for restart is neccessary.

PS: tested on version 2020.3

Get current scroll position of ScrollView in React Native

Try.

<ScrollView onScroll={this.handleScroll} />

And then:

handleScroll: function(event: Object) {
 console.log(event.nativeEvent.contentOffset.y);
},

Custom Cell Row Height setting in storyboard is not responding

The only real solution I could find is this

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = ...; // Instantiate with a "common" method you'll use again in cellForRowAtIndexPath:
    return cell.frame.size.height;
}

This works and allows not to have an horrible switch/if duplicating the logic already in the StoryBoard. Not sure about performance but I guess when arriving in cellForRow: the cell being already initalized it's as fast. Of course there are probably collateral damages here, but it looks like it works fine for me here.

I also posted this here: https://devforums.apple.com/message/772464

EDIT: Ortwin Gentz reminded me that heightForRowAtIndexPath: will be called for all cells of the TableView, not only the visible ones. Sounds logical since iOS needs to know the total height to be able to show the right scrollbars. It means it's probably fine on small TableViews (like 20 Cells) but forget about it on a 1000 Cell TableView.

Also, the previous trick with XML: Same as first comment for me. The correct value was already there.

Releasing memory in Python

First, you may want to install glances:

sudo apt-get install python-pip build-essential python-dev lm-sensors 
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances

Then run it in the terminal!

glances

In your Python code, add at the begin of the file, the following:

import os
import gc # Garbage Collector

After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:

del myBigVar
gc.collect()

In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!

Good luck!

P.S. I assume you are working on a Debian or Ubuntu system

How to merge two PDF files into one in Java?

package article14;

import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFMergerUtility;

public class Pdf
{
    public static void main(String args[])
    {
        new Pdf().createNew();
        new Pdf().combine();
        }

    public void combine()
    {
        try
        {
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        String folder ="pdf";
        File _folder = new File(folder);
        File[] filesInFolder;
        filesInFolder = _folder.listFiles();
        for (File string : filesInFolder)
        {
            mergePdf.addSource(string);    
        }
    mergePdf.setDestinationFileName("Combined.pdf");
    mergePdf.mergeDocuments();
        }
        catch(Exception e)
        {

        }  
    }

public void createNew()
{
    PDDocument document = null;
    try
    {
        String filename="test.pdf";
        document=new PDDocument();
        PDPage blankPage = new PDPage();
        document.addPage( blankPage );
        document.save( filename );
    }
    catch(Exception e)
    {

    }
}

}

Good Patterns For VBA Error Handling

Error Handling in VBA


  • On Error Goto ErrorHandlerLabel
  • Resume (Next | ErrorHandlerLabel)
  • On Error Goto 0 (disables current error handler)
  • Err object

The Err object's properties are normally reset to zero or a zero-length string in the error handling routine, but it can also be done explicitly with Err.Clear.

Errors in the error handling routine are terminating.

The range 513-65535 is available for user errors. For custom class errors, you add vbObjectError to the error number. See MS documentation about Err.Raise and the list of error numbers.

For not implemented interface members in a derived class, you should use the constant E_NOTIMPL = &H80004001.


Option Explicit

Sub HandleError()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0

  Debug.Print "This line won't be executed."

DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub RaiseAndHandleError()
  On Error GoTo errMyErrorHandler
    ' The range 513-65535 is available for user errors.
    ' For class errors, you add vbObjectError to the error number.
    Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
  On Error GoTo 0

  Debug.Print "This line will be executed."

Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
  Err.Clear
Resume Next
End Sub

Sub FailInErrorHandler()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0

  Debug.Print "This line won't be executed."

DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  a = 7 / 0 ' <== Terminating error!
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub DontDoThis()

  ' Any error will go unnoticed!
  On Error Resume Next
  ' Some complex code that fails here.
End Sub

Sub DoThisIfYouMust()

  On Error Resume Next
  ' Some code that can fail but you don't care.
  On Error GoTo 0

  ' More code here
End Sub

How to make vim paste from (and copy to) system's clipboard?

Following on from Conner's answer, which was great, but C-R C-p + and C-R C-p * in insert mode is a bit inconvenient. Ditto "*p and "+p from command mode.

a VIM guru suggested the following to map C-v to what C-r C-p + does.

You could have :inoremap <C-v> <C-o>"+p for insert mode only

if you really wanted to override blockwise visual mode (not recommended by him as visual mode is good) you could have map <C-v> "+p

Generate Row Serial Numbers in SQL Query

ALTER function dbo.FN_ReturnNumberRows(@Start int, @End int) returns @Numbers table (Number int) as
begin
    insert into @Numbers
    select n = ROW_NUMBER() OVER (ORDER BY n)+@Start-1 from (
    select top (@End-@Start+1) 1 as n from information_schema.columns as A
        cross join information_schema.columns as B
        cross join information_schema.columns as C
        cross join information_schema.columns as D
        cross join information_schema.columns as E) X
    return
end
GO

select * from dbo.FN_ReturnNumberRows(10,9999)

SVN 405 Method Not Allowed

I just fixed this in my own repository. I'm using TortoiseSVN on Windows, so I'm not sure exactly what commands this translates to on the command line, but here's what I did:

The problematic folder is called lib, and it was due to be added.

  • First I undid the add, so that SVN was no longer paying attention to it.
  • Then I renamed it (to libs, not that that matters) using the Windows context menu, added it, and committed successfully.
  • Finally I renamed it back to lib using TortoiseSVN's context menu (this is probably important), and committed again.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

The Selenium client bindings will try to locate the geckodriver executable from the system PATH. You will need to add the directory containing the executable to the system path.

  • On Unix systems you can do the following to append it to your system’s search path, if you’re using a bash-compatible shell:

    export PATH=$PATH:/path/to/geckodriver
    
  • On Windows you need to update the Path system variable to add the full directory path to the executable. The principle is the same as on Unix.

All below configuration for launching latest firefox using any programming language binding is applicable for Selenium2 to enable Marionette explicitly. With Selenium 3.0 and later, you shouldn't need to do anything to use Marionette, as it's enabled by default.

To use Marionette in your tests you will need to update your desired capabilities to use it.

Java :

As exception is clearly saying you need to download latest geckodriver.exe from here and set downloaded geckodriver.exe path where it's exists in your computer as system property with with variable webdriver.gecko.driver before initiating marionette driver and launching firefox as below :-

//if you didn't update the Path system variable to add the full directory path to the executable as above mentioned then doing this directly through code
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");

//Now you can Initialize marionette driver to launch firefox
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new MarionetteDriver(capabilities); 

And for Selenium3 use as :-

WebDriver driver = new FirefoxDriver();

If you're still in trouble follow this link as well which would help you to solving your problem

.NET :

var driver = new FirefoxDriver(new FirefoxOptions());

Python :

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

caps = DesiredCapabilities.FIREFOX

# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True

# Path to Firefox DevEdition or Nightly.
# Firefox 47 (stable) is currently not supported,
# and may give you a suboptimal experience.
#
# On Mac OS you must point to the binary executable
# inside the application package, such as
# /Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
caps["binary"] = "/usr/bin/firefox"

driver = webdriver.Firefox(capabilities=caps)

Ruby :

# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by directly passing marionette: true
# You might need to specify an alternate path for the desired version of Firefox

Selenium::WebDriver::Firefox::Binary.path = "/path/to/firefox"
driver = Selenium::WebDriver.for :firefox, marionette: true

JavaScript (Node.js) :

const webdriver = require('selenium-webdriver');
const Capabilities = require('selenium-webdriver/lib/capabilities').Capabilities;

var capabilities = Capabilities.firefox();

// Tell the Node.js bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.set('marionette', true);

var driver = new webdriver.Builder().withCapabilities(capabilities).build();

Using RemoteWebDriver

If you want to use RemoteWebDriver in any language, this will allow you to use Marionette in Selenium Grid.

Python:

caps = DesiredCapabilities.FIREFOX

# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True

driver = webdriver.Firefox(capabilities=caps)

Ruby :

# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by using the Capabilities class
# You might need to specify an alternate path for the desired version of Firefox

caps = Selenium::WebDriver::Remote::Capabilities.firefox marionette: true, firefox_binary: "/path/to/firefox"
driver = Selenium::WebDriver.for :remote, desired_capabilities: caps

Java :

DesiredCapabilities capabilities = DesiredCapabilities.firefox();

// Tell the Java bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.setCapability("marionette", true);

WebDriver driver = new RemoteWebDriver(capabilities); 

.NET

DesiredCapabilities capabilities = DesiredCapabilities.Firefox();

// Tell the .NET bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.SetCapability("marionette", true);

var driver = new RemoteWebDriver(capabilities); 

Note : Just like the other drivers available to Selenium from other browser vendors, Mozilla has released now an executable that will run alongside the browser. Follow this for more details.

You can download latest geckodriver executable to support latest firefox from here

Eclipse Build Path Nesting Errors

The accepted solution didn't work for me but I did some digging on the project settings.

The following solution fixed it for me at least IF you are using a Dynamic Web Project:

  1. Right click on the project then properties. (or alt-enter on the project)
  2. Under Deployment Assembly remove "src".

You should be able to add the src/main/java. It also automatically adds it to Deployment Assembly.

Caveat: If you added a src/test/java note that it also adds it to Deployment Assembly. Generally, you don't need this. You may remove it.

Disable back button in android

If you want to make sure your android client application is logged out from some server before your Activity gets killed --> log out with a service on its own thread (that's what you're supposed to do anyway).

Disabling the back button won't solve anything for you. You'll still have the same problem when the user receives a phone call for instance. When a phone call is received, your activity has about as much chances of getting killed before it gets a reliable answer back from the network.

That's why you should let a service wait on its own thread for the answer from the network, and then make it try again if it doesn't succeed. The android service is not only much less likely to get killed before it gets an answer back, but should it really get killed before finishing the job, it can always get revived by AlarmManager to try again.

How do you access the value of an SQL count () query in a Java program

Use aliases:

SELECT COUNT(*) AS total FROM ..

and then

rs3.getInt("total")

Python Timezone conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

time_in_new_timezone = time_in_old_timezone.astimezone(new_timezone)

Given aware_dt (a datetime object in some timezone), to convert it to other timezones and to print the times in a given time format:

#!/usr/bin/env python3
import pytz  # $ pip install pytz

time_format = "%Y-%m-%d %H:%M:%S%z"
tzids = ['Asia/Shanghai', 'Europe/London', 'America/New_York']
for tz in map(pytz.timezone, tzids):
    time_in_tz = aware_dt.astimezone(tz)
    print(f"{time_in_tz:{time_format}}")

If f"" syntax is unavailable, you could replace it with "".format(**vars())

where you could set aware_dt from the current time in the local timezone:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
aware_dt = datetime.now(local_timezone) # the current time

Or from the input time string in the local timezone:

naive_dt = datetime.strptime(time_string, time_format)
aware_dt = local_timezone.localize(naive_dt, is_dst=None)

where time_string could look like: '2016-11-19 02:21:42'. It corresponds to time_format = '%Y-%m-%d %H:%M:%S'.

is_dst=None forces an exception if the input time string corresponds to a non-existing or ambiguous local time such as during a DST transition. You could also pass is_dst=False, is_dst=True. See links with more details at Python: How do you convert datetime/timestamp from one timezone to another timezone?

anchor jumping by using javascript

Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }

Extracting the top 5 maximum values in excel

To my mind the case for a PT (as @Nathan Fisher) is a 'no brainer', but I would add a column to facilitate ordering by rank (up or down):

SO18528624 first example

OPS is entered as VALUES (Sum of) twice so I have renamed the column labels to make clearer which is which. The PT is in a different sheet from the data but could be in the same sheet.

Rank is set with a right click on a data point selected in that column and Show Values As... and Rank Largest to Smallest (there are other options) with the Base field as Player and the filter is a Value Filters, Top 10... one:

SO18528624 second example

Once in a PT the power of that feature can very easily be applied to view the data in many other ways, with no change of formula (there isn't one!).

In the case of a tie for the last position included in the filter both results are included (Top 5 would show six or more results). A tie for top rank between just two players would show as 1 1 3 4 5 for Top 5.

Properties private set;

The two common approaches are either that the class should have a constructor for the DAL to use, or the DAL should use reflection to hydrate objects.

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Converting file size in bytes to human-readable string

sizeOf = function (bytes) {
  if (bytes == 0) { return "0.00 B"; }
  var e = Math.floor(Math.log(bytes) / Math.log(1024));
  return (bytes/Math.pow(1024, e)).toFixed(2)+' '+' KMGTP'.charAt(e)+'B';
}

sizeOf(2054110009);
//=> "1.91 GB"

sizeOf(7054110);
//=> "6.73 MB"

sizeOf( (3*1024*1024) );
//=> "3.00 MB"

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

Simple two column html layout without using tables

I know this question has already been answered, but having dealt with layout a fair bit, I wanted to add an alternative answer that solves a few traditional problems with floating elements...

You can see the updated example in action here.

http://jsfiddle.net/Sohnee/EMaDB/1/

It makes no difference whether you are using HTML 4.01 or HTML5 with semantic elements (you will need to declare the left and right containers as display:block if they aren't already).

CSS

.left {
    background-color: Red;
    float: left;
    width: 50%;
}

.right {
    background-color: Aqua;
    margin-left: 50%;
}

HTML

<div class="left">
    <p>I have updated this example to show a great way of getting a two column layout.</p>
</div>
<div class="right">
    <ul>
        <li>The columns are in the right order semantically</li>
        <li>You don't have to float both columns</li>
        <li>You don't get any odd wrapping behaviour</li>
        <li>The columns are fluid to the available page...</li>
        <li>They don't have to be fluid to the available page - but any container!</li>
    </ul>
</div>

There is also a rather neat (albeit newer) addition to CSS that allows you to layout content into columns without all this playing around with divs:

column-count: 2;

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

@Pkosta 's answer is one way of doing this.

Besides using FileProvider, you can also insert the file into MediaStore (especially for image and video files), because files in MediaStore are accessible to every app:

The MediaStore is primarily aimed at video, audio and image MIME types, however beginning with Android 3.0 (API level 11) it can also store non-media types (see MediaStore.Files for more info). Files can be inserted into the MediaStore using scanFile() after which a content:// style Uri suitable for sharing is passed to the provided onScanCompleted() callback. Note that once added to the system MediaStore the content is accessible to any app on the device.

For example, you can insert a video file to MediaStore like this:

ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA, videoFilePath);
Uri contentUri = context.getContentResolver().insert(
      MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);

contentUri is like content://media/external/video/media/183473, which can be passed directly to Intent.putExtra:

intent.setType("video/*");
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(intent);

This works for me, and save the hassles of using FileProvider.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

Backup a single table with its data from a database in sql server 2008

Backup a single table with its data from a database in sql server 2008

SELECT * INTO  [dbo].[tbl_NewTable] 
FROM [dbo].[tbl_OldTable]

Python Function to test ping

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":

import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux

You can also use sys:

import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

Select a random sample of results from a query result

SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        ORDER BY
                dbms_random.value
        )
WHERE rownum <= 1000

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

How to do associative array/hashing in JavaScript

All modern browsers support a JavaScript Map object. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

Overcoming "Display forbidden by X-Frame-Options"

It appears that X-Frame-Options Allow-From https://... is depreciated and was replaced (and gets ignored) if you use Content-Security-Policy header instead.

Here is the full reference: https://content-security-policy.com/

state machines tutorials

There is a lot of lesson to learn handcrafting state machines in C, but let me also suggest Ragel state machine compiler:

http://www.complang.org/ragel/

It has quite simple way of defining state machines and then you can generate graphs, generate code in different styles (table-driven, goto-driven), analyze that code if you want to, etc. And it's powerful, can be used in production code for various protocols.

Svn switch from trunk to branch

You don't need to --relocate since the branch is within the same repository URL. Just do:

svn switch https://www.example.com/svn/branches/v1p2p3

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The basic difference between all these annotations is as follows -

  1. @BeforeEach - Use to run a common code before( eg setUp) each test method execution. analogous to JUnit 4’s @Before.
  2. @AfterEach - Use to run a common code after( eg tearDown) each test method execution. analogous to JUnit 4’s @After.
  3. @BeforeAll - Use to run once per class before any test execution. analogous to JUnit 4’s @BeforeClass.
  4. @AfterAll - Use to run once per class after all test are executed. analogous to JUnit 4’s @AfterClass.

All these annotations along with the usage is defined on Codingeek - Junit5 Test Lifecycle

Making an iframe responsive

With the following markup:

<div class="video"><iframe src="https://www.youtube.com/embed/StTqXEQ2l-Y"></iframe></div>

The following CSS makes the video full-width and 16:9:

.video {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
}

.video > .video__iframe {
    position: absolute;
    width: 100%;
    height: 100%;
    border: none;
  }
}

SyntaxError: non-default argument follows default argument

Let me clarify two points here :

  • Firstly non-default argument should not follow the default argument, it means you can't define (a = 'b',c) in function. The correct order of defining parameter in function are :
  • positional parameter or non-default parameter i.e (a,b,c)
  • keyword parameter or default parameter i.e (a = 'b',r= 'j')
  • keyword-only parameter i.e (*args)
  • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(*ab) is var-keyword parameter

so first re-arrange your parameters

  • now the second thing is you have to define len1 when you are doing hgt=len1 the len1 argument is not defined when default values are saved, Python computes and saves default values when you define the function len1 is not defined, does not exist when this happens (it exists only when the function is executed)

so second remove this "len1 = hgt" it's not allowed in python.

keep in mind the difference between argument and parameters.

Printing HashMap In Java

map.forEach((key, value) -> System.out.println(key + " " + value));

Using java 8 features

How to initialize an array in Java?

you are trying to set the 10th element of the array to the array try

data = new int[] {10,20,30,40,50,60,71,80,90,91};

FTFY

Extension gd is missing from your system - laravel composer Update

PHP 7.4.2 (cli) (built: Feb 5 2020 16:50:21) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.2, Copyright (c), by Zend Technologies

For Php 7.4.2

  1. sudo apt-get install php7.4-gd
  2. sudo phpenmod gd

How do I extract the contents of an rpm?

To debug / inspect your rpm I suggest to use redline which is a java program

Usage :

java -cp redline-1.2.1-jar-with-dependencies.jar org.redline_rpm.Scanner foo.rpm

Download : https://github.com/craigwblake/redline/releases

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

Property [title] does not exist on this collection instance

$about->first()->id or $stm->first()->title and your problem is sorted out.

How do you create an asynchronous HTTP request in JAVA?

Based on a link to Apache HTTP Components on this SO thread, I came across the Fluent facade API for HTTP Components. An example there shows how to set up a queue of asynchronous HTTP requests (and get notified of their completion/failure/cancellation). In my case, I didn't need a queue, just one async request at a time.

Here's where I ended up (also using URIBuilder from HTTP Components, example here).

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;

//...

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("myhost.com").setPath("/folder")
    .setParameter("query0", "val0")
    .setParameter("query1", "val1")
    ...;
URI requestURL = null;
try {
    requestURL = builder.build();
} catch (URISyntaxException use) {}

ExecutorService threadpool = Executors.newFixedThreadPool(2);
Async async = Async.newInstance().use(threadpool);
final Request request = Request.Get(requestURL);

Future<Content> future = async.execute(request, new FutureCallback<Content>() {
    public void failed (final Exception e) {
        System.out.println(e.getMessage() +": "+ request);
    }
    public void completed (final Content content) {
        System.out.println("Request completed: "+ request);
        System.out.println("Response:\n"+ content.asString());
    }

    public void cancelled () {}
});

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

Splitting words into letters in Java

I'm pretty sure he doesn't want the spaces to be output though.

for (char c: s.toCharArray()) {
    if (isAlpha(c)) {
       System.out.println(c);
     }
}

Find out where MySQL is installed on Mac OS X

for me it was installed in /usr/local/opt

The command I used for installation is brew install [email protected]

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Using IS NULL or IS NOT NULL on join conditions - Theory question

You're doing a LEFT OUTTER JOIN which indicates that you want every tuple from the table on the LEFT of the statement regardless of it has a matching record in the RIGHT table. This being the case, your results are being pruned from the RIGHT table but you're ending up with the same results as if you didn't include the AND at all within the ON clause.

Performing the AND in the WHERE clause causes the prune to happen after the LEFT JOIN takes place.

How to import a .cer certificate into a java keystore?

Here's a script I used to batch import a bunch of crt files in the current directory into the java keystore. Just save this to the same folder as your certificate, and run it like so:

./import_all_certs.sh

import_all_certs.sh

KEYSTORE="$(/usr/libexec/java_home)/jre/lib/security/cacerts";

function running_as_root()
{
  if [ "$EUID" -ne 0 ]
    then echo "NO"
    exit
  fi

  echo "YES"
}

function import_certs_to_java_keystore
{
  for crt in *.crt; do 
    echo prepping $crt 
    keytool -import -file $crt -storepass changeit -noprompt --alias alias__${crt} -keystore $KEYSTORE
    echo 
  done
}

if [ "$(running_as_root)" == "YES" ]
then
  import_certs_to_java_keystore
else
  echo "This script needs to be run as root!"
fi

Android- create JSON Array and JSON Object

It's too late to answer, sorry about it, for creating the below body:

{
    "username": "?Rajab",
    "email": "[email protected]",
    "phone": "+93767626554",
    "password": "123asd",
    "carType": "600fdcc646bc6409ae97e2ab",
    "fcmToken":"lljlkdsajfljasldfj;lsa",
    "profilePhoto": "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg",
    "documents": {
        "DL": [
            {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
        "Registration": [
            {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
        "Insurance":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
         "CarInside":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
         "CarOutside":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ]
    }
}

You can create dynamically like the below code:

JSONObject jsonBody = new JSONObject();
try {
    jsonBody.put("username", userName);
    jsonBody.put("email", email);
    jsonBody.put("phone", contactNumber);
    jsonBody.put("password", password);
    jsonBody.put("carType", carType);
    jsonBody.put("fcmToken", "lljlkdsajfljasldfj;lsa");
    jsonBody.put("profilePhoto", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg");

    JSONObject document = new JSONObject();

    try {
        document.put("DL", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Registration", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Insurance", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarInside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarOutside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    jsonBody.put("documents", document.toString());

    Log.i("MAHDI", "Hello: Mahdi: Data: " + jsonBody);
} catch (JSONException e) {
    e.printStackTrace();
}

And the createDocument method code:

public JSONArray createDocument(String id, String imageUrl) {

JSONObject dlObject = new JSONObject();
try {
    dlObject.put("_id", id);
    dlObject.put("uriPath", imageUrl);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
JSONArray dlArray = new JSONArray();
dlArray.put(dlObject);

return dlArray;
}

Return rows in random order

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

Count characters in textarea

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

    <script>

            function countChar(val) 
            {

             var limit = 1024;

            if ( val.length > limit )
              { 
              $("#comment").val(val.substring(0, limit-1));
              val.length = limit;
              }

              $("#count").html((limit)-(val.length));     
              }

        </script>

        <textarea id="comment" onKeyUp="countChar(this.value)" required></textarea>

        <div id="count"></div>

Use the following to skip using else and also skip getting negative count.

adb connection over tcp not working now

Just a tiny update with built-in wireless debugging in Android 11:

  • Go to Developer options > Wireless debugging
  • Enable > allow
  • Pair device with pairing code, a new port and pairing code generated and shown
  • adb pair [IP_ADDRESS]:[PORT] and type pairing code.
  • done

How to count occurrences of a column value efficiently in SQL?

This should work:

SELECT age, count(age) 
  FROM Students 
 GROUP by age

If you need the id as well you could include the above as a sub query like so:

SELECT S.id, S.age, C.cnt
  FROM Students  S
       INNER JOIN (SELECT age, count(age) as cnt
                     FROM Students 
                    GROUP BY age) C ON S.age = C.age

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

How to list files in a directory in a C program?

One tiny addition to JB Jansen's answer - in the main readdir() loop I'd add this:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Just checking if it's really file, not (sym)link, directory, or whatever.

NOTE: more about struct dirent in libc documentation.

REST / SOAP endpoints for a WCF service

MSDN seems to have an article for this now:

https://msdn.microsoft.com/en-us/library/bb412196(v=vs.110).aspx

Intro:

By default, Windows Communication Foundation (WCF) makes endpoints available only to SOAP clients. In How to: Create a Basic WCF Web HTTP Service, an endpoint is made available to non-SOAP clients. There may be times when you want to make the same contract available both ways, as a Web endpoint and as a SOAP endpoint. This topic shows an example of how to do this.

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

asp:TextBox ReadOnly=true or Enabled=false?

Think about it from the browser's point of view. For readonly the browser will send in a variable/value pair. For disabled, it won't.

Run this, then look at the URL after you hit submit:

<html>
<form action=foo.html method=get>
<input name=dis type=text disabled value="dis">
<input name=read type=text readonly value="read">
<input name=normal type=text value="normal">
<input type=submit>
</form>
</html>

How can the size of an input text box be defined in HTML?

Try this

<input type="text" style="font-size:18pt;height:420px;width:200px;">

Or else

 <input type="text" id="txtbox">

with the css:

 #txtbox
    {
     font-size:18pt;
     height:420px;
     width:200px;
    }

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

How to execute a shell script in PHP?

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

disable_functions = exec

And remove the exec, shell_exec entries if there are there.

Good Luck!

php codeigniter count rows

Use this code:

$this->db->where(['id'=>2])->from("table name")->count_all_results();

or

$this->db->from("table name")->count_all_results();

Execute script after specific delay using JavaScript

I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)

//  Show current seconds and milliseconds
//  (I know there are other ways, I was aiming for minimal code
//  and fixed width.)
function secs()
{
    var s = Date.now() + ""; s = s.substr(s.length - 5);
  return s.substr(0, 2) + "." + s.substr(2);
}

//  Log we're loading
console.log("Loading: " + secs());

//  Create a list of commands to execute
var cmds = 
[
    function() { console.log("A: " + secs()); },
    function() { console.log("B: " + secs()); },
    function() { console.log("C: " + secs()); },
    function() { console.log("D: " + secs()); },
    function() { console.log("E: " + secs()); },
  function() { console.log("done: " + secs()); }
];

//  Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
    setTimeout(cmd, ms * i);
});

// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());

You can copy the code block and paste it into a console window and see something like:

Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

document.body.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
  event.preventDefault();
  console.log('clicked ;)');
}
});

DEMO

https://jsfiddle.net/muratkezli/51rnc9ug/6/

CSS: Position loading indicator in the center of the screen

Worked for me in angular 4

by adding style="margin:0 auto;"

<mat-progress-spinner
  style="margin:0 auto;"
  *ngIf="isLoading"
  mode="indeterminate">
  </mat-progress-spinner>

Commands out of sync; you can't run this command now

You can't have two simultaneous queries because mysqli uses unbuffered queries by default (for prepared statements; it's the opposite for vanilla mysql_query). You can either fetch the first one into an array and loop through that, or tell mysqli to buffer the queries (using $stmt->store_result()).

See here for details.

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Counting Chars in EditText Changed Listener

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

How to programmatically set the ForeColor of a label to its default?

You can also use below format:

Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#22FF99");

and

HyperLink1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#22FF99");

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

jQuery to loop through elements with the same class

divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}

Bootstrap carousel resizing image

Had the same problem and none of the CSS solutions presented here worked.

What worked for me was setting up a height="360" without setting any width. My photos aren't the same size and like this they have room to adjust their with but keep the height fixed.

How do I convert an integer to binary in JavaScript?

we can also calculate the binary for positive or negative numbers as below:

_x000D_
_x000D_
function toBinary(n){
    let binary = "";
    if (n < 0) {
      n = n >>> 0;
    }
    while(Math.ceil(n/2) > 0){
        binary = n%2 + binary;
        n = Math.floor(n/2);
    }
    return binary;
}

console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
_x000D_
_x000D_

"405 method not allowed" in IIS7.5 for "PUT" method

I had this problem with WebDAV when hosting a MVC4 WebApi Project. I got around it by adding this line to the web.config:

<handlers>
  <remove name="WebDAV" />
  <add name="WebDAV" path="*" verb="*" modules="WebDAVModule"
      resourceType="Unspecified" requireAccess="None" />
</handlers>

As explained here: http://evolutionarydeveloper.blogspot.co.uk/2012/07/method-not-allowed-405-on-iis7-website.html

What is Node.js?

V8 is an implementation of JavaScript. It lets you run standalone JavaScript applications (among other things).

Node.js is simply a library written for V8 which does evented I/O. This concept is a bit trickier to explain, and I'm sure someone will answer with a better explanation than I... The gist is that rather than doing some input or output and waiting for it to happen, you just don't wait for it to finish. So for example, ask for the last edited time of a file:

// Pseudo code
stat( 'somefile' )

That might take a couple of milliseconds, or it might take seconds. With evented I/O you simply fire off the request and instead of waiting around you attach a callback that gets run when the request finishes:

// Pseudo code
stat( 'somefile', function( result ) {
  // Use the result here
} );
// ...more code here

This makes it a lot like JavaScript code in the browser (for example, with Ajax style functionality).

For more information, you should check out the article Node.js is genuinely exciting which was my introduction to the library/platform... I found it quite good.

Android: How to handle right to left swipe gestures

This question was asked many years ago. Now, there is a better solution: SmartSwipe: https://github.com/luckybilly/SmartSwipe

code looks like this:

SmartSwipe.wrap(contentView)
        .addConsumer(new StayConsumer()) //contentView stay while swiping with StayConsumer
        .enableAllDirections() //enable directions as needed
        .addListener(new SimpleSwipeListener() {
            @Override
            public void onSwipeOpened(SmartSwipeWrapper wrapper, SwipeConsumer consumer, int direction) {
                //direction: 
                //  1: left
                //  2: right
                //  4: top
                //  8: bottom
            }
        })
;

how to download file using AngularJS and calling MVC API?

There is 2 ways to do it in angularjs..

1) By directly redirecting to your service call..

<a href="some/path/to/the/file">clickme</a>

2) By submitting hidden form.

$scope.saveAsPDF = function() {
    var form = document.createElement("form");
    form.setAttribute("action", "some/path/to/the/file");
    form.setAttribute("method", "get");
    form.setAttribute("target", "_blank");

    var hiddenEle1 = document.createElement("input");
    hiddenEle1.setAttribute("type", "hidden");
    hiddenEle1.setAttribute("name", "some");
    hiddenEle1.setAttribute("value", value);

    form.append(hiddenEle1 );

    form.submit();

}

use the hidden element when you have to post some element

<button ng-click="saveAsPDF()">Save As PDF</button>

How to switch Python versions in Terminal?

Here is a nice and simple way to do it (but on CENTOS), without braking the operating system.

yum install scl-utils

next

yum install centos-release-scl-rh

And lastly you install the version that you want, lets say python3.5

yum install rh-python35

And lastly:

scl enable rh-python35 bash

Since MAC-OS is a unix operating system, the way to do it it should be quite similar.

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

Concatenate columns in Apache Spark DataFrame

In Java you can do this to concatenate multiple columns. The sample code is to provide you a scenario and how to use it for better understanding.

SparkSession spark = JavaSparkSessionSingleton.getInstance(rdd.context().getConf());
Dataset<Row> reducedInventory = spark.sql("select * from table_name")
                        .withColumn("concatenatedCol",
                                concat(col("col1"), lit("_"), col("col2"), lit("_"), col("col3")));


class JavaSparkSessionSingleton {
    private static transient SparkSession instance = null;

    public static SparkSession getInstance(SparkConf sparkConf) {
        if (instance == null) {
            instance = SparkSession.builder().config(sparkConf)
                    .getOrCreate();
        }
        return instance;
    }
}

The above code concatenated col1,col2,col3 seperated by "_" to create a column with name "concatenatedCol".

SSRS the definition of the report is invalid

This occurred for me due to changing the names of certain dataset fields within BIDS that were being referenced by parameters. I forgot to go into the parameters and reassign a default value (the default value of the parameter didn't automatically change to the newly renamed dataset field. Instead .

In plain English, what does "git reset" do?

Remember that in git you have:

  • the HEAD pointer, which tells you what commit you're working on
  • the working tree, which represents the state of the files on your system
  • the staging area (also called the index), which "stages" changes so that they can later be committed together

Please include detailed explanations about:

--hard, --soft and --merge;

In increasing order of dangerous-ness:

  • --soft moves HEAD but doesn't touch the staging area or the working tree.
  • --mixed moves HEAD and updates the staging area, but not the working tree.
  • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
  • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

concrete use cases and workflows;

  • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

--

# git reset --soft example
touch foo                            // Add a file, make some changes.
git add foo                          // 
git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
git reset --soft HEAD^               // Go back one commit and fix things.
git commit -m "good commit"          // There, now it's right.

--

  • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

  • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

  • Use --hard to wipe everything out and start a fresh slate at the new commit.

How can I scroll a web page using selenium webdriver in python?

When working with youtube the floating elements give the value "0" as the scroll height so rather than using "return document.body.scrollHeight" try using this one "return document.documentElement.scrollHeight" adjust the scroll pause time as per your internet speed else it will run for only one time and then breaks after that.

SCROLL_PAUSE_TIME = 1

# Get scroll height
"""last_height = driver.execute_script("return document.body.scrollHeight")

this dowsnt work due to floating web elements on youtube
"""

last_height = driver.execute_script("return document.documentElement.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.documentElement.scrollHeight")
    if new_height == last_height:
       print("break")
       break
    last_height = new_height

Set Content-Type to application/json in jsp file

Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

Insert and set value with max()+1 problems

insert into table1(id1) select (max(id1)+1) from table1;

How to create a JSON object

$post_data = [
  "item" => [
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
    'is_public_for_contacts' => $public_contacts
  ]
];

$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;

Retrieve WordPress root directory path?

There are 2 answers for this question Url & directory. Either way, the elegant way would be to define two constants for later use.

define (ROOT_URL, get_site_url() );
define (ROOT_DIR, get_theme_root() );

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

If you using Bootstrap:

The current version of Bootstrap (3.0.2) (with jQuery 1.10.2 & Chrome) seems to generate this warning as well.

(It does so on Twitter too, BTW.)

Update

The current version of Bootstrap (3.1.0) no longer seems to generate this warning.

From Now() to Current_timestamp in Postgresql

Here is an example ...

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

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

TextView - setting the text size programmatically doesn't seem to work

This fixed the issue for me. I got uniform font size across all devices.

 textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.font));

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Or try adding this...

$code = @"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"@
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)

By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.

Laravel blank white screen

An update to fideloper's answer for Laravel 5 and its new file structure is:

$ sudo chmod -R o+w storage/

Array of arrays (Python/NumPy)

If the file is only numerical values separated by tabs, try using the csv library: http://docs.python.org/library/csv.html (you can set the delimiter to '\t')

If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:

import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
    match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
    if match is None:
        pass # line syntax is wrong - ignore the line
    values_as_strings = match.group(1).split()
    result_matrix.append(map(int, values_as_strings))

How do I create a unique constraint that also allows nulls?

Create a view that selects only non-NULL columns and create the UNIQUE INDEX on the view:

CREATE VIEW myview
AS
SELECT  *
FROM    mytable
WHERE   mycolumn IS NOT NULL

CREATE UNIQUE INDEX ux_myview_mycolumn ON myview (mycolumn)

Note that you'll need to perform INSERT's and UPDATE's on the view instead of table.

You may do it with an INSTEAD OF trigger:

CREATE TRIGGER trg_mytable_insert ON mytable
INSTEAD OF INSERT
AS
BEGIN
        INSERT
        INTO    myview
        SELECT  *
        FROM    inserted
END

get and set in TypeScript

If you are working with TypeScript modules and are trying to add a getter that is exported, you can do something like this:

// dataStore.ts
export const myData: string = undefined;  // just for typing support
let _myData: string;  // for memoizing the getter results

Object.defineProperty(this, "myData", {
    get: (): string => {
        if (_myData === undefined) {
            _myData = "my data";  // pretend this took a long time
        }

        return _myData;
    },
});

Then, in another file you have:

import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"

Running Jupyter via command line on Windows

I had the same problem, but

py -m notebook

worked for me.

How to base64 encode image in linux bash / shell

Single line result:

base64 -w 0 DSC_0251.JPG

For HTML:

echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"

As file:

base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64

In variable:

IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"

In variable for HTML:

IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"

Get you readable data back:

base64 -d DSC_0251.base64 > DSC_0251.JPG 

See: http://www.greywyvern.com/code/php/binary2base64

GridLayout and Row/Column Span Woe

You have to set both layout_gravity and layout_columntWeight on your columns

<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />
 </android.support.v7.widget.GridLayout>

sqlplus statement from command line

Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).

I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:

sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF

The Use of Multiple JFrames: Good or Bad Practice?

The multiple JFrame approach has been something I've implemented since I began programming Swing apps. For the most part, I did it in the beginning because I didn't know any better. However, as I matured in my experience and knowledge as a developer and as began to read and absorb the opinions of so many more experienced Java devs online, I made an attempt to shift away from the multiple JFrame approach (both in current projects and future projects) only to be met with... get this... resistance from my clients! As I began implementing modal dialogs to control "child" windows and JInternalFrames for separate components, my clients began to complain! I was quite surprised, as I was doing what I thought was best-practice! But, as they say, "A happy wife is a happy life." Same goes for your clients. Of course, I am a contractor so my end-users have direct access to me, the developer, which is obviously not a common scenario.

So, I'm going to explain the benefits of the multiple JFrame approach, as well as myth-bust some of the cons that others have presented.

  1. Ultimate flexibility in layout - By allowing separate JFrames, you give your end-user the ability to spread out and control what's on his/her screen. The concept feels "open" and non-constricting. You lose this when you go towards one big JFrame and a bunch of JInternalFrames.
  2. Works well for very modularized applications - In my case, most of my applications have 3 - 5 big "modules" that really have nothing to do with each other whatsoever. For instance, one module might be a sales dashboard and one might be an accounting dashboard. They don't talk to each other or anything. However, the executive might want to open both and them being separate frames on the taskbar makes his life easier.
  3. Makes it easy for end-users to reference outside material - Once, I had this situation: My app had a "data viewer," from which you could click "Add New" and it would open a data entry screen. Initially, both were JFrames. However, I wanted the data entry screen to be a JDialog whose parent was the data viewer. I made the change, and immediately I received a call from an end-user who relied heavily on the fact that he could minimize or close the viewer and keep the editor open while he referenced another part of the program (or a website, I don't remember). He's not on a multi-monitor, so he needed the entry dialog to be first and something else to be second, with the data viewer completely hidden. This was impossible with a JDialog and certainly would've been impossible with a JInternalFrame as well. I begrudgingly changed it back to being separate JFrames for his sanity, but it taught me an important lesson.
  4. Myth: Hard to code - This is not true in my experience. I don't see why it would be any easier to create a JInternalFrame than a JFrame. In fact, in my experience, JInternalFrames offer much less flexibility. I have developed a systematic way of handling the opening & closing of JFrames in my apps that really works well. I control the frame almost completely from within the frame's code itself; the creation of the new frame, SwingWorkers that control the retrieval of data on background threads and the GUI code on EDT, restoring/bringing to front the frame if the user tries to open it twice, etc. All you need to open my JFrames is call a public static method open() and the open method, combined with a windowClosing() event handles the rest (is the frame already open? is it not open, but loading? etc.) I made this approach a template so it's not difficult to implement for each frame.
  5. Myth/Unproven: Resource Heavy - I'd like to see some facts behind this speculative statement. Although, perhaps, you could say a JFrame needs more space than a JInternalFrame, even if you open up 100 JFrames, how many more resources would you really be consuming? If your concern is memory leaks because of resources: calling dispose() frees all resources used by the frame for garbage collection (and, again I say, a JInternalFrame should invoke exactly the same concern).

I've written a lot and I feel like I could write more. Anyways, I hope I don't get down-voted simply because it's an unpopular opinion. The question is clearly a valuable one and I hope I've provided a valuable answer, even if it isn't the common opinion.

A great example of multiple frames/single document per frame (SDI) vs single frame/multiple documents per frame (MDI) is Microsoft Excel. Some of MDI benefits:

  • it is possible to have a few windows in non rectangular shape - so they don't hide desktop or other window from another process (e.g. web browser)
  • it is possible to open a window from another process over one Excel window while writing in second Excel window - with MDI, trying to write in one of internal windows will give focus to the entire Excel window, hence hiding window from another process
  • it is possible to have different documents on different screens, which is especially useful when screens do not have the same resolution

SDI (Single-Document Interface, i.e., every window can only have a single document):

enter image description here

MDI (Multiple-Document Interface, i.e., every window can have multiple documents):

enter image description here

How to conclude your merge of a file?

The easiest solution I found for this:

git commit -m "fixing merge conflicts"
git push

How to run certain task every day at a particular time using ScheduledExecutorService?

You can use a simple date parse, if the time of the day is before now, let's start tomorrow :

  String timeToStart = "12:17:30";
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss");
  SimpleDateFormat formatOnlyDay = new SimpleDateFormat("yyyy-MM-dd");
  Date now = new Date();
  Date dateToStart = format.parse(formatOnlyDay.format(now) + " at " + timeToStart);
  long diff = dateToStart.getTime() - now.getTime();
  if (diff < 0) {
    // tomorrow
    Date tomorrow = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(tomorrow);
    c.add(Calendar.DATE, 1);
    tomorrow = c.getTime();
    dateToStart = format.parse(formatOnlyDay.format(tomorrow) + " at " + timeToStart);
    diff = dateToStart.getTime() - now.getTime();
  }

  ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);            
  scheduler.scheduleAtFixedRate(new MyRunnableTask(), TimeUnit.MILLISECONDS.toSeconds(diff) ,
                                  24*60*60, TimeUnit.SECONDS);

Write / add data in JSON file using Node.js

you should read the file, every time you want to add a new property to the json, and then add the the new properties

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})

Cannot read configuration file due to insufficient permissions

The above answers were helpful, but in case this helps anyone - I had this exact problem, and it turned out that I was (windows networking) sharing the root folder that the site was being hosted from. We killed the share, and added the Users permission to read/execute and it worked again just fine.

I suspect the share messed it up.

Rename Oracle Table or View

To rename a table you can use:

RENAME mytable TO othertable;

or

ALTER TABLE mytable RENAME TO othertable;

or, if owned by another schema:

ALTER TABLE owner.mytable RENAME TO othertable;

Interestingly, ALTER VIEW does not support renaming a view. You can, however:

RENAME myview TO otherview;

The RENAME command works for tables, views, sequences and private synonyms, for your own schema only.

If the view is not in your schema, you can recompile the view with the new name and then drop the old view.

(tested in Oracle 10g)

initialize a numpy array

To initialize a numpy array with a specific matrix:

import numpy as np

mat = np.array([[1, 1, 0, 0, 0],
                [0, 1, 0, 0, 1],
                [1, 0, 0, 1, 1],
                [0, 0, 0, 0, 0],
                [1, 0, 1, 0, 1]])

print mat.shape
print mat

output:

(5, 5)
[[1 1 0 0 0]
 [0 1 0 0 1]
 [1 0 0 1 1]
 [0 0 0 0 0]
 [1 0 1 0 1]]

What is the difference between atan and atan2 in C++?

std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.

PHP - iterate on string characters

Iterate string:

for ($i = 0; $i < strlen($str); $i++){
    echo $str[$i];
}

How To Accept a File POST

The ASP.NET Core way is now here:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

Confusing "duplicate identifier" Typescript error message

If you have installed typings separately under typings folder

{
  "exclude": [
    "node_modules",
    "typings"
  ]
}

Imitating a blink tag with CSS3 animations

Another variation

_x000D_
_x000D_
.blink {_x000D_
    -webkit-animation: blink 1s step-end infinite;_x000D_
            animation: blink 1s step-end infinite;_x000D_
}_x000D_
@-webkit-keyframes blink { 50% { visibility: hidden; }}_x000D_
        @keyframes blink { 50% { visibility: hidden; }}
_x000D_
This is <span class="blink">blink</span>
_x000D_
_x000D_
_x000D_

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

Git's famous "ERROR: Permission to .git denied to user"

On Mac, if you have multiple GitHub logins and are not using SSH, force the correct login by using:

git remote set-url origin https://[email protected]/username/repo-name.git

This also works if you're having issues pushing to a private repository.

import httplib ImportError: No module named httplib

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:

apt-get install -y --no-install-recommends python

And I should not have included the --no-install-recommends flag:

apt-get install -y python

Fastest way to zero out a 2d array in C?

memset(array, 0, sizeof(array[0][0]) * m * n);

Where m and n are the width and height of the two-dimensional array (in your example, you have a square two-dimensional array, so m == n).

How to change the text on the action bar

getSupportActionBar().setTitle("title");

move column in pandas dataframe

You can use to way below. It's very simple, but similar to the good answer given by Charlie Haley.

df1 = df.pop('b') # remove column b and store it in df1
df2 = df.pop('x') # remove column x and store it in df2
df['b']=df1 # add b series as a 'new' column.
df['x']=df2 # add b series as a 'new' column.

Now you have your dataframe with the columns 'b' and 'x' in the end. You can see this video from OSPY : https://youtu.be/RlbO27N3Xg4

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

How to set Linux environment variables with Ansible

Here's a quick local task to permanently set key/values on /etc/environment (which is system-wide, all users):

- name: populate /etc/environment
  lineinfile:
    dest: "/etc/environment"
    state: present
    regexp: "^{{ item.key }}="
    line: "{{ item.key }}={{ item.value}}"
  with_items: "{{ os_environment }}"

and the vars for it:

os_environment:
  - key: DJANGO_SETTINGS_MODULE 
    value : websec.prod_settings  
  - key: DJANGO_SUPER_USER 
    value : admin

and, yes, if you ssh out and back in, env shows the new environment variables.

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');

Plotting lines connecting points

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

enter image description here

Unable to call the built in mb_internal_encoding method?

If someone is having trouble with installing php-mbstring package in ubuntu do following sudo apt-get install libapache2-mod-php5

How does a hash table work?

A hash table totally works on the fact that practical computation follows random access machine model i.e. value at any address in memory can be accessed in O(1) time or constant time.

So, if I have a universe of keys (set of all possible keys that I can use in a application, e.g. roll no. for student, if it's 4 digit then this universe is a set of numbers from 1 to 9999), and a way to map them to a finite set of numbers of size I can allocate memory in my system, theoretically my hash table is ready.

Generally, in applications the size of universe of keys is very large than number of elements I want to add to the hash table(I don't wanna waste a 1 GB memory to hash ,say, 10000 or 100000 integer values because they are 32 bit long in binary reprsentaion). So, we use this hashing. It's sort of a mixing kind of "mathematical" operation, which maps my large universe to a small set of values that I can accomodate in memory. In practical cases, often space of a hash table is of the same "order"(big-O) as the (number of elements *size of each element), So, we don't waste much memory.

Now, a large set mapped to a small set, mapping must be many-to-one. So, different keys will be alloted the same space(?? not fair). There are a few ways to handle this, I just know the popular two of them:

  • Use the space that was to be allocated to the value as a reference to a linked list. This linked list will store one or more values, that come to reside in same slot in many to one mapping. The linked list also contains keys to help someone who comes searching. It's like many people in same apartment, when a delivery-man comes, he goes to the room and asks specifically for the guy.
  • Use a double hash function in an array which gives the same sequence of values every time rather than a single value. When I go to store a value, I see whether the required memory location is free or occupied. If it's free, I can store my value there, if it's occupied I take next value from the sequence and so on until I find a free location and I store my value there. When searching or retreiving the value, I go back on same path as given by the sequence and at each location ask for the vaue if it's there until I find it or search all possible locations in the array.

Introduction to Algorithms by CLRS provides a very good insight on the topic.

Call a REST API in PHP

You can use file_get_contents to issue any http POST/PUT/DELETE/OPTIONS/HEAD methods, in addition to the GET method as the function name suggests.

How to post data in PHP using file_get_contents?

How to send email to multiple recipients with addresses stored in Excel?

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.

Windows does not have (need?) this.

Run the command with the sudo removed from the start.

Using IF ELSE statement based on Count to execute different Insert statements

Not very clear what you mean by

"I cant find any examples to help me understand how I can use this to run 2 different statements:"

. Is it using CASE like a SWITCH you are after?

select case when totalCount >= 0 and totalCount < 11 then '0-10'
            when tatalCount > 10 and totalCount < 101 then '10-100'
            else '>100' end as newColumn
from (
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) A

C/C++ NaN constant (literal)?

As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN() although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:

Only meaningful if std::numeric_limits::has_quiet_NaN == true.

and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN it says:

This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.

which as explained here if true means your platform supports IEEE 754 standard. This previous thread explains this should be true for most situations.

Run a shell script with an html button

PHP is likely the easiest.

Just make a file script.php that contains <?php shell_exec("yourscript.sh"); ?> and send anybody who clicks the button to that destination. You can return the user to the original page with header:

<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>

Reference: http://php.net/manual/en/function.shell-exec.php

Tkinter example code for multiple windows, why won't buttons load correctly?

I tried to use more than two windows using the Rushy Panchal example above. The intent was to have the change to call more windows with different widgets in them. The butnew function creates different buttons to open different windows. You pass as argument the name of the class containing the window (the second argument is nt necessary, I put it there just to test a possible use. It could be interesting to inherit from another window the widgets in common.

import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.master.geometry("400x400")
        self.frame = tk.Frame(self.master)
        self.butnew("Window 1", "ONE", Demo2)
        self.butnew("Window 2", "TWO", Demo3)
        self.frame.pack()

    def butnew(self, text, number, _class):
        tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()

    def new_window(self, number, _class):
        self.newWindow = tk.Toplevel(self.master)
        _class(self.newWindow, number)


class Demo2:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("400x400+400+400")
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.label = tk.Label(master, text=f"this is window number {number}")
        self.label.pack()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

class Demo3:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("400x400+400+400")
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.label = tk.Label(master, text=f"this is window number {number}")
        self.label.pack()
        self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
        self.label2.pack()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()




def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Open the new window only once

To avoid having the chance to press multiple times the button having multiple windows... that are the same window, I made this script (take a look at this page too)

import tkinter as tk


def new_window1():
    global win1
    try:
        if win1.state() == "normal": win1.focus()
    except:
        win1 = tk.Toplevel()
        win1.geometry("300x300+500+200")
        win1["bg"] = "navy"
        lb = tk.Label(win1, text="Hello")
        lb.pack()


win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()

How do I test axios in Jest?

Without using any other libraries:

import * as axios from "axios";

// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");

// ...

test("good response", () => {
  axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
  // ...
});

test("bad response", () => {
  axios.get.mockImplementation(() => Promise.reject({ ... }));
  // ...
});

It is possible to specify the response code:

axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));

It is possible to change the mock based on the parameters:

axios.get.mockImplementation((url) => {
    if (url === 'www.example.com') {
        return Promise.resolve({ data: {...} });
    } else {
        //...
    }
});

Jest v23 introduced some syntactic sugar for mocking Promises:

axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));

It can be simplified to

axios.get.mockResolvedValue({ data: {...} });

There is also an equivalent for rejected promises: mockRejectedValue.

Further Reading:

How do I make a new line in swift

"\n" is not working everywhere!

For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")

There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).

using this extension:

extension CharacterSet {
    var allCharacters: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:

let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
    print("Hello World \(newLine) This is a new line")
}

Then store the one you tested and worked everywhere and use it anywhere. Note that you can't relay on the index of the character set. It may change.

But most of the times "\n" just works as expected.

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

Preferred method to store PHP arrays (json_encode vs serialize)

If you are caching information that you will ultimately want to "include" at a later point in time, you may want to try using var_export. That way you only take the hit in the "serialize" and not in the "unserialize".

Is there a better alternative than this to 'switch on type'?

C# 8 enhancements of pattern matching made it possible to do it like this. In some cases it do the job and more concise.

        public Animal Animal { get; set; }
        ...
        var animalName = Animal switch
        {
            Cat cat => "Tom",
            Mouse mouse => "Jerry",
            _ => "unknown"
        };

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

if you're using the compiled bootstrap, one of the ways of fixing it is by editing the bootstrap.min.js before the line

$next[0].offsetWidth 

force reflow Change to

if (typeof $next == 'object' && $next.length) $next[0].offsetWidth // force reflow

Converting std::__cxx11::string to std::string

When I had similar issue it's happened because my lib was build using clang++, and it's linked to libstdc++.so by default on my system. While app binary was build using clang and linked with -lc++ option.

Easiest way to check dependencies is to perform ldd libName.so

To fix it you should use the same library on in app and library.

  • Easiest way. Build library using clang++ and compile app using clang++. Without extra linking options on both steps. Default stdlib will be used.

  • Build library with -stdlib=c++ and compile app with -lc++. In this case both library and app will use libc++.so.

  • Build library without extra options and link binary to -lstdc++. In this case both library and app will use libstdc++.so.

How do I make a Docker container start automatically on system boot?

You can use docker update --restart=on-failure <container ID or name>.

On top of what the name suggests, on-failure will not only restart the container on failure, but also at system boot.

Per the documentation, there are multiple restart options:

Flag            Description
no              Do not automatically restart the container. (the default)
on-failure      Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always          Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped  Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

Remove decimal values using SQL query

Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.

12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.

If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.

If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)

Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.

Angular4 - No value accessor for form control

You can use formControlName only on directives which implement ControlValueAccessor.

Implement the interface

So, in order to do what you want, you have to create a component which implements ControlValueAccessor, which means implementing the following three functions:

  • writeValue (tells Angular how to write value from model into view)
  • registerOnChange (registers a handler function that is called when the view changes)
  • registerOnTouched (registers a handler to be called when the component receives a touch event, useful for knowing if the component has been focused).

Register a provider

Then, you have to tell Angular that this directive is a ControlValueAccessor (interface is not gonna cut it since it is stripped from the code when TypeScript is compiled to JavaScript). You do this by registering a provider.

The provider should provide NG_VALUE_ACCESSOR and use an existing value. You'll also need a forwardRef here. Note that NG_VALUE_ACCESSOR should be a multi provider.

For example, if your custom directive is named MyControlComponent, you should add something along the following lines inside the object passed to @Component decorator:

providers: [
  { 
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: forwardRef(() => MyControlComponent),
  }
]

Usage

Your component is ready to be used. With template-driven forms, ngModel binding will now work properly.

With reactive forms, you can now properly use formControlName and the form control will behave as expected.

Resources

PUT vs. POST in REST

Both are used for data transmission between client to server, but there are subtle differences between them, which are:

Enter image description here

Analogy:

  • PUT i.e. take and put where it was.
  • POST as send mail in post office.

enter image description here

Social Media/Network Analogy:

  • Post on social media: when we post message, it creates new post.
  • Put(i.e. edit) for the message we already Posted.

Largest and smallest number in an array

Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
 foreach(Int i in number)

    {
       If(!Result.HasValue || i< Result)

        { 

            Result =i;
         }
     }

     Console.WriteLine(Result);
   }

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Get element type with jQuery

also you can use:

$("#elementId").get(0).tagName

load iframe in bootstrap modal

You can simply use this bootstrap helper to dialogs (only 5 kB)

it has support for ajax request, iframes, common dialogs, confirm and prompt!

you can use it as:

eModal.iframe('http://someUrl.com', 'This is a tile for iframe', callbackIfNeeded);

eModal.alert('The message', 'This title');

eModal.ajax('/mypage.html', 'This is a ajax', callbackIfNeeded);

eModal.confirm('the question', 'The title', theMandatoryCallback);

eModal.prompt('Form question', 'This is a ajax', theMandatoryCallback);

this provide a loading progress while loading the iframe!

No html required.

You can use a object literal as parameter to extra options.

Check the site form more details.

best,

Reactjs setState() with a dynamic key name?

Can use a spread syntax, something like this:

inputChangeHandler : function (event) {
    this.setState( { 
        ...this.state,
        [event.target.id]: event.target.value
    } );
},

Remove Fragment Page from ViewPager in Android

I had the idea of simply copy the source code from android.support.v4.app.FragmentPagerAdpater into a custom class named CustumFragmentPagerAdapter. This gave me the chance to modify the instantiateItem(...) so that every time it is called, it removes / destroys the currently attached fragment before it adds the new fragment received from getItem() method.

Simply modify the instantiateItem(...) in the following way:

@Override
public Object instantiateItem(ViewGroup container, int position) {
    if (mCurTransaction == null) {
        mCurTransaction = mFragmentManager.beginTransaction();
    }
    final long itemId = getItemId(position);

    // Do we already have this fragment?
    String name = makeFragmentName(container.getId(), itemId);
    Fragment fragment = mFragmentManager.findFragmentByTag(name);

    // remove / destroy current fragment
    if (fragment != null) {
        mCurTransaction.remove(fragment);
    }

    // get new fragment and add it
    fragment = getItem(position);
    mCurTransaction.add(container.getId(), fragment,    makeFragmentName(container.getId(), itemId));

    if (fragment != mCurrentPrimaryItem) {
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
    }

    return fragment;
}

What is memoization and how can I use it in Python?

cache = {}
def fib(n):
    if n <= 1:
        return n
    else:
        if n not in cache:
            cache[n] = fib(n-1) + fib(n-2)
        return cache[n]

Response::json() - Laravel 5.1

From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).

public function show($id)
{
    return Customer::find($id);
}

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Here's a zepto compatible solution

    if (!$(e.target).hasClass('scrollable') && !$(e.target).closest('.scrollable').length > 0) {
       console.log('prevented scroll');
       e.preventDefault();
       window.scroll(0,0);
       return false;
    }

Stack, Static, and Heap in C++

It's been said elaborately, just as "the short answer":

  • static variable (class)
    lifetime = program runtime (1)
    visibility = determined by access modifiers (private/protected/public)

  • static variable (global scope)
    lifetime = program runtime (1)
    visibility = the compilation unit it is instantiated in (2)

  • heap variable
    lifetime = defined by you (new to delete)
    visibility = defined by you (whatever you assign the pointer to)

  • stack variable
    visibility = from declaration until scope is exited
    lifetime = from declaration until declaring scope is exited


(1) more exactly: from initialization until deinitialization of the compilation unit (i.e. C / C++ file). Order of initialization of compilation units is not defined by the standard.

(2) Beware: if you instantiate a static variable in a header, each compilation unit gets its own copy.