Programs & Examples On #Winscard

Smart Card Resource Manager Helper Library, implementing the Personal Computer/Smart Card API in Microsoft Windows 2000 and later.

Pytorch reshape tensor dimension

you might use

a.view(1,5)
Out: 

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

Array of an unknown length in C#

If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...

e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user

int n = 0;
bool isInteger = int.TryPase(Console.ReadLine(), out n);
var x = new int[n,n];

What is lexical scope?

Lexical scope means that a function looks up variables in the context where it was defined, and not in the scope immediately around it.

Look at how lexical scope works in Lisp if you want more detail. The selected answer by Kyle Cronin in Dynamic and Lexical variables in Common Lisp is a lot clearer than the answers here.

Coincidentally I only learned about this in a Lisp class, and it happens to apply in JavaScript as well.

I ran this code in Chrome's console.

// JavaScript               Equivalent Lisp
var x = 5;                //(setf x 5)
console.debug(x);         //(print x)
function print_x(){       //(defun print-x ()
    console.debug(x);     //    (print x)
}                         //)
(function(){              //(let
    var x = 10;           //    ((x 10))
    console.debug(x);     //    (print x)
    print_x();            //    (print-x)
})();                     //)

Output:

5
10
5

How to select rows in a DataFrame between two values, in Python Pandas?

you can also use .between() method

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")

emp[emp["Salary"].between(60000, 61000)]

Output

enter image description here

How to remove all the null elements inside a generic list in one go?

Easy and without LINQ:

while (parameterList.Remove(null)) {};

Pandas create empty DataFrame with only column names

df.to_html() has a columns parameter.

Just pass the columns into the to_html() method.

df.to_html(columns=['A','B','C','D','E','F','G'])

Pure css close button

Basic idea: For the a.boxclose:

border-radius: 40px;
width:20px;
height 10px;
background-color: #c0c0c0;
border: 1px solid black;
color: white;
padding-left: 10px;
padding-top: 4px;

Adding a "X" to the content of the close box.

http://jsfiddle.net/adzFe/1/

Quick and dirty, but works.

How to Set AllowOverride all

SuSE Linux Enterprise Server

Make sure you are editing the right file https://www.suse.com/documentation/sles11/book_sle_admin/data/sec_apache2_configuration.html

httpd.conf

The main Apache server configuration file. Avoid changing this file. It primarily contains include statements and global settings. Overwrite global settings in the pertinent configuration files listed here. Change host-specific settings (such as document root) in your virtual host configuration.

In such case vhosts.d/*.conf must be edited

How set background drawable programmatically in Android

If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..

Classes vs. Modules in VB.NET

You must use a Module (rather than a Class) if you're creating Extension methods. In VB.NET I'm not aware of another option.

Being resistant to Modules myself, I just spent a worthless couple of hours trying to work out how to add some boilerplate code to resolve embedded assemblies in one, only to find out that Sub New() (Module) and Shared Sub New() (Class) are equivalent. (I didn't even know there was a callable Sub New() in a Module!)

So I just threw the EmbeddedAssembly.Load and AddHandler AppDomain.CurrentDomain.AssemblyResolve lines in there and Bob became my uncle.

Addendum: I haven't checked it out 100% yet, but I have an inkling that Sub New() runs in a different order in a Module than a Class, just going by the fact that I had to move some declarations to inside methods from outside to avoid errors.

HTTP POST Returns Error: 417 "Expectation Failed."

The web.config approach works for InfoPath form services calls to IntApp web service enabled rules.

  <system.net>
    <defaultProxy />
    <settings> <!-- 20130323 bchauvin -->
        <servicePointManager expect100Continue="false" />
    </settings>
  </system.net>

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

Finding all positions of substring in a larger string in C#

using LINQ

public static IEnumerable<int> IndexOfAll(this string sourceString, string subString)
{
    return Regex.Matches(sourceString, subString).Cast<Match>().Select(m => m.Index);
}

Password encryption/decryption code in .NET

I use RC2CryptoServiceProvider.

    public static string EncryptText(string openText)
    {
        RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
        ICryptoTransform encryptor = rc2CSP.CreateEncryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                byte[] toEncrypt = Encoding.Unicode.GetBytes(openText);

                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
                csEncrypt.FlushFinalBlock();

                byte[] encrypted = msEncrypt.ToArray();

                return Convert.ToBase64String(encrypted);
            }
        }
    }

    public static string DecryptText(string encryptedText)
    {
        RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
        ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
        using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                List<Byte> bytes = new List<byte>();
                int b;
                do
                {
                    b = csDecrypt.ReadByte();
                    if (b != -1)
                    {
                        bytes.Add(Convert.ToByte(b));
                    }

                }
                while (b != -1);

                return Encoding.Unicode.GetString(bytes.ToArray());
            }
        }
    }

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

Meaning of *& and **& in C++

An int* is a pointer to an int, so int*& must be a reference to a pointer to an int. Similarly, int** is a pointer to a pointer to an int, so int**& must be a reference to a pointer to a pointer to an int.

Python popen command. Wait until the command is finished

Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call.

#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])

If you want to do things while it is executing or feed things into stdin, you can use communicate after the popen call.

#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process

As stated in the documentation, wait can deadlock, so communicate is advisable.

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

jQuery ui 1.9 is going to take care of this for you. Heres a demo of the pre:

https://dl.dropbox.com/u/3872624/lab/touch/index.html

Just grab the jquery.mouse.ui.js out, stick it under the jQuery ui file you're loading, and that's all you should have to do! Works for sortable as well.

This code is working great for me, but if your getting errors, an updated version of jquery.mouse.ui.js can be found here:

Jquery-ui sortable doesn't work on touch devices based on Android or IOS

How to get Spinner selected item value to string?

If your Spinner was populated by SQLite cursor, then the solution is:

Spinner mySpin = (Spinner) findViewById(R.id.myspin);
mySpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {  
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
           SQLiteCursor item = (SQLiteCursor) parent.getItemAtPosition(position);
           String value = String.valueOf(item.getString(0));
           Toast.makeText(getApplicationContext(), "The option is:" + value , Toast.LENGTH_SHORT).show(); 
 }

PS: In item.getString(0) -> 0 is the index of column on cursor that you want to get.

How do I trim whitespace?

You can also use very simple, and basic function: str.replace(), works with the whitespaces and tabs:

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

Simple and easy.

Using Python's ftplib to get a directory listing, portably

There's no standard for the layout of the LIST response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls and Windows Server DIR formats. There's a lot of variety out there, though.

Fall back to the nlst method (returning the result of the NLST command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.

Shorter syntax for casting from a List<X> to a List<Y>?

You can use List<Y>.ConvertAll<T>([Converter from Y to T]);

How to make a Python script run like a service or daemon in Linux

You have two options here.

  1. Make a proper cron job that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can read more at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.

  2. Use some kind of python approach (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).

I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.

Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by Ivan Nevostruev in comments to this answer). While if the script is added as a cron job, it will just trigger again.

Remove HTML Tags from an NSString on the iPhone

I have following the accepted answer by m.kocikowski and modified is slightly to make use of an autoreleasepool to cleanup all of the temporary strings that are created by stringByReplacingCharactersInRange

In the comment for this method it states, /* Replace characters in range with the specified string, returning new string. */

So, depending on the length of your XML you may be creating a huge pile of new autorelease strings which are not cleaned up until the end of the next @autoreleasepool. If you are unsure when that may happen or if a user action could repeatedly trigger many calls to this method before then you can just wrap this up in an @autoreleasepool. These can even be nested and used within loops where possible.

Apple's reference on @autoreleasepool states this... "If you write a loop that creates many temporary objects. You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application." I have not used it in the loop, but at least this method cleans up after itself now.

- (NSString *) stringByStrippingHTML {
    NSString *retVal;
    @autoreleasepool {
        NSRange r;
        NSString *s = [[self copy] autorelease];
        while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound) {
            s = [s stringByReplacingCharactersInRange:r withString:@""];
        }
        retVal = [s copy];
    } 
    // pool is drained, release s and all temp 
    // strings created by stringByReplacingCharactersInRange
    return retVal;
}

JavaScript CSS how to add and remove multiple CSS classes to an element

Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):

div.classList.add('foo', 'bar'); // add multiple classes

From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:

let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);

Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

ASP.Net MVC How to pass data from view to controller

<form action="myController/myAction" method="POST">
 <input type="text" name="valueINeed" />
 <input type="submit" value="View Report" />
</form> 

controller:

[HttpPost]
public ActionResult myAction(string valueINeed)
{
   //....
}

Enum String Name from Value

DB to C#

EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());

C# to DB

string dbStatus = ((int)status).ToString();

Instantly detect client disconnection from server socket

The example code here http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx shows how to determine whether the Socket is still connected without sending any data.

If you called Socket.BeginReceive() on the server program and then the client closed the connection "gracefully", your receive callback will be called and EndReceive() will return 0 bytes. These 0 bytes mean that the client "may" have disconnected. You can then use the technique shown in the MSDN example code to determine for sure whether the connection was closed.

Printf width specifier to maintain precision of floating-point value

I recommend @Jens Gustedt hexadecimal solution: use %a.

OP wants “print with maximum precision (or at least to the most significant decimal)”.

A simple example would be to print one seventh as in:

#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01

But let's dig deeper ...

Mathematically, the answer is "0.142857 142857 142857 ...", but we are using finite precision floating point numbers. Let's assume IEEE 754 double-precision binary. So the OneSeventh = 1.0/7.0 results in the value below. Also shown are the preceding and following representable double floating point numbers.

OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh        = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after  = 0.1428571428571428 769682682968777953647077083587646484375

Printing the exact decimal representation of a double has limited uses.

C has 2 families of macros in <float.h> to help us.
The first set is the number of significant digits to print in a string in decimal so when scanning the string back, we get the original floating point. There are shown with the C spec's minimum value and a sample C11 compiler.

FLT_DECIMAL_DIG   6,  9 (float)                           (C11)
DBL_DECIMAL_DIG  10, 17 (double)                          (C11)
LDBL_DECIMAL_DIG 10, 21 (long double)                     (C11)
DECIMAL_DIG      10, 21 (widest supported floating type)  (C99)

The second set is the number of significant digits a string may be scanned into a floating point and then the FP printed, still retaining the same string presentation. There are shown with the C spec's minimum value and a sample C11 compiler. I believe available pre-C99.

FLT_DIG   6, 6 (float)
DBL_DIG  10, 15 (double)
LDBL_DIG 10, 18 (long double)

The first set of macros seems to meet OP's goal of significant digits. But that macro is not always available.

#ifdef DBL_DECIMAL_DIG
  #define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else  
  #ifdef DECIMAL_DIG
    #define OP_DBL_Digs (DECIMAL_DIG)
  #else  
    #define OP_DBL_Digs (DBL_DIG + 3)
  #endif
#endif

The "+ 3" was the crux of my previous answer. Its centered on if knowing the round-trip conversion string-FP-string (set #2 macros available C89), how would one determine the digits for FP-string-FP (set #1 macros available post C89)? In general, add 3 was the result.

Now how many significant digits to print is known and driven via <float.h>.

To print N significant decimal digits one may use various formats.

With "%e", the precision field is the number of digits after the lead digit and decimal point. So - 1 is in order. Note: This -1 is not in the initial int Digs = DECIMAL_DIG;

printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01

With "%f", the precision field is the number of digits after the decimal point. For a number like OneSeventh/1000000.0, one would need OP_DBL_Digs + 6 to see all the significant digits.

printf("%.*f\n", OP_DBL_Digs    , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285

Note: Many are use to "%f". That displays 6 digits after the decimal point; 6 is the display default, not the precision of the number.

In LaTeX, how can one add a header/footer in the document class Letter?

After I removed

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

it seems to have worked "correctly".

It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

FYI: MikTeX 2.7 under Vista

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

If you want to use them as in swift 2, you can use these funcs:

For CGRectMake:

func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
    return CGRect(x: x, y: y, width: width, height: height)
}

For CGPointMake:

func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
    return CGPoint(x: x, y: y)
}

For CGSizeMake:

func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
    return CGSize(width: width, height: height)
}

Just put them outside any class and it should work. (Works for me at least)

Why XML-Serializable class need a parameterless constructor

First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?

I think there is a workaround to make constructor private.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

EDIT :
http://codepen.io/gcyrillus/pen/daCyu So for a popup, you have to use position:fixed , display:table property and max-width with em or rem values :)
with this CSS basis :

#popup {
  position:fixed;
  width:100%;
  height:100%;
  display:table;
  pointer-events:none;
}
#popup > div {
  display:table-cell;
  vertical-align:middle;
}
#popup p {
  width:80%;
  max-width:20em;
  margin:auto;
  pointer-events:auto;
}

What is the difference between screenX/Y, clientX/Y and pageX/Y?

What helped me was to add an event directly to this page and click around for myself! Open up your console in developer tools/Firebug etc and paste this:

_x000D_
_x000D_
document.addEventListener('click', function(e) {_x000D_
  console.log(_x000D_
    'page: ' + e.pageX + ',' + e.pageY,_x000D_
    'client: ' + e.clientX + ',' + e.clientY,_x000D_
    'screen: ' + e.screenX + ',' + e.screenY)_x000D_
}, false);
_x000D_
Click anywhere
_x000D_
_x000D_
_x000D_

With this snippet, you can track your click position as you scroll, move the browser window, etc.

Notice that pageX/Y and clientX/Y are the same when you're scrolled all the way to the top!

Get type of all variables

lapply(your_dataframe, class) gives you something like:

$tikr [1] "factor"

$Date [1] "Date"

$Open [1] "numeric"

$High [1] "numeric"

... etc.

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

Self-explanatory code follows which first creates a std::tm corresponding to 10-10-2012 12:38:40, converts that to a std::chrono::system_clock::time_point, adds 0.123456 seconds, and then prints that out by converting back to a std::tm. How to handle the fractional seconds is in the very last step.

#include <iostream>
#include <chrono>
#include <ctime>

int main()
{
    // Create 10-10-2012 12:38:40 UTC as a std::tm
    std::tm tm = {0};
    tm.tm_sec = 40;
    tm.tm_min = 38;
    tm.tm_hour = 12;
    tm.tm_mday = 10;
    tm.tm_mon = 9;
    tm.tm_year = 112;
    tm.tm_isdst = -1;
    // Convert std::tm to std::time_t (popular extension)
    std::time_t tt = timegm(&tm);
    // Convert std::time_t to std::chrono::system_clock::time_point
    std::chrono::system_clock::time_point tp = 
                                     std::chrono::system_clock::from_time_t(tt);
    // Add 0.123456 seconds
    // This will not compile if std::chrono::system_clock::time_point has
    //   courser resolution than microseconds
    tp += std::chrono::microseconds(123456);
    
    // Now output tp

    // Convert std::chrono::system_clock::time_point to std::time_t
    tt = std::chrono::system_clock::to_time_t(tp);
    // Convert std::time_t to std::tm (popular extension)
    tm = std::tm{0};
    gmtime_r(&tt, &tm);
    // Output month
    std::cout << tm.tm_mon + 1 << '-';
    // Output day
    std::cout << tm.tm_mday << '-';
    // Output year
    std::cout << tm.tm_year+1900 << ' ';
    // Output hour
    if (tm.tm_hour <= 9)
        std::cout << '0';
    std::cout << tm.tm_hour << ':';
    // Output minute
    if (tm.tm_min <= 9)
        std::cout << '0';
    std::cout << tm.tm_min << ':';
    // Output seconds with fraction
    //   This is the heart of the question/answer.
    //   First create a double-based second
    std::chrono::duration<double> sec = tp - 
                                    std::chrono::system_clock::from_time_t(tt) +
                                    std::chrono::seconds(tm.tm_sec);
    //   Then print out that double using whatever format you prefer.
    if (sec.count() < 10)
        std::cout << '0';
    std::cout << std::fixed << sec.count() << '\n';
}

For me this outputs:

10-10-2012 12:38:40.123456

Your std::chrono::system_clock::time_point may or may not be precise enough to hold microseconds.

Update

An easier way is to just use this date library. The code simplifies down to (using C++14 duration literals):

#include "date.h"
#include <iostream>
#include <type_traits>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    static_assert(std::is_same<decltype(t),
                               time_point<system_clock, microseconds>>{}, "");
    std::cout << t << '\n';
}

which outputs:

2012-10-10 12:38:40.123456

You can skip the static_assert if you don't need to prove that the type of t is a std::chrono::time_point.

If the output isn't to your liking, for example you would really like dd-mm-yyyy ordering, you could:

#include "date.h"
#include <iomanip>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    using namespace std;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    auto dp = floor<days>(t);
    auto time = make_time(t-dp);
    auto ymd = year_month_day{dp};
    cout.fill('0');
    cout << ymd.day() << '-' << setw(2) << static_cast<unsigned>(ymd.month())
         << '-' << ymd.year() << ' ' << time << '\n';
}

which gives exactly the requested output:

10-10-2012 12:38:40.123456

Update

Here is how to neatly format the current time UTC with milliseconds precision:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    std::cout << date::format("%F %T\n", time_point_cast<milliseconds>(system_clock::now()));
}

which just output for me:

2016-10-17 16:36:02.975

C++17 will allow you to replace time_point_cast<milliseconds> with floor<milliseconds>. Until then date::floor is available in "date.h".

std::cout << date::format("%F %T\n", date::floor<milliseconds>(system_clock::now()));

Update C++20

In C++20 this is now simply:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    auto t = sys_days{10d/10/2012} + 12h + 38min + 40s + 123456us;
    std::cout << t << '\n';
}

Or just:

std::cout << std::chrono::system_clock::now() << '\n';

std::format will be available to customize the output.

export html table to csv

Should work on every modern browser and without jQuery or any dependency, here my implementation :

// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ',') {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
            // Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
            data = data.replace(/"/g, '""');
            // Push escaped string
            row.push('"' + data + '"');
        }
        csv.push(row.join(separator));
    }
    var csv_string = csv.join('\n');
    // Download it
    var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

Then add your download button/link :

<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>

CSV file is timedated and compatible with default Excel format.

Update after comments: Added second parameter "separator", it can be used to configure another character like ;, it's useful if you have user downloading your csv in different region of the world because they can use another default separator for Excel, for more information see : https://superuser.com/a/606274/908273

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

Well the first option I could think of is that you could send a list request with search parameters for your file, like title="File_1.xml" and fileExtension="xml". It will either return an empty list of files (there isn't one matching the serach criteria), or return a list with at least one file. If it's only one - it's easy. But if there are more - you'll have to select one of them based on some other fields. Remember that in gdrive you could have more than 1 file with the same name. So the more search parameters you provide, the better.

Set View Width Programmatically

check it in mdpi device.. If the ad displays correctly, the error should be in "px" to "dip" conversion..

How to resize an image to a specific size in OpenCV?

You can use CvInvoke.Resize for Emgu.CV 3.0

e.g

CvInvoke.Resize(inputImage, outputImage, new System.Drawing.Size(100, 100), 0, 0, Inter.Cubic);

Details are here

Reading file using relative path in python project

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
    test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

Page redirect after certain time PHP

You can try this:

header('Refresh: 10; URL=http://yoursite.com/page.php');

Where 10 is in seconds.

SQL - Create view from multiple tables

Thanks for the help. This is what I ended up doing in order to make it work.

CREATE VIEW V AS
    SELECT *
    FROM ((POP NATURAL FULL OUTER JOIN FOOD)
    NATURAL FULL OUTER JOIN INCOME);

Check if a file is executable

Take a look at the various test operators (this is for the test command itself, but the built-in BASH and TCSH tests are more or less the same).

You'll notice that -x FILE says FILE exists and execute (or search) permission is granted.

BASH, Bourne, Ksh, Zsh Script

if [[ -x "$file" ]]
then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
fi

TCSH or CSH Script:

if ( -x "$file" ) then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
endif

To determine the type of file it is, try the file command. You can parse the output to see exactly what type of file it is. Word 'o Warning: Sometimes file will return more than one line. Here's what happens on my Mac:

$ file /bin/ls    
/bin/ls: Mach-O universal binary with 2 architectures
/bin/ls (for architecture x86_64):  Mach-O 64-bit executable x86_64
/bin/ls (for architecture i386):    Mach-O executable i386

The file command returns different output depending upon the OS. However, the word executable will be in executable programs, and usually the architecture will appear too.

Compare the above to what I get on my Linux box:

$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), stripped

And a Solaris box:

$ file /bin/ls
/bin/ls:        ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped

In all three, you'll see the word executable and the architecture (x86-64, i386, or SPARC with 32-bit).


Addendum

Thank you very much, that seems the way to go. Before I mark this as my answer, can you please guide me as to what kind of script shell check I would have to perform (ie, what kind of parsing) on 'file' in order to check whether I can execute a program ? If such a test is too difficult to make on a general basis, I would at least like to check whether it's a linux executable or osX (Mach-O)

Off the top of my head, you could do something like this in BASH:

if [ -x "$file" ] && file "$file" | grep -q "Mach-O"
then
    echo "This is an executable Mac file"
elif [ -x "$file" ] && file "$file" | grep -q "GNU/Linux"
then
    echo "This is an executable Linux File"
elif [ -x "$file" ] && file "$file" | grep q "shell script"
then
    echo "This is an executable Shell Script"
elif [ -x "$file" ]
then
    echo "This file is merely marked executable, but what type is a mystery"
else
    echo "This file isn't even marked as being executable"
fi

Basically, I'm running the test, then if that is successful, I do a grep on the output of the file command. The grep -q means don't print any output, but use the exit code of grep to see if I found the string. If your system doesn't take grep -q, you can try grep "regex" > /dev/null 2>&1.

Again, the output of the file command may vary from system to system, so you'll have to verify that these will work on your system. Also, I'm checking the executable bit. If a file is a binary executable, but the executable bit isn't on, I'll say it's not executable. This may not be what you want.

What does %>% function mean in R?

My understanding after reading the link offered by G.Grothendieck is that %>% is an operator that pipes functions. This helps readability and productivity as it's easier to follow the flow of multiple functions through these pipes than going backwards when multiple function are nested.

How do you get a directory listing sorted by creation date in python?

This was my version:

import os

folder_path = r'D:\Movies\extra\new\dramas' # your path
os.chdir(folder_path) # make the path active
x = sorted(os.listdir(), key=os.path.getctime)  # sorted using creation time

folder = 0

for folder in range(len(x)):
    print(x[folder]) # print all the foldername inside the folder_path
    folder = +1

Android, getting resource ID from string?

How to get an application resource id from the resource name is quite a common and well answered question.

How to get a native Android resource id from the resource name is less well answered. Here's my solution to get an Android drawable resource by resource name:

public static Drawable getAndroidDrawable(String pDrawableName){
    int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", "android");
    if(resourceId==0){
        return null;
    } else {
        return Resources.getSystem().getDrawable(resourceId);
    }
}

The method can be modified to access other types of resources.

How does Python return multiple values from a function?

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

What does yield mean in PHP?

An interesting aspect, which worth to be discussed here, is yielding by reference. Every time we need to change a parameter such that it is reflected outside of the function, we have to pass this parameter by reference. To apply this to generators, we simply prepend an ampersand & to the name of the generator and to the variable used in the iteration:

 <?php 
 /**
 * Yields by reference.
 * @param int $from
 */
function &counter($from) {
    while ($from > 0) {
        yield $from;
    }
}

foreach (counter(100) as &$value) {
    $value--;
    echo $value . '...';
}

// Output: 99...98...97...96...95...

The above example shows how changing the iterated values within the foreach loop changes the $from variable within the generator. This is because $from is yielded by reference due to the ampersand before the generator name. Because of that, the $value variable within the foreach loop is a reference to the $from variable within the generator function.

How can I write to the console in PHP?

I find this helpful:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        $output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';

        echo $output;
    }
}

And use it like:

<?php
    $debug = 5; // All lower and equal priority logs will be displayed
    console('Important', 1 , $debug);
    console('Less Important', 2 , $debug);
    console('Even Less Important', 5 , $debug);
    console('Again Important', 1 , $debug);
?>

Which outputs in console:

Important
 Less Important
     Even Less Important
Again Important

And you can switch off less important logs by limiting them using the $debug value.

Set custom HTML5 required field validation message

Just need to get the element and use the method setCustomValidity.

Example

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

Copy rows from one Datatable to another DataTable?

Copy Specified Rows from Table to another

// here dttablenew is a new Table  and dttableOld is table Which having the data 

dttableNew  = dttableOld.Clone();  

foreach (DataRow drtableOld in dttableOld.Rows)
{
   if (/*put some Condition */)
   {
      dtTableNew.ImportRow(drtableOld);
   }
}

C error: undefined reference to function, but it IS defined

I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c file) from C++ code.

The .h file for the C function wasn't wrapped in this sort of guard:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:

extern "C" {
#include "legacy_C_header.h"
}

(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)

How to change folder with git bash?

The command is:

cd  /c/project/

Tip:
Use the pwd command to see which path you are currently in, handy when you did a right-click "Git Bash here..."

How do I use Spring Boot to serve static content located in Dropbox folder?

You can add your own static resource handler (it overwrites the default), e.g.

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("file:/path/to/my/dropbox/");
    }
}

There is some documentation about this in Spring Boot, but it's really just a vanilla Spring MVC feature.

Also since spring boot 1.2 (I think) you can simply set spring.resources.staticLocations.

Array from dictionary keys in swift

NSDictionary is Class(pass by reference) NSDictionary is class type Dictionary is Structure(pass by value) Dictionary is structure of key and value ====== Array from NSDictionary ======

NSDictionary has allKeys and allValues get properties with type [Any].NSDictionary has get [Any] properties for allkeys and allvalues

  let objesctNSDictionary = 
    NSDictionary.init(dictionary: ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"])
            let objectArrayOfAllKeys:Array = objesctNSDictionary.allKeys
            let objectArrayOfAllValues:Array = objesctNSDictionary.allValues
            print(objectArrayOfAllKeys)
            print(objectArrayOfAllValues)

====== Array From Dictionary ======

Apple reference for Dictionary's keys and values properties. enter image description here

enter image description here

let objectDictionary:Dictionary = 
            ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
    let objectArrayOfAllKeys:Array = Array(objectDictionary.keys)          
    let objectArrayOfAllValues:Array = Array(objectDictionary.values)
    print(objectArrayOfAllKeys)
    print(objectArrayOfAllValues)

Convert a list to a data frame

The following simple command worked for me:

myDf <- as.data.frame(myList)

Reference (Quora answer)

> myList <- list(a = c(1, 2, 3), b = c(4, 5, 6))
> myList
$a
[1] 1 2 3

$b
[1] 4 5 6

> myDf <- as.data.frame(myList)
  a b
1 1 4
2 2 5
3 3 6
> class(myDf)
[1] "data.frame"

But this will fail if it’s not obvious how to convert the list to a data frame:

> myList <- list(a = c(1, 2, 3), b = c(4, 5, 6, 7))
> myDf <- as.data.frame(myList)
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 3, 4

Note: The answer is toward the title of the question and may skips some details of the question

Any way of using frames in HTML5?

I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

How can I commit a single file using SVN over a network?

  1. svn add filename.html
  2. svn commit -m"your comment"
  3. You dont have to push

Connection string using Windows Authentication

For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.

Basically this works:

<connectionStrings>      
<add name="MyConnectionString"
         connectionString="data source=ServerName;
   Initial Catalog=DatabaseName;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
</connectionStrings> 

Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.

It is also working different according which provider you are using.

  • SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.

  • OleDb it is Integrated Security=SSPI;

  • Odbc it is Trusted_Connection=yes;
  • OracleClient it is Integrated Security=yes;

Integrated Security=true throws an exception when used with the OleDb provider.

How do I update zsh to the latest version?

I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

This worked for me!

function main() {
  var time = readLine();
  var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
  var separators = [':', ' M'];
  var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
  if (parseInt(hms[0]) < 12 && hms[3] == 'P')
      hms[0] = parseInt(hms[0]) + 12;
  else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
      hms[0] = '00';
  console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);

}

How do I run Redis on Windows?

i updated the way you can compile and run redis 5 on windows 10 using cygwin https://github.com/meiry/redis5_compiled_for_windows10

How could I convert data from string to long in c#

long l1 = Convert.ToInt64(strValue);

That should do it.

delete image from folder PHP

You can try this code. This is Simple PHP Image Deleting code from the server.

<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>

<?php
if (isset($_POST['submit'])) 
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
  {
  echo ("Error deleting $photoname");
  }
else
  {
  echo ("Deleted $photoname");
  }
}
?>

Prevent text selection after double click

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me. Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

Locate Git installation folder on Mac OS X

On most of UNIX based sys, its at /usr/bin/git (if installed with default options)
all git related scripts are at /usr/libexec/git-core

Git: How to check if a local repo is up to date?

tried to format my answer, but couldn't.Please stackoverflow team, why posting answer is so hard.

neverthless,

answer:
git fetch origin
git status (you'll see result like "Your branch is behind 'origin/master' by 9 commits")
to update to remote changes : git pull

Fullscreen Activity in Android?

show Full Immersive:

private void askForFullScreen()
    {
        getActivity().getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

move out of full immersive mode:

 private void moveOutOfFullScreen() {
        getActivity().getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

How do I pass JavaScript values to Scriptlet in JSP?

simple, you can't!

JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.

How can I save multiple documents concurrently in Mongoose/Node.js?

Add a file called mongoHelper.js

var MongoClient = require('mongodb').MongoClient;

MongoClient.saveAny = function(data, collection, callback)
{
    if(data instanceof Array)
    {
        saveRecords(data,collection, callback);
    }
    else
    {
        saveRecord(data,collection, callback);
    }
}

function saveRecord(data, collection, callback)
{
    collection.save
    (
        data,
        {w:1},
        function(err, result)
        {
            if(err)
                throw new Error(err);
            callback(result);
        }
    );
}
function saveRecords(data, collection, callback)
{
    save
    (
        data, 
        collection,
        callback
    );
}
function save(data, collection, callback)
{
    collection.save
    (
        data.pop(),
        {w:1},
        function(err, result)
        {
            if(err)
            {               
                throw new Error(err);
            }
            if(data.length > 0)
                save(data, collection, callback);
            else
                callback(result);
        }
    );
}

module.exports = MongoClient;

Then in your code change you requires to

var MongoClient = require("./mongoHelper.js");

Then when it is time to save call (after you have connected and retrieved the collection)

MongoClient.saveAny(data, collection, function(){db.close();});

You can change the error handling to suit your needs, pass back the error in the callback etc.

How to compare 2 dataTables

 public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)
 {
    if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
                return false;


    for ( int i = 0; i < tbl1.Rows.Count; i++)
    {
        for ( int c = 0; c < tbl1.Columns.Count; c++)
        {
            if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))
                        return false;
        }
     }
     return true;
  }

How to build jars from IntelliJ properly?

I recently had this problem and think these steps are easy to follow if any prior solution or link is missing detail.

How to create a .jar using IntelliJ IDEA 14.1.5:

  1. File > Save All.
  2. Run driver or class with main method.
  3. File > Project Structure.
  4. Select Tab "Artifacts".
  5. Click green plus button near top of window.
  6. Select JAR from Add drop down menu. Select "From modules with dependencies"
  7. Select main class.
  8. The radio button should be selecting "extract to the target JAR." Press OK.
  9. Check the box "Build on make"
  10. Press apply and OK.
  11. From the main menu, select the build dropdown.
  12. Select the option build artifacts.

Lambda expression to convert array/List of String to array/List of Integers

I used maptoInt() with Lambda operation for converting string to Integer

int[] arr = Arrays.stream(stringArray).mapToInt(item -> Integer.parseInt(item)).toArray();

How do I pull from a Git repository through an HTTP proxy?

Just to post this as it is the first result on Google, this blog post I found solves the problem for me by updated the curl certificates.

http://www.simplicidade.org/notes/archives/2011/06/github_ssl_ca_errors.html

Check if file is already open

(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)

This whole issue is fraught with portability issues and race conditions:

  • You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
  • It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
  • Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.

A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.

Notes:

  1. If you use the Files API instead of the File API you will get more information in the event of a failure.

  2. On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.

LINQ syntax where string value is not null or empty

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL. Proposed Solution Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post

How can I check for "undefined" in JavaScript?

In this article I read that frameworks like Underscore.js use this function:

function isUndefined(obj){
    return obj === void 0;
}

How to apply slide animation between two activities in Android?

Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.

Slide animations can be slid right, slide left, slide up and slide down.

Slide up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:toXScale="1.0"
        android:toYScale="0.0" />
</set>

Slide down

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

overridePendingTransition(R.anim.slide_down, R.anim.slide_up);

See activity transition animation examples for more activity transition examples.

Changing specific text's color using NSMutableAttributedString in Swift

You can use this method. I implemented this method in my common utility class to access globally.

func attributedString(with highlightString: String, normalString: String, highlightColor: UIColor) -> NSMutableAttributedString {
    let attributes = [NSAttributedString.Key.foregroundColor: highlightColor]
    let attributedString = NSMutableAttributedString(string: highlightString, attributes: attributes)
    attributedString.append(NSAttributedString(string: normalString))
    return attributedString
}

Pandas: ValueError: cannot convert float NaN to integer

For identifying NaN values use boolean indexing:

print(df[df['x'].isnull()])

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')

And for remove all rows with NaNs in column x use dropna:

df = df.dropna(subset=['x'])

Last convert values to ints:

df['x'] = df['x'].astype(int)

How to check for palindrome using Python logic

A pythonic way to determine if a given value is a palindrome:

str(n) == str(n)[::-1]

Explanation:

  • We're checking if the string representation of n equals the inverted string representation of n
  • The [::-1] slice takes care of inverting the string
  • After that, we compare for equality using ==

Pass in an enum as a method parameter

First change the method parameter Enum supportedPermissions to SupportedPermissions supportedPermissions.

Then create your file like this

file = new File
{  
    Name = name,
    Id = id,
    Description = description,
    SupportedPermissions = supportedPermissions
};

And the call to your method should be

CreateFile(id, name, description, SupportedPermissions.basic);

How to create a JPA query with LEFT OUTER JOIN

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

Print debugging info from stored procedure in MySQL

Option 1: Put this in your procedure to print 'comment' to stdout when it runs.

SELECT 'Comment';

Option 2: Put this in your procedure to print a variable with it to stdout:

declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);

This prints myvar is 5 to stdout when the procedure runs.

Option 3, Create a table with one text column called tmptable, and push messages to it:

declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);

You could put the above in a stored procedure, so all you would have to write is this:

CALL log(concat('the value is', myvar));

Which saves a few keystrokes.

Option 4, Log messages to file

select "penguin" as log into outfile '/tmp/result.txt';

There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.

Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.

curl POST format for CURLOPT_POSTFIELDS

EDIT: From php5 upwards, usage of http_build_query is recommended:

string http_build_query ( mixed $query_data [, string $numeric_prefix [, 
                          string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Simple example from the manual:

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";

/* output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

?>

before php5:

From the manual:

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

So something like this should work perfectly (with parameters passed in a associative array):

function preparePostFields($array) {
  $params = array();

  foreach ($array as $key => $value) {
    $params[] = $key . '=' . urlencode($value);
  }

  return implode('&', $params);
}

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

You simply need to upgrade your Tomcat version, to Tomcat 8.0.xx. Java8 <-> Tomcat8

This is the configuration that I have been using and it has always worked out well JDK version Tomcat versions

Byte Array to Hex String

hex_string = "".join("%02x" % b for b in array_alpha)

Cannot implicitly convert type 'int' to 'short'

Microsoft converts your Int16 variables into Int32 when doing the add function.

Change the following:

Int16 answer = firstNo + secondNo;

into...

Int16 answer = (Int16)(firstNo + secondNo);

What is the difference between a data flow diagram and a flow chart?

You should use whatever you like. The diagram is just a tool. Use whatever tool fits you and your problem best. I usually just use boxes and arrows and squiggles and circles and little stick figures and whatever else I think gets the point across to the viewer. In short it doesn't matter if you even use a standard diagraming standard. People are usually pretty good at understanding pictures.

Where does forever store console.log output?

This worked for me :

forever -a -o out.log -e err.log app.js

gcc error: wrong ELF class: ELFCLASS64

I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.

You can try to recompile computation.c with the '-m64' flag of gcc(1)

Can you animate a height change on a UITableViewCell when selected?

BOOL flag;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    flag = !flag;
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:@[indexPath] 
                     withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES == flag ? 20 : 40;
}

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

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

in Macbooks, you can use shift + cmd + 7 to comment a previously highlighted block

Maximum and Minimum values for ints

Python 3

In Python 3, this question doesn't apply. The plain int type is unbounded.

However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence.

Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2). See this answer for more information.

Python 2

In Python 2, the maximum value for plain int values is available as sys.maxint:

>>> sys.maxint
9223372036854775807

You can calculate the minimum value with -sys.maxint - 1 as shown here.

Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.

How do you change the document font in LaTeX?

For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:

\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}

It's the fontspec package that allows for \setmainfont and \setmonofont. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.

Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

How to SHUTDOWN Tomcat in Ubuntu?

if you are run this command

 debian@debian:~$  /usr/share/tomcat7/bin/shutdown.sh
 then your server will not stop and you will get o/p like that you provided if you use in 
 super user mode then effect will appear o/p will come like this

 debian@debian:~$ sudo /usr/share/tomcat7/bin/shutdown.sh
 [sudo] password for debian: 
 Using CATALINA_BASE:   /var/lib/tomcat
 Using CATALINA_HOME:   /var/lib/tomcat
 Using CATALINA_TMPDIR: /var/lib/tomcat/temp
 Using JRE_HOME:        /usr/lib/jvm/java-1.6.0-openjdk
 Using CLASSPATH:   /var/lib/tomcat/bin/bootstrap.jar:/var/lib/tomcat/bin/tomcat-juli.jar

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

A simpler version of your code would be:

dict(zip(names, d.values()))

If you want to keep the same structure, you can change it to:

vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}

(You can just as easily put list(d.values()) inside the comprehension instead of vlst; it's just wasteful to do so since it would be re-generating the list every time).

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

When Modernizr runs, it removes the "no-js" class and replaces it with "js". This is a way to apply different CSS rules depending on whether or not Javascript support is enabled.

See Modernizer's source code.

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

Nginx reverse proxy causing 504 Gateway Timeout

In my case i restart php for and it become ok.

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

Certificate has either expired or has been revoked

After all above step clean and Rebuild is also a factor.

Adding 30 minutes to time formatted as H:i in PHP

Just to expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):

// Return adjusted start and end times as an array.

function expandTimeByMinutes( $time, $beforeMinutes, $afterMinutes ) {

    $time = DateTime::createFromFormat( 'H:i', $time );
    $time->sub( new DateInterval( 'PT' . ( (integer) $beforeMinutes ) . 'M' ) );
    $startTime = $time->format( 'H:i' );
    $time->add( new DateInterval( 'PT' . ( (integer) $beforeMinutes + (integer) $afterMinutes ) . 'M' ) );
    $endTime = $time->format( 'H:i' );

    return [
        'startTime' => $startTime,
        'endTime'   => $endTime,
    ];
}

$adjustedStartEndTime = expandTimeByMinutes( '10:00', 30, 30 );

echo '<h1>Adjusted Start Time: ' . $adjustedStartEndTime['startTime'] . '</h1>' . PHP_EOL . PHP_EOL;
echo '<h1>Adjusted End Time: '   . $adjustedStartEndTime['endTime']   . '</h1>' . PHP_EOL . PHP_EOL;

store return json value in input hidden field

It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

Anyway, if that is an array wrapper, you'll want something like this:

$('#my-hidden-field').val(theObject[0].id);

You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;

This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

Test if a string contains any of the strings from an array

Here is one solution :

public static boolean containsAny(String str, String[] words)
{
   boolean bResult=false; // will be set, if any of the words are found
   //String[] words = {"word1", "word2", "word3", "word4", "word5"};

   List<String> list = Arrays.asList(words);
   for (String word: list ) {
       boolean bFound = str.contains(word);
       if (bFound) {bResult=bFound; break;}
   }
   return bResult;
}

Git push hangs when pushing to Github?

Its worth checking if you are using the cygwin git or an external git (ie github).

If whereis git returns just /cygdrive/c/Program Files (x86)/Git/cmd/git.exe or similar its best to install the cygwin git package, this solved the problem for me.

HashMap with multiple values under the same key

You can do it implicitly.

// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();

//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });

//edit value of a key
map.get(1)[0] = "othername";

This is very simple and effective. If you want values of diferent classes instead, you can do the following:

HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();

Convert named list to vector with values only

purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)

purrr::flatten_dbl(myList)
## [1] 1 2 3

java.lang.ClassNotFoundException: org.apache.log4j.Level

You need to download log4j and add in your classpath.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

You can try for following solutions step by step one of them should work for you.

I have tried all three steps but STEP 4 worked for me. Because I was using two different git accounts

STEP 1:

STEP 2

  • Check your current branch git branch if you are not on branch git checkout branch_name.

  • To create new branch use git checkout -b "new branch name" to switch on new branch use above command

STEP 3

  • In the special case that you are creating a new repository starting from an old repository that you used as a template (Don't do this if this is not your case). Completely erase the git files of the old repository so you can start a new one:

    rm -rf .git and repeat STEP 1

STEP 4

  • On windows, you can try putting write credentials or remove git credentials from the control panel by following way and repeat STEP 1

    Go to Win -> Control Panel -> Credential Manager -> Windows Credentials

enter image description here

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

Change UITableView height dynamically

Rob's solution is very nice, only thing that in his -(void)adjustHeightOfTableview method the calling of

[self.view needsUpdateConstraints]

does nothing, it just returns a flag, instead calling

[self.view setNeedsUpdateConstraints]

will make the desired effect.

What is a constant reference? (not a reference to a constant)

What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.

A constant reference/ Reference to a constant is denoted by:

int const &i = j; //or Alternatively
const int &i = j;
i = 1;            //Compilation Error

It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1) of variable j through const reference, i will results in error:

assignment of read-only reference ‘i’


icr=y;          // Can change the object it is pointing to so it's not like a const pointer...
icr=99;

Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.

First statement assigns the value y to i
Second statement assigns the value 99 to i

How to locate the Path of the current project directory in Java (IDE)?

File currDir = new File(".");
String path = currDir.getAbsolutePath();
System.out.println(path);

This will print . at the end. To remove, simply truncate the string by one char e.g.:

File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
System.out.println(path);

How to get body of a POST in php?

If you have the pecl/http extension installed, you can also use this:

$request = new http\Env\Request();
$request->getBody();

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to remove newlines from beginning and end of a string?

Try this

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}

Why use String.Format?

String.Format adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.

For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format (as well as xxx.WriteLine and other methods that support composite formatting) over normal concatenation operators.

How to kill a thread instantly in C#?

The reason it's hard to just kill a thread is because the language designers want to avoid the following problem: your thread takes a lock, and then you kill it before it can release it. Now anyone who needs that lock will get stuck.

What you have to do is use some global variable to tell the thread to stop. You have to manually, in your thread code, check that global variable and return if you see it indicates you should stop.

How to find the length of an array list?

System.out.println(myList.size());

Since no elements are in the list

output => 0

myList.add("newString");  // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());

Since one element is added to the list

output => 1

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

Return multiple values from a SQL Server function

Example of using a stored procedure with multiple out parameters

As User Mr. Brownstone suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:

Create PROCEDURE MultipleOutParameter
    @Input int,
    @Out1 int OUTPUT, 
    @Out2 int OUTPUT 
AS
BEGIN
    Select @Out1 = @Input + 1
    Select @Out2 = @Input + 2   
    Select 'this returns your normal Select-Statement' as Foo
          , 'amazing is it not?' as Bar

    -- Return can be used to get even more (afaik only int) values 
    Return(@Out1+@Out2+@Input)
END 

Calling the stored procedure

To execute the stored procedure a few local variables are needed to receive the value:

DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int 
EXEC @GetReturnResult = MultipleOutParameter  
    @Input = 1,
    @Out1 = @GetOut1 OUTPUT,
    @Out2 = @GetOut2 OUTPUT

To see the values content you can do the following

Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2 

This will be the result:

Result of Stored Procedure Call with multiple out parameters

jQuery get values of checked checkboxes into array

I refactored your code a bit and believe I came with the solution for which you were looking. Basically instead of setting searchIDs to be the result of the .map() I just pushed the values into an array.

$("#merge_button").click(function(event){
  event.preventDefault();

  var searchIDs = [];

  $("#find-table input:checkbox:checked").map(function(){
    searchIDs.push($(this).val());
  });

  console.log(searchIDs);
});

I created a fiddle with the code running.

@Resource vs @Autowired

As a note here: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext and SpringBeanAutowiringSupport.processInjectionBasedOnServletContext DOES NOT work with @Resource annotation. So, there are difference.

How to get streaming url from online streaming radio station

not that hard,

if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.

this is the stream url

"StreamUrl": "http://stream.radiotime.com/listen.stream?streamIds=3244651&rti=c051HQVbfRc4FEMbKg5RRVMzRU9KUBw%2fVBZHS0dPF1VIExNzJz0CGQtRcX8OS0o0CUkYRFJDDW8LEVRxGAEOEAcQXko%2bGgwSBBZrV1pQZgQZZxkWCA4L%7e%7e%7e",

which returns a JSON like that:

{
    "Streams": [
        {
            "StreamId": 3244651,
            "Reliability": 92,
            "Bandwidth": 64,
            "HasPlaylist": false,
            "MediaType": "MP3",
            "Url": "http://mp3hdfm32.hala.jo:8132",
            "Type": "Live"
        }
    ]
}

i believe that's the url you need: http://mp3hdfm32.hala.jo:8132

this is the station WebSite

Removing an activity from the history stack

You can use forwarding to remove the previous activity from the activity stack while launching the next one. There's an example of this in the APIDemos, but basically all you're doing is calling finish() immediately after calling startActivity().

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Using wamp do the following and hopefully, it will resolve an issue

Make these changes in PHP Options to correct:

max_execution_time   180

memory_limit   512M or your highest available

post_max_size  32M

upload_max_filesize   64M

How can I start an Activity from a non-Activity class?

Once you have obtained the context in your onTap() you can also do:

Intent myIntent = new Intent(mContext, theNewActivity.class);
mContext.startActivity(myIntent);

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

Powershell: How can I stop errors from being displayed in a script?

If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"

javascript create empty array of a given size

You can use both javascript methods repeat() and split() together.

" ".repeat(10).split(" ")

This code will create an array that has 10 item and each item is empty string.

_x000D_
_x000D_
const items = " ".repeat(10).split(" ")

document.getElementById("context").innerHTML = items.map((item, index) => index)

console.log("items: ", items)
_x000D_
<pre id="context">

</pre>
_x000D_
_x000D_
_x000D_

How can I clear console

#include <cstdlib>

void cls(){
#if defined(_WIN32) //if windows
    system("cls");

#else
    system("clear");    //if other
#endif  //finish

}

The just call cls() anywhere

Random date in C#

Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).

PHP mPDF save file as PDF

This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.

ob_clean();
$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');

How can I determine if a variable is 'undefined' or 'null'?

Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.

Avoiding NullPointerException in Java

You can use an interceptor before the method call. That is what aspect-oriented programming focus on.

Suppose M1(Object test) is a method and M2 is a method where we apply an aspect before a method call, M2(Object test2). If test2 != null then call M1, otherwise do another thing. It works for all methods with whom you want to apply an aspect for. If you want to apply an aspect for an instance field and constructor you can use AspectJ. Spring can also be the best choice for a method aspect.

ECONNREFUSED error when connecting to mongodb from node.js

very strange, but in my case, i switch wifi connection...

I use some public wifi and switch to my phone connection

How do you UDP multicast in Python?

To make the client code (from tolomea) work on Solaris you need to pass the ttl value for the IP_MULTICAST_TTL socket option as an unsigned char. Otherwise you will get an error. This worked for me on Solaris 10 and 11:

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
ttl = struct.pack('B', 2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

Using jQuery to center a DIV on the screen

You could use the CSS translate property:

position: absolute;
transform: translate(-50%, -50%);

Read this post for more details.

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

Difference between h:button and h:commandButton

h:button - clicking on a h:button issues a bookmarkable GET request.

h:commandbutton - Instead of a get request, h:commandbutton issues a POST request which sends the form data back to the server.

@RequestParam vs @PathVariable

@PathVariable - must be placed in the endpoint uri and access the query parameter value from the request
@RequestParam - must be passed as method parameter (optional based on the required property)
 http://localhost:8080/employee/call/7865467

 @RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
 public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = false) String callStatus) {

    }

http://localhost:8080/app/call/7865467?status=Cancelled

@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = true) String callStatus) {

}

How do I show the changes which have been staged?

Think about the gitk tool also , provided with git and very useful to see the changes

How to get the previous url using PHP

But you could make an own link for every from url.

Example: http://example.com?auth=holasite

In this example your site is: example.com

If somebody open that link it's give you the holasite value for the auth variable.

Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.

Like: $holasite = http://holasite.com (You could use mysql too..)

And just match it, and you have the url.

This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.

Form Submit jQuery does not work

Because when you call $( "#form_id" ).submit(); it triggers the external submit handler which prevents the default action, instead use

$( "#form_id" )[0].submit();       

or

$form.submit();//declare `$form as a local variable by using var $form = this;

When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element

pandas: multiple conditions while indexing data frame - unexpected behavior

As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.

That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1:

df1 = df[(df.a != -1) & (df.b != -1)]

You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1.

For df2:

df2 = df[(df.a != -1) | (df.b != -1)]

You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1.

PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc.

How to vertically center a "div" element for all browsers using CSS?

_x000D_
_x000D_
.center {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%); /* (x, y)  => position */_x000D_
  -ms-transform: translate(-50%, -50%); /* IE 9 */_x000D_
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */    _x000D_
}_x000D_
_x000D_
.vertical {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  //left: 0;_x000D_
  transform: translate(0, -50%); /* (x, y) => position */_x000D_
}_x000D_
_x000D_
.horizontal {_x000D_
  position: absolute;_x000D_
  //top: 0;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, 0); /* (x, y)  => position */_x000D_
}_x000D_
_x000D_
div {_x000D_
  padding: 1em;_x000D_
  background-color: grey; _x000D_
  color: white;_x000D_
}  
_x000D_
<body>_x000D_
  <div class="vertical">Vertically left</div>_x000D_
  <div class="horizontal">Horizontal top</div>_x000D_
  <div class="center">Vertically Horizontal</div>  _x000D_
</body>
_x000D_
_x000D_
_x000D_

Related: Center a Image

Hiding elements in responsive layout?

You can enter these module class suffixes for any module to better control where it will show or be hidden.

.visible-phone  
.visible-tablet     
.visible-desktop    
.hidden-phone   
.hidden-tablet  
.hidden-desktop 

http://twitter.github.com/bootstrap/scaffolding.html scroll to bottom

References with text in LaTeX

Using the hyperref package, you could also declare a new command by using \newcommand{\secref}[1]{\autoref{#1}. \nameref{#1}} in the pre-amble. Placing \secref{section:my} in the text generates: 1. My section.

Download old version of package with NuGet

In NuGet 3.x (Visual Studio 2015) you can just select the version from the UI

NuGet 3 package manager UI

How to disable a particular checkstyle rule for a particular line of code?

<module name="Checker">
    <module name="SuppressionCommentFilter"/>
    <module name="TreeWalker">
        <module name="FileContentsHolder"/>
    </module>
</module>

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="BEGIN GENERATED CODE"/>
  <property name="onCommentFormat" value="END GENERATED CODE"/>
</module>

//BEGIN GENERATED CODE
@Override
public boolean equals(Object obj) { ... } // No violation events will be reported

@Override
public int hashCode() { ... } // No violation events will be reported
//END GENERATED CODE

See more

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

Convert a hexadecimal string to an integer efficiently in C?

This currently only works with lower case but its super easy to make it work with both.

cout << "\nEnter a hexadecimal number: ";
cin >> hexNumber;
orighex = hexNumber;

strlength = hexNumber.length();

for (i=0;i<strlength;i++)
{
    hexa = hexNumber.substr(i,1);
    if ((hexa>="0") && (hexa<="9"))
    {
        //cout << "This is a numerical value.\n";
    }
    else
    {
        //cout << "This is a alpabetical value.\n";
        if (hexa=="a"){hexa="10";}
        else if (hexa=="b"){hexa="11";}
        else if (hexa=="c"){hexa="12";}
        else if (hexa=="d"){hexa="13";}
        else if (hexa=="e"){hexa="14";}
        else if (hexa=="f"){hexa="15";}
        else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";}
    }
    //convert from string to integer

    hx = atoi(hexa.c_str());
    finalhex = finalhex + (hx*pow(16.0,strlength-i-1));
}
cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n";

Read and write a text file in typescript

import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const.

How to encode text to base64 in python

Whilst you can of course use the base64 module, you can also to use the codecs module (referred to in your error message) for binary encodings (meaning non-standard & non-text encodings).

For example:

import codecs
my_bytes = b"Hello World!"
codecs.encode(my_bytes, "base64")
codecs.encode(my_bytes, "hex")
codecs.encode(my_bytes, "zip")
codecs.encode(my_bytes, "bz2")

This can come in useful for large data as you can chain them to get compressed and json-serializable values:

my_large_bytes = my_bytes * 10000
codecs.decode(
    codecs.encode(
        codecs.encode(
            my_large_bytes,
            "zip"
        ),
        "base64"),
    "utf8"
)

Refs:

How to get height of entire document with JavaScript?

The proper answer for 2017 is:

document.documentElement.getBoundingClientRect().height

Unlike document.body.scrollHeight this method accounts for body margins. It also gives fractional height value, which can be useful in some cases

web-api POST body object always null

In my case (.NET Core 3.0) I had to configure JSON serialization to resolve camelCase properties using AddNewtonsoftJson():

services.AddMvc(options =>
{
    // (Irrelevant for the answer)
})
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

Do this in your Startup / Dependency Injection setup.

Get last n lines of a file, similar to tail

I found the Popen above to be the best solution. It's quick and dirty and it works For python 2.6 on Unix machine i used the following

def GetLastNLines(self, n, fileName):
    """
    Name:           Get LastNLines
    Description:        Gets last n lines using Unix tail
    Output:         returns last n lines of a file
    Keyword argument:
    n -- number of last lines to return
    filename -- Name of the file you need to tail into
    """
    p = subprocess.Popen(['tail','-n',str(n),self.__fileName], stdout=subprocess.PIPE)
    soutput, sinput = p.communicate()
    return soutput

soutput will have will contain last n lines of the code. to iterate through soutput line by line do:

for line in GetLastNLines(50,'myfile.log').split('\n'):
    print line

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

CSS Animation onClick

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In my case the tensorflow install was looking for cudart64_101.dll

enter image description here

The 101 part of cudart64_101 is the Cuda version - here 101 = 10.1

I had downloaded 11.x, so the version of cudart64 on my system was cudart64_110.dll

enter image description here

This is the wrong file!! cudart64_101.dll ? cudart64_110.dll

Solution

Download Cuda 10.1 from https://developer.nvidia.com/

Install (mine crashes with NSight Visual Studio Integration, so I switched that off)

enter image description here

When the install has finished you should have a Cuda 10.1 folder, and in the bin the dll the system was complaining about being missing

enter image description here

Check that the path to the 10.1 bin folder is registered as a system environmental variable, so it will be checked when loading the library

enter image description here

You may need a reboot if the path is not picked up by the system straight away

enter image description here

Converting an int to a binary string representation in Java?

There is also the java.lang.Integer.toString(int i, int base) method, which would be more appropriate if your code might one day handle bases other than 2 (binary). Keep in mind that this method only gives you an unsigned representation of the integer i, and if it is negative, it will tack on a negative sign at the front. It won't use two's complement.

How to center a table of the screen (vertically and horizontally)

One way to center any element of unknown height and width both horizontally and vertically:

table {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

See Example

Alternatively, use a flex container:

.parent-element {
    display: flex;
    justify-content: center;
    align-items: center;
}

How to display errors on laravel 4?

Maybe not on Laravel 4 this time, but on L5.2* I had similar issue:

I simply changed the ownership of the storage/logs directory to www-data with:

# chown -R www-data:www-data logs

PS: This is on Ubuntu 15 and with apache.

My logs directory now looks like:

drwxrwxr-x  2 www-data   www-data 4096 jaan  23 09:39 logs/

Create a OpenSSL certificate on Windows

Consider using certificate depot web app to easily create private key and certificate based on it: http://www.cert-depot.com/

It can also create a PFX for you.

Disclaimer: I am the creator of certificate depot.

How to get memory available or used in C#

For the complete system you can add the Microsoft.VisualBasic Framework as a reference;

 Console.WriteLine("You have {0} bytes of RAM",
        new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
        Console.ReadLine();

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Reading specific XML elements from XML file

You could use an XPath, too. A bit old fashioned but still effective:

using System.Xml;

...

XmlDocument xmlDocument;

xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);

foreach (XmlElement xmlElement in 
    xmlDocument.DocumentElement.SelectNodes("word[category='verb']"))
{
    Console.Out.WriteLine(xmlElement.OuterXml);
}

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

How could others, on a local network, access my NodeJS app while it's running on my machine?

const express = require('express');

var app = express();    
app.listen(Port Number, "Your IP Address");
// e.g.
app.listen(3000, "192.183.190.3");

You can get your IP Address by typing ipconfig in cmd if your Windows user else you can use ifconfig.

Javascript how to split newline

The problem is that when you initialize ks, the value hasn't been set.

You need to fetch the value when user submits the form. So you need to initialize the ks inside the callback function

(function($){
   $(document).ready(function(){
      $('#data').submit(function(e){
      //Here it will fetch the value of #keywords
         var ks = $('#keywords').val().split("\n");
         ...
      });
   });
})(jQuery);

Bootstrap visible and hidden classes not working properly

As of today November 2017
Bootstrap v4 - beta

Responsive utilities

All @screen- variables have been removed in v4.0.0. Use the media-breakpoint-up(), media-breakpoint-down(), or media-breakpoint-only() Sass mixins or the $grid-breakpoints Sass map instead.

Removed from v3: .hidden-xs .hidden-sm .hidden-md .hidden-lg .visible-xs-block .visible-xs-inline .visible-xs-inline-block .visible-sm-block .visible-sm-inline .visible-sm-inline-block .visible-md-block .visible-md-inline .visible-md-inline-block .visible-lg-block .visible-lg-inline .visible-lg-inline-block

Removed from v4 alphas: .hidden-xs-up .hidden-xs-down .hidden-sm-up .hidden-sm-down .hidden-md-up .hidden-md-down .hidden-lg-up .hidden-lg-down

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

How to call Makefile from another Makefile?

Instead of the -f of make you might want to use the -C <path> option. This first changes the to the path '<path>', and then calles make there.

Example:

clean:
  rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
  rm -f ../svn-commit.tmp~
  rm -f $(BIN_DIR)/$(PROJECT)
  $(MAKE) -C gtest-1.4.0/make clean

error: src refspec master does not match any

Run the command git show-ref, the result refs/heads/YOURBRANCHNAME If your branch is not there, then you need to switch the branch by

git checkout -b "YOURBRANCHNAME"

git show-ref, will now show your branch reference.

Now you can do the operations on your branch.

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

Android charting libraries

You can use MPAndroidChart.

It's native, free, easy to use, fast and reliable.

Core features, benefits:

  • LineChart, BarChart (vertical, horizontal, stacked, grouped), PieChart, ScatterChart, CandleStickChart (for financial data), RadarChart (spider web chart), BubbleChart
  • Combined Charts (e.g. lines and bars in one)
  • Scaling on both axes (with touch-gesture, axes separately or pinch-zoom)
  • Dragging / Panning (with touch-gesture)
  • Separate (dual) y-axes
  • Highlighting values (with customizeable popup-views)
  • Save chart to SD-Card (as image)
  • Predefined color templates
  • Legends (generated automatically, customizeable)
  • Customizeable Axes (both x- and y-axis)
  • Animations (build up animations, on both x- and y-axis)
  • Limit lines (providing additional information, maximums, ...)
  • Listeners for touch, gesture & selection callbacks
  • Fully customizeable (paints, typefaces, legends, colors, background, dashed lines, ...)
  • Realm.io mobile database support via MPAndroidChart-Realm library
  • Smooth rendering for up to 10.000 data points in Line- and BarChart
  • Lightweight (method count ~1.4K)
  • Available as .jar file (only 500kb in size)
  • Available as gradle dependency and via maven
  • Good documentation
  • Example Project (code for demo-application)
  • Google-PlayStore Demo Application
  • Widely used, great support on both GitHub and stackoverflow - mpandroidchart
  • Also available for iOS: Charts (API works the same way)
  • Also available for Xamarin: MPAndroidChart.Xamarin

Drawbacks:

Disclaimer: I am the developer of this library.

Access to the path is denied

I was having the same problem while trying to create a file on the server (actually a file that is a copy from a template).

Here's the complete error message:

{ERROR} 08/07/2012 22:15:58 - System.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\SAvE\Templates\Cover.pdf' is denied.

I added a new folder called Templates inside the IIS app folder. One very important thing in my case is that I needed to give the Write (Gravar) permission for the IUSR user on that folder. You may also need to give Network Service and ASP.NET v$.# the same Write permission.

enter image description here

After doing this everything works as expected.

CSS fill remaining width

I know its quite late to answer this, but I guess it will help anyone ahead.

Well using CSS3 FlexBox. It can be acheived. Make you header as display:flex and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part. apply justify-content: between to the header container and flex-grow:1 to the searchbar. That's it. The sample code is below.

_x000D_
_x000D_
#header {_x000D_
  background-color: #323C3E;_x000D_
  justify-content: space-between;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
  align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
  flex-grow:1;_x000D_
  background-color: orange;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
  padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
  display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
    <img src="img/logo.png" />_x000D_
    <div id="searchBar">_x000D_
      <input type="text" />_x000D_
    </div>_x000D_
    <div class="buttonsHolder">_x000D_
      <div class="button orange inline" id="myAccount">_x000D_
        My Account_x000D_
      </div>_x000D_
      <div class="button red inline" id="basket">_x000D_
        Basket (2)_x000D_
      </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to test if string exists in file with Bash?

Easiest and simplest way would be:

isInFile=$(cat file.txt | grep -c "string")


if [ $isInFile -eq 0 ]; then
   #string not contained in file
else
   #string is in file at least once
fi

grep -c will return the count of how many times the string occurs in the file.

FCM getting MismatchSenderId

In my case it was very simple. I was pulling the wrong registrationId from the database. After I pulled the correct Id, it worked.

PHP form send email to multiple recipients

You can add your receipients to $email_to variable separating them with comma (,). Or you can add new fields to headers, namely CC: or BCC: and put your receipients there. BCC is most recommended

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

How do I remove all .pyc files from a project?

Further, people usually want to remove all *.pyc, *.pyo files and __pycache__ directories recursively in the current directory.

Command:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

How to convert an integer to a string in any base?

def base_changer(number,base):
    buff=97+abs(base-10)
    dic={};buff2='';buff3=10
    for i in range(97,buff+1):
        dic[buff3]=chr(i)
        buff3+=1   
    while(number>=base):
        mod=int(number%base)
        number=int(number//base)
        if (mod) in dic.keys():
            buff2+=dic[mod]
            continue
        buff2+=str(mod)
    if (number) in dic.keys():
        buff2+=dic[number]
    else:
        buff2+=str(number)

    return buff2[::-1]   

Sequelize, convert entity to plain object

I have found a solution that works fine for nested model and array using native JavaScript functions.

var results = [{},{},...]; //your result data returned from sequelize query
var jsonString = JSON.stringify(results); //convert to string to remove the sequelize specific meta data

var obj = JSON.parse(jsonString); //to make plain json
// do whatever you want to do with obj as plain json