Programs & Examples On #Fixeddocument

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

PHP decoding and encoding json with unicode characters

I have found following way to fix this issue... I hope this can help you.

json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.

i.e:

datetime.Value

but check to see if it has a value first!

if (datetime.HasValue)
{
   // work with datetime.Value
}

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

JDK is not available as a portable ZIP file, unfortunately. However, you can follow these steps:

  • Create working JDK directory (C:\JDK in this case)
  • Download latest version of JDK from Oracle (for example jdk-7u7-windows-x64.exe)
  • Download and install 7-Zip (or download 7-Zip portable version if you are not administrator)
  • With 7-Zip extract all the files from jdk-XuXX-windows-x64.exe into the directory C:\JDK
  • Execute the following commands in cmd.exe:
    • cd C:\JDK\.rsrc\1033\JAVA_CAB10
    • extrac32 111
  • Unpack C:\JDK\.rsrc\1033\JAVA_CAB10\tools.zip with 7-zip
  • Execute the following commands in cmd.exe:
    • cd C:\JDK\.rsrc\1033\JAVA_CAB10\tools\
    • for /r %x in (*.pack) do .\bin\unpack200 -r "%x" "%~dx%~px%~nx.jar" (this will convert all .pack files into .jar files)
  • Copy all contents of C:\JDK\.rsrc\1033\JAVA_CAB10\tools where you want your JDK to be
  • Setup JAVA_HOME and PATH manually to point to your JDK dir and its BIN subdirectory.

How can I get the source directory of a Bash script from within the script itself?

Here is an easy-to-remember script:

DIR="$(dirname "${BASH_SOURCE[0]}")"  # Get the directory name
DIR="$(realpath "${DIR}")"    # Resolve its full path if need be

How to repeat a string a variable number of times in C++?

As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.

While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:

#include <string>
#include <cstddef>

std::string repeat(std::string str, const std::size_t n)
{
    if (n == 0) {
        str.clear();
        str.shrink_to_fit();
        return str;
    } else if (n == 1 || str.empty()) {
        return str;
    }
    const auto period = str.size();
    if (period == 1) {
        str.append(n - 1, str.front());
        return str;
    }
    str.reserve(period * n);
    std::size_t m {2};
    for (; m < n; m *= 2) str += str;
    str.append(str.c_str(), (n - (m / 2)) * period);
    return str;
}

We can also define an operator* to get something closer to the Python version:

#include <utility>

std::string operator*(std::string str, std::size_t n)
{
    return repeat(std::move(str), n);
}

On my machine this is around 10x faster than the implementation given by Commodore, and about 2x faster than a naive 'append n - 1 times' solution.

Intent.putExtra List

If you use ArrayList instead of list then also your problem wil be solved. In your code only modify List into ArrayList.

private List<Item> data;

Selenium WebDriver.get(url) does not open the URL

A spent a lot of time on this issue and finally found that selenium 2.44 not working with node version 0.12. Use node version 0.10.38.

How to get data by SqlDataReader.GetValue by column name

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

Solving "adb server version doesn't match this client" error

  1. adb kill-server
  2. close any pc side application you are using for manage the android phone, e.g. 360mobile(360????). you might need to end them in task manager in necessary.
  3. adb start-server and it should be solved

Format certain floating dataframe columns into percentage in pandas

Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.

In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style.

For the case of just seeing two significant digits of some columns, we can use this code snippet:

Given dataframe

import numpy as np
import pandas as pd

df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
          'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
          'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})

print(df)
       var1      var2      var3
0  1.458315  1.500092 -0.005709
1  1.576704  1.608445 -0.005122
2  1.629253  1.652577 -0.004754
3  1.669331  1.685456 -0.003525
4  1.705139  1.712096 -0.003134
5  1.740447  1.741961 -0.001223
6  1.775980  1.770801 -0.001723
7  1.812037  1.799327 -0.002013
8  1.853130  1.822982 -0.001396
9  1.943985  1.868401  0.005732

Style to get required format

    df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})

Gives:

var1    var2    var3
id          
0   1.46    1.50    -0.57%
1   1.58    1.61    -0.51%
2   1.63    1.65    -0.48%
3   1.67    1.69    -0.35%
4   1.71    1.71    -0.31%
5   1.74    1.74    -0.12%
6   1.78    1.77    -0.17%
7   1.81    1.80    -0.20%
8   1.85    1.82    -0.14%
9   1.94    1.87    0.57%

Update

If display command is not found try following:

from IPython.display import display

df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})

display(df_style)

Requirements

  • To use display command, you need to have installed Ipython in your machine.
  • The display command does not work in online python interpreter which do not have IPyton installed such as https://repl.it/languages/python3
  • The display command works in jupyter-notebook, jupyter-lab, Google-colab, kaggle-kernels, IBM-watson,Mode-Analytics and many other platforms out of the box, you do not even have to import display from IPython.display

Check whether a cell contains a substring

I like Rink.Attendant.6 answer. I actually want to check for multiple strings and did it this way:

First the situation: Names that can be home builders or community names and I need to bucket the builders as one group. To do this I am looking for the word "builder" or "construction", etc. So -

=IF(OR(COUNTIF(A1,"*builder*"),COUNTIF(A1,"*builder*")),"Builder","Community")

How to open a Bootstrap modal window using jQuery?

Check out the complete solution here:

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_modal_show&stacked=h

Make sure to put libraries in required order to get result:

1- First bootstrap.min.css 2- jquery.min.js 3- bootstrap.min.js

(In other words jquery.min.js must be call before bootstrap.min.js)

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

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

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

How to make ConstraintLayout work with percentage values?

Try this code. You can change the height and width percentages with app:layout_constraintHeight_percent and app:layout_constraintWidth_percent.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FF00FF"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_percent=".6"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".4"></LinearLayout>

</android.support.constraint.ConstraintLayout>

Gradle:

dependencies {
...
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

enter image description here

Is there a way to perform "if" in python's lambda

Hope this will help a little

you can resolve this problem in the following way

f = lambda x:  x==2   

if f(3):
  print("do logic")
else:
  print("another logic")

How do I get the directory from a file's full path?

First, you have to use System.IO namespace. Then;

string filename = @"C:\MyDirectory\MyFile.bat";
string newPath = Path.GetFullPath(fileName);

or

string newPath = Path.GetFullPath(openFileDialog1.FileName));

Build .NET Core console application to output an EXE

UPDATE for .NET 5!

The below applies on/after NOV2020 when .NET 5 is officially out.

(see quick terminology section below, not just the How-to's)

How-To (CLI)

Pre-requisites

  • Download latest version of the .net 5 SDK. Link

Steps

  1. Open a terminal (e.g: bash, command prompt, powershell) and in the same directory as your .csproj file enter the below command:
dotnet publish --output "{any directory}" --runtime {runtime} --configuration {Debug|Release} -p:PublishSingleFile={true|false} -p:PublishTrimmed={true|false} --self-contained {true|false}

example:

dotnet publish --output "c:/temp/myapp" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true

How-To (GUI)

Pre-requisites

  • If reading pre NOV2020: Latest version of Visual Studio Preview*
  • If reading NOV2020+: Latest version of Visual Studio*

*In above 2 cases, the latest .net5 SDK will be automatically installed on your PC.

Steps

  1. Right-Click on Project, and click Publish
    enter image description here

  2. Click Start and choose Folder target, click next and choose Folder Choose Folder Target

  3. Enter any folder location, and click Finish

  4. Click on Edit
    enter image description here

  5. Choose a Target Runtime and tick on Produce Single File and save.* enter image description here

  6. Click Publish

  7. Open a terminal in the location you published your app, and run the .exe. Example: enter image description here

A little bit of terminology

Target Runtime
See the list of RID's

Deployment Mode

  • Framework Dependent means a small .exe file produced but app assumed .Net 5 is installed on the host machine
  • Self contained means a bigger .exe file because the .exe includes the framework but then you can run .exe on any machine, no need for .Net 5 to be pre-installed. NOTE: WHEN USING SELF CONTAINED, ADDITIONAL DEPENDENCIES (.dll's) WILL BE PRODUCED, NOT JUST THE .EXE

Enable ReadyToRun compilation
TLDR: it's .Net5's equivalent of Ahead of Time Compilation (AOT). Pre-compiled to native code, app would usually boot up faster. App more performant (or not!), depending on many factors. More info here

Trim unused assemblies
When set to true, dotnet will generate a very lean and small .exe and only include what it needs. Be careful here. Example: when using reflection in your app you probably don't want to set this flag to true.

Microsoft Doc


Previous Post

UPDATE (31-OCT-2019)

For anyone that wants to do this via a GUI and:

  • Is using Visual Studio 2019
  • Has .NET Core 3.0 installed (included in latest version of Visual Studio 2019)
  • Wants to generate a single file

Enter image description here

Enter image description here

Enter image description here

Enter image description here

Enter image description here

Enter image description here

Enter image description here

enter image description here

Enter image description here

Note

Notice the large file size for such a small application

Enter image description here

You can add the "PublishTrimmed" property. The application will only include components that are used by the application. Caution: don't do this if you are using reflection

Enter image description here

Publish again

Enter image description here

How to rename with prefix/suffix?

The easiest way to bulk rename files in directory is:

ls | xargs -I fileName mv fileName fileName.suffix

How to get every first element in 2 dimensional list

Compared the 3 methods

  1. 2D list: 5.323603868484497 seconds
  2. Numpy library : 0.3201274871826172 seconds
  3. Zip (Thanks to Joran Beasley) : 0.12395167350769043 seconds
D2_list=[list(range(100))]*100
t1=time.time()
for i in range(10**5):
    for j in range(10):
        b=[k[j] for k in D2_list]
D2_list_time=time.time()-t1

array=np.array(D2_list)
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=array[:,j]        
Numpy_time=time.time()-t1

D2_trans = list(zip(*D2_list)) 
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=D2_trans[j]
Zip_time=time.time()-t1

print ('2D List:',D2_list_time)
print ('Numpy:',Numpy_time)
print ('Zip:',Zip_time)

The Zip method works best. It was quite useful when I had to do some column wise processes for mapreduce jobs in the cluster servers where numpy was not installed.

tsql returning a table from a function or store procedure

You don't need (shouldn't use) a function as far as I can tell. The stored procedure will return tabular data from any SELECT statements you include that return tabular data.

A stored proc does not use RETURN statements.

 CREATE PROCEDURE name
 AS

 SELECT stuff INTO #temptbl1

 .......


 SELECT columns FROM #temptbln

Easy way to use variables of enum types as string in C?

I thought that a solution like Boost.Fusion one for adapting structs and classes would be nice, they even had it at some point, to use enums as a fusion sequence.

So I made just some small macros to generate the code to print the enums. This is not perfect and has nothing to see with Boost.Fusion generated boilerplate code, but can be used like the Boost Fusion macros. I want to really do generate the types needed by Boost.Fusion to integrate in this infrastructure which allows to print names of struct members, but this will happen later, for now this is just macros :

#ifndef SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP
#define SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP

#include <swissarmyknife/detail/config.hpp>

#include <string>
#include <ostream>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>


#define SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C(                     \
    R, unused, ENUMERATION_ENTRY)                                               \
    case ENUMERATION_ENTRY:                                                     \
      return BOOST_PP_STRINGIZE(ENUMERATION_ENTRY);                             \
    break;                                                                      

/**
 * \brief Adapts ENUM to reflectable types.
 *
 * \param ENUM_TYPE To be adapted
 * \param ENUMERATION_SEQ Sequence of enum states
 */
#define SWISSARMYKNIFE_ADAPT_ENUM(ENUM_TYPE, ENUMERATION_SEQ)                   \
    inline std::string to_string(const ENUM_TYPE& enum_value) {                 \
      switch (enum_value) {                                                     \
      BOOST_PP_SEQ_FOR_EACH(                                                    \
          SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C,                   \
          unused, ENUMERATION_SEQ)                                              \
        default:                                                                \
          return BOOST_PP_STRINGIZE(ENUM_TYPE);                                 \
      }                                                                         \
    }                                                                           \
                                                                                \
    inline std::ostream& operator<<(std::ostream& os, const ENUM_TYPE& value) { \
      os << to_string(value);                                                   \
      return os;                                                                \
    }

#endif

The old answer below is pretty bad, please don't use that. :)

Old answer:

I've been searching a way which solves this problem without changing too much the enums declaration syntax. I came to a solution which uses the preprocessor to retrieve a string from a stringified enum declaration.

I'm able to define non-sparse enums like this :

SMART_ENUM(State, 
    enum State {
        RUNNING,
        SLEEPING, 
        FAULT, 
        UNKNOWN
    })

And I can interact with them in different ways:

// With a stringstream
std::stringstream ss;
ss << State::FAULT;
std::string myEnumStr = ss.str();

//Directly to stdout
std::cout << State::FAULT << std::endl;

//to a string
std::string myStr = State::to_string(State::FAULT);

//from a string
State::State myEnumVal = State::from_string(State::FAULT);

Based on the following definitions :

#define SMART_ENUM(enumTypeArg, ...)                                                     \
namespace enumTypeArg {                                                                  \
    __VA_ARGS__;                                                                         \
    std::ostream& operator<<(std::ostream& os, const enumTypeArg& val) {                 \
            os << swissarmyknife::enums::to_string(#__VA_ARGS__, val);                   \
            return os;                                                                   \
    }                                                                                    \
                                                                                     \
    std::string to_string(const enumTypeArg& val) {                                      \
            return swissarmyknife::enums::to_string(#__VA_ARGS__, val);                  \
    }                                                                                    \
                                                                                     \
    enumTypeArg from_string(const std::string &str) {                                    \
            return swissarmyknife::enums::from_string<enumTypeArg>(#__VA_ARGS__, str);   \
    }                                                                                    \
}                                                                                        \


namespace swissarmyknife { namespace enums {

    static inline std::string to_string(const std::string completeEnumDeclaration, size_t enumVal) throw (std::runtime_error) {
        size_t begin = completeEnumDeclaration.find_first_of('{');
        size_t end = completeEnumDeclaration.find_last_of('}');
        const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );

        size_t count = 0;
        size_t found = 0;
        do {
            found = identifiers.find_first_of(",}", found+1);

            if (enumVal == count) {
                std::string identifiersSubset = identifiers.substr(0, found);
                size_t beginId = identifiersSubset.find_last_of("{,");
                identifiersSubset = identifiersSubset.substr(beginId+1);
                boost::algorithm::trim(identifiersSubset);
                return identifiersSubset;
            }

            ++count;
        } while (found != std::string::npos);

        throw std::runtime_error("The enum declaration provided doesn't contains this state.");
    }                                                  

    template <typename EnumType>
    static inline EnumType from_string(const std::string completeEnumDeclaration, const std::string &enumStr) throw (std::runtime_error) {
        size_t begin = completeEnumDeclaration.find_first_of('{');
        size_t end = completeEnumDeclaration.find_last_of('}');
        const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );

        size_t count = 0;
        size_t found = 0;
        do {
            found = identifiers.find_first_of(",}", found+1);

            std::string identifiersSubset = identifiers.substr(0, found);
            size_t beginId = identifiersSubset.find_last_of("{,");
            identifiersSubset = identifiersSubset.substr(beginId+1);
            boost::algorithm::trim(identifiersSubset);

            if (identifiersSubset == enumStr) {
                return static_cast<EnumType>(count);
            }

            ++count;
        } while (found != std::string::npos);

        throw std::runtime_error("No valid enum value for the provided string");
    }                      

}}

When I'll need support for sparse enum and when I'll have more time I'll improve the to_string and from_string implementations with boost::xpressive, but this will costs in compilation time because of the important templating performed and the executable generated is likely to be really bigger. But this has the advantage that it will be more readable and maintanable than this ugly manual string manipulation code. :D

Otherwise I always used boost::bimap to perform such mappings between enums value and string, but it has to be maintained manually.

Move view with keyboard using Swift

One of the popular answers on this thread uses the following code:

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}
func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}

There's an obvious problem with offsetting your view by a static amount. It'll look nice on one device but will look bad on any other size configuration. You'll need to get the keyboards height and use that as your offset value.

Here's a solution that works on all devices and handles the edge-case where the user hides the predictive text field while typing.

Solution

Important to note below, we're passing self.view.window in as our object parameter. This will provide us with data from our Keyboard, such as its height!

@IBOutlet weak var messageField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: self.view.window)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: self.view.window)
}

func keyboardWillHide(sender: NSNotification) {
    let userInfo: [NSObject : AnyObject] = sender.userInfo!
    let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
    self.view.frame.origin.y += keyboardSize.height
}

We'll make it look nice on all devices and handle the case where the user adds or removes the predictive text field.

func keyboardWillShow(sender: NSNotification) {
    let userInfo: [NSObject : AnyObject] = sender.userInfo!
    let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
    let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size

    if keyboardSize.height == offset.height {
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.frame.origin.y -= keyboardSize.height
        })
    } else {
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.frame.origin.y += keyboardSize.height - offset.height
        })
    }
}

Remove Observers

Don't forget to remove your observers before you leave the view to prevent unnecessary messages from being transmitted.

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: self.view.window)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window)
}

Update based on question from comments:

If you have two or more text-fields, you can check to see if your view.frame.origin.y is at zero.

func keyboardWillShow(sender: NSNotification) {
    let userInfo: [NSObject : AnyObject] = sender.userInfo!

    let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
    let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size

    if keyboardSize.height == offset.height {
        if self.view.frame.origin.y == 0 {
            UIView.animateWithDuration(0.1, animations: { () -> Void in
                self.view.frame.origin.y -= keyboardSize.height
            })
        }
    } else {
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.frame.origin.y += keyboardSize.height - offset.height
        })
    }
     print(self.view.frame.origin.y)
}

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Create a string of variable length, filled with a repeated character

For Evergreen browsers, this will build a staircase based on an incoming character and the number of stairs to build.
function StairCase(character, input) {
    let i = 0;
    while (i < input) {
        const spaces = " ".repeat(input - (i+1));
        const hashes = character.repeat(i + 1);
        console.log(spaces + hashes);
        i++;
    }
}

//Implement
//Refresh the console
console.clear();
StairCase("#",6);   

You can also add a polyfill for Repeat for older browsers

    if (!String.prototype.repeat) {
      String.prototype.repeat = function(count) {
        'use strict';
        if (this == null) {
          throw new TypeError('can\'t convert ' + this + ' to object');
        }
        var str = '' + this;
        count = +count;
        if (count != count) {
          count = 0;
        }
        if (count < 0) {
          throw new RangeError('repeat count must be non-negative');
        }
        if (count == Infinity) {
          throw new RangeError('repeat count must be less than infinity');
        }
        count = Math.floor(count);
        if (str.length == 0 || count == 0) {
          return '';
        }
        // Ensuring count is a 31-bit integer allows us to heavily optimize the
        // main part. But anyway, most current (August 2014) browsers can't handle
        // strings 1 << 28 chars or longer, so:
        if (str.length * count >= 1 << 28) {
          throw new RangeError('repeat count must not overflow maximum string size');
        }
        var rpt = '';
        for (;;) {
          if ((count & 1) == 1) {
            rpt += str;
          }
          count >>>= 1;
          if (count == 0) {
            break;
          }
          str += str;
        }
        // Could we try:
        // return Array(count + 1).join(this);
        return rpt;
      }
    } 

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

ls command: how can I get a recursive full-path listing, one line per file?

With having the freedom of using all possible ls options:

find -type f | xargs ls -1

How can I add a space in between two outputs?

System.out.println(Name + " " + Income);

Is that what you mean? That will put a space between the name and the income?

How do you remove Subversion control for a folder?

If you are running Windows then you can do a search on that folder for .svn and that will list them all. Pressing Ctrl + A will select all of them and pressing delete will remove all the 'pesky' Subversion stuff.

How to correctly display .csv files within Excel 2013?

Another possible problem is that the csv file contains a byte order mark "FEFF". The byte order mark is intended to detect whether the file has been moved from a system using big endian or little endian byte ordering to a system of the opposite endianness. https://en.wikipedia.org/wiki/Byte_order_mark

Removing the "FEFF" byte order mark using a hex editor should allow Excel to read the file.

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

How to convert Varchar to Int in sql server 2008?

There are two type of convert method in SQL.

CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.

Using Convert

Select convert(int,[Column1])

Using Cast

Select cast([Column1] as int)

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

HTML tag inside JavaScript

You will either have to document.write it or use the Document Object Model:

Example using document.write

<script type="text/javascript">
if(document.getElementById('number1').checked) {
    document.write("<h1>Hello member</h1>");
}
</script>

Example using DOM

<h1></h1> <!-- We are targeting this tag with JS. See code below -->
<input type="checkbox" id="number1" checked /><label for="number1">Agree</label>
<div id="container"> <p>Content</p> </div>

<script type="text/javascript">
window.onload = function() {
    if( document.getElementById('number1').checked ) {
        var h1 = document.createElement("h1");
        h1.appendChild(document.createTextNode("Hello member"));
        document.getElementById("container").appendChild(h1);
    }
}
</script>

Best practices to test protected methods with PHPUnit

If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:

protected static function getMethod($name) {
  $class = new ReflectionClass('MyClass');
  $method = $class->getMethod($name);
  $method->setAccessible(true);
  return $method;
}

public function testFoo() {
  $foo = self::getMethod('foo');
  $obj = new MyClass();
  $foo->invokeArgs($obj, array(...));
  ...
}

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Comparing Dates in Oracle SQL

31-DEC-95 isn't a string, nor is 20-JUN-94. They're numbers with some extra stuff added on the end. This should be '31-DEC-95' or '20-JUN-94' - note the single quote, '. This will enable you to do a string comparison.

However, you're not doing a string comparison; you're doing a date comparison. You should transform your string into a date. Either by using the built-in TO_DATE() function, or a date literal.

TO_DATE()

select employee_id
  from employee
 where employee_date_hired > to_date('31-DEC-95','DD-MON-YY')

This method has a few unnecessary pitfalls

  • As a_horse_with_no_name noted in the comments, DEC, doesn't necessarily mean December. It depends on your NLS_DATE_LANGUAGE and NLS_DATE_FORMAT settings. To ensure that your comparison with work in any locale you can use the datetime format model MM instead
  • The year '95 is inexact. You know you mean 1995, but what if it was '50, is that 1950 or 2050? It's always best to be explicit
select employee_id
  from employee
 where employee_date_hired > to_date('31-12-1995','DD-MM-YYYY')

Date literals

A date literal is part of the ANSI standard, which means you don't have to use an Oracle specific function. When using a literal you must specify your date in the format YYYY-MM-DD and you cannot include a time element.

select employee_id
  from employee
 where employee_date_hired > date '1995-12-31'

Remember that the Oracle date datatype includes a time elemement, so the date without a time portion is equivalent to 1995-12-31 00:00:00.

If you want to include a time portion then you'd have to use a timestamp literal, which takes the format YYYY-MM-DD HH24:MI:SS[.FF0-9]

select employee_id
  from employee
 where employee_date_hired > timestamp '1995-12-31 12:31:02'

Further information

NLS_DATE_LANGUAGE is derived from NLS_LANGUAGE and NLS_DATE_FORMAT is derived from NLS_TERRITORY. These are set when you initially created the database but they can be altered by changing your inialization parameters file - only if really required - or at the session level by using the ALTER SESSION syntax. For instance:

alter session set nls_date_format = 'DD.MM.YYYY HH24:MI:SS';

This means:

  • DD numeric day of the month, 1 - 31
  • MM numeric month of the year, 01 - 12 ( January is 01 )
  • YYYY 4 digit year - in my opinion this is always better than a 2 digit year YY as there is no confusion with what century you're referring to.
  • HH24 hour of the day, 0 - 23
  • MI minute of the hour, 0 - 59
  • SS second of the minute, 0-59

You can find out your current language and date language settings by querying V$NLS_PARAMETERSs and the full gamut of valid values by querying V$NLS_VALID_VALUES.

Further reading


Incidentally, if you want the count(*) you need to group by employee_id

select employee_id, count(*)
  from employee
 where employee_date_hired > date '1995-12-31'
 group by employee_id

This gives you the count per employee_id.

How to download and save a file from Internet using Java?

public void saveUrl(final String filename, final String urlString)
        throws MalformedURLException, IOException {
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
        in = new BufferedInputStream(new URL(urlString).openStream());
        fout = new FileOutputStream(filename);

        final byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1) {
            fout.write(data, 0, count);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
}

You'll need to handle exceptions, probably external to this method.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

the only way I know is to delete the designer file, and do a convert to web app. However when you do this, it usually pops up with the error, as to why it didn't auto-regen in the first place, its usually a control ref that isn't declared in the head of the page.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

Facebook has revised their policies now. You can’t get the whole friendlist anyway if your app does not have a Canvas implementation and if your app is not a game. Of course there’s also taggable_friends, but that one is for tagging only.

You will be able to pull the list of friends who have authorised the app only.

The apps that are using Graph API 1.0 will be working till April 30th, 2015 and after that it will be deprecated.

See the following to get more details on this:

Triangle Draw Method

There is no direct method to draw a triangle. You can use drawPolygon() method for this. It takes three parameters in the following form: drawPolygon(int x[],int y[], int number_of_points); To draw a triangle: (Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.) Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100) Do the following inside public void paint(Graphics g):

int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);

Similarly you can draw any shape using as many points as you want.

PHP : send mail in localhost

try this

ini_set("SMTP","aspmx.l.google.com");
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: [email protected]" . "\r\n";
mail("[email protected]","test subject","test body",$headers);

Convert ArrayList to String array in Android

Use the method "toArray()"

ArrayList<String>  mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
Object[] mStringArray = mStringList.toArray();

for(int i = 0; i < mStringArray.length ; i++){
    Log.d("string is",(String)mStringArray[i]);
}

or you can do it like this: (mentioned in other answers)

ArrayList<String>  mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);

for(int i = 0; i < mStringArray.length ; i++){
    Log.d("string is",(String)mStringArray[i]);
}

http://developer.android.com/reference/java/util/ArrayList.html#toArray()

Java: Sending Multiple Parameters to Method

The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?

If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:

public class MyClass
{
  public void doSomething(int i) 
  {
    ...
  }

  public void doSomething(int i, String s) 
  {
    ...
  }

  public void doSomething(int i, String s, boolean b) 
  {
    ...
  }
}

If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:

public MyClass 
{
  public void doSomething(int... integers)
  {
    for (int i : integers) 
    {
      ...
    }
  }
}

Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

Set value for particular cell in pandas DataFrame with iloc

One thing I would add here is that the at function on a dataframe is much faster particularly if you are doing a lot of assignments of individual (not slice) values.

df.at[index, 'col_name'] = x

In my experience I have gotten a 20x speedup. Here is a write up that is Spanish but still gives an impression of what's going on.

download file using an ajax request

Cross browser solution, tested on Chrome, Firefox, Edge, IE11.

In the DOM, add an hidden link tag:

<a id="target" style="display: none"></a>

Then:

var req = new XMLHttpRequest();
req.open("GET", downloadUrl, true);
req.responseType = "blob";
req.setRequestHeader('my-custom-header', 'custom-value'); // adding some headers (if needed)

req.onload = function (event) {
  var blob = req.response;
  var fileName = null;
  var contentType = req.getResponseHeader("content-type");

  // IE/EDGE seems not returning some response header
  if (req.getResponseHeader("content-disposition")) {
    var contentDisposition = req.getResponseHeader("content-disposition");
    fileName = contentDisposition.substring(contentDisposition.indexOf("=")+1);
  } else {
    fileName = "unnamed." + contentType.substring(contentType.indexOf("/")+1);
  }

  if (window.navigator.msSaveOrOpenBlob) {
    // Internet Explorer
    window.navigator.msSaveOrOpenBlob(new Blob([blob], {type: contentType}), fileName);
  } else {
    var el = document.getElementById("target");
    el.href = window.URL.createObjectURL(blob);
    el.download = fileName;
    el.click();
  }
};
req.send();

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

How to sort multidimensional array by column?

Yes. The sorted built-in accepts a key argument:

sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]

note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

or alternatively,

from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]

Read more on the python wiki.

CMake is not able to find BOOST libraries

I'm using this to set up boost from cmake in my CMakeLists.txt. Try something similar (make sure to update paths to your installation of boost).

SET (BOOST_ROOT "/opt/boost/boost_1_57_0")
SET (BOOST_INCLUDEDIR "/opt/boost/boost-1.57.0/include")
SET (BOOST_LIBRARYDIR "/opt/boost/boost-1.57.0/lib")

SET (BOOST_MIN_VERSION "1.55.0")
set (Boost_NO_BOOST_CMAKE ON)
FIND_PACKAGE(Boost ${BOOST_MIN_VERSION} REQUIRED)
if (NOT Boost_FOUND)
  message(FATAL_ERROR "Fatal error: Boost (version >= 1.55) required.")
else()
  message(STATUS "Setting up BOOST")
  message(STATUS " Includes - ${Boost_INCLUDE_DIRS}")
  message(STATUS " Library  - ${Boost_LIBRARY_DIRS}")
  include_directories(${Boost_INCLUDE_DIRS})
  link_directories(${Boost_LIBRARY_DIRS})
endif (NOT Boost_FOUND)

This will either search default paths (/usr, /usr/local) or the path provided through the cmake variables (BOOST_ROOT, BOOST_INCLUDEDIR, BOOST_LIBRARYDIR). It works for me on cmake > 2.6.

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

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This works for me in development but I can't advise that in production, it's just a different way of getting the job done that hasn't been mentioned yet but probably not the best. Anyway here goes:

You can get the origin from the request, then use that in the response header. Here's how it looks in express:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

I don't know what that would look like with your python setup but that should be easy to translate.

jQuery - Check if DOM element already exists

This should work for all elements regardless of when they are generated.

if($('some_element').length == 0) {
}

write your code in the ajax callback functions and it should work fine.

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

convert htaccess to nginx

Have not tested it yet, but the looks are better than the one Alex mentions.

The description at winginx.com/en/htaccess says:

About the htaccess to nginx converter

The service is to convert an Apache's .htaccess to nginx configuration instructions.

First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.

Note server instructions (e.g. php_value, etc.) are ignored.

The converter does not check syntax, including regular expressions and logic errors.

Please, check the result manually before use.

Make elasticsearch only return certain fields?

In Elasticsearch 5.x the above mentioned approach is deprecated. You can use the _source approach, but but in certain situations it can make sense to store a field. For instance, if you have a document with a title, a date, and a very large content field, you may want to retrieve just the title and the date without having to extract those fields from a large _source field:

In this case, you'd use:

{  
   "size": $INT_NUM_OF_DOCS_TO_RETURN,
   "stored_fields":[  
      "doc.headline",
      "doc.text",
      "doc.timestamp_utc"
   ],
   "query":{  
      "bool":{  
         "must":{  
            "term":{  
               "doc.topic":"news_on_things"
            }
         },
         "filter":{  
            "range":{  
               "doc.timestamp_utc":{  
                  "gte":1451606400000,
                  "lt":1483228800000,
                  "format":"epoch_millis"
               }
            }
         }
      }
   },
   "aggs":{  

   }
}

See the documentation on how to index stored fields. Always happy for an Upvote!

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Find OpenCV Version Installed on Ubuntu

To install this product you can see this tutorial: OpenCV on Ubuntu

There are listed the packages you need. So, with:

# dpkg -l | grep libcv2
# dpkg -l | grep libhighgui2

and more listed in the url you can find which packages are installed.

With

# dpkg -L libcv2

you can check where are installed

This operative is used for all debian packages.

Mercurial — revert back to old version and continue from there

I'd install Tortoise Hg (a free GUI for Mercurial) and use that. You can then just right-click on a revision you might want to return to - with all the commit messages there in front of your eyes - and 'Revert all files'. Makes it intuitive and easy to roll backwards and forwards between versions of a fileset, which can be really useful if you are looking to establish when a problem first appeared.

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Python dictionary get multiple values

You can use At from pydash:

from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]

Should I initialize variable within constructor or outside constructor

I would say, it depends on the default. For example

public Bar
{
  ArrayList<Foo> foos;
}

I would make a new ArrayList outside of the constructor, if I always assume foos can not be null. If Bar is a valid object, not caring if foos is null or not, I would put it in the constructor.

You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly all the constructors should do exactly the same thing(initialize foos), why duplicate that code?

Getting an "ambiguous redirect" error

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then ('shell command within quotes' + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

Select rows with same id but different value in another column

Join the same table back to itself. Use an inner join so that rows that don't match are discarded. In the joined set, there will be rows that have a matching ARIDNR in another row in the table with a different LIEFNR. Allow those ARIDNR to appear in the final set.

SELECT * FROM YourTable WHERE ARIDNR IN (
    SELECT a.ARIDNR FROM YourTable a
    JOIN YourTable b on b.ARIDNR = a.ARIDNR AND b.LIEFNR <> a.LIEFNR
)

Assert equals between 2 Lists in Junit

You mentioned that you're interested in the equality of the contents of the list (and didn't mention order). So containsExactlyInAnyOrder from AssertJ is a good fit. It comes packaged with spring-boot-starter-test, for example.

From the AssertJ docs ListAssert#containsExactlyInAnyOrder:

Verifies that the actual group contains exactly the given values and nothing else, in any order. Example:

 // an Iterable is used in the example but it would also work with an array
 Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);

 // assertion will pass
 assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);

 // assertion will fail as vilya is contained twice in elvesRings.
 assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);

how to loop through json array in jquery?

you can get the key value pair as

<pre>
function test(){    
var data=[{'com':'something'},{'com':'some other thing'}];    
$.each(data, function(key,value) {    
alert(key);  
alert(value.com);    
});    
}
</pre>

ORDER BY date and time BEFORE GROUP BY name in mysql

work for me mysql select * from (SELECT number,max(date_added) as datea FROM sms_chat group by number) as sup order by datea desc

How to check if element exists using a lambda expression?

The above answers require you to malloc a new stream object.

public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {

    for (final T z : c) {
        if (p.test(z)) {
            return true;
        }
    }
    return false;
}

public boolean containsTabById(TabPane tabPane, String id) {
    return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
   ...
}

How do I create a branch?

If you're repo is available via https, you can use this command to branch ...

svn copy https://host.example.com/repos/project/trunk \
       https://host.example.com/repos/project/branches/branch-name \
  -m "Creating a branch of project"

How to invert a grep expression

grep -v

or

grep --invert-match

You can also do the same thing using find:

find . -type f \( -iname "*" ! -iname ".exe" ! -iname ".html"\)

More info here.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

adding this worked for me.

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

JSON.net: how to deserialize without using the default constructor?

Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor] attribute to the constructor that you want Json.Net to call.

[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
    ...
}

It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]) to populate the object after constructing it.

If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:

class ResultConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Result));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON for the Result into a JObject
        JObject jo = JObject.Load(reader);

        // Read the properties which will be used as constructor parameters
        int? code = (int?)jo["Code"];
        string format = (string)jo["Format"];

        // Construct the Result object using the non-default constructor
        Result result = new Result(code, format);

        // (If anything else needs to be populated on the result object, do that here)

        // Return the result
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then, add the converter to your serializer settings, and use the settings when you deserialize:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);

How can I mimic the bottom sheet from the Maps app?

You can try my answer https://github.com/SCENEE/FloatingPanel. It provides a container view controller to display a "bottom sheet" interface.

It's easy to use and you don't mind any gesture recognizer handling! Also you can track a scroll view's(or the sibling view) in a bottom sheet if needed.

This is a simple example. Please note that you need to prepare a view controller to display your content in a bottom sheet.

import UIKit
import FloatingPanel

class ViewController: UIViewController {
    var fpc: FloatingPanelController!

    override func viewDidLoad() {
        super.viewDidLoad()

        fpc = FloatingPanelController()

        // Add "bottom sheet" in self.view.
        fpc.add(toParent: self)

        // Add a view controller to display your contents in "bottom sheet".
        let contentVC = ContentViewController()
        fpc.set(contentViewController: contentVC)

        // Track a scroll view in "bottom sheet" content if needed.
        fpc.track(scrollView: contentVC.tableView)    
    }
    ...
}

Here is another example code to display a bottom sheet to search a location like Apple Maps.

Sample App like Apple Maps

How to hide columns in an ASP.NET GridView with auto-generated columns?

I was having the same problem - need my GridView control's AutogenerateColumns to be 'true', due to it being bound by a SQL datasource, and thus I needed to hide some columns which must not be displayed in the GridView control.

The way to accomplish this is to add some code to your GridView's '_RowDataBound' event, such as this (let's assume your GridView's ID is = 'MyGridView'):

protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[<index_of_cell>].Visible = false;
    }
}

That'll do the trick just fine ;-)

Get Specific Columns Using “With()” Function in Laravel Eloquent

If you use PHP 7.4 or later you can also do it using arrow function so it looks cleaner:

Post::with(['user' => fn ($query) => $query->select('id','username')])->get();

Check if a varchar is a number (TSQL)

Damien_The_Unbeliever noted that his was only good for digits

Wade73 added a bit to handle decimal points

neizan made an additional tweak as did notwhereuareat

Unfortunately, none appear to handle negative values and they appear to have issues with a comma in the value...

Here's my tweak to pick up negative values and those with commas

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
, (N'-375.4')
, (N'-00003')
, (N'-2,000')
, (N'3-3')
, (N'3000-')
;

-- This shows that Neizan's answer allows "." to slip through.
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like '.'".
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

--Trying to tweak for negative values and the comma
--Modified when comparison
select * from (
select 
    MyVar
    , case 
        when MyVar not like N'%[^0-9.,-]%' and MyVar not like '.' and isnumeric(MyVar) = 1 then 1
        else 0 
    end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

Adding IN clause List to a JPA Query

You must convert to List as shown below:

    String[] valores = hierarquia.split(".");       
    List<String> lista =  Arrays.asList(valores);

    String jpqlQuery = "SELECT a " +
            "FROM AcessoScr a " +
            "WHERE a.scr IN :param ";

    Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);                   
    query.setParameter("param", lista);     
    List<AcessoScr> acessos = query.getResultList();

Remove a cookie

Just set the expiration date to one hour ago, if you want to "remove" the cookie, like this:

setcookie ("TestCookie", "", time() - 3600);

or

setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);

Source: http://www.php.net/manual/en/function.setcookie.php

You should use the filter_input() function for all globals which a visitor can enter/manipulate, like this:

$visitors_ip = filter_input(INPUT_COOKIE, 'id');

You can read more about it here: http://www.php.net/manual/en/function.filter-input.php and here: http://www.w3schools.com/php/func_filter_input.asp

Bootstrap number validation

It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min and max attributes (in your case only the first attribute). For example:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step attribute:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .

BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.

For a list of browsers that support it, you can look at caniuse.com.

Upload file to FTP using C#

In the first example must change those to:

requestStream.Flush();
requestStream.Close();

First flush and after that close.

How do I enable/disable log levels in Android?

Here is a more complex solution. You will get full stack trace and the method toString() will be called only if needed(Performance). The attribute BuildConfig.DEBUG will be false in the production mode so all trace and debug logs will be removed. The hot spot compiler has the chance to remove the calls because off final static properties.

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import android.util.Log;

public class Logger {

    public enum Level {
        error, warn, info, debug, trace
    }

    private static final String DEFAULT_TAG = "Project";

    private static final Level CURRENT_LEVEL = BuildConfig.DEBUG ? Level.trace : Level.info;

    private static boolean isEnabled(Level l) {
        return CURRENT_LEVEL.compareTo(l) >= 0;
    }

    static {
        Log.i(DEFAULT_TAG, "log level: " + CURRENT_LEVEL.name());
    }

    private String classname = DEFAULT_TAG;

    public void setClassName(Class<?> c) {
        classname = c.getSimpleName();
    }

    public String getClassname() {
        return classname;
    }

    public boolean isError() {
        return isEnabled(Level.error);
    }

    public boolean isWarn() {
        return isEnabled(Level.warn);
    }

    public boolean isInfo() {
        return isEnabled(Level.info);
    }

    public boolean isDebug() {
        return isEnabled(Level.debug);
    }

    public boolean isTrace() {
        return isEnabled(Level.trace);
    }

    public void error(Object... args) {
        if (isError()) Log.e(buildTag(), build(args));
    }

    public void warn(Object... args) {
        if (isWarn()) Log.w(buildTag(), build(args));
    }

    public void info(Object... args) {
        if (isInfo()) Log.i(buildTag(), build(args));
    }

    public void debug(Object... args) {
        if (isDebug()) Log.d(buildTag(), build(args));
    }

    public void trace(Object... args) {
        if (isTrace()) Log.v(buildTag(), build(args));
    }

    public void error(String msg, Throwable t) {
        if (isError()) error(buildTag(), msg, stackToString(t));
    }

    public void warn(String msg, Throwable t) {
        if (isWarn()) warn(buildTag(), msg, stackToString(t));
    }

    public void info(String msg, Throwable t) {
        if (isInfo()) info(buildTag(), msg, stackToString(t));
    }

    public void debug(String msg, Throwable t) {
        if (isDebug()) debug(buildTag(), msg, stackToString(t));
    }

    public void trace(String msg, Throwable t) {
        if (isTrace()) trace(buildTag(), msg, stackToString(t));
    }

    private String buildTag() {
        String tag ;
        if (BuildConfig.DEBUG) {
            StringBuilder b = new StringBuilder(20);
            b.append(getClassname());

            StackTraceElement stackEntry = Thread.currentThread().getStackTrace()[4];
            if (stackEntry != null) {
                b.append('.');
                b.append(stackEntry.getMethodName());
                b.append(':');
                b.append(stackEntry.getLineNumber());
            }
            tag = b.toString();
        } else {
            tag = DEFAULT_TAG;
        }
    }

    private String build(Object... args) {
        if (args == null) {
            return "null";
        } else {
            StringBuilder b = new StringBuilder(args.length * 10);
            for (Object arg : args) {
                if (arg == null) {
                    b.append("null");
                } else {
                    b.append(arg);
                }
            }
            return b.toString();
        }
    }

    private String stackToString(Throwable t) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(500);
        baos.toString();
        t.printStackTrace(new PrintStream(baos));
        return baos.toString();
    }
}

use like this:

Loggor log = new Logger();
Map foo = ...
List bar = ...
log.error("Foo:", foo, "bar:", bar);
// bad example (avoid something like this)
// log.error("Foo:" + " foo.toString() + "bar:" + bar); 

How can I get selector from jQuery object

Thank you p1nox!

My problem was to put focus back on an ajax call that was modifying part of the form.

$.ajax({  url : "ajax_invite_load.php",
        async : true,
         type : 'POST',
         data : ...
     dataType : 'html',
      success : function(html, statut) {
                    var focus = $(document.activeElement).getSelector();
                    $td_left.html(html);
                    $(focus).focus();
                }
});

I just needed to encapsulate your function in a jQuery plugin:

    !(function ($, undefined) {

    $.fn.getSelector = function () {
      if (!this || !this.length) {
        return ;
      }

      function _getChildSelector(index) {
        if (typeof index === 'undefined') {
          return '';
        }

        index = index + 1;
        return ':nth-child(' + index + ')';
      }

      function _getIdAndClassNames($el) {
        var selector = '';

        // attach id if exists
        var elId = $el.attr('id');
        if(elId){
          selector += '#' + elId;
        }

        // attach class names if exists
        var classNames = $el.attr('class');
        if(classNames){
          selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
        }

        return selector;
      }

      // get all parents siblings index and element's tag name,
      // except html and body elements
      var selector = this.parents(':not(html,body)')
        .map(function() {
          var parentIndex = $(this).index();

          return this.tagName + _getChildSelector(parentIndex);
        })
        .get()
        .reverse()
        .join(' ');

      if (selector) {
        // get node name from the element itself
        selector += ' ' + this[0].nodeName +
          // get child selector from element ifself
          _getChildSelector(this.index());
      }

      selector += _getIdAndClassNames(this);

      return selector;
    }

})(window.jQuery);

Convert serial.read() into a useable string using Arduino?

If you're using concatenate method then don't forget to trim the string if you're working with if else method.

document.getElementById vs jQuery $()

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

How to select where ID in Array Rails ActiveRecord without exception

Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

Comment.where(id: [2, 3, 5])

It will work even if some of the ids don't exist. This works in the

user.comments.where(id: avoided_ids_array)

Also for excluding ID's

Comment.where.not(id: [2, 3, 5])

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

Open Sublime Text from Terminal in macOS

The following worked for me

open -a Sublime\ Text file_name.txt
open -a Sublime\ Text Folder_Path

You can use alias to make it event simple like

Add the following line in your

~/.bash_profile

alias sublime="open -a Sublime\ Text $@"

Then next time you can use following command to open files/folders

sublime file_name.txt
sublime Folder_Path

Trust Store vs Key Store - creating with keytool

These are the steps to create a Truststore in your local machine using Keytool. Steps to create truststore for a URL in your local machine.

1) Hit the url in the browser using chrome

2) Check for the "i" icon to the left of the url in the chrome and click it

3) Check for certificate option and click it and a Dialog box will open

4) check the "certificate path" tab for the number of certificates available to create the truststore

5) Go the "details" tab -> click"Copy to File" -> Give the path and the name for the certificate you want to create.

6) Check if it has parent certificates and follow the point "5".

7) After all the certificates are being create open Command Prompt and navigate to the path where you created the certificates.

8) provide the below Keytool command to add the certificates and create a truststore.

Sample: 
   keytool -import -alias abcdefg -file abcdefg.cer -keystore cacerts
        where "abcdefg" is the alias name and "abcdefg.cer" is the actual certificate name and "cacerts" is the truststore name

9) Provide the keytool command for all the certificates and add them to the trust store.

    keytool -list -v -keystore cacerts

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

IOException: The process cannot access the file 'file path' because it is being used by another process

What is the cause?

The error message is pretty clear: you're trying to access a file, and it's not accessible because another process (or even the same process) is doing something with it (and it didn't allow any sharing).

Debugging

It may be pretty easy to solve (or pretty hard to understand), depending on your specific scenario. Let's see some.

Your process is the only one to access that file
You're sure the other process is your own process. If you know you open that file in another part of your program, then first of all you have to check that you properly close the file handle after each use. Here is an example of code with this bug:

var stream = new FileStream(path, FileAccess.Read);
var reader = new StreamReader(stream);
// Read data from this file, when I'm done I don't need it any more
File.Delete(path); // IOException: file is in use

Fortunately FileStream implements IDisposable, so it's easy to wrap all your code inside a using statement:

using (var stream = File.Open("myfile.txt", FileMode.Open)) {
    // Use stream
}

// Here stream is not accessible and it has been closed (also if
// an exception is thrown and stack unrolled

This pattern will also ensure that the file won't be left open in case of exceptions (it may be the reason the file is in use: something went wrong, and no one closed it; see this post for an example).

If everything seems fine (you're sure you always close every file you open, even in case of exceptions) and you have multiple working threads, then you have two options: rework your code to serialize file access (not always doable and not always wanted) or apply a retry pattern. It's a pretty common pattern for I/O operations: you try to do something and in case of error you wait and try again (did you ask yourself why, for example, Windows Shell takes some time to inform you that a file is in use and cannot be deleted?). In C# it's pretty easy to implement (see also better examples about disk I/O, networking and database access).

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

for (int i=1; i <= NumberOfRetries; ++i) {
    try {
        // Do stuff with file
        break; // When done we can break loop
    }
    catch (IOException e) when (i <= NumberOfRetries) {
        // You may check error code to filter some exceptions, not every error
        // can be recovered.
        Thread.Sleep(DelayOnRetry);
    }
}

Please note a common error we see very often on StackOverflow:

var stream = File.Open(path, FileOpen.Read);
var content = File.ReadAllText(path);

In this case ReadAllText() will fail because the file is in use (File.Open() in the line before). To open the file beforehand is not only unnecessary but also wrong. The same applies to all File functions that don't return a handle to the file you're working with: File.ReadAllText(), File.WriteAllText(), File.ReadAllLines(), File.WriteAllLines() and others (like File.AppendAllXyz() functions) will all open and close the file by themselves.

Your process is not the only one to access that file
If your process is not the only one to access that file, then interaction can be harder. A retry pattern will help (if the file shouldn't be open by anyone else but it is, then you need a utility like Process Explorer to check who is doing what).

Ways to avoid

When applicable, always use using statements to open files. As said in previous paragraph, it'll actively help you to avoid many common errors (see this post for an example on how not to use it).

If possible, try to decide who owns access to a specific file and centralize access through a few well-known methods. If, for example, you have a data file where your program reads and writes, then you should box all I/O code inside a single class. It'll make debug easier (because you can always put a breakpoint there and see who is doing what) and also it'll be a synchronization point (if required) for multiple access.

Don't forget I/O operations can always fail, a common example is this:

if (File.Exists(path))
    File.Delete(path);

If someone deletes the file after File.Exists() but before File.Delete(), then it'll throw an IOException in a place where you may wrongly feel safe.

Whenever it's possible, apply a retry pattern, and if you're using FileSystemWatcher, consider postponing action (because you'll get notified, but an application may still be working exclusively with that file).

Advanced scenarios
It's not always so easy, so you may need to share access with someone else. If, for example, you're reading from the beginning and writing to the end, you have at least two options.

1) share the same FileStream with proper synchronization functions (because it is not thread-safe). See this and this posts for an example.

2) use FileShare enumeration to instruct OS to allow other processes (or other parts of your own process) to access same file concurrently.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
}

In this example I showed how to open a file for writing and share for reading; please note that when reading and writing overlaps, it results in undefined or invalid data. It's a situation that must be handled when reading. Also note that this doesn't make access to the stream thread-safe, so this object can't be shared with multiple threads unless access is synchronized somehow (see previous links). Other sharing options are available, and they open up more complex scenarios. Please refer to MSDN for more details.

In general N processes can read from same file all together but only one should write, in a controlled scenario you may even enable concurrent writings but this can't be generalized in few text paragraphs inside this answer.

Is it possible to unlock a file used by another process? It's not always safe and not so easy but yes, it's possible.

Copy folder structure (without files) from one location to another

Here is a solution in php that:

  • copies the directories (not recursively, only one level)
  • preserves permissions
  • unlike the rsync solution, is fast even with directories containing thousands of files as it does not even go into the folders
  • has no problems with spaces
  • should be easy to read and adjust

Create a file like syncDirs.php with this content:

<?php
foreach (new DirectoryIterator($argv[1]) as $f) {
    if($f->isDot() || !$f->isDir()) continue;
        mkdir($argv[2].'/'.$f->getFilename(), $f->getPerms());
        chown($argv[2].'/'.$f->getFilename(), $f->getOwner());
        chgrp($argv[2].'/'.$f->getFilename(), $f->getGroup());
}

Run it as user that has enough rights:

sudo php syncDirs.php /var/source /var/destination

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

Confirmation before closing of tab/browser

Try this:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle

How to get exact browser name and version?

Use get_browser() function.

It can give you output like this:

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    .... 

Evenly distributing n points on a sphere

The Fibonacci sphere algorithm is great for this. It is fast and gives results that at a glance will easily fool the human eye. You can see an example done with processing which will show the result over time as points are added. Here's another great interactive example made by @gman. And here's a simple implementation in python.

import math


def fibonacci_sphere(samples=1):

    points = []
    phi = math.pi * (3. - math.sqrt(5.))  # golden angle in radians

    for i in range(samples):
        y = 1 - (i / float(samples - 1)) * 2  # y goes from 1 to -1
        radius = math.sqrt(1 - y * y)  # radius at y

        theta = phi * i  # golden angle increment

        x = math.cos(theta) * radius
        z = math.sin(theta) * radius

        points.append((x, y, z))

    return points

1000 samples gives you this:

enter image description here

How to auto import the necessary classes in Android Studio with shortcut?

On my Mac Auto import option was not showing it was initially hidden

Android studio ->Preferences->editor->General->Auto Import

and then typed in searched field auto then auto import option appeared. And now auto import option is now always shown as default in Editor->General. hopefully this option will also help others. See attached screenshot screenshot

Bulk insert with SQLAlchemy ORM

SQLAlchemy introduced that in version 1.0.0:

Bulk operations - SQLAlchemy docs

With these operations, you can now do bulk inserts or updates!

For instance (if you want the lowest overhead for simple table INSERTs), you can use Session.bulk_insert_mappings():

loadme = [(1, 'a'),
          (2, 'b'),
          (3, 'c')]
dicts = [dict(bar=t[0], fly=t[1]) for t in loadme]

s = Session()
s.bulk_insert_mappings(Foo, dicts)
s.commit()

Or, if you want, skip the loadme tuples and write the dictionaries directly into dicts (but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).

Android eclipse DDMS - Can't access data/data/ on phone to pull files

To set permission on the data folder and all it's subfolders and files:
Open command prompt from the ADB folder:

>> adb shell
>> su
>> find /data -type d -exec chmod 777 {} \;

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

Add some word to all or some rows in Excel?

  1. Insert a column left to the column in question(adding column A beside column B).
  2. Provide the value you want to append in 1st cell of column A
  3. Insert a column right to the column in question ( column C)
  4. Add this formula -> =CONCATENATE("A1","B1")
  5. Drag it down to apply to all values in column
  6. You will find concatenated values in column C

This worked for me !

How to obtain values of request variables using Python and Flask

If you want to retrieve POST data:

first_name = request.form.get("firstname")

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname")

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname") 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

Get data from file input in JQuery

I created a form data object and appended the file:

var form = new FormData(); 
form.append("video", $("#fileInput")[0].files[0]);

and i got:

------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv

in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla

How can I brew link a specific version?

if @simon's answer is not working in some of the mac's please follow the below process.

If you have already installed swiftgen using the following commands:

$ brew update $ brew install swiftgen

then follow the steps below in order to run swiftgen with older version.

Step 1: brew uninstall swiftgen Step 2: Navigate to: https://github.com/SwiftGen/SwiftGen/releases and download the swiftgen with version: swiftgen-4.2.0.zip.

Unzip the package in any of the directories.

Step 3: Execute the following in a terminal:

$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/

$ swiftgen --version

You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)

enter image description here

Bootstrap with jQuery Validation Plugin

this is the solution you need, you can use the errorPlacement method to override where to put the error message

$('form').validate({
    rules: {
        firstname: {
            minlength: 3,
            maxlength: 15,
            required: true
        },
        lastname: {
            minlength: 3,
            maxlength: 15,
            required: true
        }
    },
    errorPlacement: function(error, element) {
        error.insertAfter('.form-group'); //So i putted it after the .form-group so it will not include to your append/prepend group.
    }, 
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    }
});

it's works for me like magic. Cheers

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

TypeError: module.__init__() takes at most 2 arguments (3 given)

from Object import Object

or

From Class_Name import Class_name

If Object is a .py file.

String.format() to format double in java

code extracted from this link ;

Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String amountOut;

numberFormatter = NumberFormat.getNumberInstance(currentLocale);
amountOut = numberFormatter.format(amount);
System.out.println(amountOut + " " + 
                   currentLocale.toString());

The output from this example shows how the format of the same number varies with Locale:

345 987,246  fr_FR
345.987,246  de_DE
345,987.246  en_US

How to recursively list all the files in a directory in C#?

This one helped me to get all files in a directory and sub directories, May be helpful for someone. [ Inspired from above answers ]

static void Main(string[] args)
    {
        try
        {
            var root = @"G:\logs";
            DirectorySearch(root);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }





public static void DirectorySearch(string root, bool isRootItrated = false)
{
    if (!isRootItrated)
    {
        var rootDirectoryFiles = Directory.GetFiles(root);
        foreach (var file in rootDirectoryFiles)
        {
            Console.WriteLine(file);
        } 
    }

    var subDirectories = Directory.GetDirectories(root);
    if (subDirectories?.Any() == true)
    {
        foreach (var directory in subDirectories)
        {
            var files = Directory.GetFiles(directory);
            foreach (var file in files)
            {
                Console.WriteLine(file);
            }
            DirectorySearch(directory, true);
        }
    }
}

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

fetch(request, {mode: 'cors'});

However this still requires the server to enable CORS as well, and allow your domain to request the resource.

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>):

fetch(request, {mode: 'no-cors'})
.then(function(response) {
  console.log(response); 
}).catch(function(error) {  
  console.log('Request failed', error)  
});

Run PostgreSQL queries from the command line

SELECT * FROM my_table;

where my_table is the name of your table.

EDIT:

psql -c "SELECT * FROM my_table"

or just psql and then type your queries.

Google Maps API v3: Can I setZoom after fitBounds?

If I'm not mistaken, I'm assuming you want all your points to be visible on the map with the highest possible zoom level. I accomplished this by initializing the zoom level of the map to 16(not sure if it's the highest possible zoom level on V3).

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 16,
  center: marker_point,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

Then after that I did the bounds stuff:

var bounds = new google.maps.LatLngBounds();

// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop

map.fitBounds(bounds);

Result: Success!

How to set cursor position in EditText?

Let editText2 is your second EditText view .then put following piece of code in onResume()

editText2.setFocusableInTouchMode(true);
editText2.requestFocus();

or put

<requestFocus />

in your xml layout of the second EditText view.

What is the Auto-Alignment Shortcut Key in Eclipse?

auto-alignment shortcut key Ctrl+Shift+F

to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions

How to get only the last part of a path in Python?

With python 3 you can use the pathlib module (pathlib.PurePath for example):

>>> import pathlib

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/')
>>> path.name
'folderD'

If you want the last folder name where a file is located:

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py')
>>> path.parent.name
'folderD'

What does the exclamation mark do before the function?

There is a good point for using ! for function invocation marked on airbnb JavaScript guide

Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using ! will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.

!function abc(){}();
!function bca(){}();

Will work the same as

!function abc(){}();
(function bca(){})();

but saves one character and arbitrary looks better.

And by the way any of +,-,~,void operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.

abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?

but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction

!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()

Will do safe code execution, same as a very first code sample.

This one will throw error cause JavaScript ASI will not be able to do its work.

!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()

One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.

This works:

!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()

This not:

^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()

Invalid use side-effecting operator Insert within a function

Disclaimer: This is not a solution, it is more of a hack to test out something. User-defined functions cannot be used to perform actions that modify the database state.

I found one way to make insert or update using sqlcmd.exe so you need just to replace the code inside @sql variable.

CREATE FUNCTION [dbo].[_tmp_func](@orderID NVARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @sql varchar(4000), @cmd varchar(4000)
SELECT @sql = 'INSERT INTO _ord (ord_Code) VALUES (''' + @orderID + ''') '
SELECT @cmd = 'sqlcmd -S ' + @@servername +
              ' -d ' + db_name() + ' -Q "' + @sql + '"'
EXEC master..xp_cmdshell @cmd, 'no_output'
RETURN 1
END

How do you convert a DataTable into a generic list?

You can use a generic method like that for datatable to generic list

public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
    try
    {
        List<T> list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    if (propertyInfo.PropertyType.IsEnum)
                    {
                        propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString()));
                    }
                    else
                    {
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }                          
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}

javascript date + 7 days

The simple way to get a date x days in the future is to increment the date:

function addDays(dateObj, numDays) {
  return dateObj.setDate(dateObj.getDate() + numDays);
}

Note that this modifies the supplied date object, e.g.

function addDays(dateObj, numDays) {
   dateObj.setDate(dateObj.getDate() + numDays);
   return dateObj;
}

var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);

alert(
    'Today: ' + now +
    '\nTomorrow: ' + tomorrow +
    '\nNext week: ' + nextWeek
);

Absolute vs relative URLs

Should I use absolute or relative URLs?

If by absolute URLs you mean URLs including scheme (e.g. http / https) and the hostname (e.g. yourdomain.com) don't ever do that (for local resources) because it will be terrible to maintain and debug.

Let's say you have used absolute URL everywhere in your code like <img src="http://yourdomain.com/images/example.png">. Now what will happen when you are going to:

  • switch to another scheme (e.g. http -> https)
  • switch domain names (test.yourdomain.com -> yourdomain.com)

In the first example what will happen is that you will get warnings about unsafe content being requested on the page. Because all your URLs are hardcoded to use http(://yourdomain.com/images/example.png). And when running your pages over https the browser expects all resources to be loaded over https to prevent leaking of information.

In the second example when putting your site live from the test environment it would mean all resources are still pointing to your test domain instead of your live domain.

So to answer your question about whether to use absolute or relative URLs: always use relative URLs (for local resources).

What are the differences between the different URLs?

First lets have a look at the different types of urls that we can use:

  • http://yourdomain.com/images/example.png
  • //yourdomain.com/images/example.png
  • /images/example.png
  • images/example.png

What resources do these URLs try to access on the server?

In the examples below I assume the website is running from the following location on the server /var/www/mywebsite.

http://yourdomain.com/images/example.png

The above (absolute) URL tries to access the resource /var/www/website/images/example.png. This type of URL is something you would always want to avoid for requesting resources from your own website for reason outlined above. However it does have its place. For example if you have a website http://yourdomain.com and you want to request a resource from an external domain over https you should use this. E.g. https://externalsite.com/path/to/image.png.

//yourdomain.com/images/example.png

This URL is relative based on the current scheme used and should almost always be used when including external resources (images, javascripts etc).

What this type of URL does is use the current scheme of the page it is on. This means that you are on the page http://yourdomain.com and on that page is an image tag <img src="//yourdomain.com/images/example.png"> the URL of the image would resolve in http://yourdomain.com/images/example.png.
When you would have been on the page http**s**://yourdomain.com and on that page is an image tag <img src="//yourdomain.com/images/example.png"> the URL of the image would resolve in https://yourdomain.com/images/example.png.

This prevent loading resources over https when it is not needed and automatically makes sure the resource is requested over https when it is needed.

The above URL resolves in the same manner on the server side as the previous URL:

The above (absolute) URL tries to access the resource /var/www/website/images/example.png.

/images/example.png

For local resources this is the prefered way of referencing them. This is a relative URL based on the document root (/var/www/mywebsite) of your website. This means when you have <img src="/images/example.png"> it will always resolve to /var/www/mywebsite/images/example.png.

If at some point you decide to switch domain it will still work because it is relative.

images/example.png

This is also a relative URL although a bit different than the previous one. This URL is relative to the current path. What this means is that it will resolve to different paths depending on where you are in the site.

For example when you are on the page http://yourdomain.com and you use <img src="images/example.png"> it would resolve on the server to /var/www/mywebsite/images/example.png as expected, however when your are on the page http://yourdomain.com/some/path and you use the exact same image tag it suddenly will resolve to /var/www/mywebsite/some/path/images/example.png.

When to use what?

When requesting external resources you most likely want to use an URL relative to the scheme (unless you want to force a different scheme) and when dealing with local resources you want to use relative URLs based on the document root.

An example document:

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
        <link href='//fonts.googleapis.com/css?family=Lato:300italic,700italic,300,700' rel='stylesheet' type='text/css'>
        <link href="/style/style.css" rel="stylesheet" type="text/css" media="screen"></style>
    </head>
    <body>
        <img src="/images/some/localimage.png" alt="">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
    </body>
</html>

Some (kinda) duplicates

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

There's now a simpler way with .NET Standard or .NET Core:

var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());

NOTE: In order to use the JsonMediaTypeFormatter class, you will need to install the Microsoft.AspNet.WebApi.Client NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App.

Using this signature of HttpClient.PostAsync, you can pass in any object and the JsonMediaTypeFormatter will automatically take care of serialization etc.

With the response, you can use HttpContent.ReadAsAsync<T> to deserialize the response content to the type that you are expecting:

var responseObject = await response.Content.ReadAsAsync<MyResponseType>();

File being used by another process after using File.Create()

I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.

File.Create("filename").Dispose();

This way it creates and closes the file for the next process to use it.

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

Difference between hamiltonian path and euler path

I'll use a common example in biology; reconstructing a genome by making DNA samples.

De-novo assembly

To construct a genome from short reads, it's necessary to construct a graph of those reads. We do it by breaking the reads into k-mers and assemble them into a graph.

enter image description here

We can reconstruct the genome by visiting each node once as in the diagram. This is known as Hamiltonian path.

Unfortunately, constructing such path is NP-hard. It's not possible to derive an efficient algorithm for solving it. Instead, in bioinformatics we construct a Eulerian cycle where an edge represents an overlap.

enter image description here

Init method in Spring Controller (annotation version)

You can use

@PostConstruct
public void init() {
   // ...
}

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

I want to collaborate a little with the solution for the server side. So, the server is saying it does not support DSA, this is because the openssh client does not activate it by default:

OpenSSH 7.0 and greater similarly disable the ssh-dss (DSA) public key algorithm. It too is weak and we recommend against its use.

So, to fix this this in the server side I should activate other Key algorithms like RSA o ECDSA. I just had this problem with a server in a lan. I suggest the following:

Update the openssh:

yum update openssh-server

Merge new configurations in the sshd_config if there is a sshd_config.rpmnew.

Verify there are hosts keys at /etc/ssh/. If not generate new ones, see man ssh-keygen.

$ ll /etc/ssh/
total 580
-rw-r--r--. 1 root root     553185 Mar  3  2017 moduli
-rw-r--r--. 1 root root       1874 Mar  3  2017 ssh_config
drwxr-xr-x. 2 root root       4096 Apr 17 17:56 ssh_config.d
-rw-------. 1 root root       3887 Mar  3  2017 sshd_config
-rw-r-----. 1 root ssh_keys    227 Aug 30 15:33 ssh_host_ecdsa_key
-rw-r--r--. 1 root root        162 Aug 30 15:33 ssh_host_ecdsa_key.pub
-rw-r-----. 1 root ssh_keys    387 Aug 30 15:33 ssh_host_ed25519_key
-rw-r--r--. 1 root root         82 Aug 30 15:33 ssh_host_ed25519_key.pub
-rw-r-----. 1 root ssh_keys   1675 Aug 30 15:33 ssh_host_rsa_key
-rw-r--r--. 1 root root        382 Aug 30 15:33 ssh_host_rsa_key.pub

Verify in the /etc/ssh/sshd_config the HostKey configuration. It should allow the configuration of RSA and ECDSA. (If all of them are commented by default it will allow too the RSA, see in man sshd_config the part of HostKey).

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

For the client side, create a key for ssh (not a DSA like in the question) by just doing this:

ssh-keygen

After this, because there are more options than ssh-dss(DSA) the client openssh (>=v7) should connect with RSA or better algorithm.

Here another good article.

This is my first question answered, I welcome suggestions :D .

Split string in JavaScript and detect line break

Use the following:

var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);

DEMO

Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:

var splitted = $('#textArea').val().split("\n");           // will split on line breaks

Hope that helps you out!

Why is document.body null in my javascript?

Or add this part

<script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>

after the HTML, like:

    <html>
    <head>...</head>
    <body>...</body>
   <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");

    </script>

    </html>

Error: Uncaught SyntaxError: Unexpected token <

I too got this error, when developing a Backbone application using HTML5 push state in conjunction with an .htaccess which redirects any unknown files to index.html.

It turns out that when visiting a URL such as /something/5, my /index.html was effectively being served at /something/index.html (thanks to my .htaccess). This had the effect of breaking all the relative URLs to my JavaScript files (from inside the index.html ), which meant that they should have 404'd on me.

However, again due to my htaccess, instead of 404'ing when attempting to retrieve the JS files, they instead returned my index.html. Thus the browser was given an index.html for every JavaScript file it tried to pull in, and when it evaluated the HTML as if it were JavaScript, it returned a JS error due to the leading < (from my tag in index.html).

The fix in my case (as I was serving the site from inside a subdirectory) was to add a base tag in my html head.

<base href="/my-app/">

Optimal way to concatenate/aggregate strings

I found Serge's answer to be very promising, but I also encountered performance issues with it as-written. However, when I restructured it to use temporary tables and not include double CTE tables, the performance went from 1 minute 40 seconds to sub-second for 1000 combined records. Here it is for anyone who needs to do this without FOR XML on older versions of SQL Server:

DECLARE @STRUCTURED_VALUES TABLE (
     ID                 INT
    ,VALUE              VARCHAR(MAX) NULL
    ,VALUENUMBER        BIGINT
    ,VALUECOUNT         INT
);

INSERT INTO @STRUCTURED_VALUES
SELECT   ID
        ,VALUE
        ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY VALUE) AS VALUENUMBER
        ,COUNT(*) OVER (PARTITION BY ID)    AS VALUECOUNT
FROM    RAW_VALUES_TABLE;

WITH CTE AS (
    SELECT   SV.ID
            ,SV.VALUE
            ,SV.VALUENUMBER
            ,SV.VALUECOUNT
    FROM    @STRUCTURED_VALUES SV
    WHERE   VALUENUMBER = 1

    UNION ALL

    SELECT   SV.ID
            ,CTE.VALUE + ' ' + SV.VALUE AS VALUE
            ,SV.VALUENUMBER
            ,SV.VALUECOUNT
    FROM    @STRUCTURED_VALUES SV
    JOIN    CTE 
        ON  SV.ID = CTE.ID
        AND SV.VALUENUMBER = CTE.VALUENUMBER + 1

)
SELECT   ID
        ,VALUE
FROM    CTE
WHERE   VALUENUMBER = VALUECOUNT
ORDER BY ID
;

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

Python Git Module experiences?

I thought I would answer my own question, since I'm taking a different path than suggested in the answers. Nonetheless, thanks to those who answered.

First, a brief synopsis of my experiences with GitPython, PyGit, and Dulwich:

  • GitPython: After downloading, I got this imported and the appropriate object initialized. However, trying to do what was suggested in the tutorial led to errors. Lacking more documentation, I turned elsewhere.
  • PyGit: This would not even import, and I could find no documentation.
  • Dulwich: Seems to be the most promising (at least for what I wanted and saw). I made some progress with it, more than with GitPython, since its egg comes with Python source. However, after a while, I decided it may just be easier to try what I did.

Also, StGit looks interesting, but I would need the functionality extracted into a separate module and do not want wait for that to happen right now.

In (much) less time than I spent trying to get the three modules above working, I managed to get git commands working via the subprocess module, e.g.

def gitAdd(fileName, repoDir):
    cmd = ['git', 'add', fileName]
    p = subprocess.Popen(cmd, cwd=repoDir)
    p.wait()

gitAdd('exampleFile.txt', '/usr/local/example_git_repo_dir')

This isn't fully incorporated into my program yet, but I'm not anticipating a problem, except maybe speed (since I'll be processing hundreds or even thousands of files at times).

Maybe I just didn't have the patience to get things going with Dulwich or GitPython. That said, I'm hopeful the modules will get more development and be more useful soon.

python: unhashable type error

counter[row[11]]+=1

You don't show what data is, but apparently when you loop through its rows, row[11] is turning out to be a list. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11] as a key causes the defaultdict to complain that it is a mutable, i.e. unhashable, object.

The easiest fix is to change row[11] from a list to a tuple. Either by doing

counter[tuple(row[11])] += 1

or by fixing it in the caller before data is passed to medications_minimum3. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created.

Android: Storing username and password?

With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.

Show tables, describe tables equivalent in redshift

I had to select from the information schema to get details of my tables and columns; in case it helps anyone:

SELECT * FROM information_schema.tables
WHERE table_schema = 'myschema'; 

SELECT * FROM information_schema.columns
WHERE table_schema = 'myschema' AND table_name = 'mytable'; 

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

Can a main() method of class be invoked from another class in java

if I got your question correct...

main() method is defined in the class below...

public class ToBeCalledClass{

   public static void main (String args[ ]) {
      System.out.println("I am being called");
   }
}

you want to call this main method in another class.

public class CallClass{

    public void call(){
       ToBeCalledClass.main(null);
    }
}

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

Visual Studio Post Build Event - Copy to Relative Directory Location

Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.

To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.

Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.

Hope it helps Rihan

UIScrollView scroll to bottom programmatically

Xamarin.iOS version of accepted answer

var bottomOffset = new CGPoint (0,
     scrollView.ContentSize.Height - scrollView.Frame.Size.Height
     + scrollView.ContentInset.Bottom);

scrollView.SetContentOffset (bottomOffset, false);

How to get only filenames within a directory using c#?

string[] fileEntries = Directory.GetFiles(directoryPath);

foreach (var file_name in fileEntries){
    string fileName = file_name.Substring(directoryPath.Length + 1);
    Console.WriteLine(fileName);
}

Fatal error: Call to undefined function imap_open() in PHP

If your local installation is running XAMPP on Windows , That's enough : you can open the file "\xampp\php\php.ini" to activate the php exstension by removing the beginning semicolon at the line ";extension=php_imap.dll". It should be:

;extension=php_imap.dll

to

extension=php_imap.dll

Python return statement error " 'return' outside function"

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

Constants in Kotlin -- what's a recommended way to create them?

Kotlin static and constant value & method declare

object MyConstant {

@JvmField   // for access in java code 
val PI: Double = 3.14

@JvmStatic // JvmStatic annotation for access in java code
fun sumValue(v1: Int, v2: Int): Int {
    return v1 + v2
}

}

Access value anywhere

val value = MyConstant.PI
val value = MyConstant.sumValue(10,5)

Transpose list of lists

Here is a solution for transposing a list of lists that is not necessarily square:

maxCol = len(l[0])
for row in l:
    rowLength = len(row)
    if rowLength > maxCol:
        maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
    lTrans.append([])
    for row in l:
        if colIndex < len(row):
            lTrans[colIndex].append(row[colIndex])

How can I use goto in Javascript?

Actually, I see that ECMAScript (JavaScript) DOES INDEED have a goto statement. However, the JavaScript goto has two flavors!

The two JavaScript flavors of goto are called labeled continue and labeled break. There is no keyword "goto" in JavaScript. The goto is accomplished in JavaScript using the break and continue keywords.

And this is more or less explicitly stated on the w3schools website here http://www.w3schools.com/js/js_switch.asp.

I find the documentation of the labeled continue and labeled break somewhat awkwardly expressed.

The difference between the labeled continue and labeled break is where they may be used. The labeled continue can only be used inside a while loop. See w3schools for some more information.

===========

Another approach that will work is to have a giant while statement with a giant switch statement inside:

while (true)
{
    switch (goto_variable)
    {
        case 1:
            // some code
            goto_variable = 2
            break;
        case 2:
            goto_variable = 5   // case in etc. below
            break;
        case 3:
            goto_variable = 1
            break;

         etc. ...
    }

}

How to change the background color of the options menu?

This is how i solved mine. I just specified the background color and text color in styles. ie res > values > styles.xml file.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:itemBackground">#ffffff</item>
    <item name="android:textColor">#000000</item>
</style>

Return JSON response from Flask view

Pass keyword arguments to flask.jsonify and they will be output as a JSON object.

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id
    )
{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}

If you already have a dict, you can pass it directly as jsonify(d).

Best way to create a temp table with same columns and type as a permanent table

This is a MySQL-specific answer, not sure where else it works --

You can create an empty table having the same column definitions with:

CREATE TEMPORARY TABLE temp_foo LIKE foo;

And you can create a populated copy of an existing table with:

CREATE TEMPORARY TABLE temp_foo SELECT * FROM foo;

And the following works in postgres; unfortunately the different RDBMS's don't seem very consistent here:

CREATE TEMPORARY TABLE temp_foo AS SELECT * FROM foo;

Redirect within component Angular 2

callLog(){
    this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
    .subscribe(data => {
        this.getstud=data as string[];
        if(this.getstud.length!==0) {
            console.log(data)
            this.route.navigate(['home']);// used for routing after importing Router    
        }
    });
}

Is embedding background image data into CSS as Base64 good or bad practice?

Thanks for the information here. I am finding this embedding useful and particularly for mobile especially with the embedded images' css file being cached.

To help make life easier, as my file editor(s) do not natively handle this, I made a couple of simple scripts for laptop/desktop editing work, share here in case they are any use to any one else. I have stuck with php as it is handling these things directly and very well.

Under Windows 8.1 say---

C:\Users\`your user name`\AppData\Roaming\Microsoft\Windows\SendTo

... there as an Administrator you can establish a shortcut to a batch file in your path. That batch file will call a php (cli) script.

You can then right click an image in file explorer, and SendTo the batchfile.

Ok Admiinstartor request, and wait for the black command shell windows to close.

Then just simply paste the result from clipboard in your into your text editor...

<img src="|">

or

 `background-image : url("|")` 

Following should be adaptable for other OS.

Batch file...

rem @echo 0ff
rem Puts 64 encoded version of a file on clipboard
php c:\utils\php\make64Encode.php %1

And with php.exe in your path, that calls a php (cli) script...

<?php 

function putClipboard($text){
 // Windows 8.1 workaround ...

  file_put_contents("output.txt", $text);

  exec("  clip < output.txt");

}


// somewhat based on http://perishablepress.com/php-encode-decode-data-urls/
// convert image to dataURL

$img_source = $argv[1]; // image path/name
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);

$finfo = finfo_open(FILEINFO_MIME_TYPE); 
$dataType = finfo_file($finfo, $img_source); 


$build = "data:" . $dataType . ";base64," . $img_string; 

putClipboard(trim($build));

?>

RedirectToAction with parameter

It is also worth noting that you can pass through more than 1 parameter. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.

e.g.

return RedirectToAction("ACTION", "CONTROLLER", new {
           id = 99, otherParam = "Something", anotherParam = "OtherStuff" 
       });

So the url would be:

    /CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff

These can then be referenced by your controller:

public ActionResult ACTION(string id, string otherParam, string anotherParam) {
   // Your code
          }

Reading in from System.in - Java

class myFileReaderThatStarts with arguments
{

 class MissingArgumentException extends Exception{      
      MissingArgumentException(String s)
  {
     super(s);
  }

   }    
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value 
if(args.length>0)
{
    // do something with args[0]
}
else
{
// default in a path 
// or 
   throw new MissingArgumentException("You need to start this program with a path");
}
}

Remove Top Line of Text File with PowerShell

skip` didn't work, so my workaround is

$LinesCount = $(get-content $file).Count
get-content $file |
    select -Last $($LinesCount-1) | 
    set-content "$file-temp"
move "$file-temp" $file -Force

How to use random in BATCH script?

%RANDOM% gives you a random number between 0 and 32767.

Using an expression like SET /A test=%RANDOM% * 100 / 32768 + 1, you can change the range to anything you like (here the range is [1…100] instead of [0…32767]).

What is the difference between the | and || or operators?

The | operator performs a bitwise OR of its two operands (meaning both sides must evaluate to false for it to return false) while the || operator will only evaluate the second operator if it needs to.

http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx

http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx

pandas get rows which are NOT in other dataframe

This is the best way to do it:

df = df1.drop_duplicates().merge(df2.drop_duplicates(), on=df2.columns.to_list(), 
                   how='left', indicator=True)
df.loc[df._merge=='left_only',df.columns!='_merge']

Note that drop duplicated is used to minimize the comparisons. It would work without them as well. The best way is to compare the row contents themselves and not the index or one/two columns and same code can be used for other filters like 'both' and 'right_only' as well to achieve similar results. For this syntax dataframes can have any number of columns and even different indices. Only the columns should occur in both the dataframes.

Why this is the best way?

  1. index.difference only works for unique index based comparisons
  2. pandas.concat() coupled with drop_duplicated() is not ideal because it will also get rid of the rows which may be only in the dataframe you want to keep and are duplicated for valid reasons.

How to force a line break in a long word in a DIV?

From MDN:

The overflow-wrap CSS property specifies whether or not the browser should insert line breaks within words to prevent text from overflowing its content box.

In contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing.

So you can use:

overflow-wrap: break-word;

Can I use?

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

Set selected radio from radio group with a value

Try this:

$('input:radio[name="mygroup"][value="5"]').attr('checked',true);

JS Fiddle demo.

How to inject window into a service?

This is working for me currently (2018-03, angular 5.2 with AoT, tested in angular-cli and a custom webpack build):

First, create an injectable service that provides a reference to window:

import { Injectable } from '@angular/core';

// This interface is optional, showing how you can add strong typings for custom globals.
// Just use "Window" as the type if you don't have custom global stuff
export interface ICustomWindow extends Window {
    __custom_global_stuff: string;
}

function getWindow (): any {
    return window;
}

@Injectable()
export class WindowRefService {
    get nativeWindow (): ICustomWindow {
        return getWindow();
    }
}

Now, register that service with your root AppModule so it can be injected everywhere:

import { WindowRefService } from './window-ref.service';

@NgModule({        
  providers: [
    WindowRefService 
  ],
  ...
})
export class AppModule {}

and then later on where you need to inject window:

import { Component} from '@angular/core';
import { WindowRefService, ICustomWindow } from './window-ref.service';

@Component({ ... })
export default class MyCoolComponent {
    private _window: ICustomWindow;

    constructor (
        windowRef: WindowRefService
    ) {
        this._window = windowRef.nativeWindow;
    }

    public doThing (): void {
        let foo = this._window.XMLHttpRequest;
        let bar = this._window.__custom_global_stuff;
    }
...

You may also wish to add nativeDocument and other globals to this service in a similar way if you use these in your application.


edit: Updated with Truchainz suggestion. edit2: Updated for angular 2.1.2 edit3: Added AoT notes edit4: Adding any type workaround note edit5: Updated solution to use a WindowRefService which fixes an error I was getting when using previous solution with a different build edit6: adding example custom Window typing

Where does flask look for image files?

From the documentation:

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

url_for('static', filename='style.css')

The file has to be stored on the filesystem as static/style.css.

Executing multiple commands from a Windows cmd script

If you are running in Windows you can use the following command.

Drive:

cd "Script location"
schtasks /run /tn "TASK1"
schtasks /run /tn "TASK2"
schtasks /run /tn "TASK3"
exit

Syntax behind sorted(key=lambda: ...)

key is a function that will be called to transform the collection's items before they are compared. The parameter passed to key must be something that is callable.

The use of lambda creates an anonymous function (which is callable). In the case of sorted the callable only takes one parameters. Python's lambda is pretty simple. It can only do and return one thing really.

The syntax of lambda is the word lambda followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while, for, if and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.

We can compare the use of lambda with that of def to create a function.

adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2

lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.

variable is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.

How to move all files including hidden files into parent directory via *

I think this is the most elegant, as it also does not try to move ..:

mv /source/path/{.[!.],}* /destination/path

Copying files from server to local computer using SSH

that scp command must be issued on the local command-line, for putty the command is pscp.

C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\

Get specific objects from ArrayList when objects were added anonymously?

You could simply create a method to get the object by it's name.

public Party getPartyByName(String name) {
    for(Party party : parties) {
        if(name.equalsIgnoreCase(party.name)) {
            return party;
        }
    }
    return null;
}

Convert DataSet to List

Use the code below:

using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);

get index of DataTable column with name

Try this:

int index = row.Table.Columns["ColumnName"].Ordinal;

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);

How to convert an array to object in PHP?

function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

function array_to_object($data)
{
    if (is_array($data) || is_object($data))
    {
        $result= new stdClass();
        foreach ($data as $key => $value)
        {
            $result->$key = array_to_object($value);
        }
        return $result;
    }
    return $data;
}

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

Facebook login "given URL not allowed by application configuration"

I kept getting this error, when using wildcard subdomains with my app. I had the site url set to: http://myapp.com and app domain also to http://myapp.com, and also the same value for the Valid OAuth redirect URIs in the advanced tab of the settings app. I tried different combinations but only setting the http://subdomain.myapp.com as the redirect value worked, of course only for that subdomain.

The solution was to empty the redirect fields, leave it blank, that worked! ;)

How to provide shadow to Button

Sample 9 patch image with shadow

After a lots of research I found an easy method.

Create a 9 patch image and apply it as button or any other view's background.

You can create a 9 patch image with shadow using this website.

Put the 9 patch image in your drawable directory and apply it as the background for the button.

mButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable.your_9_patch_image);

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

Alternatively, you could setup your submodules so that rather than being in their default detached head state you check out a branch.

Edited to add:

One way is to checkout a particular branch of the submodule when you add it with the -b flag:

git submodule add -b master <remote-repo> <path-to-add-it-to>

Another way is to just go into the submodule directory and just check it out

git checkout master

Differences between Ant and Maven

Just to list some more differences:

  • Ant doesn't have formal conventions. You have to tell Ant exactly where to find the source, where to put the outputs, etc.
  • Ant is procedural. You have to tell Ant exactly what to do; tell it to compile, copy, then compress, etc.
  • Ant doesn't have a lifecycle.
  • Maven uses conventions. It knows where your source code is automatically, as long as you follow these conventions. You don't need to tell Maven where it is.
  • Maven is declarative; All you have to do is create a pom.xml file and put your source in the default directory. Maven will take care of the rest.
  • Maven has a lifecycle. You simply call mvn install and a series of sequence steps are executed.
  • Maven has intelligence about common project tasks. To run tests, simple execute mvn test, as long as the files are in the default location. In Ant, you would first have to JUnit JAR file is, then create a classpath that includes the JUnit JAR, then tell Ant where it should look for test source code, write a goal that compiles the test source and then finally execute the unit tests with JUnit.

Update:

This came from Maven: The Definitive Guide. Sorry, I totally forgot to cite it.

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

memcpy() vs memmove()

C11 standard draft

The C11 N1570 standard draft says:

7.24.2.1 "The memcpy function":

2 The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

7.24.2.2 "The memmove function":

2 The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1

Therefore, any overlap on memcpy leads to undefined behavior, and anything can happen: bad, nothing or even good. Good is rare though :-)

memmove however clearly says that everything happens as if an intermediate buffer is used, so clearly overlaps are OK.

C++ std::copy is more forgiving however, and allows overlaps: Does std::copy handle overlapping ranges?

how to get login option for phpmyadmin in xampp

Can you set the password to the phpmyadmin here

http://localhost/security/index.php

What resources are shared between threads?

A process has code, data, heap and stack segments. Now, the Instruction Pointer (IP) of a thread OR threads points to the code segment of the process. The data and heap segments are shared by all the threads. Now what about the stack area? What is actually the stack area? Its an area created by the process just for its thread to use... because stacks can be used in a much faster way than heaps etc. The stack area of the process is divided among threads, i.e. if there are 3 threads, then the stack area of the process is divided into 3 parts and each is given to the 3 threads. In other words, when we say that each thread has its own stack, that stack is actually a part of the process stack area allocated to each thread. When a thread finishes its execution, the stack of the thread is reclaimed by the process. In fact, not only the stack of a process is divided among threads, but all the set of registers that a thread uses like SP, PC and state registers are the registers of the process. So when it comes to sharing, the code, data and heap areas are shared, while the stack area is just divided among threads.

How to store custom objects in NSUserDefaults

Synchronize the data/object that you have saved into NSUserDefaults

-(void)saveCustomObject:(Player *)object
{ 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [prefs setObject:myEncodedObject forKey:@"testing"];
    [prefs synchronize];
}

Hope this will help you. Thanks

What is the difference between class and instance methods?

So if I understand it correctly.

A class method does not need you to allocate instance of that object to use / process it. A class method is self contained and can operate without any dependence of the state of any object of that class. A class method is expected to allocate memory for all its own work and deallocate when done, since no instance of that class will be able to free any memory allocated in previous calls to the class method.

A instance method is just the opposite. You cannot call it unless you allocate a instance of that class. Its like a normal class that has a constructor and can have a destructor (that cleans up all the allocated memory).

In most probability (unless you are writing a reusable library, you should not need a class variable.

How to remove files from git staging area?

You can reset the staging area in a few ways:

  1. Reset HEAD and add all necessary files to check-in again as below:

     git reset HEAD ---> removes all files from the staging area
     git add <files, that are required to be committed>
     git commit -m "<commit message>"
     git push 
    

Getting the last element of a list

If you do my_list[-1] this returns the last element of the list. Negative sequence indexes represent positions from the end of the array. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

How to Implement DOM Data Binding in JavaScript

Yesterday, I started to write my own way to bind data.

It's very funny to play with it.

I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.

https://jsfiddle.net/2ozoovne/1/

<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />

Here is the code:

(function(){
    if ( ! ( 'SmartBind' in window ) ) { // never run more than once
        // This hack sets a "proxy" property for HTMLInputElement.value set property
        var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        newDescriptor.set=function( value ){
            if ( 'settingDomBind' in this )
                return;
            var hasDataBind=this.hasAttribute('data-bind');
            if ( hasDataBind ) {
                this.settingDomBind=true;
                var dataBind=this.getAttribute('data-bind');
                if ( ! this.hasAttribute('data-bind-context-id') ) {
                    console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
                } else {
                    var bindContextId=this.getAttribute('data-bind-context-id');
                    if ( bindContextId in SmartBind.contexts ) {
                        var bindContext=SmartBind.contexts[bindContextId];
                        var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
                        SmartBind.setDataValue( dataTarget, value);
                    } else {
                        console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
                    }
                }
                delete this.settingDomBind;
            }
            nativeHTMLInputElementValue.set.bind(this)( value );
        }
        Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);

    var uid= function(){
           return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
               var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
               return v.toString(16);
          });
   }

        // SmartBind Functions
        window.SmartBind={};
        SmartBind.BindContext=function(){
            var _data={};
            var ctx = {
                "id" : uid()    /* Data Bind Context Id */
                , "_data": _data        /* Real data object */
                , "mapDom": {}          /* DOM Mapped objects */
                , "mapDataTarget": {}       /* Data Mapped objects */
            }
            SmartBind.contexts[ctx.id]=ctx;
            ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data"))  /* Proxy object to _data */
            return ctx;
        }

        SmartBind.getDataTarget=function(bindContext, bindPath){
            var bindedObject=
                { bindContext: bindContext
                , bindPath: bindPath 
                };
            var dataObj=bindContext;
            var dataObjLevels=bindPath.split('.');
            for( var i=0; i<dataObjLevels.length; i++ ) {
                if ( i == dataObjLevels.length-1 ) { // last level, set value
                    bindedObject={ target: dataObj
                    , item: dataObjLevels[i]
                    }
                } else {    // digg in
                    if ( ! ( dataObjLevels[i] in dataObj ) ) {
                        console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
                        break;
                    }
                    dataObj=dataObj[dataObjLevels[i]];
                }
            }
            return bindedObject ;
        }

        SmartBind.contexts={};
        SmartBind.add=function(bindContext, domObj){
            if ( typeof domObj == "undefined" ){
                console.error("No DOM Object argument given ", bindContext);
                return;
            }
            if ( ! domObj.hasAttribute('data-bind') ) {
                console.warn("Object has no data-bind attribute", domObj);
                return;
            }
            domObj.setAttribute("data-bind-context-id", bindContext.id);
            var bindPath=domObj.getAttribute('data-bind');
            if ( bindPath in bindContext.mapDom ) {
                bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
            } else {
                bindContext.mapDom[bindPath]=[domObj];
            }
            var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
            bindContext.mapDataTarget[bindPath]=bindTarget;
            domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
            domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
        }

        SmartBind.setDataValue=function(bindTarget,value){
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                    bindTarget.target=lBindTarget.target;
                    bindTarget.item=lBindTarget.item;
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
                }
            }
            if ( ( 'target' in bindTarget ) ) {
                bindTarget.target[bindTarget.item]=value;
            }
        }
        SmartBind.getDataValue=function(bindTarget){
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                    bindTarget.target=lBindTarget.target;
                    bindTarget.item=lBindTarget.item;
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
                }
            }
            if ( ( 'target' in bindTarget ) ) {
                return bindTarget.target[bindTarget.item];
            }
        }
        SmartBind.getProxyHandler=function(bindContext, bindPath){
            return  {
                get: function(target, name){
                    if ( name == '__isProxy' )
                        return true;
                    // just get the value
                    // console.debug("proxy get", bindPath, name, target[name]);
                    return target[name];
                }
                ,
                set: function(target, name, value){
                    target[name]=value;
                    bindContext.mapDataTarget[bindPath+"."+name]=value;
                    SmartBind.processBindToDom(bindContext, bindPath+"."+name);
                    // console.debug("proxy set", bindPath, name, target[name], value );
                    // and set all related objects with this target.name
                    if ( value instanceof Object) {
                        if ( !( name in target) || ! ( target[name].__isProxy ) ){
                            target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
                        }
                        // run all tree to set proxies when necessary
                        var objKeys=Object.keys(value);
                        // console.debug("...objkeys",objKeys);
                        for ( var i=0; i<objKeys.length; i++ ) {
                            bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
                            if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
                                continue;
                            target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
                        }
                        // TODO it can be faster than run all items
                        var bindKeys=Object.keys(bindContext.mapDom);
                        for ( var i=0; i<bindKeys.length; i++ ) {
                            // console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
                            if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
                                // console.log("its ok, lets update dom...", bindKeys[i]);
                                SmartBind.processBindToDom( bindContext, bindKeys[i] );
                            }
                        }
                    }
                    return true;
                }
            };
        }
        SmartBind.processBindToDom=function(bindContext, bindPath) {
            var domList=bindContext.mapDom[bindPath];
            if ( typeof domList != 'undefined' ) {
                try {
                    for ( var i=0; i < domList.length ; i++){
                        var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
                        if ( 'target' in dataTarget )
                            domList[i].value=dataTarget.target[dataTarget.item];
                        else
                            console.warn("Could not get data target", bindContext, bindPath);
                    }
                } catch (e){
                    console.warn("bind fail", bindPath, bindContext, e);
                }
            }
        }
    }
})();

Then, to set, just:

var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));

var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));

setTimeout( function() {
    document.getElementById('b').value='Via Script works too!'
}, 2000);

document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})

For now, I've just added the HTMLInputElement value bind.

Let me know if you know how to improve it.

java - path to trustStore - set property doesn't work?

You have a typo - it is trustStore.

Apart from setting the variables with System.setProperty(..), you can also use

-Djavax.net.ssl.keyStore=path/to/keystore.jks

What is the equivalent of 'describe table' in SQL Server?

Use this Query

Select * From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME = 'TABLENAME'

Finding the number of days between two dates

Calculate the difference between two dates:

$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");

$diff=date_diff($date1,$date2);

echo $diff->format("%R%a days");

Output: +272 days

The date_diff() function returns the difference between two DateTime objects.

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

You can get such a problem when you are two different commands on same connection - especially calling the second command in a loop. That is calling the second command for each record returned from the first command. If there are some 10,000 records returned by the first command, this issue will be more likely.

I used to avoid such a scenario by making it as a single command.. The first command returns all the required data and load it into a DataTable.

Note: MARS may be a solution - but it can be risky and many people dislike it.

Reference

  1. What does "A severe error occurred on the current command. The results, if any, should be discarded." SQL Azure error mean?
  2. Linq-To-Sql and MARS woes - A severe error occurred on the current command. The results, if any, should be discarded
  3. Complex GROUP BY on DataTable