Programs & Examples On #Not exists

Array.push() if does not exist?

For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf() and if it doesn't then just push the item into the array:

_x000D_
_x000D_
var newItem = "NEW_ITEM_TO_ARRAY";_x000D_
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];_x000D_
_x000D_
array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists");_x000D_
_x000D_
console.log(array)
_x000D_
_x000D_
_x000D_

Add a column to a table, if it does not already exist

Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.

IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
    ALTER TABLE Person 
    ADD ColumnName VARCHAR(MAX) NOT NULL
END

I also noticed yours is looking for where table does exist that is obviously just this

 if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null

MySQL Join Where Not Exists

There are three possible ways to do that.

  1. Option

    SELECT  lt.* FROM    table_left lt
    LEFT JOIN
        table_right rt
    ON      rt.value = lt.value
    WHERE   rt.value IS NULL
    
  2. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   lt.value NOT IN
    (
    SELECT  value
    FROM    table_right rt
    )
    
  3. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   NOT EXISTS
    (
    SELECT  NULL
    FROM    table_right rt
    WHERE   rt.value = lt.value
    )
    

How to resize datagridview control when form resizes

Use control anchoring. Set property Anchor of your GridView to Top, Left, Right and it will resize with container. If your GridView are placed inside of some container (ex Panel) then Panel should be anchored too.

How to do multiple arguments to map function where one remains the same in python?

Sometimes I resolved similar situations (such as using pandas.apply method) using closures

In order to use them, you define a function which dynamically defines and returns a wrapper for your function, effectively making one of the parameters a constant.

Something like this:

def add(x, y):
   return x + y

def add_constant(y):
    def f(x):
        return add(x, y)
    return f

Then, add_constant(y) returns a function which can be used to add y to any given value:

>>> add_constant(2)(3)
5

Which allows you to use it in any situation where parameters are given one at a time:

>>> map(add_constant(2), [1,2,3])
[3, 4, 5]

edit

If you do not want to have to write the closure function somewhere else, you always have the possibility to build it on the fly using a lambda function:

>>> map(lambda x: add(x, 2), [1, 2, 3])
[3, 4, 5]

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

I see that you are all editing or updating from our files

For those who want automatic updates you can use our Ubuntu PPA

sudo add-apt-repository ppa:phpmyadmin/ppa

And for Debian users you will need to wait for next version of Debian or use PPA

Ubuntu 20 has phpMyAdmin 4.9 or a later version

Debian issue on our tracker

Countable issues on our tracker

TLDR Update to latest 4.9 or 5.0 version to solve this issue.

What do < and > stand for?

&lt; stands for lesser than (<) symbol and, the &gt; sign stands for greater than (>) symbol.

For more information on HTML Entities, visit this link:

https://www.w3schools.com/HTML/html_entities.asp

How do I grep for all non-ASCII characters?

The easy way is to define a non-ASCII character... as a character that is not an ASCII character.

LC_ALL=C grep '[^ -~]' file.xml

Add a tab after the ^ if necessary.

Setting LC_COLLATE=C avoids nasty surprises about the meaning of character ranges in many locales. Setting LC_CTYPE=C is necessary to match single-byte characters — otherwise the command would miss invalid byte sequences in the current encoding. Setting LC_ALL=C avoids locale-dependent effects altogether.

Take the content of a list and append it to another list

If we have list like below:

list  = [2,2,3,4]

two ways to copy it into another list.

1.

x = [list]  # x =[] x.append(list) same 
print("length is {}".format(len(x)))
for i in x:
    print(i)
length is 1
[2, 2, 3, 4]

2.

x = [l for l in list]
print("length is {}".format(len(x)))
for i in x:
    print(i)
length is 4
2
2
3
4

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

How does the FetchMode work in Spring Data JPA

Spring-jpa creates the query using the entity manager, and Hibernate will ignore the fetch mode if the query was built by the entity manager.

The following is the work around that I used:

  1. Implement a custom repository which inherits from SimpleJpaRepository

  2. Override the method getQuery(Specification<T> spec, Sort sort):

    @Override
    protected TypedQuery<T> getQuery(Specification<T> spec, Sort sort) { 
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = builder.createQuery(getDomainClass());
    
        Root<T> root = applySpecificationToCriteria(spec, query);
        query.select(root);
    
        applyFetchMode(root);
    
        if (sort != null) {
            query.orderBy(toOrders(sort, root, builder));
        }
    
        return applyRepositoryMethodMetadata(entityManager.createQuery(query));
    }
    

    In the middle of the method, add applyFetchMode(root); to apply the fetch mode, to make Hibernate create the query with the correct join.

    (Unfortunately we need to copy the whole method and related private methods from the base class because there was no other extension point.)

  3. Implement applyFetchMode:

    private void applyFetchMode(Root<T> root) {
        for (Field field : getDomainClass().getDeclaredFields()) {
    
            Fetch fetch = field.getAnnotation(Fetch.class);
    
            if (fetch != null && fetch.value() == FetchMode.JOIN) {
                root.fetch(field.getName(), JoinType.LEFT);
            }
        }
    }
    

Call a function with argument list in python

The simpliest way to wrap a function

    func(*args, **kwargs)

... is to manually write a wrapper that would call func() inside itself:

    def wrapper(*args, **kwargs):
        # do something before
        try:
            return func(*a, **kwargs)
        finally:
            # do something after

In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wrapper generator for any function anyFunc():

    def wrapperGenerator(anyFunc, *args, **kwargs):
        def wrapper(*args, **kwargs):
            try:
                # do something before
                return anyFunc(*args, **kwargs)
            finally:
                #do something after
        return wrapper

Please also note that in Python when you don't know or don't want to name all the arguments of a function, you can refer to a tuple of arguments, which is denoted by its name, preceded by an asterisk in the parentheses after the function name:

    *args

For example you can define a function that would take any number of arguments:

    def testFunc(*args):
        print args    # prints the tuple of arguments

Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:

    **kwargs

A similar example that prints the keyword arguments dictionary:

    def testFunc(**kwargs):
        print kwargs    # prints the dictionary of keyword arguments

How do I multiply each element in a list by a number?

Best way is to use list comprehension:

def map_to_list(my_list, n):
# multiply every value in my_list by n
# Use list comprehension!
    my_new_list = [i * n for i in my_list]
    return my_new_list
# To test:
print(map_to_list([1,2,3], -1))

Returns: [-1, -2, -3]

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

How to wrap text in textview in Android

For the case where the TextView is inside a TableLayout, the solution is to set android:shrinkColumns="1" on the TableLayout. (Replace 1 with the column number the TextView you want to wrap is in. (0-indexed))

AFAICT, no other attributes are needed on the TextView.

For other cases, see the other answers here.

FWIW, I had initially gotten it to sort of work with

 <TextView
   android:id="@+id/inventory_text"
   android:layout_width="fill_parent"
   android:layout_weight="1"
   android:width="0dp"

but that resulted in some extra empty space at the bottom of the Dialog it was all in.

MAC addresses in JavaScript

Nope. The reason ActiveX can do it is because ActiveX is a little application that runs on the client's machine.

I would imagine access to such information via JavaScript would be a security vulnerability.

How to define a preprocessor symbol in Xcode

You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png

If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.

Leave only two decimal places after the dot

double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;

How to generate a git patch for a specific commit?

What is the way to generate a patch only for the specific SHA1?

It's quite simple:

Option 1. git show commitID > myFile.patch

Option 2. git commitID~1..commitID > myFile.patch

Note: Replace commitID with actual commit id (SHA1 commit code).

After submitting a POST form open a new window showing the result

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

How to embed a PDF?

<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

C++20 std::source_location

C++ has finally added a non-macro option, and it will likely dominate at some point in the future when C++20 becomes widespread:

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>

void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}

int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

__PRETTY_FUNCTION__ vs __FUNCTION__ vs __func__ vs std::source_location::function_name

Answered at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Android Studio Gradle Configuration with name 'default' not found

compile fileTree(dir: '//you libraries location//', include: ['android-ColorPickerPreference'])

Use above line in your app's gradle file instead of

compile project(':android-ColorPickerPreference')

Hope it helps

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

Use the UITableViewDataSource method

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How can I convert a date into an integer?

Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:

var dates_as_int = dates.map(Date.parse);

Restore the mysql database from .frm files

Just might be useful for someone:

I could only recover frm files after a disaster, at least I could get the table structure from FRM files by doing the following:

1- create some dummy tables with at least one column and SAME NAME with frm files in a new mysql database.

2-stop mysql service

3- copy and paste the old frm files to newly created table's frm files, it should ask you if you want to overwrite or not for each. replace all.

4-start mysql service, and you have your table structure...

regards. anybudy

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

i had this problem too

added this library

implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

and reinstalled the app solved this for me

Using JQuery to check if no radio button in a group has been checked

I am using this much simple

HTML

<label class="radio"><input id="job1" type="radio" name="job" value="1" checked>New Job</label>
<label class="radio"><input id="job2" type="radio" name="job" value="2">Updating Job</label>


<button type="button" class="btn btn-primary" onclick="save();">Save</button>

SCRIPT

 $('#save').on('click', function(e) {
    if (job1.checked)
        {
              alert("New Job"); 
        }
if (job2.checked)
        {
            alert("Updating Job");
        }

}

Iterate through <select> options

You can try like this too.

Your HTML Code

<select id="mySelectionBox">
    <option value="hello">Foo</option>
    <option value="hello1">Foo1</option>
    <option value="hello2">Foo2</option>
    <option value="hello3">Foo3</option>
</select>

You JQuery Code

$("#mySelectionBox option").each(function() {
    alert(this.text + ' ' + this.value);
});

OR

var select =  $('#mySelectionBox')[0];

  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    alert (option.text + ' ' + option.value);
  }

Cannot lower case button text in android studio

in XML: android:textAllCaps="false"

Programmatically:

mbutton.setAllCaps(false);

How to install popper.js with Bootstrap 4?

I had problems installing it Bootstrap as well, so I did:

Install popper.js: npm install popper.js@^1.12.3 --save

Install jQuery: npm install [email protected] --save

Then I had a high severity vulnerability message when installing [email protected] and got this message:

run npm audit fix to fix them, or npm audit for details

So I did npm audit fix, and after another npm audit fix --force it successfully installed!

Find indices of elements equal to zero in a NumPy array

You can use numpy.nonzero to find zero.

>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0)  # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))

Moving Panel in Visual Studio Code to right side

VSCode 1.42 (January 2020) introduces:

Panel on the left/right

The panel can now be moved to the left side of the editor with the setting:

"workbench.panel.defaultLocation": "left"

This removes the command View: Toggle Panel Position (workbench.action.togglePanelPosition) in favor of the following new commands:

  • View: Move Panel Left (workbench.action.positionPanelLeft)
  • View: Move Panel Right (workbench.action.positionPanelRight)
  • View: Move Panel To Bottom (workbench.action.positionPanelBottom)

I can't install python-ldap

On CentOS/RHEL 6, you need to install:

sudo yum install python-devel
sudo yum install openldap-devel

and yum will also install cyrus-sasl-devel as a dependency. Then you can run:

pip-2.7 install python-ldap

How to get Android crash logs?

If you're using Eclipse, make sure you use debug and not run. Make sure you are in the debug perspective (top right) You may have to hit 'Resume' (F8) a few times for the log to print. The crash log will be in the Logcat window at the bottom- double click for fullscreen and make sure you scroll to the bottom. You'll see red text for errors, the crash trace will be something like

09-04 21:35:15.228: ERROR/AndroidRuntime(778): Uncaught handler: thread main exiting due to uncaught exception
09-04 21:35:15.397: ERROR/AndroidRuntime(778): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dazlious.android.helloworld/com.dazlious.android.helloworld.main}: java.lang.ArrayIndexOutOfBoundsException
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268) 
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.os.Looper.loop(Looper.java:123)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.main(ActivityThread.java:3948)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at java.lang.reflect.Method.invokeNative(Native Method)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at java.lang.reflect.Method.invoke(Method.java:521)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at dalvik.system.NativeStart.main(Native Method)
09-04 21:35:15.397: ERROR/AndroidRuntime(778): Caused by: java.lang.ArrayIndexOutOfBoundsException
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.example.android.helloworld.main.onCreate(main.java:13)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     ... 11 more

The important parts for this one are

09-04 21:35:15.397: ERROR/AndroidRuntime(778): Caused by: java.lang.ArrayIndexOutOfBoundsException
09-04 21:35:15.397: ERROR/AndroidRuntime(778):     at com.example.android.helloworld.main.onCreate(main.java:13)

those tell us it was an array out of bounds exception on on line 13 of main.java in the onCrate method.

How to export data to an excel file using PHPExcel

$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
$objWriter->save('php://output');

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Here's what's working for me

on windows

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

2) create the certificate using that localdev.url

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

What is the difference between sscanf or atoi to convert a string to an integer?

You have 3 choices:

  1. atoi

This is probably the fastest if you're using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in int, the behaviour is unspecified.

  1. sscanf

Some error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of char/short/int/long/long long/size_t/ptrdiff_t/intmax_t).

The return value is the number of conversions that succeed, so scanning for "%d" will return 0 if the string does not begin with an integer. You can use "%d%n" to store the index of the first character after the integer that's read in another variable, and thereby check to see if the entire string was converted or if there's junk afterwards. However, like atoi, behaviour on integer overflow is unspecified.

  1. strtol and family

Robust error reporting, provided you set errno to 0 before making the call. Return values are specified on overflow and errno will be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading 0x and 0 as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions of long/long long/intmax_t.

If you need a smaller type you can always store the result in a temporary long or unsigned long variable and check for overflow yourself.

Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.


Personally, I would recommend the strtol family for most purposes. If you're doing something quick-and-dirty, atoi might meet your needs.

As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it's pretty damn easy to roll your own for loop, eg.,

for (x=0; (unsigned)*s-'0'<10; s++) 
    x=10*x+(*s-'0');

Or you can use (for robustness):

if (isdigit(*s))
    x=strtol(s, &s, 10);
else /* error */ 

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

How do I undo a checkout in git?

Try this first:

git checkout master

(If you're on a different branch than master, use the branch name there instead.)

If that doesn't work, try...

For a single file:

git checkout HEAD /path/to/file

For the entire repository working copy:

git reset --hard HEAD

And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:

git reflog
git reset --hard <sha from reflog>

HEAD is a name that always points to the latest commit in your current branch.

How to instantiate, initialize and populate an array in TypeScript?

A simple solution could be:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

Check div is hidden using jquery

Try

if($('#car2').is(':hidden'))
{  
    alert('car 2 is hidden');       
}

CMake unable to determine linker language with C++

I also faced a similar error while compiling my C-based code. I fixed the issue by correcting the source file path in my cmake file. Please check the source file path of each source file mentioned in your cmake file. This might help you too.

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

This occurred for me when I had a source ip constraint on the policy being used by the user (access key / secret key) to create the s3 bucket. My IP was accurate--but for some reason it wouldn't work and gave this error.

Twitter Bootstrap: div in container with 100% height

It is very simple. You can use

.fill .map 
{
  min-height: 100vh;
}

You can change height according to your requirement.

How to install MySQLi on MacOS

I recently ditched Xampp in favor of the native Apache on Mac Sierra because a new php requirement of a project. Sierra comes with php 5.6.25, but it doesn't run mysql_* out of the box, after a lot of googling, I found this site really help - https://php-osx.liip.ch. As it turns out php 5.6.25 does support mysql_* but wasn't enabled. Choose your version of php and download it, it generates a proper php.ini for your php, then you are good to go

"The page has expired due to inactivity" - Laravel 5.5

Sign in to connect to the server.

Search Error

An error has occurred: search false You don't have the peais.

Search request is longer.

Defining a variable with or without export

export NAME=value for settings and variables that have meaning to a subprocess.

NAME=value for temporary or loop variables private to the current shell process.

In more detail, export marks the variable name in the environment that copies to a subprocesses and their subprocesses upon creation. No name or value is ever copied back from the subprocess.

  • A common error is to place a space around the equal sign:

    $ export FOO = "bar"  
    bash: export: `=': not a valid identifier
    
  • Only the exported variable (B) is seen by the subprocess:

    $ A="Alice"; export B="Bob"; echo "echo A is \$A. B is \$B" | bash
    A is . B is Bob
    
  • Changes in the subprocess do not change the main shell:

    $ export B="Bob"; echo 'B="Banana"' | bash; echo $B
    Bob
    
  • Variables marked for export have values copied when the subprocess is created:

    $ export B="Bob"; echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash &
    [1] 3306
    $ B="Banana"; echo '(sleep 30; echo "Subprocess 2 has B=$B")' | bash 
    Subprocess 1 has B=Bob
    Subprocess 2 has B=Banana
    [1]+  Done         echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash
    
  • Only exported variables become part of the environment (man environ):

     $ ALICE="Alice"; export BOB="Bob"; env | grep "ALICE\|BOB"
     BOB=Bob
    

So, now it should be as clear as is the summer's sun! Thanks to Brain Agnew, alexp, and William Prusell.

SSL Error: CERT_UNTRUSTED while using npm command

npm ERR! node -v v0.8.0
npm ERR! npm -v 1.1.32

Update your node.js installation.The following commands should do it (from here):

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Edit: okay, if you really have a good reason to run an ancient version of the software, npm set ca null will fix the issue. It happened, because built-in npm certificate has expired over the years.

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

How to put a delay on AngularJS instant search?

UPDATE

Now it's easier than ever (Angular 1.3), just add a debounce option on the model.

<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">

Updated plunker:
http://plnkr.co/edit/4V13gK

Documentation on ngModelOptions:
https://docs.angularjs.org/api/ng/directive/ngModelOptions

Old method:

Here's another method with no dependencies beyond angular itself.

You need set a timeout and compare your current string with the past version, if both are the same then it performs the search.

$scope.$watch('searchStr', function (tmpStr)
{
  if (!tmpStr || tmpStr.length == 0)
    return 0;
   $timeout(function() {

    // if searchStr is still the same..
    // go ahead and retrieve the data
    if (tmpStr === $scope.searchStr)
    {
      $http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
        // update the textarea
        $scope.responseData = data.res; 
      });
    }
  }, 1000);
});

and this goes into your view:

<input type="text" data-ng-model="searchStr">

<textarea> {{responseData}} </textarea>

The mandatory plunker: http://plnkr.co/dAPmwf

How to insert a character in a string at a certain position?

For Kotlin dudes ;) from the accepted answer (@MikeThomsen's)

fun String.insert(index: Int, string: String): String {
    return this.substring(0, index) + string + this.substring(index, this.length)
}

Test ?

"ThisTest".insert(4, "Is").should.equal("ThisIsTest")

How to select a dropdown value in Selenium WebDriver using Java

WebDriver driver = new FirefoxDriver();
WebElement identifier = driver.findElement(By.id("periodId"));
Select select = new Select(identifier);
select.selectByVisibleText("Last 52 Weeks"); 

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Simple and easy:

$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

Try netstat like this: netstat -ntp, without the -l. It will show tcp connection in TIME_WAIT state.

How to start a Process as administrator mode in C#

 Process proc = new Process();                                                              
                   ProcessStartInfo info = 
                   new ProcessStartInfo("Your Process name".exe, "Arguments");
                   info.WindowStyle = ProcessWindowStyle.Hidden;
                   info.UseShellExecute =true;
                   info.Verb ="runas";
                   proc.StartInfo = info;
                   proc.Start();

Python Binomial Coefficient

Here is a function that recursively calculates the binomial coefficients using conditional expressions

def binomial(n,k):
    return 1 if k==0 else (0 if n==0 else binomial(n-1, k) + binomial(n-1, k-1))

Difference between an API and SDK

API = Dictionary of available words and their meanings (and the required grammar to combine them)

SDK = A Word processing system… for 2 year old babies… that writes right from ideas

Although you COULD go to school and become a master in your language after a few years, using the SDK will help you write whole meaningful sentences in no time (Forgiving the fact that, in this example, as a baby you haven't even gotten to learn any other language for at least to learn to use the SDK.)

Show history of a file?

The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?

You can use git blame for this, it will anotate each line with a SHA1 and a date when it was changed. git blame can also tell you when a certain line was deleted or where it was moved if you are interested in that.

If you are trying to find out, when a certain bug was introduced, git bisect is a very powerfull tool. git bisect will do a binary search on your history. You can use git bisect start to start bisecting, then git bisect bad to mark a commit where the bug is present and git bisect good to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.

Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.

If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.

Detect when an HTML5 video finishes

You can simply add onended="myFunction()" to your video tag.

<video onended="myFunction()">
  ...
  Your browser does not support the video tag.
</video>

<script type='text/javascript'>
  function myFunction(){
    console.log("The End.")
  }
</script>

What is a "callback" in C and how are they implemented?

A simple call back program. Hope it answers your question.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"

typedef void (*call_back) (S32, S32);

void test_call_back(S32 a, S32 b)
{
    printf("In call back function, a:%d \t b:%d \n", a, b);
}

void call_callback_func(call_back back)
{
    S32 a = 5;
    S32 b = 7;

    back(a, b);
}

S32 main(S32 argc, S8 *argv[])
{
    S32 ret = SUCCESS;

    call_back back;

    back = test_call_back;

    call_callback_func(back);

    return ret;
}

How to change environment's font size?

As of mid 2017 To quickly get to the settings files press ctrl + shift + p and enter settings, there you will find the user settings and the workspace settings, be aware that the workspace settings will override the user settings, so it's better to use the latter directly to make it a global change (workspace settings will create a folder in your project root), from there you will have the option to add the option "editor.fontSize": 14 to your settings as a quick suggestion, but you can do it yourself and change the value to your preferred font size.

To sum it up:

  1. ctrl + shift + p

  2. select "user settings"

  3. add "editor.fontSize": 14

Save image from url with curl PHP

try this:

function grab_image($url,$saveto){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

and ensure that in php.ini allow_url_fopen is enable

Opening a folder in explorer and selecting a file

// suppose that we have a test.txt at E:\
string filePath = @"E:\test.txt";
if (!File.Exists(filePath))
{
    return;
}

// combine the arguments together
// it doesn't matter if there is a space after ','
string argument = "/select, \"" + filePath +"\"";

System.Diagnostics.Process.Start("explorer.exe", argument);

Getting next element while cycling through a list

For strings list from 1(or whatever > 0) until end.

itens = ['car', 'house', 'moon', 'sun']

v = 0
for item in itens:
    b = itens[1 + v]
    print(b)
    print('any other command')
    if b == itens[-1]:
        print('End')
        break
    v += 1

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

Add marker to Google Map on Click

In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}

Batch file to perform start, run, %TEMP% and delete all

The following batch commands are used to delete all your temp, recent and prefetch files on your System.

Save the following code as "Clear.bat" on your local system

*********START CODE************

@ECHO OFF

del /s /f /q %userprofile%\Recent\*.*

del /s /f /q C:\Windows\Prefetch\*.*

del /s /f /q C:\Windows\Temp\*.*

del /s /f /q %USERPROFILE%\appdata\local\temp\*.*


/Below command to Show the folder after deleted files

Explorer %userprofile%\Recent

Explorer C:\Windows\Prefetch

Explorer C:\Windows\Temp

Explorer %USERPROFILE%\appdata\local\temp


*********END CODE************

Best way to disable button in Twitter's Bootstrap

Building off jeroenk's answer, here's the rundown:

$('button').addClass('disabled'); // Disables visually
$('button').prop('disabled', true); // Disables visually + functionally

$('input[type=button]').addClass('disabled'); // Disables visually
$('input[type=button]').prop('disabled', true); // Disables visually + functionally

$('a').addClass('disabled'); // Disables visually
$('a').prop('disabled', true); // Does nothing
$('a').attr('disabled', 'disabled'); // Disables visually

See fiddle

CSS background image URL failing to load

source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")

Dynamic variable names in Bash

For indexed arrays, you can reference them like so:

foo=(a b c)
bar=(d e f)

for arr_var in 'foo' 'bar'; do
    declare -a 'arr=("${'"$arr_var"'[@]}")'
    # do something with $arr
    echo "\$$arr_var contains:"
    for char in "${arr[@]}"; do
        echo "$char"
    done
done

Associative arrays can be referenced similarly but need the -A switch on declare instead of -a.

Why does Boolean.ToString output "True" and not "true"

...because the .NET environment is designed to support many languages.

System.Boolean (in mscorlib.dll) is designed to be used internally by languages to support a boolean datatype. C# uses all lowercase for its keywords, hence 'bool', 'true', and 'false'.

VB.NET however uses standard casing: hence 'Boolean', 'True', and 'False'.

Since the languages have to work together, you couldn't have true.ToString() (C#) giving a different result to True.ToString() (VB.NET). The CLR designers picked the standard CLR casing notation for the ToString() result.

The string representation of the boolean true is defined to be Boolean.TrueString.

(There's a similar case with System.String: C# presents it as the 'string' type).

How do you make websites with Java?

Read the tutorial on Java Web applications.

Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.

All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).

Here is a Tomcat tutorial.

List files ONLY in the current directory

You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

example:

files = os.listdir(os.curdir)  #files and directories

or

files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.

What's the difference between StaticResource and DynamicResource in WPF?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

How can I revert multiple Git commits (already pushed) to a published repository?

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits. 2 - reverts last commits. n - reverts last n commits

or

git reset --hard siriwjdd

How to use pip with python 3.4 on windows?

I had the same issue. The problem is that pip install tries to use C:\Users(username)\AppData\Local\Temp to unpack. You have to explicitly set those directories to R/W.I still couldn't do it because it was a work laptop and there were some permissions issues with trying to set these directories to R/W. The alternative is to go to your Env Variables, and set both Tmp and Temp to point to a writeable directory such as C:. The installation went fine. I was able to install pip.

The way I stumbled onto this is by not defaulting pip install in my installation. Even though the pip install was failing, the installer was not giving any errors. Removing pip and then trying to manually add it later is what pointed to what was going on.

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

Generate a random number in the range 1 - 10

If you are using SQL Server then correct way to get integer is

SELECT Cast(RAND()*(b-a)+a as int);

Where

  • 'b' is the upper limit
  • 'a' is lower limit

C# DateTime to UTC Time without changing the time

6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc

from

DateTime dt = DateTime.Now;            
Console.WriteLine("{0} {1}", dt, dt.Kind);
DateTime ut = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Console.WriteLine("{0} {1}", ut, ut.Kind);

How to use ImageBackground to set background image for screen in react-native

I think this will help u..

import React, { Component } from 'react';
import { homePageStyles } from '../styles/Style';
import { Text, ImageBackground } from 'react-native';
import HomePageWallpaper from '../images/homePageWallpaper.jpg';

export default class Home extends Component {
    render() {
        return (
            <ImageBackground source={HomePageWallpaper} style={{ flex: 1, justifyContent: 'center', width: null, height: null }}>
                <Container>                    
                    <Content>
                        <Text style={homePageStyles.description_text}>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</Text>
                    </Content>
                </Container >
            </ImageBackground>
        );
    }
}

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

You can use a map with your object or string like bellow :

@RequestMapping(value = "/path", 
        method = RequestMethod.GET, 
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Map<String,String>> getData(){

    Map<String,String> response = new HashMap<String, String>();

    boolean isValid = // some logic
    if (isValid){
        response.put("ok", "success saving data");
        return ResponseEntity.accepted().body(response);
    }
    else{
        response.put("error", "an error expected on processing file");
        return ResponseEntity.badRequest().body(response);
    }

}

Is it possible to center text in select box?

It's not 100% yet, but you can use this snippet!

text-align-last: center; // For Chrome text-align: center; // For Firefox

Doesn't work on Safari or Edge, for now!

What parameters should I use in a Google Maps URL to go to a lat-lon?

This is current accepted way to link to a specific lat lon (rather than search for the nearest object).

http://maps.google.com/maps?z=12&t=m&q=loc:38.9419+-78.3020
  • z is the zoom level (1-20)
  • t is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)
  • q is the search query, if it is prefixed by loc: then google assumes it is a lat lon separated by a +

How to resolve git stash conflict without commit?

git stash branch will works, which creates a new branch for you, checks out the commit you were on when you stashed your work, reapplies your work there, and then drops the stash if it applies successfully. check this

How to read a configuration file in Java

It depends.

Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding

And if none of those meet your particular needs, you could even look at using some kind of Database

How to keep a git branch in sync with master

You are thinking in the right direction. Merge master with mobiledevicesupport continuously and merge mobiledevicesupport with master when mobiledevicesupport is stable. Each developer will have his own branch and can merge to and from either on master or mobiledevicesupport depending on their role.

HTML CSS How to stop a table cell from expanding

No javascript, just CSS. Works fine!

   .no-break-out {
      /* These are technically the same, but use both */
      overflow-wrap: break-word;
      word-wrap: break-word;

      -ms-word-break: break-all;
      /* This is the dangerous one in WebKit, as it breaks things wherever */
      word-break: break-all;
      /* Instead use this non-standard one: */
      word-break: break-word;

      /* Adds a hyphen where the word breaks, if supported (No Blink) */
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

    }

Stretch image to fit full container width bootstrap

First of all if the size of the image is smaller than the container, then only "img-fluid" class will not solve your problem. you have to set the width of image to 100%, for that you can use Bootstrap class "w-100". keep in mind that "container-fluid" and "col-12" class sets left and right padding to 15px and "row" class sets left and right margin to "-15px" by default. make sure to set them to 0.

Note: "px-0" is a bootstrap class which sets left and right padding to 0 and
"mx-0" is a bootstrap class which sets left and right margin to 0

P.S. i am using Bootstrap 4.0 version.

 <div class="container-fluid px-0">
        <div class="row mx-0">
            <div class="col-12 px-0">
            <img src="images/top.jpg" class="img-fluid w-100">
            </div>
        </div>
    </div>

How do I center list items inside a UL element?

write display:inline-block instead of float:left.

li {
        display:inline-block;
        *display:inline; /*IE7*/
        *zoom:1; /*IE7*/
        background:blue;
        color:white;
        margin-right:10px;
}

http://jsfiddle.net/3Ezx2/3/

Why use the INCLUDE clause when creating an index?

If the column is not in the WHERE/JOIN/GROUP BY/ORDER BY, but only in the column list in the SELECT clause is where you use INCLUDE.

The INCLUDE clause adds the data at the lowest/leaf level, rather than in the index tree. This makes the index smaller because it's not part of the tree

INCLUDE columns are not key columns in the index, so they are not ordered. This means it isn't really useful for predicates, sorting etc as I mentioned above. However, it may be useful if you have a residual lookup in a few rows from the key column(s)

Another MSDN article with a worked example

How can I check whether an array is null / empty?

I believe that what you want is

int[] k = new int[3];

if (k != null) {  // Note, != and not == as above
    System.out.println(k.length);
}

You newed it up so it was never going to be null.

Greater than and less than in one statement

This is one ugly way to do this. I would just use a local variable.

EDIT: If size() > 0 as well.

if (orderBean.getFiles().size() + Integer.MIN_VALUE-1 < Integer.MIN_VALUE + 5-1)

How to sum up elements of a C++ vector?

I'm a Perl user, an a game we have is to find every different ways to increment a variable... that's not really different here. The answer to how many ways to find the sum of the elements of a vector in C++ is probably an infinity...

My 2 cents:

Using BOOST_FOREACH, to get free of the ugly iterator syntax:

sum = 0;
BOOST_FOREACH(int & x, myvector){
  sum += x;
}

iterating on indices (really easy to read).

int i, sum = 0;
for (i=0; i<myvector.size(); i++){
  sum += myvector[i];
}

This other one is destructive, accessing vector like a stack:

while (!myvector.empty()){
   sum+=myvector.back();
   myvector.pop_back();
}

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

Should a RESTful 'PUT' operation return something

If the backend of the REST API is a SQL relational database, then

  1. you should have RowVersion in every record that can be updated (to avoid the lost update problem)
  2. you should always return a new copy of the record after PUT (to get the new RowVersion).

If you don't care about lost updates, or if you want to force your clients to do a GET immediately after a PUT, then don't return anything from PUT.

Custom exception type

function MyError(message) {
 this.message = message;
}

MyError.prototype = new Error;

This allows for usage like..

try {
  something();
 } catch(e) {
  if(e instanceof MyError)
   doSomethingElse();
  else if(e instanceof Error)
   andNowForSomethingCompletelyDifferent();
}

How do I get a value of a <span> using jQuery?

In javascript wouldn't you use document.getElementById('item1').innertext?

How to get only the date value from a Windows Forms DateTimePicker control?

You mean how to get date without the time component? Use DateTimePicker.Value.Date But you need to format the output to your needs.

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

Exposing a port on a live Docker container

There is a handy HAProxy wrapper.

docker run -it -p LOCALPORT:PROXYPORT --rm --link TARGET_CONTAINER:EZNAME -e "BACKEND_HOST=EZNAME" -e "BACKEND_PORT=PROXYPORT" demandbase/docker-tcp-proxy

This creates an HAProxy to the target container. easy peasy.

Case vs If Else If: Which is more efficient?

I believe because cases must be constant values, the switch statement does the equivelent of a goto, so based on the value of the variable it jumps to the right case, whereas in the if/then statement it must evaluate each expression.

Run all SQL files in a directory

What I know you can use the osql or sqlcmd commands to execute multiple sql files. The drawback is that you will have to create a script for both the commands.

Using SQLCMD to Execute Multiple SQL Server Scripts

OSQL (This is for sql server 2000)

http://msdn.microsoft.com/en-us/library/aa213087(v=SQL.80).aspx

How to wrap text using CSS?

If you type "AAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRGGGGGGGGGGGGGGGGGGGGG" this will produce:

AARRRRRRRRRRRRRRRRRRRR
RRGGGGGGGGGGGGGGGGGGGG
G

I have taken my example from a couple different websites on google. I have tested this on ff 5.0, IE 8.0, and Chrome 10. It works on all of them.

.wrapword {
    white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    white-space: pre-wrap;       /* css-3 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
    white-space: -webkit-pre-wrap; /* Newer versions of Chrome/Safari*/
    word-break: break-all;
    white-space: normal;
}

<table style="table-layout:fixed; width:400px">
    <tr>
        <td class="wrapword"></td>
    </tr>
</table>

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Cygwin Make bash command not found

I faced the same problem. Follow these steps:

  1. Goto the installer once again.
  2. Do the initial setup.
  3. Select all the libraries by clicking and selecting install (the one already installed will show reinstall, so don't install them).
  4. Click next.
  5. The installation will take some time.

PHP multiline string with PHP

The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:

$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';

Reading my own Jar's Manifest

A simpler way to do this is to use getPackage(). For example, to get Implementation-Version:

Application.class.getPackage().getImplementationVersion()

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

You should use

this.router.parent.navigate(['/About']);

As well as specifying the route path, you can also specify your route's name:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

jQuery Event Keypress: Which key was pressed?

Witch ;)

/*
This code is for example. In real life you have plugins like :
https://code.google.com/p/jquery-utils/wiki/JqueryUtils
https://github.com/jeresig/jquery.hotkeys/blob/master/jquery.hotkeys.js
https://github.com/madrobby/keymaster
http://dmauro.github.io/Keypress/

http://api.jquery.com/keydown/
http://api.jquery.com/keypress/
*/

var event2key = {'97':'a', '98':'b', '99':'c', '100':'d', '101':'e', '102':'f', '103':'g', '104':'h', '105':'i', '106':'j', '107':'k', '108':'l', '109':'m', '110':'n', '111':'o', '112':'p', '113':'q', '114':'r', '115':'s', '116':'t', '117':'u', '118':'v', '119':'w', '120':'x', '121':'y', '122':'z', '37':'left', '39':'right', '38':'up', '40':'down', '13':'enter'};

var documentKeys = function(event) {
    console.log(event.type, event.which, event.keyCode);

    var keycode = event.which || event.keyCode; // par exemple : 112
    var myKey = event2key[keycode]; // par exemple : 'p'

    switch (myKey) {
        case 'a':
            $('div').css({
                left: '+=50'
            });
            break;
        case 'z':
            $('div').css({
                left: '-=50'
            });
            break;
        default:
            //console.log('keycode', keycode);
    }
};

$(document).on('keydown keyup keypress', documentKeys);

Demo : http://jsfiddle.net/molokoloco/hgXyq/24/

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

If you want to solve this issue using async/await:

(async function(){    
    try {        
        const response1, response2, response3
        response1 = await promise1()

        if(response1){
            response2 = await promise2()
        }
        if(response2){
            response3 = await promise3()
        }
        return [response1, response2, response3]
    } catch (error) {
        return []
    }

})()

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

On Windows I kept facing different errors messages when trying to use pg_upgrade.

Saved a lot of time for me to just:

  1. Backup DB
  2. Uninstall all copies of PostgreSQL
  3. Install 9.5
  4. Restore DB

How to run Selenium WebDriver test cases in Chrome

I included the binary into my projects resources directory like so:

src\main\resources\chrome\chromedriver_win32.zip
src\main\resources\chrome\chromedriver_mac64.zip
src\main\resources\chrome\chromedriver_linux64.zip

Code:

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public WebDriver getWebDriver() throws IOException {
    File tempDir = Files.createTempDirectory("chromedriver").toFile();
    tempDir.deleteOnExit();
    File chromeDriverExecutable;

    final String zipResource;
    if (SystemUtils.IS_OS_WINDOWS) {
        zipResource = "chromedriver_win32.zip";
    } else if (SystemUtils.IS_OS_LINUX) {
        zipResource = "chromedriver_linux64.zip";
    } else if (SystemUtils.IS_OS_MAC) {
        zipResource = "chrome/chromedriver_mac64.zip";
    } else {
        throw new RuntimeException("Unsuppoerted OS");
    }

    try (InputStream is = getClass().getResourceAsStream("/chrome/" + zipResource)) {
        try (ZipInputStream zis = new ZipInputStream(is)) {
            ZipEntry entry;
            entry = zis.getNextEntry();
            chromeDriverExecutable = new File(tempDir, entry.getName());
            chromeDriverExecutable.deleteOnExit();
            try (OutputStream out = new FileOutputStream(chromeDriverExecutable)) {
                IOUtils.copy(zis, out);
            }
        }
    }

    System.setProperty("webdriver.chrome.driver", chromeDriverExecutable.getAbsolutePath());
    return new ChromeDriver();
}

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Following worked for me from the command line:

aapt dump badging myapp.apk

NOTE: aapt.exe is found in a build-tools sub-folder of SDK. For example:

<sdk_path>/build-tools/23.0.2/aapt.exe

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

How to check a string for specific characters?

s=input("Enter any character:")   
if s.isalnum():   
   print("Alpha Numeric Character")   
   if s.isalpha():   
       print("Alphabet character")   
       if s.islower():   
         print("Lower case alphabet character")   
       else:   
         print("Upper case alphabet character")   
   else:   
     print("it is a digit")   
elif s.isspace():   
    print("It is space character")   

else:
print("Non Space Special Character")

Can enums be subclassed to add new elements?

Under the covers your ENUM is just a regular class generated by the compiler. That generated class extends java.lang.Enum. The technical reason you can't extend the generated class is that the generated class is final. The conceptual reasons for it being final are discussed in this topic. But I'll add the mechanics to the discussion.

Here is a test enum:

public enum TEST {  
    ONE, TWO, THREE;
}

The resulting code from javap:

public final class TEST extends java.lang.Enum<TEST> {
  public static final TEST ONE;
  public static final TEST TWO;
  public static final TEST THREE;
  static {};
  public static TEST[] values();
  public static TEST valueOf(java.lang.String);
}

Conceivably you could type this class on your own and drop the "final". But the compiler prevents you from extending "java.lang.Enum" directly. You could decide NOT to extend java.lang.Enum, but then your class and its derived classes would not be an instanceof java.lang.Enum ... which might not really matter to you any way!

Angular 5 Scroll to top on every Route click

I keep looking for a built in solution to this problem like there is in AngularJS. But until then this solution works for me, It's simple, and preserves back button functionality.

app.component.html

<router-outlet (deactivate)="onDeactivate()"></router-outlet>

app.component.ts

onDeactivate() {
  document.body.scrollTop = 0;
  // Alternatively, you can scroll to top by using this other call:
  // window.scrollTo(0, 0)
}

Answer from zurfyx original post

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

jQuery: print_r() display equivalent?

console.log is what I most often use when debugging.

I was able to find this jQuery extension though.

How to choose multiple files using File Upload Control?

The FileUpload.AllowMultiple property in .NET 4.5 and higher will allow you the control to select multiple files.

<asp:FileUpload ID="fileImages" AllowMultiple="true" runat="server" />

.NET 4 and below

 <asp:FileUpload ID="fileImages" Multiple="Multiple" runat="server" />

On the post-back, you can then:

 Dim flImages As HttpFileCollection = Request.Files                   
 For Each key As String In flImages.Keys
    Dim flfile As HttpPostedFile = flImages(key)
    flfile.SaveAs(yourpath & flfile.FileName)
 Next

Can we pass parameters to a view in SQL?

As already stated you can't.

A possible solution would be to implement a stored function, like:

CREATE FUNCTION v_emp (@pintEno INT)
RETURNS TABLE
AS
RETURN
   SELECT * FROM emp WHERE emp_id=@pintEno;

This allows you to use it as a normal view, with:

SELECT * FROM v_emp(10)

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

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class RegisterAction {


    public String execute() {


         RegisterAction mailBean = new RegisterAction();

           String subject="Your username & password ";

           String message="Hi," + username;
          message+="\n \n Your username is " + email;
          message+="\n \n Your password is " + password;
          message+="\n \n Please login to the web site with your username and password.";
          message+="\n \n Thanks";
          message+="\n \n \n Regards";

           //Getting  FROM_MAIL

           String[] recipients = new String[1];
            recipients[0] = new String();
            recipients[0] = customer.getEmail();

           try{
          mailBean.sendMail(recipients,subject,message);

          return "success";
          }catch(Exception e){
           System.out.println("Error in sending mail:"+e);
          }

        return "failure";
    }

    public void sendMail( String recipients[ ], String subject, String message)
             throws MessagingException
              {
                boolean debug = false;

                 //Set the host smtp address

                 Properties props = new Properties();
                 props.put("mail.smtp.host", "smtp.gmail.com");
                 props.put("mail.smtp.starttls.enable", true);
                 props.put("mail.smtp.auth", true);

                // create some properties and get the default Session

                Session session = Session.getDefaultInstance(props, new Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "[email protected]", "5373273437543");// Specify the Username and the PassWord
                    }

                });
                session.setDebug(debug);


                // create a message
                Message msg = new MimeMessage(session);


                InternetAddress[] addressTo = new InternetAddress[recipients.length];
                for (int i = 0; i < recipients.length; i++)
                {
                  addressTo[i] = new InternetAddress(recipients[i]);
                }

                msg.setRecipients(Message.RecipientType.TO, addressTo);

                // Optional : You can also set your custom headers  in the Email if you Want
                //msg.addHeader("MyHeaderName", "myHeaderValue");

                // Setting the Subject and Content Type
                msg.setSubject(subject);
                msg.setContent(message, "text/plain");

                //send message
                Transport.send(msg);

                System.out.println("Message Sent Successfully");
              }

}

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

The JWT aud (Audience) Claim

According to RFC 7519:

The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

The Audience (aud) claim as defined by the spec is generic, and is application specific. The intended use is to identify intended recipients of the token. What a recipient means is application specific. An audience value is either a list of strings, or it can be a single string if there is only one aud claim. The creator of the token does not enforce that aud is validated correctly, the responsibility is the recipient's to determine whether the token should be used.

Whatever the value is, when a recipient is validating the JWT and it wishes to validate that the token was intended to be used for its purposes, it MUST determine what value in aud identifies itself, and the token should only validate if the recipient's declared ID is present in the aud claim. It does not matter if this is a URL or some other application specific string. For example, if my system decides to identify itself in aud with the string: api3.app.com, then it should only accept the JWT if the aud claim contains api3.app.com in its list of audience values.

Of course, recipients may choose to disregard aud, so this is only useful if a recipient would like positive validation that the token was created for it specifically.

My interpretation based on the specification is that the aud claim is useful to create purpose-built JWTs that are only valid for certain purposes. For one system, this may mean you would like a token to be valid for some features but not for others. You could issue tokens that are restricted to only a certain "audience", while still using the same keys and validation algorithm.

Since in the typical case a JWT is generated by a trusted service, and used by other trusted systems (systems which do not want to use invalid tokens), these systems simply need to coordinate the values they will be using.

Of course, aud is completely optional and can be ignored if your use case doesn't warrant it. If you don't want to restrict tokens to being used by specific audiences, or none of your systems actually will validate the aud token, then it is useless.

Example: Access vs. Refresh Tokens

One contrived (yet simple) example I can think of is perhaps we want to use JWTs for access and refresh tokens without having to implement separate encryption keys and algorithms, but simply want to ensure that access tokens will not validate as refresh tokens, or vice-versa.

By using aud, we can specify a claim of refresh for refresh tokens and a claim of access for access tokens upon creating these tokens. When a request is made to get a new access token from a refresh token, we need to validate that the refresh token was a genuine refresh token. The aud validation as described above will tell us whether the token was actually a valid refresh token by looking specifically for a claim of refresh in aud.

OAuth Client ID vs. JWT aud Claim

The OAuth Client ID is completely unrelated, and has no direct correlation to JWT aud claims. From the perspective of OAuth, the tokens are opaque objects.

The application which accepts these tokens is responsible for parsing and validating the meaning of these tokens. I don't see much value in specifying OAuth Client ID within a JWT aud claim.

NSDictionary to NSArray?

This code is actually used to add values to the dictionary and through the data to an Array According to the Key.

NSMutableArray *arr = [[NSMutableArray alloc]init];
NSDictionary *dicto = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Hello",@"StackOverFlow",@"Key1",@"StackExchange",@"Key2", nil];
NSLog(@"The dictonary is = %@", dicto);
arr = [dicto valueForKey:@"Key1"];
NSLog(@"The array is = %@", arr);

Get ASCII value at input word

simply do

int a = ch

(also this has nothing to do with android)

No resource found that matches the given name '@style/Theme.AppCompat.Light'

What are the steps for that? where is AppCompat located?

Download the support library here:

http://developer.android.com/tools/support-library/setup.html

If you are using Eclipse:

Go to the tabs at the top and select ( Windows -> Android SDK Manager ). Under the 'extras' section, check 'Android Support Library' and check it for installation.

enter image description here

After that, the AppCompat library can be found at:

android-sdk/extras/android/support/v7/appcompat

You need to reference this AppCompat library in your Android project.

Import the library into Eclipse.

  1. Right click on your Android project.
  2. Select properties.
  3. Click 'add...' at the bottom to add a library.
  4. Select the support library
  5. Clean and rebuild your project.

How can I make a JPA OneToOne relation lazy

Unless you are using Bytecode Enhancement, you cannot fetch lazily the parent-side @OneToOne association.

However, most often, you don't even need the parent-side association if you use @MapsId on the client side:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {
 
    @Id
    private Long id;
 
    @Column(name = "created_on")
    private Date createdOn;
 
    @Column(name = "created_by")
    private String createdBy;
 
    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Post post;
 
    public PostDetails() {}
 
    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }
 
    //Getters and setters omitted for brevity
}

With @MapsId, the id property in the child table serves as both Primary Key and Foreign Key to the parent table Primary Key.

So, if you have a reference to the parent Post entity, you can easily fetch the child entity using the parent entity identifier:

PostDetails details = entityManager.find(
    PostDetails.class,
    post.getId()
);

This way, you won't have N+1 query issues that could be caused by the mappedBy @OneToOne association on the parent side.

PHP mail function doesn't complete sending of e-mail

$name = $_POST['name'];
$email = $_POST['email'];
$reciver = '/* Reciver Email address */';
if (filter_var($reciver, FILTER_VALIDATE_EMAIL)) {
    $subject = $name;
    // To send HTML mail, the Content-type header must be set.
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From:' . $email. "\r\n"; // Sender's Email
    //$headers .= 'Cc:' . $email. "\r\n"; // Carbon copy to Sender
    $template = '<div style="padding:50px; color:white;">Hello ,<br/>'
        . '<br/><br/>'
        . 'Name:' .$name.'<br/>'
        . 'Email:' .$email.'<br/>'
        . '<br/>'
        . '</div>';
    $sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
    // Message lines should not exceed 70 characters (PHP rule), so wrap it.
    $sendmessage = wordwrap($sendmessage, 70);
    // Send mail by PHP Mail Function.
    mail($reciver, $subject, $sendmessage, $headers);
    echo "Your Query has been received, We will contact you soon.";
} else {
    echo "<span>* invalid email *</span>";
}

How to convert string representation of list to a list?

Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y but works like a charm. Note also that the output is now a list of unicode strings, you didn't specify that you needed that, but it seems to make sense given unicode input.

import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
--->  [u'A', u'B', u'C', u'D']

The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.

Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

An item with the same key has already been added

I had same issue. It appeard to me after migrating to MVC 5 from MVC 3.

I had custom editor template and had to use it like this before:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField", this.ViewData)

To resolve issue I had to remove passing ViewData object. So at the end I had:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField")

Hope it helps.

Google maps API V3 method fitBounds()

I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds() at the wrong time may leave you with a result like in the Q. The best way I found is to place the call in an idle handler like this:

google.maps.event.addListenerOnce(map, 'idle', function() {
    map.fitBounds(markerBounds);
});

Access item in a list of lists

This code will print each individual number:

for myList in [[10,13,17],[3,5,1],[13,11,12]]:
    for item in myList:
        print(item)

Or for your specific use case:

((50 - List1[0][0]) + List1[0][1]) - List1[0][2]

Simple bubble sort c#

No, your algorithm works but your Write operation is misplaced within the outer loop.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();

Microsoft Excel ActiveX Controls Disabled?

I know many answers have already been posted for this, but neither one answer independently worked for my site. So here is what worked for me:

Step 1: Uninstall the following updates - KB2920789, KB2920790, KB2920792, KB2920793, KB2984942, KB2596927

Step 2: Hide these updates so they do not get installed on subsequent reboots

Step 3: Delete folder Excel8.0 from C:\Users\<>\AppData\Local\Temp

Step 4: Restart workstatiion (I would also make sure the above mentioned KBs did not inadvertently get applied)

How can I clear the terminal in Visual Studio Code?

For a MacBook, it might not be Cmd + K...

There's a long discussion for cases where Cmd + K wouldn't work. In my case, I made a quick fix with

cmd+K +cmd+ K

Go to menu Preferences -> Key shortcuts -> Search ('clear'). Change it from a single K to a double K...

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Apart from very good responses here, you could try this as well if you want to use your sub query as is.

Approach:

1) Select the desired column (Only 1) from your sub query

2) Use where to map the column name

Code:

 SELECT count(distinct dNum)
 FROM myDB.dbo.AQ
 WHERE A_ID in 
   (
    SELECT A_ID 
    FROM (SELECT DISTINCT TOP (0.1) PERCENT A_ID, COUNT(DISTINCT dNum) AS ud 
          FROM         myDB.dbo.AQ
          WHERE     M > 1 and B = 0 
          GROUP BY A_ID ORDER BY ud DESC
         ) a 
   )

What tool can decompile a DLL into C++ source code?

There are no decompilers which I know about. W32dasm is good Win32 disassembler.

Now() function with time trim

Paste this function in your Module and use it as like formula

Public Function format_date(t As String)
    format_date = Format(t, "YYYY-MM-DD")
End Function

for example in Cell A1 apply this formula

=format_date(now())

it will return in YYYY-MM-DD format. Change any format (year month date) as your wish.

Configuring Hibernate logging using Log4j XML config file?

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging

Here's the list of logger categories:

Category                    Function

org.hibernate.SQL           Log all SQL DML statements as they are executed
org.hibernate.type          Log all JDBC parameters
org.hibernate.tool.hbm2ddl  Log all SQL DDL statements as they are executed
org.hibernate.pretty        Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache         Log all second-level cache activity
org.hibernate.transaction   Log transaction related activity
org.hibernate.jdbc          Log all JDBC resource acquisition
org.hibernate.hql.ast.AST   Log HQL and SQL ASTs during query parsing
org.hibernate.secure        Log all JAAS authorization requests
org.hibernate               Log everything (a lot of information, but very useful for troubleshooting) 

Formatted for pasting into a log4j XML configuration file:

<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />

NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.

And a category is specified as such:

<logger name="org.hibernate">
    <level value="ALL" />
    <appender-ref ref="FILE"/>
</logger>

It must be placed before the root element.

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

How to change the timeout on a .NET WebClient object

You need to use HttpWebRequest rather than WebClient as you can't set the timeout on WebClient without extending it (even though it uses the HttpWebRequest). Using the HttpWebRequest instead will allow you to set the timeout.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.

app.all("/api/*", function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
  return next();
});

app.all("/api/*", function(req, res, next) {
  if (req.method.toLowerCase() !== "options") {
    return next();
  }
  return res.send(204);
});

Reference

cannot load such file -- bundler/setup (LoadError)

After spend a lot time, trying follow these answers actually after code below it worked for me. Before do it just but be sure that there is no problem in update :)

gem update --system

Add text at the end of each line

  1. You can also achieve this using the backreference technique

    sed -i.bak 's/\(.*\)/\1:80/' foo.txt
    
  2. You can also use with awk like this

    awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
    

How to generate all permutations of a list?

Anyway we could use sympy library , also support for multiset permutations

import sympy
from sympy.utilities.iterables import multiset_permutations
t = [1,2,3]
p = list(multiset_permutations(t))
print(p)

# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Answer is highly inspired by Get all permutations of a numpy array

How to get current language code with Swift?

In Swift 3:

NSLocale.current.languageCode

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

phpexcel to download

 header('Content-type: application/vnd.ms-excel');

 header('Content-Disposition: attachment; filename="file.xlsx"');

 header('Cache-Control: max-age=0');

 header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

 header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');

 header ('Cache-Control: cache, must-revalidate');

 header ('Pragma: public');

 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

 $objWriter->save('php://output');

geom_smooth() what are the methods available?

The method argument specifies the parameter of the smooth statistic. You can see stat_smooth for the list of all possible arguments to the method argument.

How are VST Plugins made?

I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.

As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.

As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:

I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.

How to see the actual Oracle SQL statement that is being executed

Sorry for the short answer but it is late. Google "oracle event 10046 sql trace". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users.

If you want to impress your Oracle DBA friends, learn how to set an oracle trace with event 10046, interpret the meaning of the wait events and find the top cpu consumers.

Quest had a free product that allowed you to capture the SQL as it went out from the client side but not sure if it works with your product/version of Oracle. Google "quest oracle sql monitor" for this.

Good night.

Iterating Through a Dictionary in Swift

If you want to iterate over all the values:

dict.values.forEach { value in
    // print(value)
}

Why are arrays of references illegal?

Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.

A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."

Is it possible to refresh a single UITableViewCell in a UITableView?

Here is a UITableView extension with Swift 5:

import UIKit

extension UITableView
{    
    func updateRow(row: Int, section: Int = 0)
    {
        let indexPath = IndexPath(row: row, section: section)

        self.beginUpdates()
        self.reloadRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
        self.endUpdates()
    }

}

Call with

self.tableView.updateRow(row: 1)

What does the restrict keyword mean in C++?

Since header files from some C libraries use the keyword, the C++ language will have to do something about it.. at the minimum, ignoring the keyword, so we don't have to #define the keyword to a blank macro to suppress the keyword.

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

afxwin.h file is missing in VC++ Express Edition

Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/

Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).

Any good, visual HTML5 Editor or IDE?

This might not interest you but just to add (0:, I like VS2008 IDE for html editing - and it doubles the fun if you have internet explorer developer toolbar (like that of firebug).

What is a simple command line program or script to backup SQL server databases?

I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:

#!/usr/bin/ksh
#
#.....
(
tsql -S {database} -U {user} -P {password} <<EOF
select * from {table}
go
quit
EOF
) >{output_file.dump}

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

C - error: storage size of ‘a’ isn’t known

correct typo of

struct xyz a;

to

struct xyx a;

Better you can try typedef, easy to b

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

I have nothing against libraries in general. In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.

Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.

function dateFormat (date, fstr, utc) {
  utc = utc ? 'getUTC' : 'get';
  return fstr.replace (/%[YmdHMS]/g, function (m) {
    switch (m) {
    case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
    case '%m': m = 1 + date[utc + 'Month'] (); break;
    case '%d': m = date[utc + 'Date'] (); break;
    case '%H': m = date[utc + 'Hours'] (); break;
    case '%M': m = date[utc + 'Minutes'] (); break;
    case '%S': m = date[utc + 'Seconds'] (); break;
    default: return m.slice (1); // unknown code, remove %
    }
    // add leading zero if required
    return ('0' + m).slice (-2);
  });
}

/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns 
   "2012-05-18 05:37:21"  */

Getting rid of bullet points from <ul>

I had the same extreme irritating problem myself since the script did not take any notice of my styelsheet. So I wrote:

<ul style="list-style-type: none;">

That did not work. So, in addition, I wrote:

<li style="list-style-type: none;">

Voila! it worked!

Why Is `Export Default Const` invalid?

You can also do something like this if you want to export default a const/let, instead of

const MyComponent = ({ attr1, attr2 }) => (<p>Now Export On other Line</p>);
export default MyComponent

You can do something like this, which I do not like personally.

let MyComponent;
export default MyComponent = ({ }) => (<p>Now Export On SameLine</p>);

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Hope my scenario can help someone else. I had the same problem with the package bcrypt. First, I have tried with npm i -g node-gyp as suggested by Anne but the problem persisted. Then I read again the error message to have a better understanding of the problem and discovered that the script fails to build the package from scratch - since a precompiled version doesn't exist. In particular, it can't find the g++ command so I solved installing the build-essential package with sudo apt install build-essential -y.

Django values_list vs values

You can get the different values with:

set(Article.objects.values_list('comment_id', flat=True))

What is the difference between SQL, PL-SQL and T-SQL?

SQL

SQL is used to communicate with a database, it is the standard language for relational database management systems.

In detail Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).

Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.

PL/SQL

PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation

Specialities of PL/SQL

  • completely portable, high-performance transaction-processing language.
  • provides a built-in interpreted and OS independent programming environment.
  • directly be called from the command-line SQL*Plus interface.
  • Direct call can also be made from external programming language calls to database.
  • general syntax is based on that of ADA and Pascal programming language.
  • Apart from Oracle, it is available in TimesTen in-memory database and IBM DB2.

T-SQL

Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL

The Structured Query Language or SQL is a programming language that focuses on managing relational databases. SQL has its own limitations which spurred the software giant Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL. Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.

T-SQL adds a number of features that are not available in SQL.

This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.

Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.

Choosing between T-SQL and SQL is all up to the user. Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.

References , Wikipedea , Tutorial Points :www.differencebetween.com

Catch paste input

 $('').bind('input propertychange', function() {....});                      

This will work for mouse paste event.

How to force Eclipse to ask for default workspace?

Version: Ecliplse CIndigo Service Release 2

  1. File > Switch Workspace > Other...
  2. In the textbox, write the path in the Workspace or Browse

It automatically sets the default Workspace during exit. To change Workspace go back to step 1.

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

I tried out all the answers listed here but no one solved my issue. In my case this error is due to my silly mistake in Appid creation. I used Wildcard App ID instead of using Explicit App ID caused the problem

If you want an application to receive remote notifications(push notification), then you need to use an Explicit App ID, such as com.tutsplus.push, instead of com.tutsplus.*

Please find the ScreenShot, enter image description here

Hibernate Query By Example and Projections

Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).

getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();

I've never used the alaistToBean, but I just read about it. You could also just loop over the results..

List<Object> rows = criteria.list();
for(Object r: rows){
  Object[] row = (Object[]) r;
  Type t = ((<Type>) row[0]);
}

If you have to you can manually populate User yourself that way.

Its sort of hard to look into the issue without some more information to diagnose the issue.

How to make a submit out of a <a href...>...</a> link?

Untested / could be better:

<form action="page-you're-submitting-to.html" method="POST">
    <a href="#" onclick="document.forms[0].submit();return false;"><img src="whatever.jpg" /></a>
</form>

javascript onclick increment number

No need to worry for incrementing/decrementing numbers using Javascript. Now HTML itself provides an easy way for it.

<input type="number" value="50">

It is that simple.The problem is that it works fine only in some browsers.Mozilla has not yet supported this feature.

What Content-Type value should I send for my XML sitemap?

Other answers here address the general question of what the proper Content-Type for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml and application/xml are permissible. However, none address whether there are any rules specific to sitemaps.

Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site: searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type should be used for serving sitemaps.

In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type of any other XML document - i.e. that it may be either text/xml or application/xml.

How to bind to a PasswordBox in MVVM

I used an authentication check followed by a sub called by a mediator class to the View (which also implements an authentication check) to write the password to the data class.

It's not a perfect solution; however, it remedied my problem of not being able to move the password.

how does Request.QueryString work?

A query string is an array of parameters sent to a web page.

This url: http://page.asp?x=1&y=hello

Request.QueryString[0] is the same as 
Request.QueryString["x"] and holds a string value "1"

Request.QueryString[1] is the same as 
Request.QueryString["y"] and holds a string value "hello"

How can I convert a string to upper- or lower-case with XSLT?

For ANSI character encoding:

 translate(//variable, 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ', 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ')

Check if an image is loaded (no errors) with jQuery

Check the complete and naturalWidth properties, in that order.

https://stereochro.me/ideas/detecting-broken-images-js

function IsImageOk(img) {
    // During the onload event, IE correctly identifies any images that
    // weren’t downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (img.naturalWidth === 0) {
        return false;
    }

    // No other way of checking: assume it’s ok.
    return true;
}

What is compiler, linker, loader?

*

explained with respect to, linux/unix based systems, though it's a basic concept for all other computing systems.

*

Linkers and Loaders from LinuxJournal explains this concept with clarity. It also explains how the classic name a.out came. (assembler output)

A quick summary,

c program --> [compiler] --> objectFile --> [linker] --> executable file (say, a.out)

we got the executable, now give this file to your friend or to your customer who is in need of this software :)

when they run this software, say by typing it in command line ./a.out

execute in command line ./a.out --> [Loader] --> [execve] --> program is loaded in memory

Once the program is loaded into the memory, control is transferred to this program by making the PC (program counter) pointing to the first instruction of a.out

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

C# Creating and using Functions

Just make your Add function static by adding the static keyword like this:

public static int Add(int x, int y)

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Delete worksheet in Excel using VBA

Try this code:

For Each aSheet In Worksheets

    Select Case aSheet.Name

        Case "ID Sheet", "Summary"
            Application.DisplayAlerts = False
            aSheet.Delete
            Application.DisplayAlerts = True

    End Select

Next aSheet

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

Setting up SSL on a local xampp/apache server

It turns out that OpenSSL is compiled and enabled in php 5.3 of XAMPP 1.7.2 and so no longer requires a separate extension dll.

However, you STILL need to enable it in your PHP.ini file the line extension=php_openssl.dll

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2