Programs & Examples On #Memory bandwidth

Youtube iframe wmode issue

Add &wmode=transparent to the url and you're done, tested.

I use that technique in my own wordpress plugin YouTube shortcode

Check its source code if you encounter any issue.

android on Text Change Listener

Another solution that may help someone. There are 2 EditText which change instead of each other after editing. By default, it led to cyclicity.

use variable:

Boolean uahEdited = false;
Boolean usdEdited = false;

add TextWatcher

uahEdit = findViewById(R.id.uahEdit);
usdEdit = findViewById(R.id.usdEdit);

uahEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!usdEdited) {
                uahEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = uahEdit.getText().toString();

            if(!tmp.isEmpty() && uahEdited) {
                uah = Double.valueOf(tmp);
                usd = uah / 27;
                usdEdit.setText(String.valueOf(usd));
            } else if (tmp.isEmpty()) {
                usdEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            uahEdited = false;
        }
    });

usdEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!uahEdited) {
                usdEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = usdEdit.getText().toString();

            if (!tmp.isEmpty() && usdEdited) {
                usd = Double.valueOf(tmp);
                uah = usd * 27;
                uahEdit.setText(String.valueOf(uah));
            } else if (tmp.isEmpty()) {
                uahEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            usdEdited = false;
        }
    });

Don't criticize too much. I am a novice developer

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

I faced same issue. Plus while I was trying to resolve from picking solutions from other devs, I faced few more issues like one listed here.

Angular 9 ng new myapp gives error The Schematic workflow failed

https://medium.com/@codewin/npm-warn-deprecated-request-2-88-2-b6da20766fd7

Finally after trying cache clean and verify and reinstall node of different versions and npm update, nvm and many other solution like set proxy and better internet connection, I still could not arrive to a resolve.

What worked for me is : I browsed a bit inside my C:\Users--- folder, I found package-lock.json and .npmrc files. I deleted those and reinstalled angular and tried. npm install and uninstall of different modules started working.

issue while creating using <code>ng new sample-app</code>

How to save and load cookies using Python + Selenium WebDriver

This is a solution that saves the profile directory for Firefox (similar to the user-data-dir (user data directory) in Chrome) (it involves manually copying the directory around. I haven't been able to find another way):

It was tested on Linux.


Short version:

  • To save the profile
driver.execute_script("window.close()")
time.sleep(0.5)
currentProfilePath = driver.capabilities["moz:profile"]
profileStoragePath = "/tmp/abc"
shutil.copytree(currentProfilePath, profileStoragePath,
                ignore_dangling_symlinks=True
                )
  • To load the profile
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
                 firefox_profile=FirefoxProfile(profileStoragePath)
                )

Long version (with demonstration that it works and a lot of explanation -- see comments in the code)

The code uses localStorage for demonstration, but it works with cookies as well.

#initial imports

from selenium.webdriver import Firefox, FirefoxProfile

import shutil
import os.path
import time

# Create a new profile

driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
                  # * I'm using this particular version. If yours is
                  # named "geckodriver" and placed in system PATH
                  # then this is not necessary
                )

# Navigate to an arbitrary page and set some local storage
driver.get("https://DuckDuckGo.com")
assert driver.execute_script(r"""{
        const tmp = localStorage.a; localStorage.a="1";
        return [tmp, localStorage.a]
    }""") == [None, "1"]

# Make sure that the browser writes the data to profile directory.
# Choose one of the below methods
if 0:
    # Wait for some time for Firefox to flush the local storage to disk.
    # It's a long time. I tried 3 seconds and it doesn't work.
    time.sleep(10)

elif 1:
    # Alternatively:
    driver.execute_script("window.close()")
    # NOTE: It might not work if there are multiple windows!

    # Wait for a bit for the browser to clean up
    # (shutil.copytree might throw some weird error if the source directory changes while copying)
    time.sleep(0.5)

else:
    pass
    # I haven't been able to find any other, more elegant way.
    #`close()` and `quit()` both delete the profile directory


# Copy the profile directory (must be done BEFORE driver.quit()!)
currentProfilePath = driver.capabilities["moz:profile"]
assert os.path.isdir(currentProfilePath)
profileStoragePath = "/tmp/abc"
try:
    shutil.rmtree(profileStoragePath)
except FileNotFoundError:
    pass

shutil.copytree(currentProfilePath, profileStoragePath,
                ignore_dangling_symlinks=True # There's a lock file in the
                                              # profile directory that symlinks
                                              # to some IP address + port
               )

driver.quit()
assert not os.path.isdir(currentProfilePath)
# Selenium cleans up properly if driver.quit() is called,
# but not necessarily if the object is destructed


# Now reopen it with the old profile

driver=Firefox(executable_path="geckodriver-v0.28.0-linux64",
               firefox_profile=FirefoxProfile(profileStoragePath)
              )

# Note that the profile directory is **copied** -- see FirefoxProfile documentation
assert driver.profile.path!=profileStoragePath
assert driver.capabilities["moz:profile"]!=profileStoragePath

# Confusingly...
assert driver.profile.path!=driver.capabilities["moz:profile"]
# And only the latter is updated.
# To save it again, use the same method as previously mentioned

# Check the data is still there

driver.get("https://DuckDuckGo.com")

data = driver.execute_script(r"""return localStorage.a""")
assert data=="1", data

driver.quit()

assert not os.path.isdir(driver.capabilities["moz:profile"])
assert not os.path.isdir(driver.profile.path)

What doesn't work:

  • Initialize Firefox(capabilities={"moz:profile": "/path/to/directory"}) -- the driver will not be able to connect.
  • options=Options(); options.add_argument("profile"); options.add_argument("/path/to/directory"); Firefox(options=options) -- same as above.

How do I find what Java version Tomcat6 is using?

At first you need to understand first, that Tomcat is a Java application. So, to see which java version Tomcat is using, you can just simply find the script file from which Tomcat is started, usually catalina.sh.

Inside this file, you will get something like below:

catalina.sh:#   JAVA_HOME       Must point at your Java Development Kit installation.
catalina.sh:#                   Defaults to JAVA_HOME if empty.
catalina.sh:  [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
catalina.sh:  JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
catalina.sh:    echo "Using JAVA_HOME:       $JAVA_HOME"

By default, JAVA_HOME should be empty, which mean it will use the default version of java, or you can test with: echo $JAVA_HOME

And then use "java -version" to see which version you default java is.

And vice versa by setting this property: JAVA_HOME, you can configure which Java version to use when starting Tomcat.

Display only 10 characters of a long string?

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

HTML <input type='file'> File Selection Event

When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.

document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick

Can you recommend a free light-weight MySQL GUI for Linux?

Try Adminer. The whole application is in one PHP file, which means that the deployment is as easy as it can get. It's more powerful than phpMyAdmin; it can edit views, procedures, triggers, etc.

Adminer is also a universal tool, it can connect to MySQL, PostgreSQL, SQLite, MS SQL, Oracle, SimpleDB, Elasticsearch and MongoDB.

You should definitely give it a try.

enter image description here

You can install on Ubuntu with sudo apt-get install adminer or you can also download the latest version from adminer.org

How to set HTTP headers (for cache-control)?

This is the best .htaccess I have used in my actual website:

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

##Tweaks##
Header set X-Frame-Options SAMEORIGIN

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_headers.c>
    Header set Connection keep-alive
    <filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
        Header set Cache-Control "max-age=2592000, public"
    </filesmatch>
    <filesmatch "\.(jpg|jpeg|png)$">
        Header set Cache-Control "max-age=1209600, public"
    </filesmatch>
    # css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
    <filesmatch "\.(css)$">
        Header set Cache-Control "max-age=31536000, private"
    </filesmatch>
    <filesmatch "\.(js)$">
        Header set Cache-Control "max-age=1209600, private"
    </filesmatch>
    <filesMatch "\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
      </filesMatch>
</IfModule>

React JSX: selecting "selected" on selected <select> option

Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.

class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};
  }

  handleChange = (event) =>
    this.setState({value: event.target.value});

  handleSubmit = (event) => {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite flavor:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
} 

jQuery loop over JSON result from AJAX Success?

I am partial to ES2015 arrow function for finding values in an array

const result = data.find(x=> x.TEST1 === '46');

Checkout Array.prototype.find() HERE

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --

I don't like setting position using css(), though often it's fine. I think the best bet is to use jQuery UI's position() setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:

const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
  left: baseOffset.left + leftOffset,
  top: baseOffset.top + topOffset
});

This has the advantage of not arbitrarily setting $div's parent to relative positioning (what if $div's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div doesn't have any offsetParent, not sure if it would return document, null, or something else entirely.

offsetParent has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.

VBScript - How to make program wait until process has finished?

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create "notepad.exe", null, null, intProcessID
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'")
Do Until i = 1
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
        i = 1
    End If
Loop
Wscript.Echo "Notepad has been terminated."

How to programmatically clear application data

Using Context,We can clear app specific files like preference,database file. I have used below code for UI testing using Espresso.

    @Rule
    public ActivityTestRule<HomeActivity> mActivityRule = new ActivityTestRule<>(
            HomeActivity.class);

    public static void clearAppInfo() {
        Activity mActivity = testRule.getActivity();
        SharedPreferences prefs =
                PreferenceManager.getDefaultSharedPreferences(mActivity);
        prefs.edit().clear().commit();
        mActivity.deleteDatabase("app_db_name.db");
    }

Accessing localhost of PC from USB connected Android mobile device

Google posted a solution for this kind of problem here.

The steps:

  • Connect your Android device and your development machine with USB debugging enabled
  • Open Chrome in your development machine, open new tab, right click in the new browser tab, click inspect
  • Click the three dots icon on right top side three dots, -> More Tools, Remote Devices.
  • Look at bottom of the screen, make sure your device name is appeared on the list with Green colored dot.
  • Look below at the settings part, check the Port forwarding mark
  • Add rule. Example, if your python web server is running on your machine localhost:5000 and you want to access it from your device port 3333, you type 3333 on the left part, and type localhost:5000, and click add rule.
  • Voila, now you can access your web server from your device. Try open new browser tab, and visit http://localhost:3333 from your device

Why do we have to normalize the input for an artificial neural network?

Looking at the neural network from the outside, it is just a function that takes some arguments and produces a result. As with all functions, it has a domain (i.e. a set of legal arguments). You have to normalize the values that you want to pass to the neural net in order to make sure it is in the domain. As with all functions, if the arguments are not in the domain, the result is not guaranteed to be appropriate.

The exact behavior of the neural net on arguments outside of the domain depends on the implementation of the neural net. But overall, the result is useless if the arguments are not within the domain.

why is plotting with Matplotlib so slow?

This may not apply to many of you, but I'm usually operating my computers under Linux, so by default I save my matplotlib plots as PNG and SVG. This works fine under Linux but is unbearably slow on my Windows 7 installations [MiKTeX under Python(x,y) or Anaconda], so I've taken to adding this code, and things work fine over there again:

import platform     # Don't save as SVG if running under Windows.
#
# Plot code goes here.
#
fig.savefig('figure_name.png', dpi = 200)
if platform.system() != 'Windows':
    # In my installations of Windows 7, it takes an inordinate amount of time to save
    # graphs as .svg files, so on that platform I've disabled the call that does so.
    # The first run of a script is still a little slow while everything is loaded in,
    # but execution times of subsequent runs are improved immensely.
    fig.savefig('figure_name.svg')

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

TLS 1.2 in .NET Framework 4.0

I meet the same issue on a Windows installed .NET Framework 4.0.
And I Solved this issue by installing .NET Framework 4.6.2.
Or you may download the newest package to have a try.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

How to execute a Windows command on a remote PC?

This can be done by using PsExec which can be downloaded here

psexec \\computer_name -u username -p password ipconfig

If this isn't working try doing this :-

  1. Open RegEdit on your remote server.
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.

  3. Add a new DWORD value called LocalAccountTokenFilterPolicy

  4. Set its value to 1.
  5. Reboot your remote server.
  6. Try running PSExec again from your local server.

Efficiently sorting a numpy array in descending order?

Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

Hope it helps you out!

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

Concatenating elements in an array to a string

Arrays.toString: (from the API, at least for the Object[] version of it)

public static String toString(Object[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

So that means it inserts the [ at the start, the ] at the end, and the , between elements.

If you want it without those characters: (StringBuilder is faster than the below, but it can't be the small amount of code)

String str = "";
for (String i:arr)
  str += i;
System.out.println(str);

Side note:

String[] arr[3]= [1,2,3] won't compile.

Presumably you wanted: String[] arr = {"1", "2", "3"};

Getting a File's MD5 Checksum in Java

Ok. I had to add. One line implementation for those who already have Spring and Apache Commons dependency or are planning to add it:

DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))

For and Apache commons only option (credit @duleshi):

DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))

Hope this helps someone.

SCRIPT438: Object doesn't support property or method IE

Implement "use strict" in all script tags to find inconsistencies and fix potential unscoped variables!

Iterate over the lines of a string

If I read Modules/cStringIO.c correctly, this should be quite efficient (although somewhat verbose):

from cStringIO import StringIO

def iterbuf(buf):
    stri = StringIO(buf)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip()
        else:
            raise StopIteration

How to copy Docker images from one host to another without using a repository

To transfer images from your local Docker installation to a minikube VM:

docker save <image> | (eval $(minikube docker-env) && docker load)

Jenkins/Hudson - accessing the current build number?

Jenkins Pipeline also provides the current build number as the property number of the currentBuild. It can be read as currentBuild.number.

For example:

// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"

Other properties of currentBuild are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

How to upgrade safely php version in wamp server

For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/

I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.

Enjoy!

How to pass command line argument to gnuplot?

You can also pass information in through the environment as is suggested here. The example by Ismail Amin is repeated here:

In the shell:

export name=plot_data_file

In a Gnuplot script:

#! /usr/bin/gnuplot

name=system("echo $name")
set title name
plot name using ($16 * 8):20 with linespoints notitle
pause -1

What is the difference between visibility:hidden and display:none?

In addition to all other answers, there's an important difference for IE8: If you use display:none and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for visibility:hidden.

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

Pass Javascript Array -> PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

$on and $broadcast in angular

If you want to $broadcast use the $rootScope:

$scope.startScanner = function() {

    $rootScope.$broadcast('scanner-started');
}

And then to receive, use the $scope of your controller:

$scope.$on('scanner-started', function(event, args) {

    // do what you want to do
});

If you want you can pass arguments when you $broadcast:

$rootScope.$broadcast('scanner-started', { any: {} });

And then receive them:

$scope.$on('scanner-started', function(event, args) {

    var anyThing = args.any;
    // do what you want to do
});

Documentation for this inside the Scope docs.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

What is your most productive shortcut with Vim?

<Ctrl> + W, V to split the screen vertically
<Ctrl> + W, W to shift between the windows

!python % [args] to run the script I am editing in this window

ZF in visual mode to fold arbitrary lines

"git checkout <commit id>" is changing branch to "no branch"

This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>

git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

Rotating a two-dimensional array in Python

There are three parts to this:

  1. original[::-1] reverses the original array. This notation is Python list slicing. This gives you a "sublist" of the original list described by [start:end:step], start is the first element, end is the last element to be used in the sublist. step says take every step'th element from first to last. Omitted start and end means the slice will be the entire list, and the negative step means that you'll get the elements in reverse. So, for example, if original was [x,y,z], the result would be [z,y,x]
  2. The * when preceding a list/tuple in the argument list of a function call means "expand" the list/tuple so that each of its elements becomes a separate argument to the function, rather than the list/tuple itself. So that if, say, args = [1,2,3], then zip(args) is the same as zip([1,2,3]), but zip(*args) is the same as zip(1,2,3).
  3. zip is a function that takes n arguments each of which is of length m and produces a list of length m, the elements of are of length n and contain the corresponding elements of each of the original lists. E.g., zip([1,2],[a,b],[x,y]) is [[1,a,x],[2,b,y]]. See also Python documentation.

SqlDataAdapter vs SqlDataReader

The answer to that can be quite broad.

Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.

Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.

WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.

Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:

Using cn As New SqlConnection("..."), _
      cmd As New SqlCommand("...", cn)

    cn.Open()
    Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            ''# ...
        End While
    End Using
End Using     

equivalent C#:

using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
    cn.Open();
    using(var rdr = cmd.ExecuteReader())
    {
        while(rdr.Read())
        {
            //...
        }
    }
}

Parse usable Street Address, City, State, Zip from a string

There are data services that given a zip code will give you list of street names in that zip code.

Use a regex to extract Zip or City State - find the correct one or if a error get both. pull the list of streets from a data source Correct the city and state, and then street address. Once you get a valid Address line 1, city, state, and zip you can then make assumptions on address line 2..3

Best way to do a split pane in HTML

Improving on Reza's answer:

  • prevent the browser from interfering with a drag
  • prevent setting an element to a negative size
  • prevent drag getting out of sync with the mouse due to incremental delta interaction with element width saturation

_x000D_
_x000D_
<html><head><style>

.splitter {
    width: 100%;
    height: 100px;
    display: flex;
}

#separator {
    cursor: col-resize;
    background-color: #aaa;
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
    background-repeat: no-repeat;
    background-position: center;
    width: 10px;
    height: 100%;

    /* Prevent the browser's built-in drag from interfering */
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

#first {
    background-color: #dde;
    width: 20%;
    height: 100%;
    min-width: 10px;
}

#second {
    background-color: #eee;
    width: 80%;
    height: 100%;
    min-width: 10px;
}

</style></head><body>

<div class="splitter">
    <div id="first"></div>
    <div id="separator" ></div>
    <div id="second" ></div>
</div>

<script>

// A function is used for dragging and moving
function dragElement(element, direction)
{
    var   md; // remember mouse down info
    const first  = document.getElementById("first");
    const second = document.getElementById("second");

    element.onmousedown = onMouseDown;

    function onMouseDown(e)
    {
        //console.log("mouse down: " + e.clientX);
        md = {e,
              offsetLeft:  element.offsetLeft,
              offsetTop:   element.offsetTop,
              firstWidth:  first.offsetWidth,
              secondWidth: second.offsetWidth
             };

        document.onmousemove = onMouseMove;
        document.onmouseup = () => {
            //console.log("mouse up");
            document.onmousemove = document.onmouseup = null;
        }
    }

    function onMouseMove(e)
    {
        //console.log("mouse move: " + e.clientX);
        var delta = {x: e.clientX - md.e.clientX,
                     y: e.clientY - md.e.clientY};

        if (direction === "H" ) // Horizontal
        {
            // Prevent negative-sized elements
            delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
                       md.secondWidth);

            element.style.left = md.offsetLeft + delta.x + "px";
            first.style.width = (md.firstWidth + delta.x) + "px";
            second.style.width = (md.secondWidth - delta.x) + "px";
        }
    }
}


dragElement( document.getElementById("separator"), "H" );

</script></body></html>
_x000D_
_x000D_
_x000D_

Changing the highlight color when selecting text in an HTML text input

Try this code to use:

/* For Mozile Firefox Browser */

::-moz-selection { background-color: #4CAF50; }

/* For Other Browser*/
::selection { background-color: #4CAF50; }

What is jQuery Unobtrusive Validation?

Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".

Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

In seeking to fix the problem of pop-up, I discovered that Apple had a way around this concern.

Indeed, when you click on this link, if you installed the application, it is rerouted to it; otherwise, you will be redirected to the webpage, without any pop-up.

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

update @Marcel Jackwerth's answer for general.

and only working with class attribute, not working with method variable.

    /**
     * get variable name as string
     * only work with class attributes
     * not work with method variable
     *
     * @param headClass variable name space
     * @param vars      object variable
     * @throws IllegalAccessException
     */
    public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
        List<Object> fooList = Arrays.asList(vars);
        for (Field field : headClass.getClass().getFields()) {
            if (fooList.contains(field.get(headClass))) {
                System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
            }
        }
    }

Update int column in table with unique incrementing values

In oracle-based products you may use the following statement:

update table set interfaceID=RowNum where condition;

How to declare a variable in MySQL?

  • Declare: SET @a = 1;

  • Usage: INSERT INTO `t` (`c`) VALUES (@a);

How do you debug PHP scripts?

You can use Firephp an add-on to firebug to debug php in the same environment as javascript.

I also use Xdebug mentioned earlier for profiling php.

Remove padding or margins from Google Charts

I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.

        var options = {
        chartArea:{left:10,top:20,width:"100%",height:"100%"}
    };

Left and top options will define the amount of padding from left and top. Hope this will help.

Difference between a SOAP message and a WSDL?

We can consider a telephone call In that Number is wsdl and exchange of information is soap.

WSDL is description how to connect with communication server.SOAP is have communication messages.

C++ passing an array pointer as a function argument

This is another method . Passing array as a pointer to the function
void generateArray(int *array,  int size) {
    srand(time(0));
    for (int j=0;j<size;j++)
        array[j]=(0+rand()%9);
}

int main(){
    const int size=5;
    int a[size];
    generateArray(a, size);
    return 0;
}

Mongoose query where value is not null

Ok guys I found a possible solution to this problem. I realized that joins do not exists in Mongo, that's why first you need to query the user's ids with the role you like, and after that do another query to the profiles document, something like this:

    const exclude: string = '-_id -created_at -gallery -wallet -MaxRequestersPerBooking -active -__v';

  // Get the _ids of users with the role equal to role.
    await User.find({role: role}, {_id: 1, role: 1, name: 1},  function(err, docs) {

        // Map the docs into an array of just the _ids
        var ids = docs.map(function(doc) { return doc._id; });

        // Get the profiles whose users are in that set.
        Profile.find({user: {$in: ids}}, function(err, profiles) {
            // docs contains your answer
            res.json({
                code: 200,
                profiles: profiles,
                page: page
            })
        })
        .select(exclude)
        .populate({
            path: 'user',
            select: '-password -verified -_id -__v'
            // group: { role: "$role"} 
          })
    });

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

How to set the UITableView Section title programmatically (iPhone/iPad)?

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   return 45.0f; 
//set height according to row or section , whatever you want to do!
}

section label text are set.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionHeaderView;

        sectionHeaderView = [[UIView alloc] initWithFrame:
                             CGRectMake(0, 0, tableView.frame.size.width, 120.0)];


    sectionHeaderView.backgroundColor = kColor(61, 201, 247);

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:
                            CGRectMake(sectionHeaderView.frame.origin.x,sectionHeaderView.frame.origin.y - 44, sectionHeaderView.frame.size.width, sectionHeaderView.frame.size.height)];

    headerLabel.backgroundColor = [UIColor clearColor];
    [headerLabel setTextColor:kColor(255, 255, 255)];
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [headerLabel setFont:kFont(20)];
    [sectionHeaderView addSubview:headerLabel];

    switch (section) {
        case 0:
            headerLabel.text = @"Section 1";
            return sectionHeaderView;
            break;
        case 1:
            headerLabel.text = @"Section 2";
            return sectionHeaderView;
            break;
        case 2:
            headerLabel.text = @"Section 3";
            return sectionHeaderView;
            break;
        default:
            break;
    }

    return sectionHeaderView;
}

How do I add an active class to a Link from React Router?

Using Jquery for active link:

$(function(){
    $('#nav a').filter(function() {
        return this.href==location.href
    })
    .parent().addClass('active').siblings().removeClass('active')

    $('#nav a').click(function(){
        $(this).parent().addClass('active').siblings().removeClass('active')
    })
});

Use Component life cycle method or document ready function as specified in Jquery.

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

The view-source url prefix trick didn't work for me using chrome on an iphone. There are apps I could have installed to do this I guess but for whatever reason I just preferred to do it myself rather than install 'yet another app'.

I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page: https://appletoolbox.com/2014/03/how-to-view-webpage-html-source-codes-on-ipad-iphone-no-app-required/

It worked flawlessly for me and now I have it set as a permanent bookmark any time I want, with no app installed.

Edit: There are basically 6 steps which should work for either Chrome or Safari. Instructions for Safari are:

  1. Open Safari and browse to an arbitrary page.
  2. Select the "Share" (or action") button in Safari (looks like a square with an arrow coming out of the top).
  3. Select "Add Bookmark"
  4. Delete the page title and replace it with something useful like "Show Page Source". Click Save.
  5. Next browse to this exact Stack Overflow answer on your phone and copy the javascript code below to your phone clipboard (code credit: Rob Flaherty):
javascript:(function(){var a=window.open('about:blank').document;a.write('<!DOCTYPE html><html><head><title>Source of '+location.href+'</title><meta name="viewport" content="width=device-width" /></head><body></body></html>');a.close();var b=a.body.appendChild(a.createElement('pre'));b.style.overflow='auto';b.style.whiteSpace='pre-wrap';b.appendChild(a.createTextNode(document.documentElement.innerHTML))})();
  1. Open the "Bookmarks" in Safari and opt to Edit the newly created Show Page Source bookmark. Delete whatever was previously saved in the Address field and instead paste in the Javascript code. Save it.
  2. (Optional) Profit!

How do I use popover from Twitter Bootstrap to display an image?

simple with generated links :) html:

<span class='preview' data-image-url="imageUrl.png" data-container="body" data-toggle="popover" data-placement="top" >preview</span>

js:

$('.preview').popover({
    'trigger':'hover',
    'html':true,
    'content':function(){
        return "<img src='"+$(this).data('imageUrl')+"'>";
    }
});

http://jsfiddle.net/A4zHC/

Parsing a JSON string in Ruby

Just to extend the answers a bit with what to do with the parsed object:

# JSON Parsing example
require "rubygems" # don't need this if you're Ruby v1.9.3 or higher
require "json"

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash

p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]

# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read

parsed = JSON.parse(json)

parsed["shop"].each do |shop|
  p shop["id"]
end

module.exports vs. export default in Node.js and ES6

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';
console.log(bar);

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_input2.default);

You can see that every access to bar is converted to access .default.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Project has no default.properties file! Edit the project properties to set one

Yet another solution as my own reminder; I got this error with FacebookSDK, importing project fails to build because it doesn't have default.properties, it has project.properties.

  1. Create empty default.properties (right click -> new, file)
  2. Edit project properties, select android, check correct SDK version, hit ok
  3. Clean projects

Toolbar overlapping below status bar

I removed all lines mentioned below from /res/values-v21/styles.xml and now it is working fine.

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@android:color/transparent</item>


 <item name="windowActionBar">false</item>
 <item name="android:windowDisablePreview">true</item>

 <item name="windowNoTitle">true</item>

 <item name="android:fitsSystemWindows">true</item>

How do I get the file extension of a file in Java?

try this.

String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg

Among $_REQUEST, $_GET and $_POST which one is the fastest?

GET vs. POST

1) Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

3) $_GET is an array of variables passed to the current script via the URL parameters.

4) $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

How to create a windows service from java app

I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.

Changing navigation bar color in Swift

To do this on storyboard (Interface Builder Inspector)

With help of IBDesignable, we can add more options to Interface Builder Inspector for UINavigationController and tweak them on storyboard. First, add the following code to your project.

@IBDesignable extension UINavigationController {
    @IBInspectable var barTintColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            navigationBar.barTintColor = uiColor
        }
        get {
            guard let color = navigationBar.barTintColor else { return nil }
            return color
        }
    }
}

Then simply set the attributes for navigation controller on storyboard.

enter image description here

This approach may also be used to manage the color of the navigation bar text from the storyboard:

@IBInspectable var barTextColor: UIColor? {
  set {
    guard let uiColor = newValue else {return}
    navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: uiColor]
  }
  get {
    guard let textAttributes = navigationBar.titleTextAttributes else { return nil }
    return textAttributes[NSAttributedStringKey.foregroundColor] as? UIColor
  }
}

How to clear radio button in Javascript?

An ES6 approach to clearing a group of radio buttons:

    Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );

How can I use the apply() function for a single column?

You don't need a function at all. You can work on a whole column directly.

Example data:

>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df

      a     b     c
0   100   200   300
1  1000  2000  3000

Half all the values in column a:

>>> df.a = df.a / 2
>>> df

     a     b     c
0   50   200   300
1  500  2000  3000

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

Count the number of occurrences of a character in a string in Javascript

I have found that the best approach to search for a character in a very large string (that is 1 000 000 characters long, for example) is to use the replace() method.

window.count_replace = function (str, schar) {
    return str.length - str.replace(RegExp(schar), '').length;
};

You can see yet another JSPerf suite to test this method along with other methods of finding a character in a string.

How to re-index all subarray elements of a multidimensional array?

PHP native function exists for this. See http://php.net/manual/en/function.reset.php

Simply do this: mixed reset ( array &$array )

How to scroll to specific item using jQuery?

Not sure why no one says the obvious, as there's a built in javascript scrollTo function:

scrollTo( $('#element').position().top );

Reference.

PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

I would like to give another example in which multiple (3) joins are used.

 DataClasses1DataContext ctx = new DataClasses1DataContext();

        var Owners = ctx.OwnerMasters;
        var Category = ctx.CategoryMasters;
        var Status = ctx.StatusMasters;
        var Tasks = ctx.TaskMasters;

        var xyz = from t in Tasks
                  join c in Category
                  on t.TaskCategory equals c.CategoryID
                  join s in Status
                  on t.TaskStatus equals s.StatusID
                  join o in Owners
                  on t.TaskOwner equals o.OwnerID
                  select new
                  {
                      t.TaskID,
                      t.TaskShortDescription,
                      c.CategoryName,
                      s.StatusName,
                      o.OwnerName
                  };

NLS_NUMERIC_CHARACTERS setting for decimal

To know SESSION decimal separator, you can use following SQL command:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select SUBSTR(value,1,1) as "SEPARATOR"
      ,'using NLS-PARAMETER' as "Explanation"
  from nls_session_parameters
  where parameter = 'NLS_NUMERIC_CHARACTERS'

UNION ALL

select SUBSTR(0.5,1,1) as "SEPARATOR" 
      ,'using NUMBER IMPLICIT CASTING' as "Explanation"
  from DUAL;

The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS table. The decimal separator is the first character of the returned value.

The second SELECT command convert IMPLICITELY the 0.5 rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.

The both command return same value.

I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.

To test what I say, I have used following SQL commands:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;

DECLARE
    S VARCHAR2(10) := '?';
BEGIN

    select .5 INTO S from dual;

    DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/

The shorter command to know decimal separator is:

SELECT .5 FROM DUAL;

That return 0,5 if decimal separator is a COMMA and 0.5 if decimal separator is a POINT.

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

How can I print each command before executing?

set -o xtrace

or

bash -x myscript.sh

This works with standard /bin/sh as well IIRC (it might be a POSIX thing then)

And remember, there is bashdb (bash Shell Debugger, release 4.0-0.4)


To revert to normal, exit the subshell or

set +o xtrace

How to add property to object in PHP >= 5.3 strict mode without generating error

you should use magic methods __Set and __get. Simple example:

class Foo
{
    //This array stores your properties
private $content = array();

public function __set($key, $value)
{
            //Perform data validation here before inserting data
    $this->content[$key] = $value;
    return $this;
}

public function __get($value)
{       //You might want to check that the data exists here
    return $this->$content[$value];
}

}

Of course, don't use this example as this : no security at all :)

EDIT : seen your comments, here could be an alternative based on reflection and a decorator :

 class Foo
 {
private $content = array();
private $stdInstance;

public function __construct($stdInstance)
{
    $this->stdInstance = $stdInstance;
}

public function __set($key, $value)
{
    //Reflection for the stdClass object
    $ref = new ReflectionClass($this->stdInstance);
    //Fetch the props of the object

    $props = $ref->getProperties();

    if (in_array($key, $props)) {
        $this->stdInstance->$key = $value;
    } else {
        $this->content[$key] = $value;
    }
    return $this;
}

public function __get($value)
{
    //Search first your array as it is faster than using reflection
    if (array_key_exists($value, $this->content))
    {
        return $this->content[$value];
    } else {
        $ref = new ReflectionClass($this->stdInstance);

        //Fetch the props of the object
        $props = $ref->getProperties();

        if (in_array($value, $props)) {

        return $this->stdInstance->$value;
    } else {
        throw new \Exception('No prop in here...');
    }
}
 }
}

PS : I didn't test my code, just the general idea...

Linking a qtDesigner .ui file to python/pyqt?

You can also use uic in PyQt5 with the following code.

from PyQt5 import uic, QtWidgets
import sys

class Ui(QtWidgets.QDialog):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('SomeUi.ui', self)
        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Ui()
    sys.exit(app.exec_())

Java - How to create new Entry (key, value)

org.apache.commons.lang3.tuple.Pair implements java.util.Map.Entry and can also be used standalone.

Also as others mentioned Guava's com.google.common.collect.Maps.immutableEntry(K, V) does the trick.

I prefer Pair for its fluent Pair.of(L, R) syntax.

Find all special characters in a column in SQL Server 2008

Negatives are your friend here:

SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'

Which says that you want any rows where Col1 consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.

If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A, a, Z and z, which is what I've given (originally I had it the wrong way around. a comes before A. Z comes after z)


Or, to put it another way, you could have written your original WHERE as:

Col1 LIKE '[!@#$%]'

But, as you observed, you'd need to know all of the characters to include in the [].

Utils to read resource text file to String (Java)

Yes, Guava provides this in the Resources class. For example:

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);

See changes to a specific file using git

You can execute

git status -s

This will show modified files name and then by copying the interested file path you can see changes using git diff

git diff <filepath + filename>

Windows command to get service status?

You can call net start "service name" on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

How to download a file from a website in C#

You may need to know the status during the file download or use credentials before making the request.

Here is an example that covers these options:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

And the callback's functions implemented as follows:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - Lambda notation: other possible option for handling the events

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - We can do better

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - Or

client.DownloadProgressChanged += (o, e) =>
{
    Console.WriteLine($"Download status: {e.ProgressPercentage}%.");

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (o, e) => 
{
    Console.WriteLine("Download finished!");
};

Get encoding of a file in Windows

Here's my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii when no BOM is present (like most text editors, the default would be UTF8 if you want to match the HTTP/web ecosystem).

Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.

# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
    $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)

    if(!$bytes) { return 'utf8' }

    switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
        '^efbbbf'   { return 'utf8' }
        '^2b2f76'   { return 'utf7' }
        '^fffe'     { return 'unicode' }
        '^feff'     { return 'bigendianunicode' }
        '^0000feff' { return 'utf32' }
        default     { return 'ascii' }
    }
}

dir ~\Documents\WindowsPowershell -File | 
    select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} | 
    ft -AutoSize

Recommendation: This can work reasonably well if the dir, ls, or Get-ChildItem only checks known text files, and when you're only looking for "bad encodings" from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Use Message.get_payload

b = email.message_from_string(a)
if b.is_multipart():
    for payload in b.get_payload():
        # if payload.is_multipart(): ...
        print payload.get_payload()
else:
    print b.get_payload()

How do I capture SIGINT in Python?

Register your handler with signal.signal like this:

#!/usr/bin/env python
import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

Code adapted from here.

More documentation on signal can be found here.  

How can I combine flexbox and vertical scroll in a full-height app?

Flexbox spec editor here.

This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.

  • Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.

  • Since your header and footer aren't meant to flex, they should both have flex: none; set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto, so they start at their auto height and can shrink but not grow, but they're also overflow:visible by default, which triggers their default min-height:auto to prevent them from shrinking at all. If you ever set an overflow on them, the behavior of min-height:auto changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article> element.)

  • You can simplify the <article> flex too - just set flex: 1; and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.

How to create a new variable in a data.frame based on a condition?

If you have a very limited number of levels, you could try converting y into factor and change its levels.

> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
  x y    w
1 1 1 good
2 2 4 fair
3 4 5  bad

Start and stop a timer PHP

Also you can use HRTime package. It has a class StopWatch.

connecting MySQL server to NetBeans

check the context.xml file in Web Pages -> META-INF, the username="user" must be the same as the database user, in my case was root, that solved the connection error

Hope helps

How to open an existing project in Eclipse?

In Eclipse, try Project > Open Project and select the projects to be opened.

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

How to list running screen sessions?

In most cases a screen -RRx $username/ will suffice :)

If you still want to list all screens then put the following script in your path and call it screen or whatever you like:

#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
    exec /usr/bin/screen "$@"
else
    shopt -s nullglob
    screens=(/var/run/screen/S-*/*)
    if (( ${#screens[@]} == 0 )); then
        echo "no screen session found in /var/run/screen"
    else
        echo "${screens[@]#*S-}"
    fi
fi

It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.

Way to go from recursion to iteration

Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.

var stack = [];
stack.push(firstObject);

// while not empty
while (stack.length) {

    // Pop off end of stack.
    obj = stack.pop();

    // Do stuff.
    // Push other objects on the stack as needed.
    ...

}

Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:

foo(first);
foo(second);

has to be replaced by

stack.push(second);
stack.push(first);

Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.

Switch: Multiple values in one case?

You can't specify a range in the case statement, can do as follows.

case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
   MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;

case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
   MessageBox.Show("You are only " + age + " years old\n That's too young!");
   break;

...........etc.

How to make a class JSON serializable

If you don't mind installing a package for it, you can use json-tricks:

pip install json-tricks

After that you just need to import dump(s) from json_tricks instead of json, and it'll usually work:

from json_tricks import dumps
json_str = dumps(cls_instance, indent=4)

which'll give

{
        "__instance_type__": [
                "module_name.test_class",
                "MyTestCls"
        ],
        "attributes": {
                "attr": "val",
                "dct_attr": {
                        "hello": 42
                }
        }
}

And that's basically it!


This will work great in general. There are some exceptions, e.g. if special things happen in __new__, or more metaclass magic is going on.

Obviously loading also works (otherwise what's the point):

from json_tricks import loads
json_str = loads(json_str)

This does assume that module_name.test_class.MyTestCls can be imported and hasn't changed in non-compatible ways. You'll get back an instance, not some dictionary or something, and it should be an identical copy to the one you dumped.

If you want to customize how something gets (de)serialized, you can add special methods to your class, like so:

class CustomEncodeCls:
        def __init__(self):
                self.relevant = 42
                self.irrelevant = 37

        def __json_encode__(self):
                # should return primitive, serializable types like dict, list, int, string, float...
                return {'relevant': self.relevant}

        def __json_decode__(self, **attrs):
                # should initialize all properties; note that __init__ is not called implicitly
                self.relevant = attrs['relevant']
                self.irrelevant = 12

which serializes only part of the attributes parameters, as an example.

And as a free bonus, you get (de)serialization of numpy arrays, date & times, ordered maps, as well as the ability to include comments in json.

Disclaimer: I created json_tricks, because I had the same problem as you.

How to test abstract class in Java with JUnit?

If you need a solution anyway (e.g. because you have too many implementations of the abstract class and the testing would always repeat the same procedures) then you could create an abstract test class with an abstract factory method which will be excuted by the implementation of that test class. This examples works or me with TestNG:

The abstract test class of Car:

abstract class CarTest {

// the factory method
abstract Car createCar(int speed, int fuel);

// all test methods need to make use of the factory method to create the instance of a car
@Test
public void testGetSpeed() {
    Car car = createCar(33, 44);
    assertEquals(car.getSpeed(), 33);
    ...

Implementation of Car

class ElectricCar extends Car {

    private final int batteryCapacity;

    public ElectricCar(int speed, int fuel, int batteryCapacity) {
        super(speed, fuel);
        this.batteryCapacity = batteryCapacity;
    }

    ...

Unit test class ElectricCarTest of the Class ElectricCar:

class ElectricCarTest extends CarTest {

    // implementation of the abstract factory method
    Car createCar(int speed, int fuel) {
        return new ElectricCar(speed, fuel, 0);
    }

    // here you cann add specific test methods
    ...

How do I return clean JSON from a WCF Service?

If you want nice json without hardcoding attributes into your service classes,

use <webHttp defaultOutgoingResponseFormat="Json"/> in your behavior config

Unix shell script find out which directory the script file resides?

Assuming you're using bash

#!/bin/bash

current_dir=$(pwd)
script_dir=$(dirname "$0")

echo $current_dir
echo $script_dir

This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from / with the script in /home/mez/, it outputs

/
/home/mez

Remember, when assigning variables from the output of a command, wrap the command in $( and ) - or you won't get the desired output.

Is there a way to programmatically minimize a window

Form myForm;
myForm.WindowState = FormWindowState.Minimized;

How do I change select2 box height

Just add in select2.css

/* Make Select2 boxes match Bootstrap3 as well as Bootstrap4 heights: */
.select2-selection__rendered {
line-height: 32px !important;
}

.select2-selection {
height: 34px !important;
}

Allow only numbers and dot in script

This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {
    var rgx = /^[0-9]*\.?[0-9]*$/;
    return s.match(rgx);
}

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

You can also test the above regex here:


Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!

how to set ul/li bullet point color?

Apply the color to the li and set the span (or other child element) color to whatever color the text should be.

ul
{
    list-style-type: square;
}

ul > li
{
    color: green;
}

ul > li > span
{
    color: black;
}

JSFiddle

Convert tabs to spaces in Notepad++

You need to replace \t - make sure you use extended mode!

Replace

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I had a similar issue using the Chrome driver (v2.23) / running the tests thru TeamCity. I was able to fix the issue by adding the "no-sandbox" flag to the Chrome options:

var options = new ChromeOptions();
options.AddArgument("no-sandbox");

I'm not sure if there is a similar option for the FF driver. From what I understand the issue has something to do with TeamCity running Selenium under the SYSTEM account.

Convert columns to string in Pandas

pandas >= 1.0: It's time to stop using astype(str)!

Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:

# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will 
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')

From pandas 1.0 onwards, consider using "string" type instead.

# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype

Here's why, as quoted by the docs:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than 'string'.

See also the section on Behavioral Differences between "string" and object.

Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float). But pandas can using Nullable Integer columns.


Why should I stop using it?

Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.

# pandas <= 0.25
pd.Series(['a', 'b', 1.23])   # whoops, this should have been "1.23"

0       a
1       b
2    1.23
dtype: object

pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23]   # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")

0       a
1       b
2    1.23
dtype: string

pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23']   # it's a string and we just averted some potentially nasty bugs.

Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.

Consider,

# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
 
   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.

# pandas <= 0.25  
df.dtypes

A    object
B    object
dtype: object

df.select_dtypes(object)

   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

From pandas 1.0, this becomes a lot simpler:

# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes

A    string
B    object
dtype: object

df.select_dtypes("string")

   A
0  a
1  b
2  c

Readability
This is self-explanatory ;-)


OK, so should I stop using it right now?

...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string" columns as opposed to objects. With that said, however, it's never too early to form good habits!

How to print pandas DataFrame without index

If you just want a string/json to print it can be solved with:

print(df.to_string(index=False))

Buf if you want to serialize the data too or even send to a MongoDB, would be better to do something like:

document = df.to_dict(orient='list')

There are 6 ways by now to orient the data, check more in the panda docs which better fits you.

PHP Get Highest Value from Array

$abc=array("a"=>1,"b"=>2,"c"=>4,"e"=>7,"d"=>5);
/*program to find max value*/
$lagest = array();
$i=0;
foreach($abc as $key=>$a) {
    if($i==0) $b=$a;
    if($b<$a) {
        $b=$a;
        $k=$key;
    }
    $i++;
 }
 $lagest[$k]=$b;
 print_r($lagest);

A column-vector y was passed when a 1d array was expected

Another way of doing this is to use ravel

model = forest.fit(train_fold, train_y.values.reshape(-1,))

When to use dynamic vs. static libraries

We use a lot of DLL's (> 100) in our project. These DLL's have dependencies on each other and therefore we chose the setup of dynamic linking. However it has the following disadvantages:

  • slow startup (> 10 seconds)
  • DLL's had to be versioned, since windows loads modules on uniqueness of names. Own written components would otherwise get the wrong version of the DLL (i.e. the one already loaded instead of its own distributed set)
  • optimizer can only optimize within DLL boundaries. For example the optimizer tries to place frequently used data and code next to each other, but this will not work across DLL boundaries

Maybe a better setup was to make everything a static library (and therefore you just have one executable). This works only if no code duplication takes place. A test seems to support this assumption, but i couldn't find an official MSDN quote. So for example make 1 exe with:

  • exe uses shared_lib1, shared_lib2
  • shared_lib1 use shared_lib2
  • shared_lib2

The code and variables of shared_lib2 should be present in the final merged executable only once. Can anyone support this question?

twitter bootstrap text-center when in xs mode

Responsive text alignment has been added in Bootstrap V4:

https://getbootstrap.com/docs/4.0/utilities/text/#text-alignment

For left, right, and center alignment, responsive classes are available that use the same viewport width breakpoints as the grid system.

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>

Java Multithreading concept and join() method

See the concept is very simple.

1) All threads are started in the constructor and thus are in ready to run state. Main is already the running thread.

2) Now you called the t1.join(). Here what happens is that the main thread gets knotted behind the t1 thread. So you can imagine a longer thread with main attached to the lower end of t1.

3) Now there are three threads which could run: t2, t3 and combined thread(t1 + main).

4)Now since till t1 is finished main can't run. so the execution of the other two join statements has been stopped.

5) So the scheduler now decides which of the above mentioned(in point 3) threads run which explains the output.

Get program path in VB.NET?

For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.

What is a user agent stylesheet?

Define the values that you don't want to be used from Chrome's user agent style in your own CSS content.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You guys copied the wrong code.

Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)

How do you get the file size in C#?

MSDN FileInfo.Length says that it is "the size of the current file in bytes."

My typical Google search for something like this is: msdn FileInfo

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

I had a same problem, and I solved my problem.
First go to config.default.php and change

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

to

$cfg['Servers'][$i]['AllowNoPassword'] = true;

What's the difference between 'r+' and 'a+' when open file in python?

Python opens files almost in the same way as in C:

  • r+ Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).

How to determine if string contains specific substring within the first X characters

This is what you need :

if (Value1.StartsWith("abc"))
{
found = true;
}

Angular is automatically adding 'ng-invalid' class on 'required' fields

Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:

input.ng-pristine.ng-invalid {
    -webkit-box-shadow: none;
    -ms-box-shadow: none;
    box-shadow:none;
}

Undefined symbols for architecture x86_64 on Xcode 6.1

Apparently, your class "Format" is involved in the problem. Check your declaration of this class, especially if you did it inside another class you probably forgot the @implementation or something similar.

Object passed as parameter to another class, by value or reference?

I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

In other words, my Increment method modifies its parameter myClass everytime its called.

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.Value);  // Displays 1
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 2
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 3           
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 4
        Console.WriteLine("Hit Enter to exit.");
        Console.ReadLine();
    }

    public static void Increment(MyClass myClassRef)
    {
        myClassRef.Value++;
    }
}

public class MyClass
{
    public int Value {get;set;}
    public MyClass()
    {
        Value = 1;
    }
}

WebSockets protocol vs HTTP

For the TL;DR, here are 2 cents and a simpler version for your questions:

  1. WebSockets provides these benefits over HTTP:

    • Persistent stateful connection for the duration of the connection
    • Low latency: near-real-time communication between server/client due to no overhead of reestablishing connections for each request as HTTP requires.
    • Full duplex: both server and client can send/receive simultaneously
  2. WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.

Testing the type of a DOM element in JavaScript

You can use typeof(N) to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.

In that case, use the elem.tagName or elem.nodeName property.

if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.

Ansible: copy a directory content to another directory

How to copy directory and sub dirs's and files from ansible server to remote host

- name: copy nmonchart39 directory  to {{ inventory_hostname }}
  copy:
    src: /home/ansib.usr.srv/automation/monitoring/nmonchart39
    dest: /var/nmon/data


Where:
copy entire directory: src: /automation/monitoring/nmonchart39
copy directory contents src: nmonchart39/

How do malloc() and free() work?

How malloc() and free() works depends on the runtime library used. Generally, malloc() allocates a heap (a block of memory) from the operating system. Each request to malloc() then allocates a small chunk of this memory be returning a pointer to the caller. The memory allocation routines will have to store some extra information about the block of memory allocated to be able to keep track of used and free memory on the heap. This information is often stored in a few bytes just before the pointer returned by malloc() and it can be a linked list of memory blocks.

By writing past the block of memory allocated by malloc() you will most likely destroy some of the book-keeping information of the next block which may be the remaining unused block of memory.

One place where you program may also crash is when copying too many characters into the buffer. If the extra characters are located outside the heap you may get an access violation as you are trying to write to non-existing memory.

Representing Directory & File Structure in Markdown Syntax

There is an NPM module for this:

npm dree

It allows you to have a representation of a directory tree as a string or an object. Using it with the command line will allow you to save the representation in a txt file.

Example:

$ npm dree parse myDirectory --dest ./generated --name tree

How can I programmatically get the MAC address of an iphone

A lot of these questions only address the Mac address. If you also require the IP address I just wrote this, may need some work but seems to work well on my machine...

- (NSString *)getLocalIPAddress
{
    NSArray *ipAddresses = [[NSHost currentHost] addresses];
    NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.allowsFloats = NO;

    for (NSString *potentialIPAddress in sortedIPAddresses)
    {
        if ([potentialIPAddress isEqualToString:@"127.0.0.1"]) {
            continue;
        }

        NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:@"."];

        BOOL isMatch = YES;

        for (NSString *ipPart in ipParts) {
            if (![numberFormatter numberFromString:ipPart]) {
                isMatch = NO;
                break;
            }
        }
        if (isMatch) {
            return potentialIPAddress;
        }
    }

    // No IP found
    return @"?.?.?.?";
}

What is the best place for storing uploaded images, SQL database or disk file system?

The only benefit for the option B is having all the data in one system, yet it's a false benefit! You may argue that your code is also a form of data, and therefore also can be stored in database - how would you like it?

Unless you have some unique case:

  • Business logic belongs in code.
  • Structured data belongs in database (relational or non-relational).
  • Bulk data belongs in storage (filesystem or other).

Files, Code, Data

It is not necessary to use filesystem to keep files. Instead you may use cloud storage (such as Amazon S3) or Infrastructure-as-a-service on top of it (such as Uploadcare):

https://uploadcare.com/upload-api-cloud-storage-and-cdn/

But storing files in the database is a bad idea.

How do you manually execute SQL commands in Ruby On Rails using NuoDB

For me, I couldn't get this to return a hash.

results = ActiveRecord::Base.connection.execute(sql)

But using the exec_query method worked.

results = ActiveRecord::Base.connection.exec_query(sql)

How do you find the current user in a Windows environment?

It's always annoyed me how Windows doesn't have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:

#include <windows.h>
#include <stdio.h>

int main(int argc, char **argv) {
    printf("%s", GetUserName());
}

And just use that in your batch file.

mailto link with HTML body

As you can see in RFC 6068, this is not possible at all:

The special <hfname> "body" indicates that the associated <hfvalue> is the body of the message. The "body" field value is intended to contain the content for the first text/plain body part of the message. The "body" pseudo header field is primarily intended for the generation of short text messages for automatic processing (such as "subscribe" messages for mailing lists), not for general MIME bodies.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I had this issue but it was fixed easily by going to the Internet Information Services (IIS) Manager, double clicking Directory Browsing and clicking Enable.

In my case, I could access files directly but could not access folders.

How to select min and max values of a column in a datatable?

Performance wise, this should be comparable. Use Select statement and Sort to get a list and then pick the first or last (depending on your sort order).

var col = dt.Select("AccountLevel", "AccountLevel ASC");

var min = col.First();
var max = col.Last();

How do you know if Tomcat Server is installed on your PC

For linux ubuntu 18.04:

Go to terminal and command:$ sudo systemctl status tomcat

Python unittest passing arguments

Have a same problem. My solution is after you handle with parsing arguments using argparse or other way, remove arguments from sys.argv

sys.argv = sys.argv[:1]  

If you need you can filter unittest arguments from main.parseArgs()

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

setAllowUrlEncodedSlash(true) didn't work for me. Still internal method isNormalized return false when having double slash.

I replaced StrictHttpFirewall with DefaultHttpFirewall by having the following code only:

@Bean
public HttpFirewall defaultHttpFirewall() {
    return new DefaultHttpFirewall();
}

Working well for me.
Any risk by using DefaultHttpFirewall?

How to sort a dataframe by multiple column(s)

I learned about order with the following example which then confused me for a long time:

set.seed(1234)

ID        = 1:10
Age       = round(rnorm(10, 50, 1))
diag      = c("Depression", "Bipolar")
Diagnosis = sample(diag, 10, replace=TRUE)

data = data.frame(ID, Age, Diagnosis)

databyAge = data[order(Age),]
databyAge

The only reason this example works is because order is sorting by the vector Age, not by the column named Age in the data frame data.

To see this create an identical data frame using read.table with slightly different column names and without making use of any of the above vectors:

my.data <- read.table(text = '

  id age  diagnosis
   1  49 Depression
   2  50 Depression
   3  51 Depression
   4  48 Depression
   5  50 Depression
   6  51    Bipolar
   7  49    Bipolar
   8  49    Bipolar
   9  49    Bipolar
  10  49 Depression

', header = TRUE)

The above line structure for order no longer works because there is no vector named age:

databyage = my.data[order(age),]

The following line works because order sorts on the column age in my.data.

databyage = my.data[order(my.data$age),]

I thought this was worth posting given how confused I was by this example for so long. If this post is not deemed appropriate for the thread I can remove it.

EDIT: May 13, 2014

Below is a generalized way of sorting a data frame by every column without specifying column names. The code below shows how to sort from left to right or by right to left. This works if every column is numeric. I have not tried with a character column added.

I found the do.call code a month or two ago in an old post on a different site, but only after extensive and difficult searching. I am not sure I could relocate that post now. The present thread is the first hit for ordering a data.frame in R. So, I thought my expanded version of that original do.call code might be useful.

set.seed(1234)

v1  <- c(0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1)
v2  <- c(0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1)
v3  <- c(0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1)
v4  <- c(0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1)

df.1 <- data.frame(v1, v2, v3, v4) 
df.1

rdf.1 <- df.1[sample(nrow(df.1), nrow(df.1), replace = FALSE),]
rdf.1

order.rdf.1 <- rdf.1[do.call(order, as.list(rdf.1)),]
order.rdf.1

order.rdf.2 <- rdf.1[do.call(order, rev(as.list(rdf.1))),]
order.rdf.2

rdf.3 <- data.frame(rdf.1$v2, rdf.1$v4, rdf.1$v3, rdf.1$v1) 
rdf.3

order.rdf.3 <- rdf.1[do.call(order, as.list(rdf.3)),]
order.rdf.3

Pushing empty commits to remote

Is there any disadvantages/consequences of pushing empty commits?

Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.

You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f back to remote.

Easiest way to loop through a filtered list with VBA?

One way assuming filtered data in A1 downwards;

dim Rng as Range
set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
...
for each cell in Rng 
   ...     

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

MSVCP120d.dll missing

I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Parse time of format hh:mm:ss

As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:

    String myDateString = "13:24:40";
    LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
    int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
    int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
    int second = localTime.get(ChronoField.SECOND_OF_MINUTE);

    //prints "hour: 13, minute: 24, second: 40":
    System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));

Remarks:

  • since the OP's question contains a concrete example of a time instant containing only hours, minutes and seconds (no day, month, etc.), the answer above only uses LocalTime. If wanting to parse a string that also contains days, month, etc. then LocalDateTime would be required. Its usage is pretty much analogous to that of LocalTime.
  • since the time instant int OP's question doesn't contain any information about timezone, the answer uses the LocalXXX version of the date/time classes (LocalTime, LocalDateTime). If the time string that needs to be parsed also contains timezone information, then ZonedDateTime needs to be used.

====== Below is the old (original) answer for this question, using pre-Java8 API: =====

I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.

A SimpleDateFormat might do the trick here:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

It should be something like:

String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);

Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds

The gotchas you should be aware of:

  • the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this

  • Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.

How do a send an HTTPS request through a proxy in Java?

HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.

You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,

http://www.javaworld.com/javaworld/javatips/jw-javatip111.html

EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,

 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
      tunnelHost = proxyhost;
      tunnelPort = Integer.parseInt(proxyport);
      dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
 }

 ...

 connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
 connection.setDefaultHostnameVerifier( new HostnameVerifier()
 {
    public boolean verify( String arg0, SSLSession arg1 )
    {
        return true;
    }
 }  );

EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,

http://bugs.sun.com/view_bug.do?bug_id=6614957

The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,

public class SSLContextTest {

    public static void main(String[] args) {

        System.setProperty("https.proxyHost", "proxy.xxx.com");
        System.setProperty("https.proxyPort", "8888");

        try {

            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkServerTrusted =============");
                }
            } }, new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(
                    sslContext.getSocketFactory());

            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String arg0, SSLSession arg1) {
                            System.out.println("hostnameVerifier =============");
                            return true;
                        }
                    });

            URL url = new URL("https://www.verisign.net");
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

This is what I get when I run the program,

checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......

As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.

Change color inside strings.xml

You do not set such attributes in strings.xml type of files. You need to set it in your code. or (which is better solution) create style with colors you want and apply to your TextView

HTTP response code for POST when resource already exists

More likely it is 400 Bad Request

6.5.1. 400 Bad Request


The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

As the request contains duplicate value(value that already exists), it can be perceived as a client error. Need to change the request before the next try.
By considering these facts we can conclude as HTTP STATUS 400 Bad Request.

Print a div content using Jquery

https://github.com/jasonday/printThis

$("#myID").printThis();

Great Jquery plugin to do exactly what your after

How to navigate to a directory in C:\ with Cygwin?

You already accepted an answer, but I just thought I'd mention that the following also works in Cygwin:

cd "C:\Foo"

I think the cd /cygdrive/c method is better, but sometimes it's useful to know that you can do this too.

How to put a jar in classpath in Eclipse?

In your Android Developer Tools , From the SDK Manager, install Extras > Google Cloud Messaging for Android Library . After the installation is complete restart your SDK.Then navigate to sdk\extras\google\gcm\gcm-client\dist . there will be your gcm.jar file.

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:

add(3,5)

which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

Changing a specific column name in pandas DataFrame

pandas version 0.23.4

df.rename(index=str,columns={'old_name':'new_name'},inplace=True)

For the record:

omitting index=str will give error replace has an unexpected argument 'columns'

Get last n lines of a file, similar to tail

Here is a pretty simple implementation:

with open('/etc/passwd', 'r') as f:
  try:
    f.seek(0,2)
    s = ''
    while s.count('\n') < 11:
      cur = f.tell()
      f.seek((cur - 10))
      s = f.read(10) + s
      f.seek((cur - 10))
    print s
  except Exception as e:
    f.readlines()

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

The <prev> tag doesn't exist, but it's probably the <pre> HTML tag to put around debug output, to improve readability. It's not a secret PHP hack. :)

label or @html.Label ASP.net MVC 4

When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance

  • When dealing with hyperlinks, since the HTML helper simplifies routing
  • When you bind to your model, using @Html.LabelFor, @Html.TextBoxFor, etc
  • When you use the @Html.EditorFor, as you can assign specific behavior och looks in a editor view

Multiple radio button groups in one form

This is very simple you need to keep different names of every radio input group.

_x000D_
_x000D_
      <input type="radio" name="price">Thousand<br>_x000D_
      <input type="radio" name="price">Lakh<br>_x000D_
      <input type="radio" name="price">Crore_x000D_
      _x000D_
      </br><hr>_x000D_
_x000D_
      <input type="radio" name="gender">Male<br>_x000D_
      <input type="radio" name="gender">Female<br>_x000D_
      <input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_

java.text.ParseException: Unparseable date

        String date="Sat Jun 01 12:53:10 IST 2013";
        SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
        Date currentdate=sdf.parse(date);
        SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
        System.out.println(sdf2.format(currentdate));

sql how to cast a select query

And when you use a case :

CASE
WHEN TB1.COD IS NULL THEN
    TB1.COD || ' - ' || TB1.NAME
ELSE
    TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,

Base64 length calculation?

I don't see the simplified formula in other responses. The logic is covered but I wanted a most basic form for my embedded use:

  Unpadded = ((4 * n) + 2) / 3

  Padded = 4 * ((n + 2) / 3)

NOTE: When calculating the unpadded count we round up the integer division i.e. add Divisor-1 which is +2 in this case

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How to use the PRINT statement to track execution as stored procedure is running?

I'm sure you can use RAISERROR ... WITH NOWAIT

If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.

jQuery document.createElement equivalent?

Creating new DOM elements is a core feature of the jQuery() method, see:

How would one write object-oriented code in C?

Trivial example with an Animal and Dog: You mirror C++'s vtable mechanism (largely anyway). You also separate allocation and instantiation (Animal_Alloc, Animal_New) so we don't call malloc() multiple times. We must also explicitly pass the this pointer around.

If you were to do non-virtual functions, that's trival. You just don't add them to the vtable and static functions don't require a this pointer. Multiple inheritance generally requires multiple vtables to resolve ambiguities.

Also, you should be able to use setjmp/longjmp to do exception handling.

struct Animal_Vtable{
    typedef void (*Walk_Fun)(struct Animal *a_This);
    typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);

    Walk_Fun Walk;
    Dtor_Fun Dtor;
};

struct Animal{
    Animal_Vtable vtable;

    char *Name;
};

struct Dog{
    Animal_Vtable vtable;

    char *Name; // Mirror member variables for easy access
    char *Type;
};

void Animal_Walk(struct Animal *a_This){
    printf("Animal (%s) walking\n", a_This->Name);
}

struct Animal* Animal_Dtor(struct Animal *a_This){
    printf("animal::dtor\n");
    return a_This;
}

Animal *Animal_Alloc(){
    return (Animal*)malloc(sizeof(Animal));
}

Animal *Animal_New(Animal *a_Animal){
    a_Animal->vtable.Walk = Animal_Walk;
    a_Animal->vtable.Dtor = Animal_Dtor;
    a_Animal->Name = "Anonymous";
    return a_Animal;
}

void Animal_Free(Animal *a_This){
    a_This->vtable.Dtor(a_This);

    free(a_This);
}

void Dog_Walk(struct Dog *a_This){
    printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}

Dog* Dog_Dtor(struct Dog *a_This){
    // Explicit call to parent destructor
    Animal_Dtor((Animal*)a_This);

    printf("dog::dtor\n");

    return a_This;
}

Dog *Dog_Alloc(){
    return (Dog*)malloc(sizeof(Dog));
}

Dog *Dog_New(Dog *a_Dog){
    // Explict call to parent constructor
    Animal_New((Animal*)a_Dog);

    a_Dog->Type = "Dog type";
    a_Dog->vtable.Walk = (Animal_Vtable::Walk_Fun) Dog_Walk;
    a_Dog->vtable.Dtor = (Animal_Vtable::Dtor_Fun) Dog_Dtor;

    return a_Dog;
}

int main(int argc, char **argv){
    /*
      Base class:

        Animal *a_Animal = Animal_New(Animal_Alloc());
    */
    Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());

    a_Animal->vtable.Walk(a_Animal);

    Animal_Free(a_Animal);
}

PS. This is tested on a C++ compiler, but it should be easy to make it work on a C compiler.

PowerShell equivalent to grep -f

but select-String doesn't seem to have this option.

Correct. PowerShell is not a clone of *nix shells' toolset.

However it is not hard to build something like it yourself:

$regexes = Get-Content RegexFile.txt | 
           Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }

$fileList | Get-Content | Where-Object {
  foreach ($r in $regexes) {
    if ($r.IsMatch($_)) {
      $true
      break
    }
  }
  $false
}

What is the correct JSON content type?

As some research,

Most commonly MIME type is

application/json

Let's see a example to differentiate with json and javascript.

  • application/json

It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used.

For example-

<?php 
  
header('Content-type:application/json');     
   
$directory =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

    
// Showing the json data 

echo json_encode($directory);     


   ?>

Output is,

[{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}]

  • application/javascript

it is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. 

For example

<?php 

header('Content-type:application/javascript'); 

$dir =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

echo "Function_call(".json_encode($dir).");"; 

  

?> 

Output is,

Function_call([{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}])

And for other MIME Types see full detail here,

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types

How can I create numbered map markers in Google Maps V3?

Unfortunately it's not very easy. You could create your own custom marker based on the OverlayView class (an example) and put your own HTML in it, including a counter. This will leave you with a very basic marker, that you can't drag around or add shadows easily, but it is very customisable.

Alternatively, you could add a label to the default marker. This will be less customisable but should work. It also keeps all the useful things the standard marker does.

You can read more about the overlays in Google's article Fun with MVC Objects.

Edit: if you don't want to create a JavaScript class, you could use Google's Chart API. For example:

Numbered marker:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000

Text marker:

http://chart.apis.google.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|foo

This is the quick and easy route, but it's less customisable, and requires a new image to be downloaded by the client for each marker.

JavaFX Location is not set error message

I think problem is either incorrect layout name or invalid layout file path.

for IntelliJ, you can create resource directory and place layout files there.

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
rootLayout = loader.load();

Parse JSON in TSQL

I do also have a huge masochistic streak as that I've written yet another JSON parser. This one uses a procedural approach. It uses a similat SQL hierarchy list table to store the parsed data. Also in the package are:

  • Reverse process: from hierarchy to JSON
  • Querying functions: to fetch particular values from a JSON object

Please feel free to use and have fun with it

http://www.codeproject.com/Articles/1000953/JSON-for-Sql-Server-Part

How do I create a comma delimited string from an ArrayList?

Here's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:

List<string> histList = new List<string>();
histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff"));
histList.Add(Index.ToString());
/*arValue is array of Singles */
foreach (Single s in arValue)
{
     histList.Add(s.ToString());
}
String HistLine = String.Join(",", histList.ToArray());

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

How can I control Chromedriver open window size?

If you are using Clojure and https://github.com/semperos/clj-webdriver you can use this snippet to resize the browser.

(require '[clj-webdriver.taxi :as taxi])

; Open browser
(taxi/set-driver! {:browser :chrome} "about:blank")

; Resize browser
(-> taxi/*driver* (.webdriver) (.manage) (.window) 
  (.setSize (org.openqa.selenium.Dimension. 0 0)))

Why can I not create a wheel in python?

I also ran into the error message invalid command 'bdist_wheel'

It turns out the package setup.py used distutils rather than setuptools. Changing it as follows enabled me to build the wheel.

#from distutils.core import setup
from setuptools import setup

How to get thread id from a thread pool?

If you are using logging then thread names will be helpful. A thread factory helps with this:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Main {

    static Logger LOG = LoggerFactory.getLogger(Main.class);

    static class MyTask implements Runnable {
        public void run() {
            LOG.info("A pool thread is doing this task");
        }
    }

    public static void main(String[] args) {
        ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
        taskExecutor.execute(new MyTask());
        taskExecutor.shutdown();
    }
}

class MyThreadFactory implements ThreadFactory {
    private int counter;
    public Thread newThread(Runnable r) {
        return new Thread(r, "My thread # " + counter++);
    }
}

Output:

[   My thread # 0] Main         INFO  A pool thread is doing this task

Removing padding gutter from grid columns in Bootstrap 4

Bootstrap4: Comes with .no-gutters out of the box. source: https://github.com/twbs/bootstrap/pull/21211/files

Bootstrap3:

Requires custom CSS.

Stylesheet:

.row.no-gutters {
  margin-right: 0;
  margin-left: 0;

  & > [class^="col-"],
  & > [class*=" col-"] {
    padding-right: 0;
    padding-left: 0;
  }
}

Then to use:

<div class="row no-gutters">
  <div class="col-xs-4">...</div>
  <div class="col-xs-4">...</div>
  <div class="col-xs-4">...</div>
</div>

It will:

  • Remove margin from the row
  • Remove padding from all columns directly beneath the row

Converting from IEnumerable to List

In case you're working with a regular old System.Collections.IEnumerable instead of IEnumerable<T> you can use enumerable.Cast<object>().ToList()

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

How to get year and month from a date - PHP

$dateValue = '2012-01-05';
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));

Why is there no String.Empty in Java?

All those "" literals are the same object. Why make all that extra complexity? It's just longer to type and less clear (the cost to the compiler is minimal). Since Java's strings are immutable objects, there's never any need at all to distinguish between them except possibly as an efficiency thing, but with the empty string literal that's not a big deal.

If you really want an EmptyString constant, make it yourself. But all it will do is encourage even more verbose code; there will never be any benefit to doing so.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

It sounds like you are using Visual Studio's Web Compiler extension. There is an open issue for this found here: https://github.com/madskristensen/WebCompiler/issues/413

There is a workaround posted in that issue:

  1. Close Visual Studio
  2. Head to C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X (X is the version of WebCompiler)
  3. Delete following folders from node_modules folder: caniuse-lite and browserslist Open up CMD (inside C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X) and run: npm i caniuse-lite browserslist

Integrate ZXing in Android Studio

buttion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
            }
        });

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }



dependencies {
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    compile 'com.android.support:appcompat-v7:23.1.0'
}

How can I view the Git history in Visual Studio Code?

If you need to know the Commit history only, So don't use much Meshed up and bulky plugins,

I will recommend you a Basic simple plugin like "Git Commits"

I use it too :

https://marketplace.visualstudio.com/items?itemName=exelord.git-commits

Enjoy

iOS 7 - Status bar overlaps the view

For Navigation Bar :

Writing this code :

self.navigationController.navigationBar.translucent = NO;

just did the trick for me.

How do you count the elements of an array in java

Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().

Div height 100% and expands to fit content

Old question, but in my case i found using position:fixed solved it for me. My situation might have been a little different though. I had an overlayed semi transparent div with a loading animation in it that I needed displayed while the page was loading. So using height:auto / 100% or min-height: 100% both filled the window but not the off-screen area. Using position:fixed made this overlay scroll with the user, so it always covered the visible area and kept my preloading animation centred on the screen.

django order_by query set, ascending and descending

for ascending order:

Reserved.objects.filter(client=client_id).order_by('check_in')

for descending order:

1.  Reserved.objects.filter(client=client_id).order_by('-check_in')

or

2.  Reserved.objects.filter(client=client_id).order_by('check_in')[::-1]

Dynamic constant assignment

Constants in ruby cannot be defined inside methods. See the notes at the bottom of this page, for example

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

how to filter out a null value from spark dataframe

There are two ways to do it: creating filter condition 1) Manually 2) Dynamically.

Sample DataFrame:

val df = spark.createDataFrame(Seq(
  (0, "a1", "b1", "c1", "d1"),
  (1, "a2", "b2", "c2", "d2"),
  (2, "a3", "b3", null, "d3"),
  (3, "a4", null, "c4", "d4"),
  (4, null, "b5", "c5", "d5")
)).toDF("id", "col1", "col2", "col3", "col4")

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  0|  a1|  b1|  c1|  d1|
|  1|  a2|  b2|  c2|  d2|
|  2|  a3|  b3|null|  d3|
|  3|  a4|null|  c4|  d4|
|  4|null|  b5|  c5|  d5|
+---+----+----+----+----+

1) Creating filter condition manually i.e. using DataFrame where or filter function

df.filter(col("col1").isNotNull && col("col2").isNotNull).show

or

df.where("col1 is not null and col2 is not null").show

Result:

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  0|  a1|  b1|  c1|  d1|
|  1|  a2|  b2|  c2|  d2|
|  2|  a3|  b3|null|  d3|
+---+----+----+----+----+

2) Creating filter condition dynamically: This is useful when we don't want any column to have null value and there are large number of columns, which is mostly the case.

To create the filter condition manually in these cases will waste a lot of time. In below code we are including all columns dynamically using map and reduce function on DataFrame columns:

val filterCond = df.columns.map(x=>col(x).isNotNull).reduce(_ && _)

How filterCond looks:

filterCond: org.apache.spark.sql.Column = (((((id IS NOT NULL) AND (col1 IS NOT NULL)) AND (col2 IS NOT NULL)) AND (col3 IS NOT NULL)) AND (col4 IS NOT NULL))

Filtering:

val filteredDf = df.filter(filterCond)

Result:

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  0|  a1|  b1|  c1|  d1|
|  1|  a2|  b2|  c2|  d2|
+---+----+----+----+----+

Allow access permission to write in Program Files of Windows 7

It would be neater to create a folder named "c:\programs writable\" and put you app below that one. That way a jungle of low c-folders can be avoided.

The underlying trade-off is security versus ease-of-use. If you know what you are doing you want to be god on you own pc. If you must maintain healthy systems for your local anarchistic society, you may want to add some security.