Programs & Examples On #Mtom

Message Transmission Optimization Mechanism (MTOM) is a method to efficiently send binary data to and from Web services, it is a W3C Recommendation.

WCF gives an unsecured or incorrectly secured fault error

I was getting this error due to the BasicHttpBinding not sending a compatible messageVersion to the service i was calling. My solution was to use a custom binding like below

 <bindings>
  <customBinding>
    <binding name="Soap11UserNameOverTransport" openTimeout="00:01:00" receiveTimeout="00:1:00" >
      <security authenticationMode="UserNameOverTransport">
      </security>          
      <textMessageEncoding messageVersion="Soap11WSAddressing10" writeEncoding="utf-8" />
      <httpsTransport></httpsTransport>
    </binding>
  </customBinding>      
</bindings>

Does List<T> guarantee insertion order?

This is the code I have for moving an item down one place in a list:

if (this.folderImages.SelectedIndex > -1 && this.folderImages.SelectedIndex < this.folderImages.Items.Count - 1)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index + 1, imageName);
    this.folderImages.SelectedIndex = index + 1;
 }

and this for moving it one place up:

if (this.folderImages.SelectedIndex > 0)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index - 1, imageName);
    this.folderImages.SelectedIndex = index - 1;
}

folderImages is a ListBox of course so the list is a ListBox.ObjectCollection, not a List<T>, but it does inherit from IList so it should behave the same. Does this help?

Of course the former only works if the selected item is not the last item in the list and the latter if the selected item is not the first item.

What is the difference between Cygwin and MinGW?

Cygwin uses a DLL, cygwin.dll, (or maybe a set of DLLs) to provide a POSIX-like runtime on Windows.

MinGW compiles to a native Win32 application.

If you build something with Cygwin, any system you install it to will also need the Cygwin DLL(s). A MinGW application does not need any special runtime.

How to hide status bar in Android

This solution work for me :)

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 19) {
           getWindow().setFlags(AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT);
           getWindow().getDecorView().setSystemUiVisibility(3328);
    }else{
           requestWindowFeature(Window.FEATURE_NO_TITLE);
           this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    DataBindingUtil.setContentView(this, R.layout.activity_hse_video_details);

Difference between [routerLink] and routerLink

Assume that you have

const appRoutes: Routes = [
  {path: 'recipes', component: RecipesComponent }
];

<a routerLink ="recipes">Recipes</a>

It means that clicking Recipes hyperlink will jump to http://localhost:4200/recipes

Assume that the parameter is 1

<a [routerLink] = "['/recipes', parameter]"></a>

It means that passing dynamic parameter, 1 to the link, then you navigate to http://localhost:4200/recipes/1

Can linux cat command be used for writing text to file?

Another way to write text to file using cat would be something like this

cat >file.txt <<< Write something here

Is multiplication and division using shift operators in C actually faster?

I agree with the marked answer by Drew Hall. The answer could use some additional notes though.

For the vast majority of software developers the processor and compiler are no longer relevant to the question. Most of us are far beyond the 8088 and MS-DOS. It is perhaps only relevant for those who are still developing for embedded processors...

At my software company Math (add/sub/mul/div) should be used for all mathematics. While Shift should be used when converting between data types eg. ushort to byte as n>>8 and not n/256.

Datagridview: How to set a cell in editing mode?

Well, I would check if any of your columns are set as ReadOnly. I have never had to use BeginEdit, but maybe there is some legitimate use. Once you have done dataGridView1.Columns[".."].ReadOnly = False;, the fields that are not ReadOnly should be editable. You can use the DataGridView CellEnter event to determine what cell was entered and then turn on editing on those cells after you have passed editing from the first two columns to the next set of columns and turn off editing on the last two columns.

Java Runtime.getRuntime(): getting output from executing a command line program

If use are already have Apache commons-io available on the classpath, you may use:

Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

How to disable GCC warnings for a few lines of code

For those who found this page looking for a way to do this in IAR, try this:

#pragma diag_suppress=Pe177
void foo1( void )
{
   /* The following line of code would normally provoke diagnostic 
      message #177-D: variable "x" was declared but never referenced.
      Instead, we have suppressed this warning throughout the entire 
      scope of foo1(). 
   */
   int x;
}
#pragma diag_default=Pe177

See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0472m/chr1359124244797.html for reference.

.NET Excel Library that can read/write .xls files

Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:

private DataTable LoadExcelData(string fileName)
{
  string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

  OleDbConnection con = new OleDbConnection(Connection);

  OleDbCommand command = new OleDbCommand();

  DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);

  myCommand.Fill(dt);

  Console.WriteLine(dt.Rows.Count);

  return dt;
}

You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

How to get text with Selenium WebDriver in Python

You can use:

element = driver.find_element_by_class_name("class_name").text

This will return the text within the element and will allow you to verify it after that.

How to remove &quot; from my Json in javascript?

The following works for me:

function decodeHtml(html) {
    let areaElement = document.createElement("textarea");
    areaElement.innerHTML = html;

    return areaElement.value;
}

Push origin master error on new repository

go to control panel -> manage your credentials and delete github credentials if any.

How to generate .env file for laravel?

I had this problem of no .env files showing up in the project.

Turns out the IDE I was using (Netbeans, try not to judge) will show certain types of .hidden files but not all.

After racking my brains for a bit I checked the file system and found the .env + .env.example files / modified them with a text editor.

Leaving this answer for the rare situation someones using a dodgy IDE like myself.

How to convert date to string and to date again?

try this:

 String DATE_FORMAT_NOW = "yyyy-MM-dd";
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
 String stringDate = sdf.format(date );
    try {
        Date date2 = sdf.parse(stringDate);
    } catch(ParseException e){
     //Exception handling
    } catch(Exception e){
     //handle exception
    }

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:

SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;

Omitting the parenthesis was solving it for me.

SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;

Git push failed, "Non-fast forward updates were rejected"

I've hade the same problem. I resolved with

git checkout <name branch>
git pull origin <name branch>
git push origin <name branch>

How do I parse a string with a decimal point to a double?

The below is less efficient, but I use this logic. This is valid only if you have two digits after decimal point.

double val;

if (temp.Text.Split('.').Length > 1)
{
    val = double.Parse(temp.Text.Split('.')[0]);

    if (temp.Text.Split('.')[1].Length == 1)
        val += (0.1 * double.Parse(temp.Text.Split('.')[1]));
    else
        val += (0.01 * double.Parse(temp.Text.Split('.')[1]));
}
else
    val = double.Parse(RR(temp.Text));

How do you find the row count for all your tables in Postgres

I like Daniel Vérité's answer. But when you can't use a CREATE statement you can either use a bash solution or, if you're a windows user, a powershell one:

# You don't need this if you have pgpass.conf
$env:PGPASSWORD = "userpass"

# Get table list
$tables = & 'C:\Program Files\PostgreSQL\9.4\bin\psql.exe' -U user -w -d dbname -At -c "select table_name from information_schema.tables where table_type='BASE TABLE' AND table_schema='schema1'"

foreach ($table in $tables) {
    & 'C:\path_to_postresql\bin\psql.exe' -U root -w -d dbname -At -c "select '$table', count(*) from $table"
}

Using a custom typeface in Android

I was able to do this in a centralized way, here is the result:

enter image description here

I have following Activity and I extend from it if I need custom fonts:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater.Factory;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class CustomFontActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    getLayoutInflater().setFactory(new Factory() {

        @Override
        public View onCreateView(String name, Context context,
                AttributeSet attrs) {
            View v = tryInflate(name, context, attrs);
            if (v instanceof TextView) {
                setTypeFace((TextView) v);
            }
            return v;
        }
    });
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

private View tryInflate(String name, Context context, AttributeSet attrs) {
    LayoutInflater li = LayoutInflater.from(context);
    View v = null;
    try {
        v = li.createView(name, null, attrs); 
    } catch (Exception e) {
        try {
            v = li.createView("android.widget." + name, null, attrs);
        } catch (Exception e1) {
        }
    }
    return v;
}

private void setTypeFace(TextView tv) {
    tv.setTypeface(FontUtils.getFonts(this, "MTCORSVA.TTF"));
}
}

But if I am using an activity from support package e.g. FragmentActivity then I use this Activity:

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class CustomFontFragmentActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

// we can't setLayout Factory as its already set by FragmentActivity so we
// use this approach
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
    View v = super.onCreateView(name, context, attrs);
    if (v == null) {
        v = tryInflate(name, context, attrs);
        if (v instanceof TextView) {
            setTypeFace((TextView) v);
        }
    }
    return v;
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(View parent, String name, Context context,
        AttributeSet attrs) {
    View v = super.onCreateView(parent, name, context, attrs);
    if (v == null) {
        v = tryInflate(name, context, attrs);
        if (v instanceof TextView) {
            setTypeFace((TextView) v);
        }
    }
    return v;
}

private View tryInflate(String name, Context context, AttributeSet attrs) {
    LayoutInflater li = LayoutInflater.from(context);
    View v = null;
    try {
        v = li.createView(name, null, attrs);
    } catch (Exception e) {
        try {
            v = li.createView("android.widget." + name, null, attrs);
        } catch (Exception e1) {
        }
    }
    return v;
}

private void setTypeFace(TextView tv) {
    tv.setTypeface(FontUtils.getFonts(this, "MTCORSVA.TTF"));
}
}

I haven't tested this code with Fragments yet, but hopefully it will work.

My FontUtils is simple which also solves the pre-ICS issue mentioned here https://code.google.com/p/android/issues/detail?id=9904:

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Typeface;

public class FontUtils {

private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();

public static Typeface getFonts(Context context, String name) { 
    Typeface typeface = TYPEFACE.get(name);
    if (typeface == null) {
        typeface = Typeface.createFromAsset(context.getAssets(), "fonts/"
                + name);
        TYPEFACE.put(name, typeface);
    }
    return typeface;
}
}

How to convert string to boolean php

You should be able to cast to a boolean using (bool) but I'm not sure without checking whether this works on the strings "true" and "false".

This might be worth a pop though

$myBool = (bool)"False"; 

if ($myBool) {
    //do something
}

It is worth knowing that the following will evaluate to the boolean False when put inside

if()
  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Everytyhing else will evaluate to true.

As descried here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

How to Flatten a Multidimensional Array?

I needed to represent PHP multidimensional array in HTML input format.

$test = [
    'a' => [
        'b' => [
            'c' => ['a', 'b']
        ]
    ],
    'b' => 'c',
    'c' => [
        'd' => 'e'
    ]
];

$flatten = function ($input, $parent = []) use (&$flatten) {
    $return = [];

    foreach ($input as $k => $v) {
        if (is_array($v)) {
            $return = array_merge($return, $flatten($v, array_merge($parent, [$k])));
        } else {
            if ($parent) {
                $key = implode('][', $parent) . '][' . $k . ']';

                if (substr_count($key, ']') != substr_count($key, '[')) {
                    $key = preg_replace('/\]/', '', $key, 1);
                }
            } else {
                $key = $k;
            }           

            $return[$key] = $v;
        }
    }

    return $return;
};

die(var_dump( $flatten($test) ));

array(4) {
  ["a[b][c][0]"]=>
  string(1) "a"
  ["a[b][c][1]"]=>
  string(1) "b"
  ["b"]=>
  string(1) "c"
  ["c[d]"]=>
  string(1) "e"
}

Convert a String to a byte array and then back to the original String

import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
{
    String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

    while(true)
    {
        len = is.read(buf);
        if(len < 0) break;
        md.update(buf, 0, len);
    }

    // close the input stream

    is.close();

    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
    {
        System.out.println(b + ", ");
    }

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);

    System.out.println();

    System.out.println("===")

    System.out.println(verification);

    System.out.println("Equals? " + verification.equals(compare));

}

}

Android Studio Stuck at Gradle Download on create new project

Invalidate Caches and Restart

It worked for me.

Run R script from command line

One more way of running an R script from the command line would be:

R < scriptName.R --no-save  

or with --save.

See also What's the best way to use R scripts on the command line (terminal)?.

How to get query string parameter from MVC Razor markup?

For Asp.net Core 2

ViewContext.ModelState["id"].AttemptedValue

UITableView - scroll to the top

func scrollToTop() {
        NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
        [tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

call this function wherever you want UITableView scroll to top

OPTION (RECOMPILE) is Always Faster; Why?

The very first actions before tunning queries is to defrag/rebuild the indexes and statistics, otherway you're wasting your time.

You must check the execution plan to see if it's stable (is the same when you change the parameters), if not, you might have to create a cover index (in this case for each table) (knowing th system you can create one that is usefull for other queries too).

as an example : create index idx01_datafeed_trans On datafeed_trans ( feedid, feedDate) INCLUDE( acctNo, tradeDate)

if the plan is stable or you can stabilize it you can execute the sentence with sp_executesql('sql sentence') to save and use a fixed execution plan.

if the plan is unstable you have to use an ad-hoc statement or EXEC('sql sentence') to evaluate and create an execution plan each time. (or a stored procedure "with recompile").

Hope it helps.

Safe navigation operator (?.) or (!.) and null property paths

Update:

Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352


You can try to write a custom function like that.

The main advantage of the approach is a type-checking and partial intellisense.

export function nullSafe<T, 
    K0 extends keyof T, 
    K1 extends keyof T[K0],
    K2 extends keyof T[K0][K1],
    K3 extends keyof T[K0][K1][K2],
    K4 extends keyof T[K0][K1][K2][K3],
    K5 extends keyof T[K0][K1][K2][K3][K4]>
    (obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
    let result: any = obj;

    const keysCount = arguments.length - 1;
    for (var i = 1; i <= keysCount; i++) {
        if (result === null || result === undefined) return result;
        result = result[arguments[i]];
    }

    return result;
}

And usage (supports up to 5 parameters and can be extended):

nullSafe(a, 'b', 'c');

Example on playground.

How to check if one of the following items is in a list?

Simple.

_new_list = []
for item in a:
    if item in b:
        _new_list.append(item)
    else:
        pass

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

Only you need to empty /tmp directory using command & hit reboot your system. now you are able to play on asterisk CLI whatever you want.

How to get max value of a column using Entity Framework?

Maybe help, if you want to add some filter:

context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

Yet another Googlemare Landmine.... Somehow, if you mess up, the icon line on your .gen file dies. (Empirical proof of mine after struggling 2 hours)

Insert a new icon 72x72 icon on the hdpi folder with a different name from the original, and update the name on the manifest also.

The icon somehow resurrects on the Gen file and voila!! time to move on.

Number of days in particular month of particular year?

Code for java.util.Calendar

If you have to use java.util.Calendar, I suspect you want:

int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

Code for Joda Time

Personally, however, I'd suggest using Joda Time instead of java.util.{Calendar, Date} to start with, in which case you could use:

int days = chronology.dayOfMonth().getMaximumValue(date);

Note that rather than parsing the string values individually, it would be better to get whichever date/time API you're using to parse it. In java.util.* you might use SimpleDateFormat; in Joda Time you'd use a DateTimeFormatter.

Why am I getting InputMismatchException?

Instead of using a dot, like: 1.2, try to input like this: 1,2.

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

jQuery delete all table rows except first

Easiest way :

$("#mytable").find($("tr")).slice(1).remove()

-first reference the table
-get the list of elements and slice it and remove the selected elements of the list

SSRS expression to format two decimal places does not show zeros

Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

What is the best open source help ticket system?

It absolutely depens on what your goals are. The Bugzilla and Trac systems mentioned are nice but geared towards bug tracking, which is just very different from a tool you'd want to use in a helpdesk-type setup where end users would raise incidents.

If the latter is what you are looking for I'd suggest you take a look at OTRS which is a very capable trouble ticketing system. It also has ITSM extensions, which makes it able to support ITIL processes if you need to.

Bootstrap 4 Dropdown Menu not working?

It's an issue with popper.js file. What I found at the official site was that bundle files include popper in itself but not jquery. I managed to fix it by adding link to these files:

bootstrap.bundle.js
bootstrap.bundle.min.js

I removed popper.js however since it comes within the bundle file.

Linux command to print directory structure in the form of a tree

Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.

function tree() {
    find ${1:-.} | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/"
}

This works in gitbash too.

Source: Comment from @javasheriff here

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

Remove folder and its contents from git/GitHub's history

In addition to the popular answer above I would like to add a few notes for Windows-systems. The command

git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
  • works perfectly without any modification! Therefore, you must not use Remove-Item, del or anything else instead of rm -rf.

  • If you need to specify a path to a file or directory use slashes like ./path/to/node_modules

Perl read line by line

#!/usr/bin/perl
use utf8                       ;
use 5.10.1                     ;
use strict                     ;
use autodie                    ;
use warnings FATAL => q  ?all?;
binmode STDOUT     => q ?:utf8?;                  END {
close   STDOUT                 ;                     }
our    $FOLIO      =  q + SnPmaster.txt +            ;
open    FOLIO                  ;                 END {
close   FOLIO                  ;                     }
binmode FOLIO      => q{       :crlf
                               :encoding(CP-1252)    };
while (<FOLIO>)  { print       ;                     }
       continue  { ${.} ^015^  __LINE__  ||   exit   }
                                                                                                                                                                                                                                              __END__
unlink  $FOLIO                 ;
unlink ~$HOME ||
  clri ~$HOME                  ;
reboot                         ;

How can I make a CSS glass/blur effect work for an overlay?

_x000D_
_x000D_
#bg, #search-bg {_x000D_
  background-image: url('https://images.pexels.com/photos/719609/pexels-photo-719609.jpeg?w=940&h=650&auto=compress&cs=tinysrgb');_x000D_
  background-repeat: no-repeat;_x000D_
  background-size: 1080px auto;_x000D_
}_x000D_
_x000D_
#bg {_x000D_
  background-position: center top;_x000D_
  padding: 70px 90px 120px 90px;_x000D_
}_x000D_
_x000D_
#search-container {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#search-bg {_x000D_
  /* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  bottom: 0px;_x000D_
  left: 0px;_x000D_
  z-index: 99;_x000D_
_x000D_
  /* Pull the background 70px higher to the same place as #bg's */_x000D_
  background-position: center -70px;_x000D_
_x000D_
  -webkit-filter: blur(10px);_x000D_
  filter: url('/media/blur.svg#blur');_x000D_
  filter: blur(10px);_x000D_
}_x000D_
_x000D_
#search {_x000D_
  /* Put this on top of the blurred layer */_x000D_
  position: relative;_x000D_
  z-index: 100;_x000D_
  padding: 20px;_x000D_
  background: rgb(34,34,34); /* for IE */_x000D_
  background: rgba(34,34,34,0.75);_x000D_
}_x000D_
_x000D_
@media (max-width: 600px ) {_x000D_
  #bg { padding: 10px; }_x000D_
  #search-bg { background-position: center -10px; }_x000D_
}_x000D_
_x000D_
#search h2, #search h5, #search h5 a { text-align: center; color: #fefefe; font-weight: normal; }_x000D_
#search h2 { margin-bottom: 50px }_x000D_
#search h5 { margin-top: 70px }
_x000D_
<div id="bg">_x000D_
  <div id="search-container">_x000D_
    <div id="search-bg"></div>_x000D_
    <div id="search">_x000D_
      <h2>Awesome</h2>_x000D_
      <h5><a href="#">How it works »</a></h5>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Exception: There is already an open DataReader associated with this Connection which must be closed first

This exception also happens if don't use transactions properly. In my case, I put transaction.Commit() right after command.ExecuteReaderAsync(), and did not wait to commit the transaction until reader.ReadAsync() were called. The proper order:

  1. Create transaction.
  2. Create reader.
  3. Read the data.
  4. Commit the transaction.

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

JOIN queries vs multiple queries

There are several factors which means there is no binary answer. The question of what is best for performance depends on your environment. By the way, if your single select with an identifier is not sub-second, something may be wrong with your configuration.

The real question to ask is how do you want to access the data. Single selects support late-binding. For example if you only want employee information, you can select from the Employees table. The foreign key relationships can be used to retrieve related resources at a later time and as needed. The selects will already have a key to point to so they should be extremely fast, and you only have to retrieve what you need. Network latency must always be taken into account.

Joins will retrieve all of the data at once. If you are generating a report or populating a grid, this may be exactly what you want. Compiled and optomized joins are simply going to be faster than single selects in this scenario. Remember, Ad-hoc joins may not be as fast--you should compile them (into a stored proc). The speed answer depends on the execution plan, which details exactly what steps the DBMS takes to retrieve the data.

How to save to local storage using Flutter?

If you are in a situation where you wanna save a small value that you wanna refer later. then you should store your data as key-value data using shared_preferences

but if you want to store large data you should go with SQLITE

however you can always use firebase database which is available offline

Since we are talking about local storage you can always read and write files to the disk

Other solutions :

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

Change app language programmatically in Android

Alex Volovoy answer only works for me if it's in onCreate method of the activity.

The answer that works in all the methods is in another thread

Change language programmatically in Android

Here is the adaptation of the code



    Resources standardResources = getBaseContext().getResources();

    AssetManager assets = standardResources.getAssets();

    DisplayMetrics metrics = standardResources.getDisplayMetrics();

    Configuration config = new Configuration(standardResources.getConfiguration());

    config.locale = new Locale(languageToLoad);

    Resources defaultResources = new Resources(assets, metrics, config);

Hope that it helps.

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

HashMap allows duplicates?

Each key in a HashMap must be unique.

When "adding a duplicate key" the old value (for the same key, as keys must be unique) is simply replaced; see HashMap.put:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Returns the previous value associated with key, or null if there was no mapping for key.

As far as nulls: a single null key is allowed (as keys must be unique) but the HashMap can have any number of null values, and a null key need not have a null value. Per the documentation:

[.. HashMap] permits null values and [a] null key.

However, the documentation says nothing about null/null needing to be a specific key/value pair or null/"a" being invalid.

Path to MSBuild

Poking around the registry, it looks like

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0

may be what you're after; fire up regedit.exe and have a look.

Query via command line (per Nikolay Botev)

reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0" /v MSBuildToolsPath

Query via PowerShell (per MovGP0)

dir HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

import { FormsModule,ReactiveFormsModule }from'@angular/forms';

imports:[
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule/*This one in particular*/,...
],

in app.module.ts to permanently solve errors like "cannot bind [formGroup] or no directive with export as".

How to declare a static const char* in your header file?

To answer the why question, integral types are special in that they are not a reference to an allocated object but rather values that are duplicated and copied. It's just an implementation decision made when the language was defined, which was to handle values outside the object system and in as efficient and "inline" a fashion as possible.

This doesn't exactly explain why they are allowed as initializors in a type, but think of it as essentially a #define and then it will make sense as part of the type and not part of the object.

How to enumerate an enum

This question appears in Chapter 10 of "C# Step by Step 2013"

The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):

class Pack
{
    public const int NumSuits = 4;
    public const int CardsPerSuit = 13;
    private PlayingCard[,] cardPack;

    public Pack()
    {
        this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
        for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
        {
            for (Value value = Value.Two; value <= Value.Ace; value++)
            {
                cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
            }
        }
    }
}

In this case, Suit and Value are both enumerations:

enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}

and PlayingCard is a card object with a defined Suit and Value:

class PlayingCard
{
    private readonly Suit suit;
    private readonly Value value;

    public PlayingCard(Suit s, Value v)
    {
        this.suit = s;
        this.value = v;
    }
}

Regex for not empty and not whitespace

/^$|\s+/ This matches when empty or white spaces

/(?!^$)([^\s])/ This matches when its not empty or white spaces

How do I enable C++11 in gcc?

H2CO3 is right, you can use a makefile with the CXXFLAGS set with -std=c++11 A makefile is a simple text file with instructions about how to compile your program. Create a new file named Makefile (with a capital M). To automatically compile your code just type the make command in a terminal. You may have to install make.

Here's a simple one :

CXX=clang++
CXXFLAGS=-g -std=c++11 -Wall -pedantic
BIN=prog

SRC=$(wildcard *.cpp)
OBJ=$(SRC:%.cpp=%.o)

all: $(OBJ)
    $(CXX) -o $(BIN) $^

%.o: %.c
    $(CXX) $@ -c $<

clean:
    rm -f *.o
    rm $(BIN)

It assumes that all the .cpp files are in the same directory as the makefile. But you can easily tweak your makefile to support a src, include and build directories.

Edit : I modified the default c++ compiler, my version of g++ isn't up-to-date. With clang++ this makefile works fine.

how to change color of TextinputLayout's label and edittext underline android

I used all of the above answers and none worked. This answer works for API 21+. Use app:hintTextColor attribute when text field is focused and app:textColorHint attribute when in other states. To change the bottmline color use this attribute app:boxStrokeColor as demonstrated below:

<com.google.android.material.textfield.TextInputLayout
            app:boxStrokeColor="@color/colorAccent"
            app:hintTextColor="@color/colorAccent"
            android:textColorHint="@android:color/darker_gray"
    
       <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>

It works for AutoCompleteTextView as well. Hope it works for you:)

Returning JSON response from Servlet to Javascript/JSP page

I used JSONObject as shown below in Servlet.

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

The Servlet returns this JSON object as shown below:

    response.setContentType("application/json");
    response.getWriter().write(jsonReturn.toString());

This Servlet is called from Browser using AngularJs as below

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName

Adding Google Translate to a web site

Here's the markup that should work, both locally and remotely - copied from html-5-tutorial.com:

<div id="google_translate_element"></div>
<script>
    function googleTranslateElementInit() {
        new google.translate.TranslateElement(
            {pageLanguage: 'en'},
            'google_translate_element'
        );
    }
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

How to style the <option> with only CSS?

I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I was on Windows when this problem appeared.

The error is strange because it happens before I could enter my username and my password. What if there was a cache or something like this? I dig it online and found this answer on gitlab's support forum:

I open "Control Panel => User Accounts => Manage your credentials => Windows Credentials" I found two for https://@github.com and one was the wrong user. I deleted it and on the next "git push" I was reprompted and provided the correct credentials and it worked! Some other notes - this could have happened with any git remote.

In the Windows Credentials, I found two GitLab entries for an old account. I remove both and now it works!

The panel:

enter image description here

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

How to get file_get_contents() to work with HTTPS?

Try the following script to see if there is an https wrapper available for your php scripts.

$w = stream_get_wrappers();
echo 'openssl: ',  extension_loaded  ('openssl') ? 'yes':'no', "\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "\n";
echo 'wrappers: ', var_export($w);

the output should be something like

openssl: yes
http wrapper: yes
https wrapper: yes
wrappers: array(11) {
  [...]
}

YouTube: How to present embed video with sound muted

This is easy. Just add mute=1 to the src parameter of iframe.

Example:

<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?controls=0&mute=1&showinfo=0&rel=0&autoplay=1&loop=1&playlist=uNRGWVJ10gQ" frameborder="0" allowfullscreen></iframe>

Stored procedure return into DataSet in C# .Net

Try this

    DataSet ds = new DataSet("TimeRanges");
    using(SqlConnection conn = new SqlConnection("ConnectionString"))
    {               
            SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
            sqlComm.Parameters.AddWithValue("@Start", StartTime);
            sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
            sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);

            sqlComm.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlComm;

            da.Fill(ds);
     }

Is there a simple way to convert C++ enum to string?

@hydroo: Without the extra file:

#define SOME_ENUM(DO) \
    DO(Foo) \
    DO(Bar) \
    DO(Baz)

#define MAKE_ENUM(VAR) VAR,
enum MetaSyntacticVariable{
    SOME_ENUM(MAKE_ENUM)
};

#define MAKE_STRINGS(VAR) #VAR,
const char* const MetaSyntacticVariableNames[] = {
    SOME_ENUM(MAKE_STRINGS)
};

Hex colors: Numeric representation for "transparent"?

Transparency is a property outside the color itself, also known as alpha component. You can't code it as RGB.

If you want a transparent background, you can do this:

background: transparent;

Additionally, I don't know if it might be helpful or not but, you could set the opacity property:

.half{
  opacity: 0.5;
  filter: alpha(opacity=50);
}

You need both in order to get it working in IE and all other decent browsers.

How to avoid warning when introducing NAs by coercion

suppressWarnings() has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.

> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion 
> y <- destring(c("1", "2", "X"))
> y
[1]  1  2 NA
> x
[1]  1  2 NA

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

apply drop shadow to border-top only?

Multiple box shadows did it for me.

box-shadow:
        inset 0 -8px 4px 4px rgb(255,255,255),
        inset 0 2px 4px 0px rgba(50, 50, 50, 0.75);

http://jsfiddle.net/kk66f/

What is the purpose of the var keyword and when should I use it (or omit it)?

As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.

If you run this code:

var local = true;
var global = true;


function test(){
  var local = false;
  var global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output will read as: false, false, true, true

Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:

var local = true;
var global = true;


function test(){
  local = false;
  global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output is false, false, false, false

This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I'm using PreviewKeyDown

    private void _calendar_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e){
        switch (e.KeyCode){
            case Keys.Down:
            case Keys.Right:
                //action
                break;
            case Keys.Up:
            case Keys.Left:
                //action
                break;
        }
    }

How to check if a registry value exists using C#?

        internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
        {
            // get registry key with Microsoft.Win32.Registrys
            RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
            if ((rk) == null) // if the RegistryKey is null which means it does not exist
            {
                // the key does not exist
                return false; // return false because it does not exist
            }
            // the registry key does exist
            return true; // return true because it does exist
        };

usage:

        // usage:
        /* Create Key - while (loading)
        {
            RegistryKey k;
            k = Registry.CurrentUser.CreateSubKey("stuff");
            k.SetValue("value", "value");
            Thread.Sleep(int.MaxValue);
        }; // no need to k.close because exiting control */


        if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
        {
             // key exists
             return;
        }
        // key does not exist

Read XLSX file in Java

docx4j now covers xlsx as well.

"Why would you use docx4j to do this", I hear you ask, "rather than POI, which focuses on xlsx and binary xls?"

Probably because you like JAXB (as opposed to XML Beans), or you are already using docx4j for docx or pptx, and need to be able to do some stuff with xlsx as well.

Another possible reason is that the jar XML Beans generates from the OpenXML schemas is too big for your purposes. (To get around this, POI offers a 'lite' subset: the 'big' ooxml-schemas-1.0.jar is 14.5 MB! But if you need to support arbitrary spreadsheets, you'll probably need the complete jar). In contrast, the whole of docx4j/pptx4j/xlsx4j weighs in at about the same as POI's lite subset.

If you are processing spreadsheets only (ie not docx or pptx), and preceding paragraph is not a concern for you, then you would probably be best off using POI.

Storing and Retrieving ArrayList values from hashmap

You could try using MultiMap instead of HashMap

Initialising it will require fewer lines of codes. Adding and retrieving the values will also make it shorter.

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

would become:

Multimap<String, Integer> multiMap = ArrayListMultimap.create();

You can check this link: http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

Use SELECT inside an UPDATE query

Well, it looks like Access can't do aggregates in UPDATE queries. But it can do aggregates in SELECT queries. So create a query with a definition like:

SELECT func_id, min(tax_code) as MinOfTax_Code
FROM Functions
INNER JOIN Tax 
ON (Functions.Func_Year = Tax.Tax_Year) 
AND (Functions.Func_Pure <= Tax.Tax_ToPrice) 
GROUP BY Func_Id

And save it as YourQuery. Now we have to work around another Access restriction. UPDATE queries can't operate on queries, but they can operate on multiple tables. So let's turn the query into a table with a Make Table query:

SELECT YourQuery.* 
INTO MinOfTax_Code
FROM YourQuery

This stores the content of the view in a table called MinOfTax_Code. Now you can do an UPDATE query:

UPDATE MinOfTax_Code 
INNER JOIN Functions ON MinOfTax_Code.func_id = Functions.Func_ID 
SET Functions.Func_TaxRef = [MinOfTax_Code].[MinOfTax_Code]

Doing SQL in Access is a bit of a stretch, I'd look into Sql Server Express Edition for your project!

Sorting table rows according to table header column using javascript or jquery

You can use jQuery DataTables plugin for applying column sorting in desired way.

Column Sorting using DataTable

Convert a string to integer with decimal in Python

What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:

s = '234.67'
i = int(round(float(s)))

Otherwise, just do:

s = '234.67'
i = int(float(s))

Get a timestamp in C in microseconds?

struct timeval contains two components, the second and the microsecond. A timestamp with microsecond precision is represented as seconds since the epoch stored in the tv_sec field and the fractional microseconds in tv_usec. Thus you cannot just ignore tv_sec and expect sensible results.

If you use Linux or *BSD, you can use timersub() to subtract two struct timeval values, which might be what you want.

Constantly print Subprocess output while process is running

@tokland

tried your code and corrected it for 3.4 and windows dir.cmd is a simple dir command, saved as cmd-file

import subprocess
c = "dir.cmd"

def execute(command):
    popen = subprocess.Popen(command, stdout=subprocess.PIPE,bufsize=1)
    lines_iterator = iter(popen.stdout.readline, b"")
    while popen.poll() is None:
        for line in lines_iterator:
            nline = line.rstrip()
            print(nline.decode("latin"), end = "\r\n",flush =True) # yield line

execute(c)

javascript - match string against the array of regular expressions

Consider breaking this problem up into two pieces:

  1. filter out the items that match the given regular expression
  2. determine if that filtered list has 0 matches in it
const sampleStringData = ["frog", "pig", "tiger"];

const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));

if (matches.length === 0) {
  console.log("No matches");
}

java.math.BigInteger cannot be cast to java.lang.Long

You need to add an alias for the count to your query and then use the addScalar() method as the default for list() method in Hibernate seams to be BigInteger for numeric SQL types. Here is an example:

List<Long> sqlResult = session.createSQLQuery("SELECT column AS num FROM table")
    .addScalar("num", StandardBasicTypes.LONG).list();

MySQL joins and COUNT(*) from another table

Maybe I am off the mark here and not understanding the OP but why are you joining tables?

If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.

If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.

AngularJS : When to use service instead of factory

Even when they say that all services and factories are singleton, I don't agree 100 percent with that. I would say that factories are not singletons and this is the point of my answer. I would really think about the name that defines every component(Service/Factory), I mean:

A factory because is not a singleton, you can create as many as you want when you inject, so it works like a factory of objects. You can create a factory of an entity of your domain and work more comfortably with this objects which could be like an object of your model. When you retrieve several objects you can map them in this objects and it can act kind of another layer between the DDBB and the AngularJs model.You can add methods to the objects so you oriented to objects a little bit more your AngularJs App.

Meanwhile a service is a singleton, so we can only create 1 of a kind, maybe not create but we have only 1 instance when we inject in a controller, so a service provides more like a common service(rest calls,functionality.. ) to the controllers.

Conceptually you can think like services provide a service, factories can create multiple instances(objects) of a class

ffmpeg usage to encode a video to H264 codec format

I believe you have libx264 installed and configured with ffmpeg to convert video to h264... Then you can try with -vcodec libx264... The -format option is for showing available formats, this is not a conversion option I think...

How do I create a transparent Activity on Android?

It goes like this:

<activity android:name=".usual.activity.Declaration" android:theme="@android:style/Theme.Translucent.NoTitleBar" />

How to add a footer in ListView?

In this Question, best answer not work for me. After that i found this method to show listview footer,

LayoutInflater inflater = getLayoutInflater();
ViewGroup footerView = (ViewGroup)inflater.inflate(R.layout.footer_layout,listView,false);
listView.addFooterView(footerView, null, false);

And create new layout call footer_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Done"
        android:textStyle="italic"
        android:background="#d6cf55"
        android:padding="10dp"/>
</LinearLayout>

If not work refer this article hear

Enable UTF-8 encoding for JavaScript

I too had this issue, I would copy the whole piece of code and put in Notepad, before pasting in Notepad, make sure you save the file type as ALL files and save the doc as utf-8 format. then you can paste your code and run, It should work. ?????? obiviously means unreadable characters.

insert a NOT NULL column to an existing table

ALTER TABLE `MY_TABLE` ADD COLUMN `STAGE` INTEGER UNSIGNED NOT NULL AFTER `PREV_COLUMN`;

Logging with Retrofit 2

Kotlin Code

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
        val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit.create(PointApi::class.java)

Installing MySQL-python

On Ubuntu it is advised to use the distributions repository. So installing python-mysqldb should be straight forward:

sudo apt-get install python-mysqldb

If you actually want to use pip to install, which is as mentioned before not the suggested path but possible, please have a look at this previously asked question and answer: pip install mysql-python fails with EnvironmentError: mysql_config not found

Here is a very comprehensive guide by the developer: http://mysql-python.blogspot.no/2012/11/is-mysqldb-hard-to-install.html

To get all the prerequisites for python-mysqld to install it using pip (which you will want to do if you are using virtualenv), run this:

sudo apt-get install build-essential python-dev libmysqlclient-dev

Check if an array contains any element of another array in JavaScript

You can use a nested Array.prototype.some call. This has the benefit that it will bail at the first match instead of other solutions that will run through the full nested loop.

eg.

var arr = [1, 2, 3];
var match = [2, 4];

var hasMatch = arr.some(a => match.some(m => a === m));

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

As someone mentioned, just use:

dt.Rows.Clear()

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

How do you add a scroll bar to a div?

<div class="scrollingDiv">foo</div> 

div.scrollingDiv
{
   overflow:scroll;
}

CSS content property: is it possible to insert HTML instead of Text?

As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()) in combination with svg's <foreignObject> element.

You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup))

But note that it is mostly a hack and that there are a lot of limitations :

  • You can not load any external resources from this markup (no CSS, no images, no media etc.).
  • You can not execute script.
  • Since this won't be part of the DOM, the only way to alter it, is to pass the markup as a dataURI, and edit this dataURI in document.styleSheets. for this part, DOMParser and XMLSerializer may help.
  • While the same operation allows us to load url-encoded media in <img> tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).

Now, a small demo of some html markup in a pseudo element :

_x000D_
_x000D_
/* _x000D_
**  original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
*     xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
*  I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
  content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
_x000D_
_x000D_

jQuery if div contains this text, replace that part of the text

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

Jquery mouseenter() vs mouseover()

Old question, but still no good up-to-date answer with insight imo.

As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:

  • both event pairs
    • the mouse can “jump” from outside/outer elements to inner/innermost elements when moved faster than the browser samples its position
    • any enter/over gets a corresponding leave/out (possibly late/jumpy)
    • events go to the visible element below the pointer (invisible elements can’t be target)
  • mouseenter/mouseleave
    • does not bubble (event not useful for delegate handlers)
    • the event registration itself defines the area of observation and abstraction
    • works on the target area, like a park with a pond: the pond is considered part of the park
    • the event is emitted on the target/area whenever the element itself or any descendant directly is entered/left the first time
    • entering a descendant, moving from one descendant to another or moving back into the target does not finish/restart the mouseenter/mouseleave cycle (i.e. no events fire)
    • if you want to observe multiple areas with one handler, register it on each area/element or use the other event pair discussed next
    • descendants of registered areas/elements can have their own handlers, creating an independent observation area with its independent mouseenter/mouseleave event cycles
    • if you think about how a bubbling version of mouseenter/mouseleave could look like, you end up with with something like mouseover/mouseout
  • mouseover/mouseout
    • events bubble
    • events fire whenever the element below the pointer changes
      • mouseout on the previously sampled element
      • followed by mouseover on the new element
      • the events don’t “nest”: before e.g. a child is “overed” the parent will be “out”
    • target/relatedTarget indicate new and previous element
    • if you want to watch different areas
      • register one handler on a common parent (or multiple parents, which together cover all elements you want to watch)
      • look for the element you are interested in between the handler element and the target element; maybe $(event.target).closest(...) suits your needs

Not-so-trivial mouseover/mouseout example:

$('.side-menu, .top-widget')
  .on('mouseover mouseout', event => {
    const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
    const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
    // do something with `thing`
  });

These days, all browsers support mouseover/mouseout and mouseenter/mouseleave natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave, but silently puts them on a wrappers around mouseover/mouseout as the code below exposes.

The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout events that a mouseenter/mouseleave would not get, but the target is messed. The real mouseenter/mouseleave would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout carried.

For that reason I do not use jQuery for those events, but e.g.:

$el[0].addEventListener('mouseover', e => ...);

_x000D_
_x000D_
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);

function log(tag, event) {
  const li = list.insertBefore(document.createElement('li'), list.firstChild);
  // only jQuery handlers have originalEvent
  const e = event.originalEvent || event;
  li.append(`${tag} got ${e.type} on ${e.target.id}`);
}

outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
  margin: 20px;
  border: solid black 2px;
}

#inner {
  min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id=outer>
    <ul id=log>
    </ul>
  </div>
</body>
_x000D_
_x000D_
_x000D_


Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):

$(parent).on("mouseover", e => {
  if ($(e.target).closest('.gold').length) {...};
});

instead of

$(parent).on("mouseover", '.gold', e => {...});

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

What is a mixin, and why are they useful?

Mixins is a concept in Programming in which the class provides functionalities but it is not meant to be used for instantiation. Main purpose of Mixins is to provide functionalities which are standalone and it would be best if the mixins itself do not have inheritance with other mixins and also avoid state. In languages such as Ruby, there is some direct language support but for Python, there isn't. However, you could used multi-class inheritance to execute the functionality provided in Python.

I watched this video http://www.youtube.com/watch?v=v_uKI2NOLEM to understand the basics of mixins. It is quite useful for a beginner to understand the basics of mixins and how they work and the problems you might face in implementing them.

Wikipedia is still the best: http://en.wikipedia.org/wiki/Mixin

Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

ComboData looks like:

public class ComboData
{ 
  public int Id { get; set; } 
  public string Value { get; set; } 
}

(note that Id and Value have to be properties, not class fields)

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.

Date.prototype.getISOTimezoneOffset = function () {
    const offset = this.getTimezoneOffset();
    return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}

Date.prototype.toISOLocaleString = function () {
    return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
        this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
        this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
        this.getMilliseconds().leftPad(3);
}

Number.prototype.leftPad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) {
        s = "0" + s;
    }
    return s;
}

Example usage:

var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"

I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.

(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)

How to get the date from jQuery UI datepicker

I just made some web scraping to discover the behaviour of JequeryUI datepicker, it was necessary for me because I'm not familiar with JS object so:

var month = $(".ui-datepicker-current-day").attr("data-month");
var year = $(".ui-datepicker-current-day").attr("data-year");
var day = $(".ui-state-active").text();

it just pick the value in relation of the changing of class, so you can implement the onchange event:

$(document).on('change', '#datepicker', function() { 
    var month = $(".ui-datepicker-current-day").attr("data-month");
    var year = $(".ui-datepicker-current-day").attr("data-year");
    var day= $(".ui-state-active").text();
   $("#chosenday").text( day + " " + month  + " " + year )  ;
                        
});

or check if the current day is selected:

   if( $("a").hasClass("ui-state-active") ){ 
     var month = $(".ui-datepicker-current-day").attr("data-month");
     var year = $(".ui-datepicker-current-day").attr("data-year");
     var day= $(".ui-state-active").text();
     $("#chosenday").text( day + " " + month  + " " + year );
    }

Using HTML and Local Images Within UIWebView

Swift Version of Lithu T.V's answer:

webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)

AngularJS is rendering <br> as text not as a newline

You need to either use ng-bind-html-unsafe ... or you need to include the ngSanitize module and use ng-bind-html:

with ng-bind-html-unsafe

Use this if you trust the source of the HTML you're rendering it will render the raw output of whatever you put into it.

<div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div>

OR with ng-bind-html

Use this if you DON'T trust the source of the HTML (i.e. it's user input). It will sanitize the html to make sure it doesn't include things like script tags or other sources of potential security risks.

Make sure you include this:

<script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script>

Then reference it in your application module:

var app = angular.module('myApp', ['ngSanitize']);

THEN use it:

<div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div>

How to increase apache timeout directive in .htaccess?

This solution is for Litespeed Server (Apache as well)

Add the following code in .htaccess

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

Litespeed reference

WPF TemplateBinding vs RelativeSource TemplatedParent

TemplateBinding - More limiting than using regular Binding

  • More efficient than a Binding but it has less functionality
  • Only works inside a ControlTemplate's visual tree
  • Doesn't work with properties on Freezables
  • Doesn't work within a ControlTemplate's Trigger
  • Provides a shortcut in setting properties(not as verbose),e.g. {TemplateBinding targetProperty}

Regular Binding - Does not have above limitations of TemplateBinding

  • Respects Parent Properties
  • Resets Target Values to clear out any explicitly set values
  • Example: <Ellipse Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}"/>

How do I seed a random class to avoid getting duplicate random values

In case you can't for some reason use the same Random again and again, try initializing it with something that changes all the time, like the time itself.

new Random(new System.DateTime().Millisecond).Next();

Remember this is bad practice though.

EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:

Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.

The code below is probably your best option:

new Random().Next();

Shuffle DataFrame rows

You can simply use sklearn for this

from sklearn.utils import shuffle
df = shuffle(df)

How can I connect to MySQL on a WAMP server?

Try opening Port 3306, and using that in the connection string not 8080.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

<ui:composition>  
  <h:form id="form1">
    <p:dialog id="dialog1">
      <p:commandButton value="Save" action="#{bean.method1}" /> <!--Working-->
    </p:dialog>
  </h:form>

  <h:form id="form2">
    <p:dialog id="dialog2">
      <p:commandButton value="Save" action="#{bean.method2}" /> <!--Not Working-->
    </p:dialog>
  </h:form>
</ui:composition>

To solve;

<ui:composition>  
  <h:form id="form1">
    <p:dialog id="dialog1">
      <p:commandButton value="Save" action="#{bean.method1}" />   <!-- Working  -->
    </p:dialog>

    <p:dialog id="dialog2">
      <p:commandButton value="Save" action="#{bean.method2}" />   <!--Working  -->
    </p:dialog>
  </h:form>
  <h:form id="form2">
    <!-- ..........  -->
  </h:form>
</ui:composition>

What causes HttpHostConnectException?

You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

How to find pg_config path

To summarize -- PostgreSQL installs its files (including its binary or executable files) in different locations, depending on the version number and the installation method.

Some of the possibilities:

/usr/local/bin/
/Library/PostgreSQL/9.2/bin/
/Applications/Postgres93.app/Contents/MacOS/bin/
/Applications/Postgres.app/Contents/Versions/9.3/bin/

No wonder people get confused!

Also, if your $PATH environment variable includes a path to the directory that includes an executable file (to confirm this, use echo $PATH on the command line) then you can run which pg_config, which psql, etc. to find out where the file is located.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

You can also use named arguments which are optional and can be given in any order.

Set namedArguments = WScript.Arguments.Named

Here's a little helper function:

Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
  If WScript.Arguments.Named.Exists(argumentName) Then
    GetNamedArgument = WScript.Arguments.Named.Item(argumentName) 
  Else  
    GetNamedArgument = defaultValue
  End If
End Function

Example VBS:

'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg

Example Usage:

test.vbs /testArg:123

Git Clone: Just the files, please?

git archive --format=tar --remote=<repository URL> HEAD | tar xf -

taken from here

Regular expression for first and last name

First name would be

"([a-zA-Z]{3,30}\s*)+"

If you need the whole first name part to be shorter than 30 letters, you need to check that seperately, I think. The expression ".{3,30}" should do that.

Your last name requirements would translate into

"[a-zA-Z]{3,30}"

but you should check these. There are plenty of last names containing spaces.

How to Reload ReCaptcha using JavaScript?

grecaptcha.reset(opt_widget_id)

Resets the reCAPTCHA widget. An optional widget id can be passed, otherwise the function resets the first widget created. (from Google's web page)

How to get the Parent's parent directory in Powershell?

You can split it at the backslashes, and take the next-to-last one with negative array indexing to get just the grandparent directory name.

($scriptpath -split '\\')[-2]

You have to double the backslash to escape it in the regex.

To get the entire path:

($path -split '\\')[0..(($path -split '\\').count -2)] -join '\'

And, looking at the parameters for split-path, it takes the path as pipeline input, so:

$rootpath = $scriptpath | split-path -parent | split-path -parent

Why are the Level.FINE logging messages not showing?

why is my java logging not working

provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.

Working with TIFFs (import, export) in Python using numpy

Using cv2

import cv2
image = cv2.imread(tiff_file.tif)
cv2.imshow('tif image',image)

Is it possible to install both 32bit and 64bit Java on Windows 7?

As stated by pnt you can have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

Taking it further from there: Here's how it might be possible to set any runtime parameters for each of those installations:

You can run javacpl.exe or javacpl.cpl of the respective Java-version itself (bin-folder). The specific control panel opens fine. Adding parameters there is possible.

Angular ReactiveForms: Producing an array of checkbox values?

TEMPLATE PART:-

    <div class="form-group">
         <label for="options">Options:</label>
         <div *ngFor="let option of options">
            <label>
                <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"
                                />
                  {{option.name}}
                  </label>
              </div>
              <br/>
         <button (click)="getselectedOptions()"  >Get Selected Items</button>
     </div>

CONTROLLER PART:-

        export class Angular2NgFor {

          constructor() {
             this.options = [
              {name:'OptionA', value:'first_opt', checked:true},
              {name:'OptionB', value:'second_opt', checked:false},
              {name:'OptionC', value:'third_opt', checked:true}
             ];


             this.getselectedOptions = function() {
               alert(this.options
                  .filter(opt => opt.checked)
                  .map(opt => opt.value));
                }
             }

        }

how to dynamically add options to an existing select in vanilla javascript

Use the document.createElement function and then add it as a child of your select.

var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);

PostgreSQL: Why psql can't connect to server?

In my case I saw this error and postgres was not running.

The problem was that the instalation failed to create the required cluster.

The solution was to create the folder /etc/postgres/{postgresql-version}/main

and then create the cluster with:

pg_createcluster {postgresql-version} main

After that wiht just restarting the postgresql service everything should work.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to get current route

_x000D_
_x000D_
router.events.subscribe(e => {_x000D_
      if (e instanceof NavigationEnd) {_x000D_
        this.currentUrl = e.url;_x000D_
      }_x000D_
    });
_x000D_
_x000D_
_x000D_

Change background color on mouseover and remove it after mouseout

HTML:

<div id="id">
</div>
<div id="hiddenDiv" style="display:none;"></div>

jQuery:

$('#id').hover(function(){
    $("#hiddenDiv").css('display','block');
  },
  function(){
    $("#hiddenDiv").css('display','none');
  }
);

jQuery/JavaScript to replace broken images

I found this to work best, if any image fails to load the first time, it is completely removed from the DOM. Executing console.clear() keeps the console window clean, since the 404 errors cannot be omitted with try/catch blocks.

$('img').one('error', function(err) {
    // console.log(JSON.stringify(err, null, 4))
    $(this).remove()
    console.clear()
})

Remove trailing newline from the elements of a string list

All other answers, and mainly about list comprehension, are great. But just to explain your error:

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())

a is a member of your list, not an index. What you could write is this:

[...]
for a in lines:
    strip_list.append(a.strip())

Another important comment: you can create an empty list this way:

strip_list = [0] * 20

But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.

So your code should be like:

strip_list = []
for a in lines:
    strip_list.append(a.strip())

But, for sure, the best one is this one, as this is exactly the same thing:

stripped = [line.strip() for line in lines]

In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript/Jquery to change class onclick?

      <div class="liveChatContainer online">
        <div class="actions" id="change">
         <span class="item title">Need help?</span>
              <a href="/test" onclick="demo()"><i class="fa fa-smile-o"></i>Chat</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Call</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Email</a>
        </div>
              <a href="#" class="liveChatLabel">Contact</a>
     </div>
             <style>
               .actions_one{
               background-color: red;
                      } 
              </style>



           <script>
          function demo(){
      document.getElementById("change").setAttribute("class","actions_one");}
            </script>      

Video 100% width and height

You can use Javascript to dynamically set the height to 100% of the window and then center it using a negative left margin based on the ratio of video width to window width.

http://jsfiddle.net/RfV5C/

var $video  = $('video'),
    $window = $(window); 

$(window).resize(function(){
    var height = $window.height();
    $video.css('height', height);

    var videoWidth = $video.width(),
        windowWidth = $window.width(),
    marginLeftAdjust =   (windowWidth - videoWidth) / 2;

    $video.css({
        'height': height, 
        'marginLeft' : marginLeftAdjust
    });
}).resize();

How do I use extern to share variables between source files?

A very short solution I use to allow a header file to contain the extern reference or actual implementation of an object. The file that actually contains the object just does #define GLOBAL_FOO_IMPLEMENTATION. Then when I add a new object to this file it shows up in that file also without me having to copy and paste the definition.

I use this pattern across multiple files. So in order to keep things as self contained as possible, I just reuse the single GLOBAL macro in each header. My header looks like this:

//file foo_globals.h
#pragma once  
#include "foo.h"  //contains definition of foo

#ifdef GLOBAL  
#undef GLOBAL  
#endif  

#ifdef GLOBAL_FOO_IMPLEMENTATION  
#define GLOBAL  
#else  
#define GLOBAL extern  
#endif  

GLOBAL Foo foo1;  
GLOBAL Foo foo2;


//file main.cpp
#define GLOBAL_FOO_IMPLEMENTATION
#include "foo_globals.h"

//file uses_extern_foo.cpp
#include "foo_globals.h

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

Assembly code vs Machine code vs Object code?

I think these are the main differences

  • readability of the code
  • control over what is your code doing

Readability can make the code improved or substituted 6 months after it was created with litte effort, on the other hand, if performance is critical you may want to use a low level language to target the specific hardware you will have in production, so to get faster execution.

IMO today computers are fast enough to let a programmer gain fast execution with OOP.

How to copy to clipboard using Access/VBA?

I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm

Which works nicely. :)

How can I enable cURL for an installed Ubuntu LAMP stack?

Try this:

sudo apt-get install -y curl

Control the dashed border stroke length and distance between strokes

The native dashed border property value does not offer control over the dashes themselves... so bring on the border-image property!

Brew your own border with border-image

Compatibility: It offers great browser support (IE 11 and all modern browsers). A normal border can be set as a fallback for older browsers.

Let's create these

These borders will display exactly the same cross-browser!

Goal example Goal example with wider gaps

Step 1 - Create a suitable image

This example is 15 pixels wide by 15 pixels high and the gaps are currently 5px wide. It is a .png with transparency.

This is what it looks like in photoshop when zoomed in:

Example Border Image Background Blown Up

This is what it looks like to scale:

Example Border Image Background Actual Size

Controlling gap and stroke length

To create wider / shorter gaps or strokes, widen / shorten the gaps or strokes in the image.

Here is an image with wider 10px gaps:

Larger gaps correctly scaled = Larger gaps to scale

Step 2 - Create the CSS — this example requires 4 basic steps

  1. Define the border-image-source:

    border-image-source:url("http://i.stack.imgur.com/wLdVc.png");  
    
  2. Optional - Define the border-image-width:

    border-image-width: 1;
    

    The default value is 1. It can also be set with a pixel value, percentage value, or as another multiple (1x, 2x, 3x etc). This overrides any border-width set.

  3. Define the border-image-slice:

    In this example, the thickness of the images top, right, bottom and left borders is 2px, and there is no gap outside of them, so our slice value is 2:

    border-image-slice: 2; 
    

    The slices look like this, 2 pixels from the top, right, bottom and left:

    Slices example

  4. Define the border-image-repeat:

    In this example, we want the pattern to repeat itself evenly around our div. So we choose:

    border-image-repeat: round;
    

Writing shorthand

The properties above can be set individually, or in shorthand using border-image:

border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;

Complete example

Note the border: dashed 4px #000 fallback. Non-supporting browsers will receive this border.

_x000D_
_x000D_
.bordered {_x000D_
  display: inline-block;_x000D_
  padding: 20px;_x000D_
  /* Fallback dashed border_x000D_
     - the 4px width here is overwritten with the border-image-width (if set)_x000D_
     - the border-image-width can be omitted below if it is the same as the 4px here_x000D_
  */_x000D_
  border: dashed 4px #000;_x000D_
  _x000D_
  /* Individual border image properties */_x000D_
  border-image-source: url("http://i.stack.imgur.com/wLdVc.png");_x000D_
  border-image-slice: 2;_x000D_
  border-image-repeat: round;  _x000D_
  _x000D_
  /* or use the shorthand border-image */_x000D_
  border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;_x000D_
}_x000D_
_x000D_
_x000D_
/*The border image of this one creates wider gaps*/_x000D_
.largeGaps {_x000D_
  border-image-source: url("http://i.stack.imgur.com/LKclP.png");_x000D_
  margin: 0 20px;_x000D_
}
_x000D_
<div class="bordered">This is bordered!</div>_x000D_
_x000D_
<div class="bordered largeGaps">This is bordered and has larger gaps!</div>
_x000D_
_x000D_
_x000D_

Troubleshooting BadImageFormatException

I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

Your not applying Date formator. rather you are just parsing the date. to get output in this format

yyyy-MM-dd HH:mm:ss.SSSSSS

we have to use format() method here is full example:- Here is full example:- it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {

public static void main(String args[]) throws ParseException {

    SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
     Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");  
    System.out.println(thisDate);
    System.out.println("----------------------------"); 
    System.out.println("After applying formating :");
    String strDateOutput = changeFormat.format(temp);
    System.out.println(strDateOutput);

}

}

Working example screen

nano error: Error opening terminal: xterm-256color

I had this problem connecting to http://sdf.org through Mac OS X Lion. I changed under Terminal Preferences (?+,) > Advanced pane, Declare Terminal as to VT-100.

I also marked Delete Sends Ctrl-H because this Mac connection was confusing zsh.

It appears to be working for my use case.

How do I replace text in a selection?

This frustrated the heck out of me, and none of the above answers really got me what I wanted. I finally found the answer I was looking for, on a mac if you do ? + option + F it will bring up a Find-Replace bar at the bottom of your editor which is local to the file you have open.

There is an icon option which when hovered over says "In Selection" that you can select to find and replace within a selection. I've pointed to the correct icon in the screenshot below.

enter image description here

Hit replace all, and voila, all instances of '0' will be replaced with '255'.

Note: this feature is ONLY available when you use ? + option + F.

It does NOT appear when you use ? + shift + F.

Note: this will replace all instances of '0' with '255'. If you wanted to replace 0 (without the quotes) with 255, then just put 0 (without quotes) and 255 in the Find What: and Replace With: fields respectively.

Note:

option key is also labeled as the alt key.

? key is also labeled as the command key.

How do you decompile a swf file

I've had good luck with the SWF::File library on CPAN, and particularly the dumpswf.plx tool that comes with that distribution. It generates Perl code that, when run, regenerates your SWF.

store return json value in input hidden field

You can use input.value = JSON.stringify(obj) to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)

The JSON object is available on modern browsers or you can use the json2.js library from json.org

SQL Server after update trigger

Here is my example after a test

CREATE TRIGGER [dbo].UpdateTasadoresName 
ON [dbo].Tasadores  
FOR  UPDATE
AS 
      UPDATE Tasadores 
      SET NombreCompleto = RTRIM( Tasadores.Nombre + ' ' + isnull(Tasadores.ApellidoPaterno,'') + ' ' + isnull(Tasadores.ApellidoMaterno,'')    )  
      FROM Tasadores 
    INNER JOIN INSERTED i ON Tasadores.id = i.id

The inserted special table will have the information from the updated record.

Lazy Method for Reading Big File in Python?

I'm in a somewhat similar situation. It's not clear whether you know chunk size in bytes; I usually don't, but the number of records (lines) that is required is known:

def get_line():
     with open('4gb_file') as file:
         for i in file:
             yield i

lines_required = 100
gen = get_line()
chunk = [i for i, j in zip(gen, range(lines_required))]

Update: Thanks nosklo. Here's what I meant. It almost works, except that it loses a line 'between' chunks.

chunk = [next(gen) for i in range(lines_required)]

Does the trick w/o losing any lines, but it doesn't look very nice.

Sum up a column from a specific row down

If you don't mind using OFFSET(), which is a volatile function that recalculates everytime a cell is changed, then this is a good solution that is both dynamic and reusable:

=OFFSET($COL:$COL, ROW(), 1, 1048576 - ROW(), 1)

where $COL is the letter of the column you are going to operate upon, and ROW() is the row function that dynamically selects the same row as the cell containing this formula. You could also replace the ROW() function with a static number ($ROW).

=OFFSET($COL:$COL, $ROW, 1, 1048576 - $ROW, 1)

You could further clean up the formula by defining a named constant for the 1048576 as 'maxRows'. This can be done in the 'Define Name' menu of the Formulas tab.

=OFFSET($COL:$COL, $ROW, 1, maxRows - $ROW, 1)

A quick example: to Sum from C6 to the end of column C, you could do:

=SUM(OFFSET(C:C, 6, 1, maxRows - 6, 1))

or =SUM(OFFSET(C:C, ROW(), 1, maxRows - ROW(),1))

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

The apk must be signed with the same certificates as the previous version

Nothing. Read the documentation: Publishing Updates on Android Market

Before uploading the updated application, be sure that you have incremented the android:versionCode and android:versionName attributes in the element of the manifest file. Also, the package name must be the same and the .apk must be signed with the same private key. If the package name and signing certificate do not match those of the existing version, Market will consider it a new application and will not offer it to users as an update.

Calling C/C++ from Python?

I think cffi for python can be an option.

The goal is to call C code from Python. You should be able to do so without learning a 3rd language: every alternative requires you to learn their own language (Cython, SWIG) or API (ctypes). So we tried to assume that you know Python and C and minimize the extra bits of API that you need to learn.

http://cffi.readthedocs.org/en/release-0.7/

Dictionary returning a default value if the key does not exist

I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.

I wish this were just part of the base Dictionary class.

public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
  TValue _default;
  public TValue DefaultValue {
    get { return _default; }
    set { _default = value; }
  }
  public DictionaryWithDefault() : base() { }
  public DictionaryWithDefault(TValue defaultValue) : base() {
    _default = defaultValue;
  }
  public new TValue this[TKey key]
  {
    get { 
      TValue t;
      return base.TryGetValue(key, out t) ? t : _default;
    }
    set { base[key] = value; }
  }
}

Beware, however. By subclassing and using new (since override is not available on the native Dictionary type), if a DictionaryWithDefault object is upcast to a plain Dictionary, calling the indexer will use the base Dictionary implementation (throwing an exception if missing) rather than the subclass's implementation.

Extension exists but uuid_generate_v4 fails

If the extension is already there but you don't see the uuid_generate_v4() function when you do a describe functions \df command then all you need to do is drop the extension and re-add it so that the functions are also added. Here is the issue replication:

db=# \df
                       List of functions
 Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)
CREATE EXTENSION "uuid-ossp";
ERROR:  extension "uuid-ossp" already exists
DROP EXTENSION "uuid-ossp";
CREATE EXTENSION "uuid-ossp";
db=# \df
                                  List of functions
 Schema |        Name        | Result data type |    Argument data types    |  Type
--------+--------------------+------------------+---------------------------+--------
 public | uuid_generate_v1   | uuid             |                           | normal
 public | uuid_generate_v1mc | uuid             |                           | normal
 public | uuid_generate_v3   | uuid             | namespace uuid, name text | normal
 public | uuid_generate_v4   | uuid             |                           | normal

db=# select uuid_generate_v4();
           uuid_generate_v4
--------------------------------------
 b19d597c-8f54-41ba-ba73-02299c1adf92
(1 row)

What probably happened is that the extension was originally added to the cluster at some point in the past and then you probably created a new database within that cluster afterward. If that was the case then the new database will only be "aware" of the extension but it will not have the uuid functions added which happens when you add the extension. Therefore you must re-add it.

SQL Server: Get data for only the past year

GETDATE() returns current date and time.

If last year starts in midnight of current day last year (like in original example) you should use something like:

DECLARE @start datetime
SET @start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) --  getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= @start

clear javascript console in Google Chrome

I'm going to add to this, as it's a search that came out top on google..

When using ExtJS / Javascript I insert this and the console is cleared out - unless there is an error..

console.log('\033[2J');

I'm more than likely way off course, but this is how I clear the console for each page load/refresh.

Visibility of global variables in imported modules

Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)

There are different ways to solve this, depending on your actual use case.


Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it's just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

Don't use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.


Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:

import builtins
import module1
builtins.a = 3
module1.f()

Convert Text to Date?

To the OP... I also got a type mismatch error the first time I tried running your subroutine. In my case it was cause by non-date-like data in the first cell (i.e. a header). When I changed the contents of the header cell to date-style txt for testing, it ran just fine...

Hope this helps as well.

Programmatically register a broadcast receiver

Create a broadcast receiver

[BroadcastReceiver(Enabled = true, Exported = false)]

public class BCReceiver : BroadcastReceiver
{

    BCReceiver receiver;

    public override void OnReceive(Context context, Intent intent)
    {
        //Do something here
    }
}

From your activity add this code:

LocalBroadcastManager.getInstance(ApplicationContext)
    .registerReceiver(receiver, filter);

How can I trigger a JavaScript event click


Please call trigger function any where and button will click.


<a href="#" id="myBtn" title="" >Button click </a>

function trigger(){
    document.getElementById("myBtn").click();
}

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

Close iOS Keyboard by touching anywhere using Swift

Add this extension to your ViewController :

  extension UIViewController {
// Ends editing view when touches to view 
  open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    self.view.endEditing(true)
  }
}

List of all special characters that need to be escaped in a regex

You can look at the javadoc of the Pattern class: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

You need to escape any char listed there if you want the regular char and not the special meaning.

As a maybe simpler solution, you can put the template between \Q and \E - everything between them is considered as escaped.

How to execute an oracle stored procedure?

Oracle 10g Express Edition ships with Oracle Application Express (Apex) built-in. You're running this in its SQL Commands window, which doesn't support SQL*Plus syntax.

That doesn't matter, because (as you have discovered) the BEGIN...END syntax does work in Apex.

Check number of arguments passed to a Bash script

There is a lot of good information here, but I wanted to add a simple snippet that I find useful.

How does it differ from some above?

  • Prints usage to stderr, which is more proper than printing to stdout
  • Return with exit code mentioned in this other answer
  • Does not make it into a one liner...
_usage(){
    _echoerr "Usage: $0 <args>"
}

_echoerr(){
    echo "$*" >&2
}

if [ "$#" -eq 0 ]; then # NOTE: May need to customize this conditional
    _usage
    exit 2
fi
main "$@"

Round a floating-point number down to the nearest integer?

x//1

The // operator returns the floor of the division. Since dividing by 1 doesn't change your number, this is equivalent to floor but no import is needed. Notes:

  1. This returns a float
  2. This rounds towards -8

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

select t.*
from (
    select RequestID, max(CreatedDate) as MaxCreatedDate
    from table1
    group by RequestID
) tm
inner join table1 t on tm.RequestID = t.RequestID and tm.MaxCreatedDate = t.CreatedDate

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:

$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie

$cfg['Servers'][$i]['user'] = 'root'; // MySQL user

$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password

Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:

$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // true = allow root login

This way you have your root password set.

C++ display stack trace on exception

On Windows, check out BugTrap. Its not longer at the original link, but its still available on CodeProject.

Comparing two byte arrays in .NET

I have not seen many linq solutions here.

I am not sure of the performance implications, however I generally stick to linq as rule of thumb and then optimize later if necessary.

public bool CompareTwoArrays(byte[] array1, byte[] array2)
 {
   return !array1.Where((t, i) => t != array2[i]).Any();
 }

Please do note this only works if they are the same size arrays. an extension could look like so

public bool CompareTwoArrays(byte[] array1, byte[] array2)
 {
   if (array1.Length != array2.Length) return false;
   return !array1.Where((t, i) => t != array2[i]).Any();
 }

How can I use iptables on centos 7?

And to add, you should also be able to do the same for ip6tables after running the systemctl mask firewalld command:

    systemctl start ip6tables.service
    systemctl enable ip6tables.service

React this.setState is not a function

The callback is made in a different context. You need to bind to this in order to have access inside the callback:

VK.api('users.get',{fields: 'photo_50'},function(data){
    if(data.response){
        this.setState({ //the error happens here
            FirstName: data.response[0].first_name
        });
        console.info(this.state.FirstName);
    }

}.bind(this));

EDIT: Looks like you have to bind both the init and api calls:

VK.init(function(){
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},function(data){
            if(data.response){
                this.setState({ //the error happens here
                    FirstName: data.response[0].first_name
                });
                console.info(this.state.FirstName);
            }

        }.bind(this));
    }.bind(this), function(){
    console.info("API initialisation failed");

    }, '5.34');

How to take character input in java

You can simply use (char) System.in.read(); casting to char is necessary to convert int to char

How to display default text "--Select Team --" in combo box on pageload in WPF?

I know this is semi old but what about this way:

<DataTemplate x:Key="italComboWM">
    <TextBlock FontSize="11" FontFamily="Segoe UI" FontStyle="Italic" Text="--Select an item--" />
</DataTemplate>

<ComboBox EmptySelectionBoxTemplate="{StaticResource italComboWM}" />

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

How to start automatic download of a file in Internet Explorer?

I checked and found, it will work on button click via writing onclick event to Anchor tag or Input button

onclick='javascript:setTimeout(window.location=[File location], 1000);'

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

How to edit default.aspx on SharePoint site without SharePoint Designer

You can always use Sharepoint Solution Generator to create a project and edit in VS2008.

You can find the Generator along with Sharepoint Developer tools.

What is the difference between baud rate and bit rate?

Bit rate is a measure of the number of data bits (that's 0's and 1's) transmitted in one second. A figure of 2400 bits per second means 2400 zeros or ones can be transmitted in one second, hence the abbreviation 'bps'.

Baud rate by definition means the number of times a signal in a communications channel changes state. For example, a 2400 baud rate means that the channel can change states up to 2400 times per second. When I say 'change state' I mean that it can change from 0 to 1 up to 2400 times per second. If you think about this, it's pretty much similar to the bit rate, which in the above example was 2400 bps.

Whether you can transmit 2400 zeros or ones in one second (bit rate), or change the state of a digital signal up to 2400 times per second (baud rate), it the same thing.

how to read value from string.xml in android?

while u write R. you are referring to the R.java class created by eclipse, use getResources().getString() and pass the id of the resource from which you are trying to read inside the getString() method.

Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

How to call multiple functions with @click in vue?

The Vue event handling only allows for single function calls. If you need to do multiple ones you can either do a wrapper that includes both:

<div @click="handler"></div>
////////////////////////////
handler: function() { //Syntax assuming its in the 'methods' option of Vue instance
    fn1('foo');
    fn2('bar');
}

EDIT

Another option is to edit the first handler to have a callback and pass the second in.

<div @click="fn1('foo', fn2)"></div>
////////////////////////////////////
fn1: function(value, callback) {
    console.log(value);
    callback('bar');
},
fn2: function(value) {
    console.log(value);
}

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

Is there a reason for C#'s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

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

I got around a similar issue by setting defaultProps:

ComponentName.defaultProps = {
  propName: ''
}

<select value="this.props.propName" ...

So now I avoid errors on compilation if my prop does not exist until mounting.