Programs & Examples On #Allegrograph

AllegroGraph is a closed source Graph database.

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

Image resizing in React Native

**After setting the width and the height of the image then use the resizeMode property by setting it to cover or contain.The following blocks of code translate from normal css to react-native StyleSheet

// In normal css
.image{
   width: 100px;
   height: 100px;
   object-fit: cover;
 }

// in react-native StyleSheet
image:{
   width: 100;
   height: 100;
   resizeMode: "cover";
 }

OR object-fit contain

// In normal css

.image{
   width: 100px;
   height: 100px;
   object-fit: contain;
 }

 // in react-native StyleSheet
image:{
   width: 100;
   height: 100;
   resizeMode: "contain";
 }

How to change int into int64?

This is called type conversion :

i := 23
var i64 int64
i64 = int64(i)

Junit - run set up method once

JUnit 5 @BeforeAll can be non static provided the lifecycle of the test class is per class, i.e., annotate the test class with a @TestInstance(Lifecycle.PER_CLASS) and you are good to go

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

navbar color in Twitter Bootstrap

If you are using LESS, you can use Mixins for less code. Here I will add a gradient, border, and border-radius:

.navbar-inner {
  #gradient > .vertical(#ffffff, #ECECEC);
  border: #E2E2E2;
  .border-radius(6px);
}

*If you are using the rails gem, twitter-bootstrap-rails, I do this directly in the file bootstrap_and_overrides.css.less*

How do you read from stdin?

Regarding this:

for line in sys.stdin:

I just tried it on python 2.7 (following someone else's suggestion) for a very large file, and I don't recommend it, precisely for the reasons mentioned above (nothing happens for a long time).

I ended up with a slightly more pythonic solution (and it works on bigger files):

with open(sys.argv[1], 'r') as f:
    for line in f:

Then I can run the script locally as:

python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work

Test if a property is available on a dynamic variable

For me this works:

if (IsProperty(() => DynamicObject.MyProperty))
  ; // do stuff



delegate string GetValueDelegate();

private bool IsProperty(GetValueDelegate getValueMethod)
{
    try
    {
        //we're not interesting in the return value.
        //What we need to know is whether an exception occurred or not

        var v = getValueMethod();
        return v != null;
    }
    catch (RuntimeBinderException)
    {
        return false;
    }
    catch
    {
        return true;
    }
}

Convert UTC date time to local date time

I believe this is the best solution:

  let date = new Date(objDate);
  date.setMinutes(date.getTimezoneOffset());

This will update your date by the offset appropriately since it is presented in minutes.

How to create a label inside an <input> element?

I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here: https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/

Here example with Label inside Input fields: codepen.io/jdax/pen/mEBJNa

Capturing multiple line output into a Bash variable

After trying most of the solutions here, the easiest thing I found was the obvious - using a temp file. I'm not sure what you want to do with your multiple line output, but you can then deal with it line by line using read. About the only thing you can't really do is easily stick it all in the same variable, but for most practical purposes this is way easier to deal with.

./myscript.sh > /tmp/foo
while read line ; do 
    echo 'whatever you want to do with $line'
done < /tmp/foo

Quick hack to make it do the requested action:

result=""
./myscript.sh > /tmp/foo
while read line ; do
  result="$result$line\n"
done < /tmp/foo
echo -e $result

Note this adds an extra line. If you work on it you can code around it, I'm just too lazy.


EDIT: While this case works perfectly well, people reading this should be aware that you can easily squash your stdin inside the while loop, thus giving you a script that will run one line, clear stdin, and exit. Like ssh will do that I think? I just saw it recently, other code examples here: https://unix.stackexchange.com/questions/24260/reading-lines-from-a-file-with-bash-for-vs-while

One more time! This time with a different filehandle (stdin, stdout, stderr are 0-2, so we can use &3 or higher in bash).

result=""
./test>/tmp/foo
while read line  <&3; do
    result="$result$line\n"
done 3</tmp/foo
echo -e $result

you can also use mktemp, but this is just a quick code example. Usage for mktemp looks like:

filenamevar=`mktemp /tmp/tempXXXXXX`
./test > $filenamevar

Then use $filenamevar like you would the actual name of a file. Probably doesn't need to be explained here but someone complained in the comments.

Java regex email

Try the below code for email is format of

[email protected]

1st part -jsmith 2nd part [email protected]

1. In the 1 part it will allow 0-9,A-Z,dot sign(.),underscore sign(_)
 2. In the 2 part it will allow A-Z, must be @ and .

^[a-zA-Z0-9_.]+@[a-zA-Z.]+?\.[a-zA-Z]{2,3}$

[Ljava.lang.Object; cannot be cast to

Your query execution will return list of Object[].

List result_source = LoadSource.list();
for(Object[] objA : result_source) {
    // read it all
}

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

adding to scotty's answer:

Option 1: Either include this in your JS file:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

Option 2: or just use the URL to download 'angular-route.min.js' to your local.

and then (whatever option you choose) add this 'ngRoute' as dependency.

explained: var app = angular.module('myapp', ['ngRoute']);

Cheers!!!

How do I extract text that lies between parentheses (round brackets)?

A very simple way to do it is by using regular expressions:

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value

As a response to the (very funny) comment, here's the same Regex with some explanation:

\(             # Escaped parenthesis, means "starts with a '(' character"
    (          # Parentheses in a regex mean "put (capture) the stuff 
               #     in between into the Groups array" 
       [^)]    # Any character that is not a ')' character
       *       # Zero or more occurrences of the aforementioned "non ')' char"
    )          # Close the capturing group
\)             # "Ends with a ')' character"

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

perform an action on checkbox checked or unchecked event on html form

Given you use JQuery, you can do something like below :

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onclick="doalert()"/>
</form>

JS

function doalert() {
  if ($("#g01-01").is(":checked")) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

Convert char to int in C#

char c = '1';
int i = (int)(c-'0');

and you can create a static method out of it:

static int ToInt(this char c)
{
    return (int)(c - '0');
}

Visual Studio Code - Convert spaces to tabs

Check this from official vscode setting:

// Controls whether `editor.tabSize#` and `#editor.insertSpaces` will be automatically detected when a file is opened based on the file contents.
"editor.detectIndentation": true,

// The number of spaces a tab is equal to. This setting is overridden based on the file contents when `editor.detectIndentation` is on.
"editor.tabSize": 4,

// Config the editor that making the "space" instead of "tab"
"editor.insertSpaces": true,

// Configure editor settings to be overridden for [html] language.
"[html]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2,
    "editor.autoIndent": false
}

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

Java HashMap: How to get a key and value by index?

HashMaps are not ordered, unless you use a LinkedHashMap or SortedMap. In this case, you may want a LinkedHashMap. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would be

int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
    String key = e.getKey();
    ArrayList<String> val = e.getValue();
    index++;
}

There is no direct get(index) in a map because it is an unordered list of key/value pairs. LinkedHashMap is a special case that keeps the order.

Folder is locked and I can't unlock it

If the file was locked by yourself(same svn account), you can follow these steps:

Right click on the locked file or folder, and select TortoiseSVN->Get lock... , and check on "[] Steal the locks" at the bottom left corner of the dialog, click "OK". If it complete successfully, that's ok. When you right click on the file again, you can see TortoiseSVN->Release lock..., click to unlock.

Which MySQL data type to use for storing boolean values

You can use BOOL, BOOLEAN data type for storing boolean values.

These types are synonyms for TINYINT(1)

However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.

MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).

Further, read documentation

MD5 hashing in Android

The accepted answer didn't work for me in Android 2.2. I don't know why, but it was "eating" some of my zeros (0) . Apache commons also didn't work on Android 2.2, because it uses methods that are supported only starting from Android 2.3.x. Also, if you want to just MD5 a string, Apache commons is too complex for that. Why one should keep a whole library to use just a small function from it...

Finally I found the following code snippet here which worked perfectly for me. I hope it will be useful for someone...

public String MD5(String md5) {
   try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes("UTF-8"));
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
       }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch(UnsupportedEncodingException ex){
    }
    return null;
}

how to insert datetime into the SQL Database table?

myConn.Execute "INSERT INTO DayTr (dtID, DTSuID, DTDaTi, DTGrKg) VALUES (" & Val(txtTrNo) & "," & Val(txtCID) & ", '" & Format(txtTrDate, "yyyy-mm-dd") & "' ," & Val(Format(txtGross, "######0.00")) & ")"

Done in vb with all text type variables.

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.

HTML:

<form class="form-create-container form-create"> </form>   

JS

$(document).on('submit', '.form-create', function(){ 
..... ..... ..... 
$('.form-create-container').removeClass('form-create').submit();

});

How to start an application using android ADB tools?

Try this, for opening an android photo app & with specific image file to open as parameter.

adb shell am start -n com.google.android.apps.photos/.home.HomeActivity -d file:///mnt/user/0/primary/Pictures/Screenshots/Screenshot.png

It will work on latest android, no pop up will come to select an application to open as you are giving specific app to which you want to open your image with

How to refresh datagrid in WPF

Try mydatagrid.Items.Refresh()

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader

Limit Decimal Places in Android EditText

The simplest way to achieve that is:

et.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        String text = arg0.toString();
        if (text.contains(".") && text.substring(text.indexOf(".") + 1).length() > 2) {
            et.setText(text.substring(0, text.length() - 1));
            et.setSelection(et.getText().length());
        }
    }

    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

    }

    public void afterTextChanged(Editable arg0) {
    }
});

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Filter rows which contain a certain string

Solution

It is possible to use str_detect of the stringr package included in the tidyverse package. str_detect returns True or False as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr package.

library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1     ? purrr   0.2.4
# ? tibble  1.4.2     ? dplyr   0.7.4
# ? tidyr   0.7.2     ? stringr 1.2.0
# ? readr   1.1.1     ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag()    masks stats::lag()

mtcars$type <- rownames(mtcars)
mtcars %>%
  filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
# 1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
# 2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
# 4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

The good things about Stringr

We should use rather stringr::str_detect() than base::grepl(). This is because there are the following reasons.

  • The functions provided by the stringr package start with the prefix str_, which makes the code easier to read.
  • The first argument of the functions of stringr package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"

Benchmark

The results of the benchmark test are as follows. For large dataframe, str_detect is faster.

library(rbenchmark)
library(tidyverse)

# The data. Data expo 09. ASA Statistics Computing and Graphics 
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728      29

benchmark(
  "str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
  "grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
  replications = 10,
  columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2      grepl           10  16.480    1.513    16.195    0.248
# 1 str_detect           10  10.891    1.000     9.594    1.281

Python: subplot within a loop: first panel appears in wrong position

Using your code with some random data, this would work:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):

    axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
    axs[i].set_title(str(250+i))

The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here

TypeScript and field initializers

In some scenarios it may be acceptable to use Object.create. The Mozilla reference includes a polyfill if you need back-compatibility or want to roll your own initializer function.

Applied to your example:

Object.create(Person.prototype, {
    'Field1': { value: 'ASD' },
    'Field2': { value: 'QWE' }
});

Useful Scenarios

  • Unit Tests
  • Inline declaration

In my case I found this useful in unit tests for two reasons:

  1. When testing expectations I often want to create a slim object as an expectation
  2. Unit test frameworks (like Jasmine) may compare the object prototype (__proto__) and fail the test. For example:
var actual = new MyClass();
actual.field1 = "ASD";
expect({ field1: "ASD" }).toEqual(actual); // fails

The output of the unit test failure will not yield a clue about what is mismatched.

  1. In unit tests I can be selective about what browsers I support

Finally, the solution proposed at http://typescript.codeplex.com/workitem/334 does not support inline json-style declaration. For example, the following does not compile:

var o = { 
  m: MyClass: { Field1:"ASD" }
};

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

Like it's written up there, you forget to type #include <sstream>

#include <sstream>
using namespace std;

QString Stats_Manager::convertInt(int num)
{
   stringstream ss;
   ss << num;
   return ss.str();
}

You can also use some other ways to convert int to string, like

char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

check this!

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

In apache2.conf, replace or delete <Directory /> AllowOverride None Require all denied </Directory>, like suggested Jan Czarny.

For example:

<Directory />
    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

This worked in Ubuntu 14.04 (Trusty Tahr).

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

PDF Blob - Pop up window not showing content

If you set { responseType: 'blob' }, no need to create Blob on your own. You can simply create url based with response content:

$http({
    url: "...",
    method: "POST",
    responseType: "blob"
}).then(function(response) {
    var fileURL = URL.createObjectURL(response.data);
    window.open(fileURL);
});

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

List(of String) or Array or ArrayList

You can do something like this,

  Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}

Collection Initializers

How to use if statements in underscore.js templates?

Here is a simple if/else check in underscore.js, if you need to include a null check.

<div class="editor-label">
    <label>First Name : </label>
</div>
<div class="editor-field">
    <% if(FirstName == null) { %>
        <input type="text" id="txtFirstName" value="" />
    <% } else { %>
        <input type="text" id="txtFirstName" value="<%=FirstName%>" />
    <% } %>
</div>

Argument Exception "Item with Same Key has already been added"

To illustrate the problem you are having, let's look at some code...

Dictionary<string, string> test = new Dictionary<string, string>();

test.Add("Key1", "Value1");  // Works fine
test.Add("Key2", "Value2");  // Works fine
test.Add("Key1", "Value3");  // Fails because of duplicate key

The reason that a dictionary has a key/value pair is a feature so you can do this...

var myString = test["Key2"];  // myString is now Value2.

If Dictionary had 2 Key2's, it wouldn't know which one to return, so it limits you to a unique key.

How do I pass variables and data from PHP to JavaScript?

Here is is the trick:

  1. Here is your 'PHP' to use that variable:

    <?php
        $name = 'PHP variable';
        echo '<script>';
        echo 'var name = ' . json_encode($name) . ';';
        echo '</script>';
    ?>
    
  2. Now you have a JavaScript variable called 'name', and here is your JavaScript code to use that variable:

    <script>
         console.log("I am everywhere " + name);
    </script>
    

1052: Column 'id' in field list is ambiguous

What you are probably really wanting to do here is use the union operator like this:

(select ID from Logo where AccountID = 1 and Rendered = 'True')
  union
  (select ID from Design where AccountID = 1 and Rendered = 'True')
  order by ID limit 0, 51

Here's the docs for it https://dev.mysql.com/doc/refman/5.0/en/union.html

Auto reloading python Flask app upon code changes

app.run(use_reloader=True)

we can use this, use_reloader so every time we reload the page our code changes will be updated.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

Address validation using Google Maps API

The answer depends upon the degree of confidence you place in the data and how your data is being used. For example, if you're using it for mailing or shipping, you'll want to be be confident that the data is correct. If you're just using it as another fraud-prevention mechanism then you could potentially allow a degree of error to creep into the data.

If you want any degree of real accuracy, you're need to go with a service that does real address verification and you're going to have to pay for it. As has been mentioned by Adam, address verification and validation at first seems simple and easy, but it's a black hole fraught with challenges and, unless you've some underlying data to work with, virtually impossible to do by yourself. Trust me, you're actually saving money by using a service. You're welcome to go down this road yourself to experience what I mean, but I can guarantee you'll see the light, so to speak, after even a few hours (or days) of spinning your wheels.

I should mention that I'm the founder of SmartyStreets. We do address validation and verification addresses and we offer this for the USA and international as well. I'm more than happy to personally answer any questions you have on the topic of address cleansing, standardization, and validation.

anaconda update all possible packages?

Imagine the dependency graph of packages, when the number of packages grows large, the chance of encountering a conflict when upgrading/adding packages is much higher. To avoid this, simply create a new environment in Anaconda.

Be frugal, install only what you need. For me, I installed the following packages in my new environment:

  • pandas
  • scikit-learn
  • matplotlib
  • notebook
  • keras

And I have 84 packages in total.

MVC 4 @Scripts "does not exist"

When i started using MVC4 recently i faced the above issue while creating a project with the empty templates. Steps to fix the issue.

  1. Goto TOOLS --> Library Package Manager --> Packager Manager Console Paste the below command and press enter Install-Package Microsoft.AspNet.Web.Optimization Note: wait for successful installation.
  2. Goto Web.Config file in root level and add below namespace in pages namespace section. add <namespace="System.Web.Optimization" />
  3. Goto Web.Config in Views folder and follow the step 2.
  4. Build the solution and run.

The Package mentioned in step 1 will add few system libraries into the solution references like System.Web.Optimization is not a default reference for empty templates in MVC4.

I hope this helps. Thank you

What is the printf format specifier for bool?

You can't, but you can print 0 or 1

_Bool b = 1;
printf("%d\n", b);

source

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

this works for ubuntu 15.10:

sudo locale-gen "en_US.UTF-8"
sudo dpkg-reconfigure locales

Python get current time in right timezone

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

from datetime import datetime
naive_dt = datetime.now()

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

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

naive_utc_dt = datetime.utcnow()

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

from datetime import datetime, timezone

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

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

import pytz

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

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

Fatal error: Maximum execution time of 300 seconds exceeded

If above answers will not work, try to check your code,,In my experience,having an infinite loop will also cause that problem.Check your else if statement.

How to get the full path of running process?

Try:

using System.Diagnostics;

ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
string processpathfilename;
string processmodulename;
if (modules.Count > 0) {
    processpathfilename = modules[0].FileName;
    processmodulename= modules[0].ModuleName;
} else {
    throw new ExecutionEngineException("Something critical occurred with the running process.");
}

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

This is the disassembled code from .NET Reflector for Path.Combine method. Check IsPathRooted function. If the second path is rooted (starts with a DirectorySeparatorChar), return second path as it is.

public static string Combine(string path1, string path2)
{
    if ((path1 == null) || (path2 == null))
    {
        throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
    }
    CheckInvalidPathChars(path1);
    CheckInvalidPathChars(path2);
    if (path2.Length == 0)
    {
        return path1;
    }
    if (path1.Length == 0)
    {
        return path2;
    }
    if (IsPathRooted(path2))
    {
        return path2;
    }
    char ch = path1[path1.Length - 1];
    if (((ch != DirectorySeparatorChar) &&
         (ch != AltDirectorySeparatorChar)) &&
         (ch != VolumeSeparatorChar))
    {
        return (path1 + DirectorySeparatorChar + path2);
    }
    return (path1 + path2);
}


public static bool IsPathRooted(string path)
{
    if (path != null)
    {
        CheckInvalidPathChars(path);
        int length = path.Length;
        if (
              (
                  (length >= 1) &&
                  (
                      (path[0] == DirectorySeparatorChar) ||
                      (path[0] == AltDirectorySeparatorChar)
                  )
              )

              ||

              ((length >= 2) &&
              (path[1] == VolumeSeparatorChar))
           )
        {
            return true;
        }
    }
    return false;
}

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

To switch to C99 mode in CodeBlocks, follow the next steps:

Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99 in the text area, and click Ok.

This will turn C99 mode on for your Compiler.

I hope this will help someone!

No module named MySQLdb

mysqldb is a module for Python that doesn't come pre-installed or with Django. You can download mysqldb here.

Is there a way to automatically generate getters and setters in Eclipse?

All the other answers are just focus on the IDE level, these are not the most effective and elegant way to generate getters and setters. If you have tens of attributes, the relevant getters and setters methods will make your class code very verbose.

The best way I ever used to generate getters and setters automatically is using project lombok annotations in your java project, lombok.jar will generate getter and setter method when you compile java code.

You just focus on class attributes/variables naming and definition, lombok will do the rest. This is easy to maintain your code.

For example, if you want to add getter and setter method for age variable, you just add two lombok annotations:

@Getter @Setter 
public int age = 10;

This is equal to code like that:

private int age = 10;
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

You can find more details about lombok here: Project Lombok

JNI and Gradle in Android Studio

Android Studio 2.2 came out with the ability to use ndk-build and cMake. Though, we had to wait til 2.2.3 for the Application.mk support. I've tried it, it works...though, my variables aren't showing up in the debugger. I can still query them via command line though.

You need to do something like this:

externalNativeBuild{
   ndkBuild{
        path "Android.mk"
    }
}

defaultConfig {
  externalNativeBuild{
    ndkBuild {
      arguments "NDK_APPLICATION_MK:=Application.mk"
      cFlags "-DTEST_C_FLAG1"  "-DTEST_C_FLAG2"
      cppFlags "-DTEST_CPP_FLAG2"  "-DTEST_CPP_FLAG2"
      abiFilters "armeabi-v7a", "armeabi"
    }
  } 
}

See http://tools.android.com/tech-docs/external-c-builds

NB: The extra nesting of externalNativeBuild inside defaultConfig was a breaking change introduced with Android Studio 2.2 Preview 5 (July 8, 2016). See the release notes at the above link.

How to access property of anonymous type in C#?

Recently, I had the same problem within .NET 3.5 (no dynamic available). Here is how I solved:

// pass anonymous object as argument
var args = new { Title = "Find", Type = typeof(FindCondition) };

using (frmFind f = new frmFind(args)) 
{
...
...
}

Adapted from somewhere on stackoverflow:

// Use a custom cast extension
public static T CastTo<T>(this Object x, T targetType)
{
   return (T)x;
}

Now get back the object via cast:

public partial class frmFind: Form
{
    public frmFind(object arguments)
    {

        InitializeComponent();

        var args = arguments.CastTo(new { Title = "", Type = typeof(Nullable) });

        this.Text = args.Title;

        ...
    }
    ...
}

C++ printing spaces or tabs given a user input integer

Appending single space to output file with stream variable.

// declare output file stream varaible and open file ofstream fout; fout.open("flux_capacitor.txt"); fout << var << " ";

Regex to get NUMBER only from String

The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:

string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

#1292 - Incorrect date value: '0000-00-00'

After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.

It's incorrect to use zeros in date or in datetime, just put null instead of zeros.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

I know it might be late but I'm just adding to Lanti's answer since it's the most popular, I had the same problem as Wouter Vanherck in the comments and I can't comment yet.

What helped for me was instead of just replacing \xampp\apache\conf\extra\httpd-xampp.conf I replaced the whole apache folder. I basically did the same thing with it as with the php folder (steps 2 and 3).

Now the error is fixed and Apache starts just fine.

"unexpected token import" in Nodejs5 and babel?

In your app, you must declare your require() modules, not using the 'import' keyword:

const app = require("example_dependency");

Then, create a .babelrc file:

{
"presets": [ 
    ["es2015", { "modules": false }]
]
}

Then, in your gulpfile, be sure to declare your require() modules:

var gulp = require("gulp");

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Even when using an Authenticator I had to set mail.smtp.auth property to true. Here is a working example:

final Properties props = new Properties();
props.put("mail.smtp.host", config.getSmtpHost());
props.setProperty("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{
  protected PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication(config.getSmtpUser(), config.getSmtpPassword());
  }
});

Java: Instanceof and Generics

I had the same problem and here is my solution (very humble, @george: this time compiling AND working ...).

My probem was inside an abstract class that implements Observer. The Observable fires method update(...) with Object class that can be any kind of Object.

I only want to handler Objects of type T

The solution is to pass the class to the constructor in order to be able to compare types at runtime.

public abstract class AbstractOne<T> implements Observer {

  private Class<T> tClass;
    public AbstractOne(Class<T> clazz) {
    tClass = clazz;
  }

  @Override
  public void update(Observable o, Object arg) {
    if (tClass.isInstance(arg)) {
      // Here I am, arg has the type T
      foo((T) arg);
    }
  }

  public abstract foo(T t);

}

For the implementation we just have to pass the Class to the constructor

public class OneImpl extends AbstractOne<Rule> {
  public OneImpl() {
    super(Rule.class);
  }

  @Override
  public void foo(Rule t){
  }
}

<div> cannot appear as a descendant of <p>

This is a constraint of browsers. You should use div or article or something like that in the render method of App because that way you can put whatever you like inside it. Paragraph tags are limited to only containing a limited set of tags (mostly tags for formatting text. You cannot have a div inside a paragraph

<p><div></div></p>

is not valid HTML. Per the tag omission rules listed in the spec, the <p> tag is automatically closed by the <div> tag, which leaves the </p> tag without a matching <p>. The browser is well within its rights to attempt to correct it by adding an open <p> tag after the <div>:

<p></p><div></div><p></p>

You can't put a <div> inside a <p> and get consistent results from various browsers. Provide the browsers with valid HTML and they will behave better.

You can put <div> inside a <div> though so if you replace your <p> with <div class="p"> and style it appropriately, you can get what you want.

How to uninstall mini conda? python

To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.

Python try-else

That's it. The 'else' block of a try-except clause exists for code that runs when (and only when) the tried operation succeeds. It can be used, and it can be abused.

try:
    fp= open("configuration_file", "rb")
except EnvironmentError:
    confdata= '' # it's ok if the file can't be opened
else:
    confdata= fp.read()
    fp.close()

# your code continues here
# working with (possibly empty) confdata

Personally, I like it and use it when appropriate. It semantically groups statements.

What static analysis tools are available for C#?

Aside from the excellent list by madgnome, I would add a duplicate code detector that is based off the command line (but is free):

http://sourceforge.net/projects/duplo/

Adding script tag to React/JSX

According to Alex McMillan's solution, I have the following adaptation.
My own environment: React 16.8+, next v9+

// add a custom component named Script
// hooks/Script.js

import { useEffect } from 'react'

const useScript = (url, async) => {
  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = (typeof async === 'undefined' ? true : async )

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])
}

export default function Script({ src, async=true}) {

  useScript(src, async)

  return null  // Return null is necessary for the moment.
}

// Use the custom compoennt, just import it and substitute the old lower case <script> tag with the custom camel case <Script> tag would suffice.
// index.js

import Script from "../hooks/Script";

<Fragment>
  {/* Google Map */}
  <div ref={el => this.el = el} className="gmap"></div>

  {/* Old html script */}
  {/*<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>*/}

  {/* new custom Script component */}
  <Script src='http://maps.google.com/maps/api/js' async={false} />
</Fragment>

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

This happens because in r6 it shows an error when you try to extend private styles.

Refer to this link

Defined Edges With CSS3 Filter Blur

I found that, in my case, I did not have to add a wrapper.

I just added -

margin: -1px;

or

margin: 1px; // any non-zero margin
overflow: hidden;

My blurred element was absolutely positioned.

Daemon Threads Explanation

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

How to downgrade python from 3.7 to 3.6

pyenv can be used in Linux/MacOS for python version management. pyenv-win is the fork of pyenv which can be used on Windows.

Installation

MacOS

Tested on Mac Catalina

  1. Install pyenv.

    brew install pyenv
    
  2. Add following to your shell config file:

    • .bashrc/.bash_profile - For Bash
    • .zshrc - For Zsh
    export PYENV_ROOT="$HOME/.pyenv"
    export PATH="$PYENV_ROOT/bin:$PATH"
    eval "$(pyenv init -)"
    
  3. Restart your shell. Start a new shell or run exec "$SHELL" in your current shell.

Linux / Windows on Linux Subsystem

Tested on Arch Linux

  1. Install pyenv on your system.

    curl https://pyenv.run | bash
    
  2. Follow same steps as in Step 2 and 3 of MacOS installation.

Windows

  1. Install pyenv-win on Windows.

    In Powershell

    pip install pyenv-win --target "$HOME\.pyenv"
    

    In cmd.exe

    pip install pyenv-win --target "%USERPROFILE%\.pyenv"
    
  2. Setup the environment variables using Powershell/Terminal.

    [System.Environment]::SetEnvironmentVariable('PYENV',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
    [System.Environment]::SetEnvironmentVariable('PYENV_HOME',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
    [System.Environment]::SetEnvironmentVariable('path', $HOME + "\.pyenv\pyenv-win\bin;" + $HOME + "\.pyenv\pyenv-win\shims;" + $env:Path,"User")
    
  3. Close and re-open your terminal. Run pyenv --version on the terminal.

    a. If the return value is the installed version of pyenv, then continue below. b. If you receive a command not found error, ensure the environment variables are properly set via the GUI: This PC ? Properties ? Advanced system settings ? Advanced ? Environment Variables... ? PATH c. If you receive a command not found error and you are using Visual Studio Code or another IDE with a built in terminal, restart it and try again.

  4. Run pyenv rehash from the home directory.

Usage

Check installed python versions

pyenv versions

Example

$ pyenv versions
* system (set by /home/souser/.pyenv/version)
  3.6.9

Installed a specific python version

pyenv install <version-number>

Uninstall an installed python version

pyenv uninstall <version-number>

Set a python version as system-wide python version

pyenv global <version-number> # <version-number> is the name assigned to your python in output of `pyenv versions`

Example

$ python --version
Python 3.9.1
$ pyenv global 3.6.9
$ python --version
Python 3.6.9
Set a python version for a directory and all it's sub-directories
pyenv local <version-number> # <version-number> is the name assigned to your python in output of `pyenv versions`

Example

~/tmp/temp$ python --version
Python 3.9.1
~/tmp/temp$ pyenv local 3.6.9
~/tmp/temp$ python --version
Python 3.6.9

For more details, you can check the Github repos : pyenv and pyenv-win.

What are the benefits to marking a field as `readonly` in C#?

I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value.

However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. The readonly keyword compiles down to .initonly which is verifiable by the CLR.

The real advantage of this keyword is to generate immutable data structures. Immutable data structures by definition cannot be changed once constructed. This makes it very easy to reason about the behavior of a structure at runtime. For instance, there is no danger of passing an immutable structure to another random portion of code. They can't changed it ever so you can program reliably against that structure.

Here is a good entry about one of the benefits of immutability: Threading

How can I sort an ArrayList of Strings in Java?

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

Remove all files in a directory

#python 2.7
import tempfile
import shutil
import exceptions
import os

def TempCleaner():
    temp_dir_name = tempfile.gettempdir()
    for currentdir in os.listdir(temp_dir_name):
        try:
           shutil.rmtree(os.path.join(temp_dir_name, currentdir))
        except exceptions.WindowsError, e:
            print u'?? ??????? ???????:'+ e.filename

Best way to check if object exists in Entity Framework?

I just check if object is null , it works 100% for me

    try
    {
        var ID = Convert.ToInt32(Request.Params["ID"]);
        var Cert = (from cert in db.TblCompCertUploads where cert.CertID == ID select cert).FirstOrDefault();
        if (Cert != null)
        {
            db.TblCompCertUploads.DeleteObject(Cert);
            db.SaveChanges();
            ViewBag.Msg = "Deleted Successfully";
        }
        else
        {
            ViewBag.Msg = "Not Found !!";
        }                           
    }
    catch
    {
        ViewBag.Msg = "Something Went wrong";
    }

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

Can comments be used in JSON?

JSON doesn't allow comments, per se. The reasoning is utterly foolish, because you can use JSON itself to create comments, which obviates the reasoning entirely, and loads the parser data space for no good reason at all for exactly the same result and potential issues, such as they are: a JSON file with comments.

If you try to put comments in (using // or /* */ or # for instance), then some parsers will fail because this is strictly not within the JSON specification. So you should never do that.

Here, for instance, where my image manipulation system has saved image notations and some basic formatted (comment) information relating to them (at the bottom):

{
    "Notations": [
        {
            "anchorX": 333,
            "anchorY": 265,
            "areaMode": "Ellipse",
            "extentX": 356,
            "extentY": 294,
            "opacity": 0.5,
            "text": "Elliptical area on top",
            "textX": 333,
            "textY": 265,
            "title": "Notation 1"
        },
        {
            "anchorX": 87,
            "anchorY": 385,
            "areaMode": "Rectangle",
            "extentX": 109,
            "extentY": 412,
            "opacity": 0.5,
            "text": "Rect area\non bottom",
            "textX": 98,
            "textY": 385,
            "title": "Notation 2"
        },
        {
            "anchorX": 69,
            "anchorY": 104,
            "areaMode": "Polygon",
            "extentX": 102,
            "extentY": 136,
            "opacity": 0.5,
            "pointList": [
                {
                    "i": 0,
                    "x": 83,
                    "y": 104
                },
                {
                    "i": 1,
                    "x": 69,
                    "y": 136
                },
                {
                    "i": 2,
                    "x": 102,
                    "y": 132
                },
                {
                    "i": 3,
                    "x": 83,
                    "y": 104
                }
            ],
            "text": "Simple polygon",
            "textX": 85,
            "textY": 104,
            "title": "Notation 3"
        }
    ],
    "imageXW": 512,
    "imageYW": 512,
    "imageName": "lena_std.ato",
    "tinyDocs": {
        "c01": "JSON image notation data:",
        "c02": "-------------------------",
        "c03": "",
        "c04": "This data contains image notations and related area",
        "c05": "selection information that provides a means for an",
        "c06": "image gallery to display notations with elliptical,",
        "c07": "rectangular, polygonal or freehand area indications",
        "c08": "over an image displayed to a gallery visitor.",
        "c09": "",
        "c10": "X and Y positions are all in image space. The image",
        "c11": "resolution is given as imageXW and imageYW, which",
        "c12": "you use to scale the notation areas to their proper",
        "c13": "locations and sizes for your display of the image,",
        "c14": "regardless of scale.",
        "c15": "",
        "c16": "For Ellipses, anchor is the  center of the ellipse,",
        "c17": "and the extents are the X and Y radii respectively.",
        "c18": "",
        "c19": "For Rectangles, the anchor is the top left and the",
        "c20": "extents are the bottom right.",
        "c21": "",
        "c22": "For Freehand and Polygon area modes, the pointList",
        "c23": "contains a series of numbered XY points. If the area",
        "c24": "is closed, the last point will be the same as the",
        "c25": "first, so all you have to be concerned with is drawing",
        "c26": "lines between the points in the list. Anchor and extent",
        "c27": "are set to the top left and bottom right of the indicated",
        "c28": "region, and can be used as a simplistic rectangular",
        "c29": "detect for the mouse hover position over these types",
        "c30": "of areas.",
        "c31": "",
        "c32": "The textx and texty positions provide basic positioning",
        "c33": "information to help you locate the text information",
        "c34": "in a reasonable location associated with the area",
        "c35": "indication.",
        "c36": "",
        "c37": "Opacity is a value between 0 and 1, where .5 represents",
        "c38": "a 50% opaque backdrop and 1.0 represents a fully opaque",
        "c39": "backdrop. Recommendation is that regions be drawn",
        "c40": "only if the user hovers the pointer over the image,",
        "c41": "and that the text associated with the regions be drawn",
        "c42": "only if the user hovers the pointer over the indicated",
        "c43": "region."
    }
}

Better way to generate array of all letters in the alphabet

Simplicity is a virtue. Use this naturally readable array:

char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

Python: can't assign to literal

You are trying to assign to literal integer values. 1, 2, etc. are not valid names; they are only valid integers:

>>> 1
1
>>> 1 = 'something'
  File "<stdin>", line 1
SyntaxError: can't assign to literal

You probably want to use a list or dictionary instead:

names = []
for i in range(1, 6):
    name = input("Please enter name {}:".format(i))
    names.append(name)

Using a list makes it much easier to pick a random value too:

winner = random.choice(names)
print('Well done {}. You are the winner!'.format(winner))

Angularjs on page load call function

you can use it directly with $scope instance

     $scope.init=function()
        {
            console.log("entered");
            data={};
            /*do whatever you want such as initialising scope variable,
              using $http instance etcc..*/
        }
       //simple call init function on controller
       $scope.init();

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

How to get/generate the create statement for an existing hive table?

As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE which "shows the CREATE TABLE statement that creates a given table, or the CREATE VIEW statement that creates a given view."

Usage:

SHOW CREATE TABLE myTable;

Wait until all jQuery Ajax requests are done?

Use the ajaxStop event.

For example, let's say you have a loading ... message while fetching 100 ajax requests and you want to hide that message once loaded.

From the jQuery doc:

$("#loading").ajaxStop(function() {
  $(this).hide();
});

Do note that it will wait for all ajax requests being done on that page.

How to get current language code with Swift?

In Swift 3

let langStr = Locale.current.languageCode

Port 80 is being used by SYSTEM (PID 4), what is that?

PID=4 does not show up in Task Manager even after placing check mark on 'Show processes from all users". Well there is only one user.

However, netstat -b shows multiple connections poiting to the same PID=4 which on this computer displayed the following.

enter image description here

I have only chosen those pertaining to TCP protocol.

This was acquired while trouble shooting IIS which did not start after trying out many others. I do not think you should stop this process.

How to access List elements

Learn python the hard way ex 34

try this

animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']

# print "The first (1st) animal is at 0 and is a bear." 

for i in range(len(animals)):
    print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])

# "The animal at 0 is the 1st animal and is a bear."

for i in range(len(animals)):
    print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])

Root password inside a Docker container

try the following command to get the root access

$ sudo -i 

Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

How to get the groups of a user in Active Directory? (c#, asp.net)

In my case the only way I could keep using GetGroups() without any expcetion was adding the user (USER_WITH_PERMISSION) to the group which has permission to read the AD (Active Directory). It's extremely essential to construct the PrincipalContext passing this user and password.

var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();

Steps you may follow inside Active Directory to get it working:

  1. Into Active Directory create a group (or take one) and under secutiry tab add "Windows Authorization Access Group"
  2. Click on "Advanced" button
  3. Select "Windows Authorization Access Group" and click on "View"
  4. Check "Read tokenGroupsGlobalAndUniversal"
  5. Locate the desired user and add to the group you created (taken) from the first step

How to implement a FSM - Finite State Machine in Java

The heart of a state machine is the transition table, which takes a state and a symbol (what you're calling an event) to a new state. That's just a two-index array of states. For sanity and type safety, declare the states and symbols as enumerations. I always add a "length" member in some way (language-specific) for checking array bounds. When I've hand-coded FSM's, I format the code in row and column format with whitespace fiddling. The other elements of a state machine are the initial state and the set of accepting states. The most direct implementation of the set of accepting states is an array of booleans indexed by the states. In Java, however, enumerations are classes, and you can specify an argument "accepting" in the declaration for each enumerated value and initialize it in the constructor for the enumeration.

For the machine type, you can write it as a generic class. It would take two type arguments, one for the states and one for the symbols, an array argument for the transition table, a single state for the initial. The only other detail (though it's critical) is that you have to call Enum.ordinal() to get an integer suitable for indexing the transition array, since you there's no syntax for directly declaring an array with a enumeration index (though there ought to be).

To preempt one issue, EnumMap won't work for the transition table, because the key required is a pair of enumeration values, not a single one.

enum State {
    Initial( false ),
    Final( true ),
    Error( false );
    static public final Integer length = 1 + Error.ordinal();

    final boolean accepting;

    State( boolean accepting ) {
        this.accepting = accepting;
    }
}

enum Symbol {
    A, B, C;
    static public final Integer length = 1 + C.ordinal();
}

State transition[][] = {
    //  A               B               C
    {
        State.Initial,  State.Final,    State.Error
    }, {
        State.Final,    State.Initial,  State.Error
    }
};

Most efficient way to remove special characters from string

public static string RemoveSpecialCharacters(string str){
    return str.replaceAll("[^A-Za-z0-9_\\\\.]", "");
}

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

offsetting an html anchor to adjust for fixed header

Here's the solution that we use on our site. Adjust the headerHeight variable to whatever your header height is. Add the js-scroll class to the anchor that should scroll on click.

// SCROLL ON CLICK
// --------------------------------------------------------------------------
$('.js-scroll').click(function(){
    var headerHeight = 60;

    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight
    }, 500);
    return false;
});

How does one create an InputStream from a String?

Java 7+

It's possible to take advantage of the StandardCharsets JDK class:

String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

String.equals() with multiple conditions (and one action on result)

Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with

while (m.find()) {
    //do something???
}   

Use regex to find a match maybe?

Or create an array

 String[] a = new String[]{
        "tom",
        "bob",
        "harry"
 };

 if(a.contains(stringtomatch)){
     //do something
 }

MySQL error - #1062 - Duplicate entry ' ' for key 2

  1. Drop the primary key first: (The primary key is your responsibility)

    ALTER TABLE Persons DROP PRIMARY KEY ;
    
  2. Then make all insertions:

  3. Add new primary key just like before dropping:

    ALTER TABLE Persons ADD PRIMARY KEY (P_Id);
    

How to start/stop/restart a thread in Java?

Review java.lang.Thread.

To start or restart (once a thread is stopped, you can't restart that same thread, but it doesn't matter; just create a new Thread instance):

// Create your Runnable instance
Task task = new Task(...);

// Start a thread and run your Runnable
Thread t = new Thread(task);

To stop it, have a method on your Task instance that sets a flag to tell the run method to exit; returning from run exits the thread. If your calling code needs to know the thread really has stopped before it returns, you can use join:

// Tell Task to stop
task.setStopFlag(true);

// Wait for it to do so
t.join();

Regarding restarting: Even though a Thread can't be restarted, you can reuse your Runnable instance with a new thread if it has state and such you want to keep; that comes to the same thing. Just make sure your Runnable is designed to allow multiple calls to run.

Populate nested array in mongoose

It's is the best solution:

Car
 .find()
 .populate({
   path: 'pages.page.components'
})

Angular JS POST request not sending JSON data

You can use FormData API https://developer.mozilla.org/en-US/docs/Web/API/FormData

var data = new FormData;
data.append('from', from);
data.append('to', to);

$http({
    url: '/path',
    method: 'POST',
    data: data,
    transformRequest: false,
    headers: { 'Content-Type': undefined }
})

This solution from http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

Is iterating ConcurrentHashMap values thread safe?

What does it mean?

It means that you should not try to use the same iterator in two threads. If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.

What happens if I try to iterate the map with two threads at the same time?

It is not entirely clear what would happen if you broke this rule. You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing. You could also get non-thread-safe behavior.

But if the two threads used different iterators, you should be fine.

What happens if I put or remove a value from the map while iterating it?

That's a separate issue, but the javadoc section that you quoted adequately answers it. Basically, the iterators are thread-safe, but it is not defined whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator. In practice, it probably depends on where in the map the updates occur.

How can I read a text file in Android?

Try this

try {
        reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      String line="";
      String s ="";
   try 
   {
       line = reader.readLine();
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }

Is there any way to kill a Thread?

You can execute your command in a process and then kill it using the process id. I needed to sync between two thread one of which doesn’t return by itself.

processIds = []

def executeRecord(command):
    print(command)

    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    processIds.append(process.pid)
    print(processIds[0])

    #Command that doesn't return by itself
    process.stdout.read().decode("utf-8")
    return;


def recordThread(command, timeOut):

    thread = Thread(target=executeRecord, args=(command,))
    thread.start()
    thread.join(timeOut)

    os.kill(processIds.pop(), signal.SIGINT)

    return;

How to create a .NET DateTime from ISO 8601 format

This solution makes use of the DateTimeStyles enumeration, and it also works with Z.

DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

This prints the solution perfectly.

axios post request to send form data

2020 ES6 way of doing

Having the form in html I binded in data like so:

DATA:

form: {
   name: 'Joan Cap de porc',
   email: '[email protected]',
   phone: 2323,
   query: 'cap d\ou'
   file: null,
   legal: false
},

onSubmit:

async submitForm() {
  const formData = new FormData()
  Object.keys(this.form).forEach((key) => {
    formData.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formData)
    this.$emit('formSent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

Canvas width and height in HTML5

The canvas DOM element has .height and .width properties that correspond to the height="…" and width="…" attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 800;
canvas.height = 600;

Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height); to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.

Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height and style.width CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:

// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width  = 400;
canvas.height = 300; 
canvas.style.width  = '800px';
canvas.style.height = '600px';

See this live example of a canvas that is zoomed in by 4x.

_x000D_
_x000D_
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth   = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle   = '#eff';_x000D_
_x000D_
ctx.fillRect(  10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect(   40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect(   70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
_x000D_
_x000D_

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Not really solve your question but it's an important alternative.

If you want to add custom html to the beginning of the page (inside <body> element), you may use Page.ClientScript.RegisterClientScriptBlock().

Although the method is called "script", but you can add arbitary string, including html.

How to call same method for a list of objects?

maybe map, but since you don't want to make a list, you can write your own...

def call_for_all(f, seq):
    for i in seq:
        f(i)

then you can do:

call_for_all(lamda x: x.start(), all)
call_for_all(lamda x: x.stop(), all)

by the way, all is a built in function, don't overwrite it ;-)

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

"call to undefined function" error when calling class method

Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()

i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.

Remove border radius from Select tag in bootstrap 3

Using the SVG from @ArnoTenkink as an data url combined with the accepted answer, this gives us the perfect solution for retina displays.

select.form-control:not([multiple]) {
    border-radius: 0;
    appearance: none;
    background-position: right 50%;
    background-repeat: no-repeat;
    background-image: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%20%3C%21DOCTYPE%20svg%20PUBLIC%20%22-//W3C//DTD%20SVG%201.1//EN%22%20%22http%3A//www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22%3E%20%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2214px%22%20height%3D%2212px%22%20viewBox%3D%220%200%2014%2012%22%20enable-background%3D%22new%200%200%2014%2012%22%20xml%3Aspace%3D%22preserve%22%3E%20%3Cpolygon%20points%3D%223.862%2C7.931%200%2C4.069%207.725%2C4.069%20%22/%3E%3C/svg%3E);
    padding: .5em;
    padding-right: 1.5em
}

How to style the parent element when hovering a child element?

Another, simpler approach (to an old question)..
would be to place elements as siblings and use:

Adjacent Sibling Selector (+) or General Sibling Selector (~)

<div id="parent">
  <!-- control should come before the target... think "cascading" ! -->
  <button id="control">Hover Me!</button>
  <div id="target">I'm hovered too!</div>
</div>
#parent {
  position: relative;
  height: 100px;
}

/* Move button control to bottom. */
#control {
  position: absolute;
  bottom: 0;
}

#control:hover ~ #target {
  background: red;
}

enter image description here

Demo Fiddle here.

How can I get the request URL from a Java Filter?

Is this what you're looking for?

if (request instanceof HttpServletRequest) {
 String url = ((HttpServletRequest)request).getRequestURL().toString();
 String queryString = ((HttpServletRequest)request).getQueryString();
}

To Reconstruct:

System.out.println(url + "?" + queryString);

Info on HttpServletRequest.getRequestURL() and HttpServletRequest.getQueryString().

How do I read image data from a URL in Python?

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

Matplotlib scatter plot legend

2D scatter plot

Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry.

In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()

enter image description here

3D scatter plot

To plot a scatter in 3D, use the plot method, as the legend does not support Patch3DCollection as is returned by the scatter method of an Axes3D instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle and marker parameters.

import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()

enter image description here

Python, Pandas : write content of DataFrame into text File

I used a slightly modified version:

with open(file_name, 'w', encoding = 'utf-8') as f:
    for rec_index, rec in df.iterrows():
        f.write(rec['<field>'] + '\n')

I had to write the contents of a dataframe field (that was delimited) as a text file.

Swift UIView background color opacity

You can set background color of view to the UIColor with alpha, and not affect view.alpha:

view.backgroundColor = UIColor(white: 1, alpha: 0.5)

or

view.backgroundColor = UIColor.red.withAlphaComponent(0.5)

PHP 7 RC3: How to install missing MySQL PDO

I had, pretty much, the same problem. I was able to see that PDO was enabled but I had no available drivers (using PHP 7-RC4). I managed to resolve the issue by adding the php_pdo_mysql extension to those which were enabled.

Hope this helps!

how to add button click event in android studio

Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:

Button btn1 = (Button)findViewById(R.id.button1);

btn1.setOnClickListener(new View.OnClickListener() {            
    @Override
    public void onClick(View v) {
//your stuff here.
    }
});

Execute command on all files in a directory

One quick and dirty way which gets the job done sometimes is:

find directory/ | xargs  Command 

For example to find number of lines in all files in the current directory, you can do:

find . | xargs wc -l

How to find GCD, LCM on a set of numbers

There is an Euclid's algorithm for GCD,

public int GCF(int a, int b) {
    if (b == 0) return a;
    else return (GCF (b, a % b));
}

By the way, a and b should be greater or equal 0, and LCM = |ab| / GCF(a, b)

Get current date/time in seconds

Better short cuts:

+new Date # Milliseconds since Linux epoch
+new Date / 1000 # Seconds since Linux epoch
Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch

How to use 'git pull' from the command line?

Open up your git bash and type

echo $HOME

This shall be the same folder as you get when you open your command window (cmd) and type

echo %USERPROFILE%

And – of course – the .ssh folder shall be present on THAT directory.

Windows Batch: How to add Host-Entries?

Create a new addHostEntry.bat file with the following content in it:

@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END


:ACCEPTED
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
FIND /C /I "mydomain.com" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    mydomain.com>>%WINDIR%\system32\drivers\etc\hosts
ECHO Finished
GOTO END


:END
ECHO.
ping -n 11 127.0.0.1 > nul
EXIT

Hope this helps!

Checking for an empty file in C++

use this: data.peek() != '\0'

I've been searching for an hour until finaly this helped!

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

How to highlight text using javascript

I have the same problem, a bunch of text comes in through a xmlhttp request. This text is html formatted. I need to highlight every occurrence.

str='<img src="brown fox.jpg" title="The brown fox" />'
    +'<p>some text containing fox.</p>'

The problem is that I don't need to highlight text in tags. For example I need to highlight fox:

Now I can replace it with:

var word="fox";
word="(\\b"+ 
    word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
        + "\\b)";
var r = new RegExp(word,"igm");
str.replace(r,"<span class='hl'>$1</span>")

To answer your question: you can leave out the g in regexp options and only first occurrence will be replaced but this is still the one in the img src property and destroys the image tag:

<img src="brown <span class='hl'>fox</span>.jpg" title="The brown <span 
class='hl'>fox</span> />

This is the way I solved it but was wondering if there is a better way, something I've missed in regular expressions:

str='<img src="brown fox.jpg" title="The brown fox" />'
    +'<p>some text containing fox.</p>'
var word="fox";
word="(\\b"+ 
    word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
    + "\\b)";
var r = new RegExp(word,"igm");
str.replace(/(>[^<]+<)/igm,function(a){
    return a.replace(r,"<span class='hl'>$1</span>");
});

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.

PHP - Copy image to my server direct from URL

From Copy images from url to server, delete all images after

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://www.foodtest.ru/images/big_img/sausage_3.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./tmp/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('tmp/'.$imagename,$image);       

What is thread Safe in java?

As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.

Consider the following method:

private int myInt = 0;
public int AddOne()
{
    int tmp = myInt;
    tmp = tmp + 1;
    myInt = tmp;
    return tmp;
}

Now thread A and thread B both would like to execute AddOne(). but A starts first and reads the value of myInt (0) into tmp. Now for some reason the scheduler decides to halt thread A and defer execution to thread B. Thread B now also reads the value of myInt (still 0) into it's own variable tmp. Thread B finishes the entire method, so in the end myInt = 1. And 1 is returned. Now it's Thread A's turn again. Thread A continues. And adds 1 to tmp (tmp was 0 for thread A). And then saves this value in myInt. myInt is again 1.

So in this case the method AddOne() was called two times, but because the method was not implemented in a thread safe way the value of myInt is not 2, as expected, but 1 because the second thread read the variable myInt before the first thread finished updating it.

Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

Consider defining a bean of type 'service' in your configuration [Spring boot]

I fixed the problem adding this line @ComponentScan(basePackages = {"com.example.DemoApplication"}) to main class file, just up from the class name

_x000D_
_x000D_
package com.example.demo;_x000D_
_x000D_
import org.springframework.boot.SpringApplication;_x000D_
import org.springframework.boot.autoconfigure.SpringBootApplication;_x000D_
import org.springframework.context.annotation.ComponentScan;_x000D_
_x000D_
@SpringBootApplication_x000D_
@ComponentScan(basePackages = {"com.example.DemoApplication"})_x000D_
public class DemoApplication {_x000D_
_x000D_
 public static void main(String[] args) {_x000D_
  SpringApplication.run(DemoApplication.class, args);_x000D_
 }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

How does a PreparedStatement avoid or prevent SQL injection?

Prepared statement is more secure. It will convert a parameter to the specified type.

For example stmt.setString(1, user); will convert the user parameter to a String.

Suppose that the parameter contains a SQL string containing an executable command: using a prepared statement will not allow that.

It adds metacharacter (a.k.a. auto conversion) to that.

This makes it is more safe.

JQuery ajax call default timeout value

As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.

Here's an example:

$.ajax({
    url: "/ajax_json_echo/",
    timeout: 500,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus); // this will be "timeout"
    }
});

Here it is on jsfiddle.

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

Python 3: ImportError "No Module named Setuptools"

A few years ago I inherited a python (2.7.1) project running under Django-1.2.3 and now was asked to enhance it with QR possibilities. Got the same problem and did not find pip or apt-get either. So I solved it in a totally different but easy way. I /bin/vi-ed the setup.py and changed the line "from setuptools import setup" into: "from distutils.core import setup" That did it for me, so I thought I should post this for other users running old pythons. Regards, Roger Vermeir

Sorting an Array of int using BubbleSort

java code

public void bubbleSort(int[] arr){   

    boolean isSwapped = true;

    for(int i = arr.length - 1; isSwapped; i--){

        isSwapped = false;

        for(int j = 0; j < i; j++){

            if(arr[j] > arr[j+1]}{
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                isSwapped = true;
            }
        }

    }

}

How can I print a quotation mark in C?

You have to escape the quotationmark:

printf("\"");

How to simulate a mouse click using JavaScript?

(Modified version to make it work without prototype.js)

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}

You can use it like this:

simulate(document.getElementById("btn"), "click");

Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })

You can use a similar approach to override other default options.

Credits should go to kangax. Here's the original source (prototype.js specific).

Return different type of data from a method in java?

No. Java methods can only return one result (void, a primitive, or an object), and creating a struct-type class like this is exactly how you do it.

As a note, it is frequently possible to make classes like your ReturningValues immutable like this:

public class ReturningValues {
    public final String value;
    public final int index;

    public ReturningValues(String value, int index) {
        this.value = value;
        this.index = index;
    }
}

This has the advantage that a ReturningValues can be passed around, such as between threads, with no concerns about accidentally getting things out of sync.

Text Editor For Linux (Besides Vi)?

I've used Emacs for 20 years. It's great and it works everywhere. I also have TextMate, which I use for some things on the Mac (HTML mode is great). If you want to do Ruby development, Netbeans supports Ruby and it also runs on all platforms.

http://www.netbeans.org/features/ruby/index.html

I've seen some blogs, etc claiming that it's the best Ruby environment available.

Data truncated for column?

However I get an error which doesn't make sense seeing as the column's data type was properly modified?

| Level | Code | Msg | Warn | 12 | Data truncated for column 'incoming_Cid' at row 1

You can often get this message when you are doing something like the following:

REPLACE INTO table2 (SELECT * FROM table1);

Resulted in our case in the following error:

SQL Exception: Data truncated for column 'level' at row 1

The problem turned out to be column misalignment that resulted in a tinyint trying to be stored in a datetime field or vice versa.

What does 'x packages are looking for funding' mean when running `npm install`?

npm install --silent

Seems to suppress the funding issue.

The name 'controlname' does not exist in the current context

1) Check the CodeFile property in <%@Page CodeFile="filename.aspx.cs" %> in "filename.aspx" page , your Code behind file name and this Property name should be same.

2)you may miss runat="server" in code

CodeIgniter 404 Page Not Found, but why?

The cause of the problem was that the server was running PHP using FastCGI.

After changing the config.php to

$config['uri_protocol'] = "REQUEST_URI";

everything worked.

Disable Enable Trigger SQL server for a table

Below is the simplest way

Try the code

ALTER TRIGGER trigger_name DISABLE

That's it :)

How to find length of a string array?

I think you are looking for this

String[] car = new String[10];
int size = car.length;

How to add footnotes to GitHub-flavoured Markdown?

GitHub Flavored Markdown doesn't support footnotes, but you can manually fake it¹ with Unicode characters or superscript tags, e.g. <sup>1</sup>.

¹Of course this isn't ideal, as you are now responsible for maintaining the numbering of your footnotes. It works reasonably well if you only have one or two, though.

SQL Server SELECT LAST N Rows

To display last 3 rows without using order by:

select * from Lms_Books_Details where Book_Code not in 
 (select top((select COUNT(*) from Lms_Books_Details ) -3 ) book_code from Lms_Books_Details) 

How to check for empty array in vba macro

Public Function arrayIsEmpty(arrayToCheck() As Variant) As Boolean
    On Error GoTo Err:
    Dim forCheck
    forCheck = arrayToCheck(0)
    arrayIsEmpty = False
    Exit Function
Err:
    arrayIsEmpty = True
End Function

Define global constants

The solution for the configuration provided by the angular team itself can be found here.

Here is all the relevant code:

1) app.config.ts

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("app.config");

export interface IAppConfig {
    apiEndpoint: string;
}

export const AppConfig: IAppConfig = {    
    apiEndpoint: "http://localhost:15422/api/"    
};

2) app.module.ts

import { APP_CONFIG, AppConfig } from './app.config';

@NgModule({
    providers: [
        { provide: APP_CONFIG, useValue: AppConfig }
    ]
})

3) your.service.ts

import { APP_CONFIG, IAppConfig } from './app.config';

@Injectable()
export class YourService {

    constructor(@Inject(APP_CONFIG) private config: IAppConfig) {
             // You can use config.apiEndpoint now
    }   
}

Now you can inject the config everywhere without using the string names and with the use of your interface for static checks.

You can of course separate the Interface and the constant further to be able to supply different values in production and development e.g.

What does "TypeError 'xxx' object is not callable" means?

I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:

class DOH(object):
def __init__(self, property=None):
    self.property=property

def property():
    return property

x = DOH(1)
print(x.property())

Results

$ python3 t.py
Traceback (most recent call last):
  File "t.py", line 9, in <module>
    print(x.property())
TypeError: 'int' object is not callable

The problem here of course is that the function is overwritten with a property.

set up device for development (???????????? no permissions)

Enter the following commands:

adb kill-server
sudo ./adb start-server
adb devices

This happens when you are not running adb server as root.

stop all instances of node.js server

The fastest way is

killall node

Works with Linux, OS X

How to find all trigger associated with a table with SQL Server?

With this query you can find all Trigger in all tables and all views.

    ;WITH
        TableTrigger
        AS
        (
            Select 
                Object_Kind = 'Table',
                Sys.Tables.Name As TableOrView_Name , 
                Sys.Tables.Object_Id As Table_Object_Id ,
                Sys.Triggers.Name As Trigger_Name, 
                Sys.Triggers.Object_Id As Trigger_Object_Id 
            From Sys.Tables 
            INNER Join Sys.Triggers On ( Sys.Triggers.Parent_id = Sys.Tables.Object_Id )
            Where ( Sys.Tables.Is_MS_Shipped = 0 )
        ),
        ViewTrigger
        AS
        (
            Select 
                Object_Kind = 'View',
                Sys.Views.Name As TableOrView_Name , 
                Sys.Views.Object_Id As TableOrView_Object_Id ,
                Sys.Triggers.Name As Trigger_Name, 
                Sys.Triggers.Object_Id As Trigger_Object_Id 
            From Sys.Views 
            INNER Join Sys.Triggers On ( Sys.Triggers.Parent_id = Sys.Views.Object_Id )
            Where ( Sys.Views.Is_MS_Shipped = 0 )
        ),
        AllObject
        AS
        (
            SELECT * FROM TableTrigger

            Union ALL

            SELECT * FROM ViewTrigger
        )


    Select 
        * 
    From AllObject
    Order By Object_Kind, Table_Object_Id 

sequelize findAll sort order in nodejs

I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)

So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2) but is just an arbitrary sequence (2,4,11,2,9,0).

When I hit this issue with findAll, here was my solution (sub in your returned results for numbers):

var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});

Which returns [2, 23, 20, 53, 9]. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne, but then you're doing n queries when 1 will do.

HTML/CSS: how to put text both right and left aligned in a paragraph

Least amount of markup possible (you only need one span):

<p>This text is left. <span>This text is right.</span></p>

How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.

The full HTML:

<p class="split-para">This text is left. <span>This text is right.</span></p>

And the CSS:

.split-para      { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}

Linux bash: Multiple variable assignment

Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.

read month day year << DATE_COMMAND
 $(date "+%m %d %Y")
DATE_COMMAND
echo $month $day $year

You could also pipe into the read command, but then you'd have to use the variables within a subshell:

day=n/a; month=n/a; year=n/a
date "+%d %m %Y" | { read day month year ; echo $day $month $year; }
echo $day $month $year

results in...

13 08 2013
n/a n/a n/a

Angular ng-if not true

use this

ng-if="area == false"

OR

ng-if="area == true"

this may help someone

Running Node.js in apache?

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

You could also define a __call__() method inside your someClass(), which calls someClass.go() and then pass an instance of someClass() to the pool. This object is pickleable and it works fine (for me)...

class someClass(object):
   def __init__(self):
       pass
   def f(self, x):
       return x*x

   def go(self):
      p = Pool(4)
      sc = p.map(self, range(4))
      print sc

   def __call__(self, x):   
     return self.f(x)

sc = someClass()
sc.go()

How to change Android usb connect mode to charge only?

In your phone go to Settings->Connect to PC.

There you will see the option Default Connection Type. Select it and set it to your preference.

How can I enable or disable the GPS programmatically on Android?

You just need to remove the LocationListener from LocationManager

manager.removeUpdates(listener);

How can I convert an HTML element to a canvas element?

The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.

How to prevent going back to the previous activity?

I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android

  MyActivity.java =>
    @Override
    public void onBackPressed() {

       return;
    }

How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>

Java GC (Allocation Failure)

When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.

 -Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps 

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Format the date using Ruby on Rails

Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

Note that you have to require 'date' for that to work, then you can call it either as Date.strptime (if you only care about the date) or DateTime.strptime (if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

Define css class in django Forms

Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: django-widget-tweaks. Hope somebody will find it useful.

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Using node.js as a simple web server

Is very easy with the tons of libraries presents today. Answers here are functional. If you want another version for start faster and simple

Of course first install node.js. Later:

> # module with zero dependencies
> npm install -g @kawix/core@latest 
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static

Here the content of "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" (you don't need download it, i posted for understand how works behind)

// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" 

// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'

var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)

var app = express() 
app.use(express.static(folder)) 
app.listen(8181)
console.log("Listening on 8181")

What method in the String class returns only the first N characters?

string truncatedToNLength = new string(s.Take(n).ToArray());  

This solution has a tiny bonus in that if n is greater than s.Length, it still does the right thing.

is the + operator less performant than StringBuffer.append()

Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.

Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis

join() once, concat() once, join() for, += for, concat() for

More:
Ajaxian >> String Performance in IE: Array.join vs += continued

Dictionary of dictionaries in Python?

Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

Here it's used twice: for the resulting dict, and for each of the values in the dict.

import collections

def aggregate_names(errors):
    result = collections.defaultdict(lambda: collections.defaultdict(list))
    for real_name, false_name, location in errors:
        result[real_name][false_name].append(location)
    return result

Combining this with your code:

dictionary = aggregate_names(previousFunction(string))

Or to test:

EXAMPLES = [
    ('Fred', 'Frad', 123),
    ('Jim', 'Jam', 100),
    ('Fred', 'Frod', 200),
    ('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)

Can I open a dropdownlist using jQuery

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Character reading from file in Python

It is also possible to read an encoded text file using the python 3 read method:

f = open (file.txt, 'r', encoding='utf-8')
text = f.read()
f.close()

With this variation, there is no need to import any additional libraries

Alternative to the HTML Bold tag

<p style="font-weight:bold;"></p>

VSCode regex find & replace submatch math?

Another simple example:

Search: style="(.+?)"
Replace: css={css`$1`}

Useful for converting HTML to JSX with emotion/css!

CSS selector for first element with class

For some reason none of the above answers seemed to be addressing the case of the real first and only first child of the parent.

#element_id > .class_name:first-child

All the above answers will fail if you want to apply the style to only the first class child within this code.

<aside id="element_id">
  Content
  <div class="class_name">First content that need to be styled</div>
  <div class="class_name">
    Second content that don't need to be styled
    <div>
      <div>
        <div class="class_name">deep content - no style</div>
        <div class="class_name">deep content - no style</div>
        <div>
          <div class="class_name">deep content - no style</div>
        </div>
      </div>
    </div>
  </div>
</aside>

Adding to a vector of pair

Try using another temporary pair:

pair<string,double> temp;
vector<pair<string,double>> revenue;

// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);

get string from right hand side

the pattern maybe looks like this :

substr(STRING, ( length(STRING) - (TOTAL_GET_LENGTH - 1) ),TOTAL_GET_LENGTH)

in your case , it will like this :

substr('299123456789', (length('299123456789')-(9 - 1)),9)

substr('299123456789', (12-8),9)

substr('299123456789', 4,9)

the result ? of course '123456789'

the length is dynamic , voila :)

How to capitalize the first letter of text in a TextView in an Android Application

For future visitors, you can also (best IMHO) import WordUtil from Apache and add a lot of useful methods to you app, like capitalize as shown here:

How to capitalize the first character of each word in a string

What are ODEX files in Android?

This Blog article explains the internals of ODEX files:

WHAT IS AN ODEX FILE?

In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.

How do I pass a list as a parameter in a stored procedure?

I solved this problem through the following:

  1. In C # I built a String variable.

string userId="";

  1. I put my list's item in this variable. I separated the ','.

for example: in C#

userId= "5,44,72,81,126";

and Send to SQL-Server

 SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
  1. I Create Separated Function in SQL-server For Convert my Received List (that it's type is NVARCHAR(Max)) to Table.
CREATE FUNCTION dbo.SplitInts  
(  
   @List      VARCHAR(MAX),  
   @Delimiter VARCHAR(255)  
)  
RETURNS TABLE  
AS  
  RETURN ( SELECT Item = CONVERT(INT, Item) FROM  
      ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')  
        FROM ( SELECT [XML] = CONVERT(XML, '<i>'  
        + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')  
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y  
      WHERE Item IS NOT NULL  
  );
  1. In the main Store Procedure, using the command below, I use the entry list.

SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

My app has a fragment to loading in 3 secs, but when the fist screen is preparing to show, I press home button and resume run it, it show the same error, so It edit my code and it ran very smooth:

new Handler().post(new Runnable() {
        public void run() {
            if (saveIns == null) {
                mFragment = new Fragment_S1_loading();
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, mFragment).commit();
            }
            getActionBar().hide();
            // Loading screen in 3 secs:
            mCountDownTimerLoading = new CountDownTimer(3000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (saveIns == null) {// TODO bug when start app and press home
                                            // button
                        getFragmentManager()
                                .beginTransaction()
                                .replace(R.id.container,
                                        new Fragment_S2_sesstion1()).commitAllowingStateLoss();
                    }
                    getActionBar().show();
                }
            }.start();
        }
    });

NOTE: add commitAllowingStateLoss() instead of commit()