Q:

Seg Fault 11 when inserting element into binary search tree

I am writing a program in C++ and I can't figure out why I keep getting a segmentation fault. Here is the part of the code I am currently working with that is causing me trouble:
In my main function:
Tree* myTree;
myTree = CreateBST();

const Element a = 23;
InsertBST(myTree, a);

const Element b = 8;   //If I get rid of this line and the next one, the error goes away.
InsertBST(myTree, b);  //But I need to be able to insert data into my tree beyond just the root!

And then the insertBST function itself and its helper function:
void InsertBST(Tree * rTree, const Element nData){
    rTree->root = InsertNodeBST(rTree->root, nData);
}

//========================================================================================
TreeNode* InsertNodeBST(TreeNode* rNode, const Element nData)
{
    if(rNode->data == -999)   //A new tree's root->data will always be initialized to -999
   {
       TreeNode* rNew = new TreeNode;
       rNew->data = nData;
       rNew->left = NULL;
       rNew->right = NULL;
       return rNew;
   }
   else if(rNode == NULL)
   {
       TreeNode* rNew = new TreeNode;
       rNew->data = nData;
       rNew->left = NULL;
       rNew->right = NULL;
       return rNew;
   }
   else if(nData == rNode->data)
   {
       return rNode;
   }
   else if(nData < rNode->data)
   {
       rNode->left = InsertNodeBST(rNode->left, nData);
       return rNode;
   }
   else
   {
       rNode->right = InsertNodeBST(rNode->right, nData);
       return rNode;
   }

}

The structures we are required to use are as follows:
struct TreeNode {
  Element data;
  TreeNode *left;
  TreeNode *right;
};

struct Tree{
    TreeNode *root;
};

Does anyone see what I am clearly missing that could be causing my segmentation fault? I'm new to CS and I am taking my first CS class in 7 years, so I apologize if it is a glaringly obvious mistake. Thanks.

A:

if (rNode->data == -999)
{
    ...
}
else if (rNode == NULL)
{
    ...
}

If rNode is NULL, rNode->data crashes. Did you mean to put these ifs in the reverse order?


Q:

PHP & json_decode - how to get property of object

CONTEXT
I'm using json_decode to convert the contents of an Facebook open graph call into a php object.
EDIT to add code
My code looks like this:
$json = json_decode(file_get_contents("http://graph.facebook.com/http://example.com"),true);
var_dump($json);

A var_dump of the resulting object looks like this:
ARRAY(3) { ["ID"]=> STRING(18) "HTTP://EXAMPLE.COM" ["SHARES"]=> INT(14604317) ["COMMENTS"]=> INT(11300) }

PROBLEM
I would like to get the 12 from this object. I assumed that $json->shares would return 12, but instead it returns null. Any idea what the correct syntax for retrieving the 12 would be?

A:

Your array doesn't look right. Check out http://graph.facebook.com/http://example.com in a browser, notice how the keys and values are all lowercase, not uppercase like you have.
If you really are testing http://graph.facebook.com/http://example.com, then this will just work:
$array = json_decode(file_get_contents('http://graph.facebook.com/http://example.com'), true);
echo $array['shares'];

This gives me 14604317 which I can see in my browser is the correct result.
Note you have an array, not an object. So use array notation:


Q:

Programme to print mulitples of 5 in a range specified by user

Im new to python and im trying to write a code which determine all the multiples of 5 in a range specified by the user. Im getting the code to go up in units of 5. eg if the range was 6 and 21, it would say that the multiples are 6,11,16,21.
a = int(input("Enter a value of a : "))
b = int(input("Enter a vlue of b : "))

if a%5 ==0:
    a = a+5

multiples = []

for value in range(a, b+1,5):
    multiples.append(value)

print(multiples)

I'm expected just multiples of 5 to be printed.

A:

If your expected output from the range 6 to 21 is [10, 15, 20], you can first test if the starting point is a multiple of 5 as you did with if a % 5 == 0, and if it is true, we can add 5 repeatedly until we hit the end of range, while appending all the steps into the output list.
However if a % 5 == 0 gives you false, then we need to find the value to add to this starting point so that we can get the first multiple of 5 in this range, i.e.
diff = 5 - a % 5

and add this value to the starting point a, we get the first value:
first = a + diff

Then we can add 5 repeatedly until we hit the end of range.
To put all the above into code:
# get user input for the range a to b
a = int(input("Enter a value of a : "))
b = int(input("Enter a value of b : "))

output_list = []

# determine first value
if a % 5 == 0:
    first_val = a
else:
    first_val = a + (5 - (a % 5))

# go through the range between the first value and the end, with step=5
for val in range(first_val, b + 1, 5):
    # append value to the list
    output_list.append(val)

print(output_list)


Q:

ExpandablelistView on fragment

I'm trying to use a expandablelistView in my code but I have some problems.I'm trying to implement this code in a fragment. Can help me make this code to be used in a fragment ? I need to use it in a fragment.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TextExpandable extends AppCompatActivity {

    ExpandableListView expandableListView;
    ExpandableListAdapter expandableListAdapter;
    List<String> expandableListTitle;
    HashMap<String, List<String>> expandableListDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
        expandableListDetail = ExpandableListDataPump.getData();
        expandableListTitle = new ArrayList<String>(expandableListDetail.keySet());
        expandableListAdapter = new CustomExpandableListAdapter(this, expandableListTitle, expandableListDetail);
        expandableListView.setAdapter(expandableListAdapter);
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        expandableListTitle.get(groupPosition) + " List Expanded.",
                        Toast.LENGTH_SHORT).show();
            }
        });

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        expandableListTitle.get(groupPosition) + " List Collapsed.",
                        Toast.LENGTH_SHORT).show();

            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                Toast.makeText(
                        getApplicationContext(),
                        expandableListTitle.get(groupPosition)
                                + " -> "
                                + expandableListDetail.get(
                                expandableListTitle.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT
                ).show();
                return false;
            }
        });
    }

}

A:

just extend your class with fragment. operation you are doing in onCreate() do the same as oncreateView() of fragement.
import android.app.Fragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aksu.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class BlankFragment extends Fragment {

    ExpandableListView expandableListView;
    ExpandableListAdapter expandableListAdapter;
    List<String> expandableListTitle;
    HashMap<String, List<String>> expandableListDetail;
    public BlankFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return init(inflater.inflate(R.layout.activity_main, container, false));
    }

    private View init(View inflate) {
        expandableListView = (ExpandableListView) inflate.findViewById(R.id.expandableListView);
        expandableListDetail = ExpandableListDataPump.getData();
        expandableListTitle = new ArrayList<String>(expandableListDetail.keySet());
        expandableListAdapter = new CustomExpandableListAdapter(inflate., expandableListTitle, expandableListDetail);
        expandableListView.setAdapter(expandableListAdapter);
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(inflate.,
                        expandableListTitle.get(groupPosition) + " List Expanded.",
                        Toast.LENGTH_SHORT).show();
            }
        });

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(inflate.,
                        expandableListTitle.get(groupPosition) + " List Collapsed.",
                        Toast.LENGTH_SHORT).show();

            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                Toast.makeText(
                        inflate.,
                        expandableListTitle.get(groupPosition)
                                + " -> "
                                + expandableListDetail.get(
                                expandableListTitle.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT
                ).show();
                return false;
            }
        });
    }
}


Q:

Deploying Django+React to Heroku - Uncaught SyntaxError: Unexpected token '<'

I am trying to deploy my Django + React application to Heroku.
(Django for only api and React for frontend.)
I followed this video, but cannot resolve this problem for several days.
There is no error during deploy process, but after deploy, only white blank screen is showed up.
This is the only clue I can find until now...
I tried adding type="text/babel" to your script tag, adding base href tag to index.html, and changing several package.json and settings.py options.
This is my package.json file.
{
  "name": "frontend",
  "version": "0.1.0",
  "homepage": "https://myapp.herokuapp.com/",
  "private": true,
  "proxy": "http://localhost:8000",
  "dependencies": {
    "@material-ui/core": "^4.9.5",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.46",
    "@material-ui/styles": "^4.9.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "babel-preset-react": "^6.24.1",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-redux": "^5.0.7",
    "react-scripts": "3.2.0",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postinstall": "npm run build"
  },
  "engines": {
    "node": "12.14.0",
    "npm": "6.13.4"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "axios": "^0.19.2",
    "react-router-dom": "^5.1.2"
  }
}

And this is settings.py file.
"""
Django settings for gradproj project.

Generated by 'django-admin startproject' using Django 2.0.13.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['127.0.0.1', 'myapp.herokuapp.com']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'corsheaders',
    'rest_framework',
    'rest_framework.authtoken',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'rest_auth',
    'rest_auth.registration',

    'whitenoise.runserver_nostatic',

    'community',
    'universities',
    'user',
]

SITE_ID = 1

MIDDLEWARE = [
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'gradproj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'build')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'gradproj.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myapp',
        'USER': 'user',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '',
    }
}

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static'),
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}

CORS_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIST = [
#     'http://localhost:3000',
# ]

CSRF_COOKIE_NAME = "csrftoken"

ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_VERIFICATION = 'none'

And this is index.html file.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>Project Title</title>

    You need to enable JavaScript to run this app.

I didn't touch anything about webpack and babel because I used create-react-app to create application.
For database, I used MySQL. I unpacked both Django and React folder, so every folders are in same directory like this.
I almost read every single posts related to this problem in google and now I have no idea what should I try.
Any help will be very thankful!!

A:

I tried completely different method and succeed it!
This is the link I am referred to.
https://dev.to/shakib609/deploy-your-django-react-js-app-to-heroku-2bck


Q:

maven-site-plugin not generating apidocs folder with javadocs

I inherited a project that is supposed to build javadoc files and place them in the site directory.  This is not being done.  I have looked at all the examples I can find and I can't figure out where the configuration is broken.
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.0</version>
            <executions>
                <execution>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>site</goal>
                    </goals>
                    <configuration>
                        <reportPlugins>
                            <plugin>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-javadoc-plugin</artifactId>
                                <version>2.8</version>
                            </plugin>
                        </reportPlugins>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Any and all help is greatly appreciated.

A:

You have bound maven site plugin's site goal to prepare-package phase.  You have configured javadoc generation in this plugin configuration.
As such, if you run maven's default lifecycle goals like mvn package or mvn install you should get site report with javadocs.
If you ran mvn site, it would skip prepare-package phase to which your plugin configuration is bound and hence would not generate javadoc.


Q:

libxpc.dylib arm64 build error

I have created an objective c static library target 7.0+, trying to run it in an app on device running arm64 fails getting:
'/usr/lib/system/libxpc.dylib', missing required architecture arm64 in file /usr/lib/system/libxpc.dylib (2 slices) for architecture arm64 in compile/build time.
My architecures has: arm64.
Build/compiling/running on ios 6 simualtor works.
Any clues?

A:

Ok I think I got it there is a bug with developer site xcode it seems to be no the exact same version.
Uninstall xcode 6 and install from App Store.


Q:

Is there any way allows my Android wear connect to MYSQL

Just like what I mentioned from the question.
My watch is LG Urban, when I was developing my android app, I can use the mysql connector to connect with my DB server. Can I use the same to make my Android wear connect to mysql?
Thank you!

A:

Starting with Android Wear 2, proxying data requests through the phone has been replaced by direct network access from the watch. So going forward, your existing code to connect to a MySQL server should work essentially unchanged on the watch.
More details here: https://developer.android.com/training/wearables/data-layer/network-access.html
A couple of caveats:

Wear 2 is only now rolling out to the majority of devices (your Urbane probably doesn't have it yet, for example).
You should try to minimize the data being transferred to/from the watch; these devices have enough issues with battery life as it is.


Q:

Need help understanding this rotation matrix math code.

private Mat4 calcLookAtMatrix(Vec3 cameraPt, Vec3 lookPt, Vec3 upPt) {
    Vec3 lookDir = Glm.normalize(Vec3.sub(lookPt, cameraPt));
    Vec3 upDir = Glm.normalize(upPt);

    Vec3 rightDir = Glm.normalize(Glm.cross(lookDir, upDir));
    Vec3 perpUpDir = Glm.cross(rightDir, lookDir);

    Mat4 rotMat = new Mat4(1.0f);
    rotMat.setColumn(0, new Vec4(rightDir, 0.0f));
    rotMat.setColumn(1, new Vec4(perpUpDir, 0.0f));
    rotMat.setColumn(2, new Vec4(Vec3.negate(lookDir), 0.0f));

    rotMat = Glm.transpose(rotMat);

    Mat4 transMat = new Mat4(1.0f);
    transMat.setColumn(3, new Vec4(Vec3.negate(cameraPt), 1.0f));

    return rotMat.mul(transMat);
}

This code generates a matrix that transforms world space into camera space.
I understand everything except how the rotation matrix is formed. Basically, it puts in normalized vectors and transposes the matrix, and somehow that comes out with a rotation matrix. Explain that math.

A:

The matrix is made of normalised vectors that are orthogonal, therefore its transpose is also its inverse. Assuming the camera coordinates are written in the world basis, this would yield the transformation matrix allowing you to transform world coordinates into camera coordinates.
If $V$ is the vector of coordinates in the world basis, and $C$ the vector of coordinates in the camera basis, then
$$V=BC$$
where $B$ is the matrix made of the coordinates (world basis), of the camera basis. Therefore
$$C=B^{-1}V$$
and if i'm not mistaken that's exactly what's being done at the end with rotMat.mul(transMat);, since $B^{-1}=B^T$ here (http://en.wikipedia.org/wiki/Orthogonal_matrix)


Q:

Unexpected observation: var_dump() of an array is flagging referenced elements... since when?

I've just been running some simple debug tests against arrays, and noticed that when I do a var_dump() of an array, the output is flagging any element in the array that is referenced by another variable. As a simple experiment, I ran the following code:
$array = range(1,4);

var_dump($array);
echo '
';

foreach($array as &$value) {
}

var_dump($array);
echo '
';

$value2 = &$array[1];

var_dump($array);
echo '
';

which gives the following output:
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) }
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> ∫(4) }
array(4) { [0]=> int(1) [1]=> ∫(2) [2]=> int(3) [3]=> ∫(4) }

Note the ∫ symbol alongside element 3 and subsequently element 1. Note also that those entries don't show the entry's datatype.
Following some experimentation, I don't see this if I var_dump a scalar type, or with objects or resources. If the array contains string data, the symbol is a & (and it does still show the datatype), likewise with float, boolean and object entries.
This is running against PHP 5.2.8
First question: When did this behaviour start, or is it something that I simply haven't noticed before now?
Second question: If referenced elements can be flagged in this way by var_dump(), is there any function in core PHP that will allow me to identify if an array element is referenced by another variable; or that will return the refcount or ref flag from a _zval_struct?

A:

Not sure if this answers your question, but you can use
debug_zval_dump($array);

to get the refcount:
array(4) refcount(2){
    [0]=> long(1) refcount(1)
    [1]=> &long(2) refcount(2)
    [2]=> long(3) refcount(1)
    [3]=> &long(4) refcount(2)
}

Also see this Article by Derick Rethans (PHP Core Dev) about Refcounting.


Q:

How to Embed Image in Outlook Signature?

Is it possible to create an HTML email signature for Outlook 2003 or above that doesn't reference external images?
That is, using those special "cid" reference but embed the image itself in the signature and not on the file system or network.
This is for an web application that generates a "standard" email signature based on various input from a user.  It has worked fine so far with a single "embedded" image.  But a new feature is going to require the possible addition of multiple tiny images.
Getting to user to save one email signature template and one image to the user's machine is about the limit of what I'd like to require of the user.  But forcing the user to save multiple images seem to be pushing things a little to far in my opinion.
So my problem is trying to embed the images into without having to inconvenience the user with multiple downloads first.

A:

If you reference the image using a file:/// URI Outlook will automatically change it into a cid: URI and add the image as an attachment on insertion.
BTW: What has this got to do with programming?
EDIT: OK, considering your update to the question: I'm afraid this isn't possible. It's not a limitation specific to signatures or Outlook though. It's just the way HTML works. If you want images inside an HTML document these will have to be separate. No way around that without proprietary formats, none of which Outlook would accept as a signature.
However, if this is for an intranet application you can get away with placing the images on a network share and referencing via UNC, e.g.

A:

Is it possible to base64 encode the image?

Just a thought


Q:

DbUnit HSQLDB - invalid schema name: C

When running a test with the following query, HSQLDB mistakes the table alias as a schema.
SELECT c.country_ml2country as CTRY_PK, c.name as CTRY_NAME,
l.name as LANGUAGE_NAME, l.code as LANGUAGE_CODE
FROM country_ml as c, language as l
WHERE c.language(+) = l.id and c.country_ml2country(+) = ?
ORDER BY l.name ASC;

Has anyone experienced this before?  If "yes", then what is the fix?
Note that if I change FROM country_ml as c to FROM country_ml as bob, then the error message changes accordingly to invalid schema name: BOB.

A:

The problem is the non-standard Oracle-style OUTER JOIN syntax, which is specific to Oracle and not supported by other SQL dialects.
WHERE c.language(+) = l.id and c.country_ml2country(+) = ?

You should use instead the following standard syntax, which Oracle also supports:
SELECT c.country_ml2country as CTRY_PK, c.name as CTRY_NAME,
l.name as LANGUAGE_NAME, l.code as LANGUAGE_CODE
FROM country_ml as c RIGHT OUTER JOIN language as l
ON c.language = l.id and c.country_ml2country = ?
ORDER BY l.name ASC


Q:

ToDouble() is not working?

I'm trying to implement the following lines of code but it gives me errors:
var distanceTravelRight = 10.0;
var tick = DateTime.Now.Ticks();
var velLeft = distanceTravelRight / tick.ToDouble;

Non-invocable member 'System.DateTime.Ticks' cannot be used like a method.
'string' does not contain a definition for 'ToDouble' and no extension method 'ToDouble' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

I would appreciate if anyone could point out the problems so that I can learn!

A:

Ticks is a property, not a method so you do not need to call it with parenthesis ().
var tick = DateTime.Now.Ticks;

Also, to convert a string to a double, use double.TryParse.
double yourDouble;
if (double.TryParse(yourString, out yourDouble))
{
   // It is safe to use `yourDouble` here
}


Q:

Using GROUP BY and HAVING on a LEFT JOIN table where there is no records stored

There is a table where payment data towards invoices are recorded.  I am using SUM to count the total payment amount towards the invoice.  I only want to show invoices that have not been paid.  So I created a WHERE clause using GROUP BY and HAVING to only show records that have records sum'ing to less than the total invoice amount.
But...If there are no records to find in the Payments table, the system cannot find any invoices to display.  Anyone else had this issue?  I'm open to changing to a different format but I need it to function the same way where it only finds invoices with payment amounts of less than the total invoice amount due OR no payments at all.
$query = "
SELECT o.id, o.user_id,o.invoice_number,o.total,SUM(p.payment_amount) as paid
FROM User_Order_Details as o
LEFT JOIN User_Payments as p ON (p.user_id = o.user_id AND p.order_id = o.id)
WHERE o.user_id = '1' AND o.invoice_number != ''
GROUP BY p.order_id
HAVING SUM(p.payment_amount) < o.total
ORDER BY o.ship_date DESC
");

A:

Your issue is that when no payments have been made, SUM(p.payment_amount) is NULL, and comparing NULL to anything always results in FALSE (hence HAVING SUM(p.payment_amount) < o.total doesn't return those rows). So you need to use COALESCE to convert that value into 0, which can then be successfully compared. Note that MySQL allows you to use aliases in the HAVING clause, so you can just use paid there:
$query = "
SELECT o.id, o.user_id,o.invoice_number,o.total, COALESCE(SUM(p.payment_amount),0) as paid
FROM User_Order_Details as o
LEFT JOIN User_Payments as p ON (p.user_id = o.user_id AND p.order_id = o.id)
WHERE o.user_id = '1' AND o.invoice_number != ''
GROUP BY p.order_id
HAVING paid < o.total
ORDER BY o.ship_date DESC
");


Q:

Array group by date and remap objects

I want to transform this data set:
[
        {
            "id": 470830,
            "input": "MANUAL",
            "value": 10000,
            "date": "2019-09-23T08:01:09.976Z"
        },
        {
            "id": 435258,
            "input": "AUTO",
            "value": 20000,
            "date": "2019-09-23T10:01:09.976Z"
        },
        {
            "id": 435207,
            "input": "MANUAL",
            "value": 5000,
            "date": "2019-09-24T12:01:09.976Z"
        },
        {
            "id": 435208,
            "input": "AUTO",
            "value": 15000,
            "date": "2019-09-24T14:01:09.976Z"
        }
]

to this
[
        {
            "date": "2019-09-23"
            "total": 30000,
            "manual": 10000,
            "auto": 20000,
        },
        {
            "date": "2019-09-24"
            "total": 20000,
            "manual": 5000,
            "auto": 15000,
        }
]

Objects are grouped by date (not DateTime) and remapped to have value props from AUTO and MANUAL + the sum of these.
What is the most efficient way to do this with JavaScript?
--- EDIT ---
Removed id on transformed object as a comment suggests

A:

You can do:

const data = [{"id": 470830,"input": "MANUAL","value": 10000,"date": "2019-09-23T08:01:09.976Z"},{"id": 435258,"input": "AUTO","value": 20000,"date": "2019-09-23T10:01:09.976Z"},{"id": 435207,"input": "MANUAL","value": 5000,"date": "2019-09-24T12:01:09.976Z"},{"id": 435208,"input": "AUTO","value": 15000,"date": "2019-09-24T14:01:09.976Z"}]
const result = Object
  .values(data.reduce((acc, { id, input, value, date }) => {
    const ds = date.substring(0, 10)
    acc[ds] = acc[ds] || { id, auto: 0, manual: 0, value: 0, date: ds }
    acc[ds] = {
      id: acc[ds].id,
      date: ds,
      value: acc[ds].value + value,
      manual: input === 'MANUAL' ? acc[ds].manual + value : acc[ds].manual,
      auto: input === 'AUTO' ? acc[ds].auto + value : acc[ds].auto
    }
    return acc
  }, {}))

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }


Q:

partial screen background image slider jQuery

I have an image size of 1680 x 602 pixels. I’m using sliderJs to show the slider of 2 images. The jQuery slider works. My problem is my page shows a horizontal scrollbar after setting the images. How do I eliminate the horizontal scrollbar?
Thanks!

A:

depending where the scrollbar appears you can hide it with css
.slidercontainer{overflow-x:hidden;}

or
#slides{overflow-x:hidden;}


Q:

Golang proper use of interfaces

I am new to Go and am running into a situation that I am unsure how to solve. I am working on some code that takes a DNS packet in raw bytes and returns a struct called DNSPacket.
The struct looks like the following
type DNSPacket struct {
    ...some fields
    Questions  []Question
    Answers    []Answer
    ...some more fields
}

The issue I am having is with the Answers type which looks like this.
 type Answer struct {
    Name     string
    Type     int
    Class    int
    TTL      uint32
    RdLength int
    Data     []byte
}

Depending on the type of Answer the Data field must be decoded differently. For example if the Answer is an A record (Type 1) the data is simply an ipv4 address. However if the Answer is an SRV record (Type 33) then the data is contains port, priority, weight and target encoded in the byte slice.
I thought it would be great if I could have a method on Answer called DecodeData() that returns the correct data depending on the type, however since there is no overriding or inheritance in Go I am unsure how to solve this. I tried using an interface to solve this, but it would not compile. I tried something like
type DNSRecordType interface {
    Decode(data []byte)
}

type RecordTypeSRV struct {
   target string
   ...more fields
}
//to 'implement' the DNSRecordType interface
func (record *RecordTypeSRV) Decode(data []byte) {
    //do the work to decode appropriately and set
    //the fields on the record
}

Then in the Answer method
func (a *Answer) DecodeData() DNSRecordType {
    if a.Type === SRVType {
       record := RecordTypeSRV{}
       record.Decode(a.Data)
       return record
    }

    //do something similar for other record types
 }

What would be the correct Go way of having a single Answer type, but be able to return different types of Answer Data depending on their type?
Sorry, if this is a completely beginner question as I am still very new to Go.
Thanks!

A:

Let me summarize your question.
You have a DNS Packet with the list of Answers. Based on the type of answer you have to process the data in the answer.
type DNSPacket struct {
    ...some fields
    Questions  []Question
    Answers    []Answer
    ...some more fields
}
type Answer struct {
    Name     string
    Type     int
    Class    int
    TTL      uint32
    RdLength int
    Data     []byte
}

Answer
Let's create an interface that should be implemented to process data.
type PacketProcessor interface {
    Process(Answer)
}

Let SRV implements the PacketProcessor
type SRV struct {
    ...
}

func (s *SRV) Process(a Answer) {
    ...
}

Your processing logic should be as follows
func (a *Answer) Process() {
    var p PacketProcessor
    switch a.Type {
        case SRVType:
        p = &SRV{}
        ...
        //other cases
    }

    //finally
    p.Process(*a)
}

Hope it helps :).
There is a Gurgaon based golang community that is always ready to help developers with their problems.
You can join the community via slack


Q:

Subversion merging changes from a different repository

I'm really confused. I want to do something that a) seems like it should be pretty simple, and b) other people must do all the time, but I cant find out the best way to do it anywhere.
There's an external repository that contains some 3rd party code. I want to take a copy of version 1 of the code and put it in my own repository, and then customise it for my own needs. When version 2 of that code is released I want to be able to upgrade my customised version with all of the version 2 changes, retaining my customisations.
I've read about vendor branches (http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html) but I don't understand why merging the previous copy of the vendor code and the new copy of the vendor code needs to be so complicated (ie. svn_load_dirs.pl). Surely, if the 3rd party code is stored in an SVN repository, all of the history regarding which files have moved/been deleted is known, so why do you need to tell it what's changed manually?
Quote:

For example, you will have the opportunity to tell the script that you know that the file math.c in version 1.0 of libcomplex was renamed to arithmetic.c in libcomplex 1.1.

I've also read (http://svn.haxx.se/users/archive-2006-04/0285.shtml) that it is possible to simply run a merge between different repositories, but I didn't think that was possible, and whenever I've tried it it's failed (though I could have been doing something wrong).
Can anyone clarify this for me, and suggest the best solution?

A:

I've just tried a brief experiment with TortoiseSVN:
Creating the test repositories

create two new repositories in rep1 and rep2
check out rep1 into co1
add a text file to co1 and check it in
export rep1 to ex1
import ex1 into rep2

At this stage you will be in the state of having created your local 'branch' in a new repository. The last two steps are all you need for an existing project.
To simulate some changes to the original repo, modify the text file in co1 and commit the changes.
Merging Changes
Now, to create your own working copy, check out rep2 into co2.
We should be ready to try merging from rep1 into co2.
Open the merge dialog for co2 and point it at rep1.
For the 'from' revision select the revision at which you exported your copy (in this case revision 1), or the revision that you last updated your local copy to.
For the 'to' revision select the HEAD or the latest update you want to apply.
Results
This seems to work as expected, with the modifications from rep1 being applied to the working copy of rep2 in co2. These then need to be committed back to your local repository.

A:

The vendor branches link you provided does effectively describe the process of what you want to do. It is a perfect solution relative to allowing you to do a straight update (import) of the vendor branch, and then as you allude to, will then allow you to merge the vendor's updates in with your changes in the main development branch.
The problem is that Subversion really doesn't provide direct support for file renames and moves of files between directories for the successive update from the vendor code because you are just getting snapshots of the source files' content....something needs to run the commands into the version system to indicate what changes are being made to the tree of file names that make up the new version. This is the purpose of the svn_load_dirs.pl script process. It helps you to get your version history manipulated around to match up the branches so that you can then proceed with the merge. If the vendor didn't rename and/or move files around between versions you imported, you would not have this problem.
In any case, the process described there is what you/need to do.


Q:

How To InvalidateRect With GDIPlus

All of the GDIPlus demo code I can find draws without invalidation.  So how do you invalidate a rectangle in GDIPlus API when drawing with MouseMove with TImage on a TScrollbox?
function NormalizeRect ( R: TRect ): TRect;
begin

  // This routine normalizes a rectangle. It makes sure that the Left,Top
  // coords are always above and to the left of the Bottom,Right coords.

  with R do
  begin

    if Left > Right then
      if Top > Bottom then
        Result := Rect ( Right, Bottom, Left, Top )
      else
        Result := Rect ( Right, Top, Left, Bottom )
    else if Top > Bottom then
      Result := Rect ( Left, Bottom, Right, Top )
    else
      Result := Rect ( Left, Top, Right, Bottom );

  end;

end;

procedure TFormMain.Image1MouseDown ( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer );
begin
  if Line1.Down then
  begin
    GPPointStart := MakePoint ( X, Y );
  end;
end;

procedure TFormMain.Image1MouseMove ( Sender: TObject; Shift: TShiftState; X, Y: Integer );
var
  graphics: TGPGraphics;
  pen: TGPPen;
  SolidBrush: TGPSolidBrush;
  rgbTriple: windows.RGBTRIPLE;
  iRect: TRect;
begin
  if Line1.Down then
  begin
    if ssLeft in Shift then
    begin
      iRect := NormalizeRect ( Rect ( X, Y, Image1.Picture.Bitmap.Width, Image1.Picture.Bitmap.Height ) );
      InvalidateRect ( ScrollBox1.Handle, @iRect, TRUE );
      graphics := TGPGraphics.Create ( Image1.Picture.Bitmap.Canvas.Handle );
      graphics.Flush ( FlushIntentionFlush );
      GPPointEnd := MakePoint ( X, Y );
      rgbTriple := ColorToRGBTriple ( ColorBox1.Selected );
      pen := TGPPen.Create ( MakeColor ( StrToInt ( Alpha1.Text ), rgbTriple.rgbtRed, rgbTriple.rgbtGreen, rgbTriple.rgbtBlue )
        );
      pen.SetWidth ( StrToInt ( Size1.Text ) );
      graphics.DrawLine ( pen, GPPointStart.X, GPPointStart.Y, GPPointEnd.X, GPPointEnd.Y );
      graphics.Free;
      Image1.Refresh;
    end;
   end;
end;

This is what it looks like:

Using GDIPlus Library from http://www.progdigy.com with Delphi 2010.

A:

The InvalidateRect command has nothing to do with GDI+. It's a command that tells the OS that a certain portion of a window is invalid and should be repainted. When the OS next decides to repaint that window, the program can ask the OS how much of the window needs painting.
Your code is calling InvalidateRect, and then it's painting over that same portion of the window. The window is still invalidated, though, so the OS will ask your program to repaint that area later, when you next process a wm_Paint message.
I don't know why you would expect your image to look any different, and it has nothing to do with invalidating the scroll box. It looks like you clicked on the character's eye, and the dragged the mouse down and the the right, clockwise.
At each mouse movement, you draw a new line from the original pint to the current mouse position. You draw the line directly on the currently displayed bitmap, and then you ask the image control to redraw itself. It obeys and draws the bitmap — that bitmap that you just added another line to.
I suspect what you intended to happen was for each mouse movement to result in one black line to appear over an otherwise unsullied image. InvalidateRect won't help with that. You need to redraw the original image over the previous line position, and the draw the new line. InvalidateRect does not help you "undo" a previous graphic operation. It just  tells the OS that a certain portion of a window should be repainted sometime. It doesn't say what colors those invalidated pixels should be repainted with. That's what wm_Paint is for.


Q:

Usage of a different kind of functions in one Java Class

I am following this tutorial to create my first Spring Hibernate JSF app, and in this tutorial http://marco-ng.blogspot.com/2014/02/primefaces-jsf2-spring-security-spring.html?showComment=1440293840519#c5483896447188701172 the developer used a UserDAO and CustomerDAO which are one for getting login name and the other to manager customers. For my sample, I'm using one class User merging the two used functions (User will login, and then he will manager totality of Users).
My Question is, can I simply merge those two DAO in one UserDAO :
User DAO :
package spring.dao;

import spring.model.User;

public interface UserDAO {
    public User getUser(String login);
}

Custommer DAO :
package spring.dao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import spring.dao.CustomerDAO.ComponentScan;
import spring.model.Customer;

import java.util.List;

@Repository
public class CustomerDAO {

    public @interface ComponentScan {

    }

    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void addCustomer(Customer customer) {
        getSessionFactory().getCurrentSession().save(customer);
    }

    public void deleteCustomer(Customer customer) {
        getSessionFactory().getCurrentSession().delete(customer);
    }

    public void updateCustomer(Customer customer) {
        getSessionFactory().getCurrentSession().update(customer);
    }

    public Customer getCustomerById(int id) {
        List list = getSessionFactory().getCurrentSession().createQuery("from Customer where id=?").setParameter(0, id).list();
        return (Customer)list.get(0);
    }

    public List<Customer> getCustomers() {
        List list = getSessionFactory().getCurrentSession().createQuery("from Customer").list();
        return list;
    }

}

The goal of all this is about using Management functions as long as Login from same class. And as I'm following a tuto to learn, I can't know the exceptions or things that are impossible to do before asking about them.
Thank you

A:

The DAO can't be merged because login needs an interface which is has no superclass but an interface. This means both DAO remains but both inherit data from model UserDAO.


Q:

Has the Labour Party introduced limited liability for its senior officials since 2008?

On Sunday, April 19th, the Jewish Chronicle posted an article which stated that, due to lawsuits relating to breach of confidence, invasion of privacy, and libel claims as a result of the leaked antisemitism report, (related question) the Labour party could face a bill of up to £8 million:

Labour could be bankrupted by lawsuits after an antisemitism report
  compiled by allies of former party leader Jeremy Cobyn (sic) was
  leaked to the public.
[...]
Sources close to those complainants say more than 30 individuals may
  sue the party over breach of privacy and for putting their safety at
  risk.
Labour could face a legal bill as high as £8 million over the leak,
  which could bankrupt the party, according to the sources.
[...]
Mark Lewis of law firm Patron Law, who is representing 20 of the
  people affected, said: “If this bankrupts the Labour Party or
  individuals, so be it. Actions have consequences.

This reminded me of a situation that occurred in 2008, when the Guardian reported that due to the party's large amount of debt, party officials could become personally liable for the sum:

Senior officials in the Labour party, including Gordon Brown, could
  become personally liable for millions of pounds in debt unless new
  donors can be found within weeks, the Guardian has learned.
[...]
The advice from City solicitors Slaughter and May said unequivocally
  that leading party officials and members of the NEC would be " jointly
  and severally" responsible for the party's debt.
The reason is that the Labour party constitution is framed like a
  local club or society, and has no provision for limiting the liability
  of its officials or managers.
[...]
The Labour party is said to be investigating whether it can change its
  status to a limited liability company to protect its officials and NEC
  members - but such a move could be open to legal challenge until it
  clears its debts.

Has any such change of status taken place, either by amending the Party's constitution or through some other method?

A:

As far as I can tell, the answer appears to be no. An article published by the Independent in October 2019, reports on the fears of members of the NEC:

Members of Labour’s ruling executive have privately voiced fears that
  the party could be bankrupted as a result of an official inquiry into
  antisemitism, The Independent has learnt.
Members of the National Executive Committee (NEC) have expressed
  concerns that a damning verdict from the equalities watchdog about
  Labour’s handling of antisemitic abuse could open the party up to a
  slew of lawsuits from Jewish members and former members, possibly
  resulting in hefty damages having to be paid.
It is understood that the issue was discussed at a recent NEC meeting,
  with members of the committee voicing major concerns about the fallout
  from the probe and who would be financially responsible.

As a result of these fears, members inquired as to what indemnity the Labour Party has against such claims:

They believe that, like trustees of a charity, they are legally and
  financially responsible for the party.
Others committee members are said to have been “stunned” when it was
  pointed out that they may be personally liable.
One NEC member said of the EHRC inquiry: “If it’s really bad then it
  opens up all sorts of possibilities and it has been raised that the
  whole thing could basically bankrupt the party.
“People are really worried. The party has been asked to let us know
  what indemnity it has because there are concerns that NEC members are
  going to ultimately be responsible for this.
“If we were a charity, the Charity Commission would have been all over
  us months ago. The EHRC is effectively playing the same role as the
  Charity Commission and we are effectively the trustees. That means we
  are legally responsible.”

However, no answers appear to have been forthcoming:

Another Labour source with an understanding of the situation added:
  “There are fears that if the EHRC goes against the party then
  individual victims will have the right to go for damages from the
  party, and who knows where that ends up – nobody can be sure because
  there’s no precedent for it.
“Nobody quite knows what the liability is for the individuals NEC
  members. If they are liable then it makes it even more damaging that
  Jennie [Formby, Labour’s general secretary] and her team won’t share
  their understanding of what the damages might be and the possible
  implications. Clearly, NEC members are worried about that scenario but
  the conversation got completely shut down.”

It would seem, then, that nothing has changed legally since the article in the question, which means the legal advice given then, that "leading party officials and members of the NEC would be 'jointly and severally' responsible for the party's debt", presumably still applies.


Q:

Calculate derivative of integral

I tried to calculate the derivative of this integral:
$$\int_{2}^{3+\sqrt{r}}  (3 + \sqrt{r}-c) \frac{1}{2}\,{\rm d}c $$
First I took the anti-derivative of the integral:
$$\frac{1}{2}\left(\frac{-c^2}{2}+c\sqrt{r}+3c\right)$$
Then I evaluated the integral:
$$-\frac{1}{2}\left(\frac{3+\sqrt{r})^2}{2} + (3 + \sqrt{r})\sqrt{r}+3(3+\sqrt{r})\right)-\frac{1}{2}\left(-\frac{(2^2)}{2}+2\sqrt{r}+3\cdot 2\right)$$
After I simplified I got:
$$\frac{1 + 2\sqrt{r}+r}{4}$$
I should get:
$$\frac{1 + \sqrt{r}}{4\sqrt{r}}$$
But I cannot get this result.
Can someone help? what am I missing?

A:

As it appears the derivative is taken with respect to $r$. The integral in question is given by, and evaluated as, the following:
\begin{align}
I(r) &= \frac{1}{2} \, \int_{2}^{3+\sqrt{r}} (3 + \sqrt{r} - t) \, dt \\
&= \frac{1}{2} \, \left[ (3 + \sqrt{r}) t - \frac{t^{2}}{2} \right]_{2}^{3 + \sqrt{r}} \\
I(r) &= \frac{(3 + \sqrt{r})^{2}}{4} - (2 + \sqrt{r}).
\end{align}
Now by differentiation
\begin{align}
\frac{dI}{dr} &=  \frac{2}{4} \cdot (3 + \sqrt{r}) \cdot \frac{1}{2 \sqrt{r}} - \frac{1}{2 \sqrt{r}} \\
&= \frac{3 + \sqrt{r}}{4 \sqrt{r}} - \frac{1}{2 \sqrt{r}} = \frac{1 + \sqrt{r}}{4 \, \sqrt{r}}.
\end{align}


Q:

Is there a way to represent logical not with && or ||

Is there a way to represent logical not, with && or || or some statement like if or ?:
I want to implement this in some other way:
boolean isRunning = true;
startButton.setEnabled(!isRunning); // <<== ???

A:

Assuming that you are doing this as an exercise, ternary operator lets you replace ! in a simple and straightforward way:
startButton.setEnabled(isRunning ? false : true);

As far as using && and || by themselves goes, this pair of operators is not functionally complete, i.e. there are operations that cannot be implemented by using a sequence of &&s and ||s alone; not ! operation is among operations that cannot be implemented with ands and ors.


Q:

Ul li Column Count with If Condition in Less Or jQuery

I am using column counter in ul li. i want 15 numbers in one counter li and then i want 15-15 li in each counter group. i have also share pic what i need actual.
is it possible in jQuery or Less Or JavaScript ??
thanks in advance.
Attachment : Images1
jsfiddle link : link1

.counter-list{
  list-style:none;
  padding:0px;
  column-count: 2;
}
.counter-list li {

}

list 1

list 2

list 3

list 4

list 5

list 6

list 7

list 8

list 9

list 10

 list 11

list 12

list 13

list 14

list 15

list 16

list 17

list 18

list 19

list 20

 list 21

list 22

list 23

list 24

list 25

list 26

list 27

list 28

list 29

list 30

list 31

A:

I change your CSS to display 15 items. See below example.

.counter-list {
  list-style: none;
  padding: 0px;
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: repeat(15, 1fr);
}

.counter-list li {}

list 1

list 2

list 3

list 4

list 5

list 6

list 7

list 8

list 9

list 10

 list 11

list 12

list 13

list 14

list 15

list 16

list 17

list 18

list 19

list 20

 list 21

list 22

list 23

list 24

list 25

list 26

list 27

list 28

list 29

list 30

list 31

A:

try below code: (Just change min_items_per_col)

$(function($) {
    var num_cols = 0,
    container = $('.counter-list'),
    listItem = 'li',
    listClass = 'sub-list';
    container.each(function() {
        var items_per_col = new Array(),
        items = $(this).find(listItem),
        min_items_per_col = 15,//Math.floor(items.length / num_cols),
        num_cols = Math.ceil((items.length) / min_items_per_col),
        difference = items.length - (min_items_per_col * num_cols);

        for (var i = 0; i < num_cols; i++) {
            if (i < difference) {
                items_per_col[i] = min_items_per_col + 1;
            } else {
                items_per_col[i] = min_items_per_col;
            }
        }
        for (var i = 0; i < num_cols; i++) {
            $(this).append($('

').addClass(listClass));
            for (var j = 0; j < items_per_col[i]; j++) {
                var pointer = 0;
                for (var k = 0; k < i; k++) {
                    pointer += items_per_col[k];
                }
                $(this).find('.' + listClass).last().append(items[j + pointer]);
            }
        }
    });
});
.counter-list ul{
  float: left;
  list-style:none;
  border-bottom: 1px solid;
}
.counter-list li{
  line-height: 1.5em;
  counter-increment: step-counter;
 }
.counter-list li:before {
    content: counter(step-counter);
  margin-right: 5px;
  font-size: 80%;
  background-color: rgb(0,200,200);
  color: white;
  font-weight: bold;
  padding: 3px 8px;
  border-radius: 3px;
 }

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List

List


Q:

Get id (undefined) of object

I have an code if I do console.log(resp)
I got to see  (see img) but when I do console.log(resp[id]) of console.log(resp[{id}])

I see undefined.
How can I access the id that is been created ?
    var request = gapi.client.request({
               'path': '/drive/v2/files/',
               'method': 'POST',
               'headers': {
                   'Content-Type': 'application/json',
               },
               'body':{
                   "title" : name,
                   "mimeType" : "application/vnd.google-apps.folder",
                   "parents": [{
                        "kind": "drive#file",
                        "id": FOLDER_ID,
                    }],
               }

this is the code I use. the id is not the same id as id : FOLDER_id
how can I access that id ?

A:

Your accessing the property the wrong way, try this
resp.id or resp["id"]
Note the second way is wrapped into quote to make it a string.


Q:

Simplicially enriched cartesian closed categories

In this question I asked whether for a complete and cocomplete cartesian closed category $V$, there can be a complete and cocomplete $V$-category $C$  (with powers and copowers) whose underlying ordinary category is cartesian closed, but such that $C$ is not $V$-cartesian closed.  The answers gave a general way to find such examples: let $P$ be a small cartesian monoidal category and $V = [P^{\rm op},\rm Set]$ its presheaf category with the Day convolution closed monoidal structure, which when $P$ is cartesian happens to also be cartesian.  Now let $C$ be any locally presentable category on which $P$ acts through cocontinuous functors; the action then extends to an action of $V$ that has both adjoints, hence makes $C$ a $V$-category with powers and copowers, yet the enrichment is "unrelated" to any cartesian closure that $C$ started with and hence the latter will often not be $V$-cartesian-closure.  In particular, $C$ could itself be a presheaf category $[J^{\rm op},\rm Set]$ with action induced from an action of $P$ on $J$.
This is great, but doesn't quite work for the case I'm really interested in when $V=[\Delta^{\rm op},\rm Set]$ is simplicial sets, since $\Delta$ is not cartesian monoidal.  It could be generalized to that case since the cartesian closed structure of simplicial sets is, like any closed monoidal structure on a presheaf category, induced by a promonoidal structure on $\Delta$, so we could imagine a corresponding "pro-action" of $\Delta$ on some $J$ inducing a simplicial enrichment on $[J^{\rm op},\rm Set]$.  However, I don't immediately see how to describe such a pro-action of $\Delta$ in concrete terms to make it easier to construct one.
So the question is, does there exist a complete and cocomplete category $C$ that is simplicially enriched with powers and copowers, and whose underlying ordinary category is cartesian closed, but such that the cartesian-closure adjunction is not simplicially enriched?
The answers to the other question certainly make it seem likely that the answer is yes.  But note that there does exist at least one complete and cocomplete cartesian closed category $V$ such that every cartesian closed $V$-category is $V$-cartesian-closed — namely, $V=\rm Set$.  Of course that is a very degenerate case, but it means that constructing a counterexample for any particular $V$, like simplicial sets, must use something about $V$ itself.

A:

$\newcommand{\y}{\mathbf{y}}
$Take $C = \mathcal{P}(a \stackrel{t}{\to} b) = \mathrm{Set}^{\cdot \leftarrow \cdot}$, so $C$ is freely generated under colimits by a morphism $\y t : \y a \to \y b$. Again I'll equip $C$ with the structure of a $V$-module, this time for $V = \mathrm{sSet}$. Suppose I know two (strong) monoidal left adjoints $A$, $B : V \to \mathrm{Set}$ and a monoidal transformation $\tau : A \to B$. Then define the action $- \odot - : V \otimes C \to C$ by
$$K \odot \y a = A(K) \cdot \y a,$$
$$K \odot \y b = B(K) \cdot \y b,$$
with $K \odot \y t$ given by the composition of $\tau_K \cdot \y a : A(K) \cdot \y a \to B(K) \cdot \y a$ and $B(K) \cdot \y t : B(K) \cdot \y a \to B(K) \cdot \y b$, extending by preservation of colimits in the $C$ argument. Here $S \cdot X$ denotes the copower of $X$ by the set $S$. These formulas are functorial and colimit-preserving in $K$, so $\odot$ is an adjunction of two variables.
From the form of the action, we have an isomorphism between $K \odot (L \odot \y a) = A(K) \cdot (A(L) \cdot \y a) = (A(K) \times A(L)) \cdot \y a$ and $(K \times L) \cdot \y a = A(K \times L) \cdot \y a$ given by the strong monoidal structure of $A$, and similarly for $\y b$ and $B$; these isomorphisms are compatible with the map $\y a \to \y b$ because $\tau$ is a monoidal transformation. Extending by colimits, we obtain an associator isomorphism $K \odot (L \odot -) \cong (K \times L) \odot -$. Similarly the unit isomorphisms of $A$ and $B$ and their compatibility with $\tau$ provide a unitor $- \cong 1_V \odot -$, and (though I haven't checked the details) presumably the coherence conditions on $A$ and $B$ imply the coherence conditions making $\odot$ a monoidal action.
The map from
$$K \odot \y a = A(K) \cdot \y a$$
to
$$(K \odot 1) \times \y a = (K \odot \y b) \times \y a = (B(K) \cdot \y b) \times \y a = B(K) \cdot \y a$$
is given by $\tau_K \cdot \y a$, and so it is only a natural isomorphism when $\tau_K$ is.
Now luckily there are in fact two different strong monoidal left adjoints $\mathrm{sSet} \to \mathrm{Set}$ related by a monoidal natural transformation, namely
$$A(K) = K_0, \quad B(K) = \pi_0 K,$$
with $\tau : A \to B$ the obvious natural transformation, which is not an isomorphism for $K = \Delta^1$.
One can compute the mapping spaces explicitly: for objects $X = (X_a \leftarrow X_b)$, $Y = (Y_a \leftarrow Y_b)$ of $C$, the simplicial set $\mathrm{Map}(X, Y)$ turns out to be the Čech nerve of the map $\mathrm{Hom}(X, Y) \to \mathrm{Hom}(X_b, Y_b)$. I'm not sure whether this description is very enlightening however.


Q:

Cable modem and wireless routers set up

I have cable internet, 60meg. I have just bought a Asus rt-ac56r wireless router. I also have a Linksys wrt320N. I tried to get the Linksys to be a repeater by downloading and installing dd-wrt but could never seem to get it to work right. I have purchased a long ethernet cable and have run it from my Asus router to the Linsys and set up the Linsys to use in my bedroom. I can only seem to get 30meg on my iPad and PC that are using wireless on either router. What is the best setup for this equipment? Should i get a Ethernet splitter and connect both straight to the modem or is the way i have it ok? Want to get as much speed as possible.

A:

If you're set on having two WAP's in your house then there are a few things to consider.

Network congestion:

Position your access points away from obstructions and other electronic devices.
Ensure there are no other wifi signals on your channel. Otherwise, you could be experiencing a high amount of collisions. When a collision occurs the devices must retransmit the packet which is very costly on network throughput. Use a wifi analysis tool like the free version of Acrylic to find other wifi signals in your area.
Try to use the 5GHz band if your devices support it. In my area anyhow there are far fewer 5GHz devices than there are 2.4GHz.
If you're not competing with other signals increase the channel width to 40MHz. This will increase the bandwidth.

Power

Adjust your antenna's power to suit the environment. DD-WRT specifically has a lot of adjustment capabilities for your antennas. You may find that increasing the TX power will give you better results. Be careful not to push it too far though, you'll need to consider heat dissipation. Also, often reducing the power can increase your speeds, have a play around with it.

Configuration

You will want to setup one of your WAP's in Bridge mode. This basically joins one WAP to the other alleviating the need for your devices to jump between the different wifi networks. It can also reduce the cost of control type transmissions like authentication.
You can prefer to have two separate networks if you like but keep in mind all the extra overhead of having two default gateways both performing routing functions that could be done by just one of them.

If I was you I would do some testing to see exactly what's happening. Wireshark is a great tool to analyse your network. You'll be able to see if there are excessive retransmissions and it may give you a better idea of what the problem is. GLHF


Q:

How to organize cmake file hierarchy with multiple optional dependencies

I have a C++ project with a core which is basically self-contained but with a lot of interfaces to third party codes that a user may or may not want to compile. We build the code using CMake and I am now trying to organize the code a bit better.
The solution I came up with is to add to the top CMakeLists.txt file a set of options which determine whether a dependent package should be located or not.
option(WITH_FOO "Compile the interface to Foo, if found" ON)
option(REQUIRE_FOO "Require that the Foo interface to be compiled" OFF)
option(WITH_BAR "Compile the interface to Bar, if found" ON)
option(REQUIRE_BAR "Require that the Bar interface to be compiled" OFF)
...
if(WITH_FOO)
  if(REQUIRE_FOO)
    find_package(Foo REQUIRED)
  else(REQUIRE_FOO)
    find_package(Foo)
  endif(REQUIRE_FOO)
else(WITH_FOO)
  set(FOO_FOUND FALSE)
endif(WITH_FOO)

if(WITH_BAR)
  if(REQUIRE_BAR)
    find_package(Bar REQUIRED)
  else(REQUIRE_BAR)
    find_package(Bar)
  endif(REQUIRE_BAR)
else(WITH_BAR)
  set(BAR_FOUND FALSE)
endif(WITH_BAR)

Then in the the CMakeLists.txt files in the subdirectories, there will be statements such as:
if(BAR_FOUND)
  add_subdirectory(bar_interface)
endif(BAR_FOUND)

I don't particularly like this solution, partly because it is very verbose and partly because I feel that there should be some more standardized way of doing this. Is anyone aware of a better, more maintainable solution?

A:

Have a look at the following standard CMake modules:

FeatureSummary - Macros for generating a summary of enabled/disabled features
CMakeDependentOption - Macro to provide an option dependent on other options

Examples of using FeatureSummary (from manual):
option(WITH_FOO "Help for foo" ON)
add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")

find_package(LibXml2)
set_package_properties(LibXml2 PROPERTIES DESCRIPTION "A XML processing library." URL "http://xmlsoft.org/")
set_package_properties(LibXml2 PROPERTIES TYPE RECOMMENDED PURPOSE "Enables HTML-import in MyWordProcessor")
set_package_properties(LibXml2 PROPERTIES TYPE OPTIONAL PURPOSE "Enables odt-export in MyWordProcessor")

feature_summary(WHAT ALL)


Q:

Build string into Android .apk but keep out of source control

How do I take an environment variable at build-time and make it available as R.string.api_key at app runtime?

A:

A typical pattern is to put the string in gradle.properties:
API_KEY=whatever-it-is

If you really want it to be a string resource, you can then use resValue in build.gradle:
defaultConfig {
    // other stuff here
    resValue "string", "api_key", API_KEY
}

(as values in gradle.properties get exposed as global variables to your Gradle script)
Or, if you need the value in Java code, you could use buildConfigField:
defaultConfig {
    // other stuff here
    buildConfigField "String", "API_KEY", '"'+API_KEY+'"'
}

then reference it as BuildConfig.API_KEY.
And, of course, do not check gradle.properties into version control.


Q:

Windows: get processes exec path on non-admin user

This is for Windows (XP, 7, or 8) related question.
Is it possible to get processes exec path without admin rights?
If possible, can you advice?
UPDATE:
Sample working code:
#RequireAdmin
#include <array.au3>

Dim $proc[1][3]
Dim $i = 0

$WMI = ObjGet("winmgmts:\\.\root\CIMV2")
$result = $WMI.ExecQuery("SELECT * FROM Win32_Process", "WQL",0x10 + 0x20)

If IsObj($result) Then
   For $res In $result
      $Proc[UBound($proc)-1][0] = $res.Name
      $Proc[UBound($proc)-1][1] = $res.Handle
      $Proc[UBound($proc)-1][2] = $res.ExecutablePath
      ReDim $proc[UBound($proc) + 1][3]
   Next
   ReDim $proc[UBound($proc) - 1][3]
Else
   Msgbox(0,'Result','No result found')
Endif

_ArrayDisplay($Proc,'Process List')][1]

Output:

A:

If you have a process ID, use OpenProcess() to get a HANDLE to the process, then use GetProcessImageFileName() or QueryFullProcessImageName() to get the filename of the process.
If you need the command-line parameters that were passed to the process, that is much harder to do.  You have to use NtQueryInformationProcess() to get the address of the process's PEBstructure and then use ReadProcessMemory() to read the contents of the PEB's ProcessParameters.CommandLine member, which is a UNICODE_STRING structure.  Note that this will fail if you try to access processes that belong to other user accounts, or running with higher privileges, unless your process has the SeDebugPrivilege privilege, such as by enabling it with AdjustTokenPrivileges().


Q:

How create static functions/objects in javascript/nodejs (ES6)

I want to create a static class using Javascript/Node JS. I used google but i can't find any usefull example.
I want to create in Javascript ES6 something like this (C#):
public static MyStaticClass {
   public static void someMethod() {
      //do stuff here
   }
}

For now, I have this class, but I think that this code will creates a new instance every time that it be called from "require".
function MyStaticClass() {
   let someMethod = () => {
      //do some stuff
   }
}
var myInstance = new MyStaticClass();
module.exports = factory;

A:

Note that JS is prototype-based programming, instead of class-based.
Instead of creating the class multiple times to access its method, you can just create a method in an object, like
var MyStaticClass = {
    someMethod: function () {
        console.log('Doing someMethod');
    }
}

MyStaticClass.someMethod(); // Doing someMethod

Since in JS, everything is an object (except primitive types + undefined + null). Like when you create someMethod function above, you actually created a new function object that can be accessed with someMethod inside MyStaticClass object. (That's why you can access the properties of someMethod object like MyStaticClass.someMethod.prototype or MyStaticClass.someMethod.name)
However, if you find it more convenient to use class. ES6 now works with static methods.
E.g.
MyStaticClass.js
class MyStaticClass {
    static someMethod () {
        console.log('Doing someMethod');
    }

    static anotherMethod () {
        console.log('Doing anotherMethod');
    }
}

module.exports = MyStaticClass;

Main.js
var MyStaticClass = require("./MyStaticClass");

MyStaticClass.someMethod(); // Doing someMethod
MyStaticClass.anotherMethod(); // Doing anotherMethod

A:

I would use an object literal:
const myObject = {
  someMethod() {
    // do stuff here
  }
}

module.exports = myObject;

A:

You can use the static keyword to define a method for a class

class MyStatisticsClass {
  static someMethod() {
    return "MyStatisticsClass static method"
  }
}

console.log(MyStatisticsClass.someMethod());


Q:

How can I convert function types with the same signature?

In a package, I have this:
package pkg1

type SomeFuncType func (a interface{}, b interface{}) int

func PkgApiCall (x SomeFuncType) {
   ...
}

In my code using this package, I have some very similar:
type MyFuncType func (a interface{}, b interface{}) int

Now I want to call pkg1.PkgApiCall(), but with a variable of MyFuncType as argument:
package mypackage

func doingSomeThing(x MyFuncType) {
  pkg1.PkgApiCall(x)
}

It doesn't compile. I get the error
./src1.go:97:7: error: incompatible type in initialization (cannot use type mypackage.MyFuncType as type pkg1.SomeFuncType)

How could I get over this? These function types define functions with exactly the same signature.

A:

The usual type conversions work for function types just as well as they work for non-function types:
pkg1.PkgApiCall(SomeFuncType(x))


Q:

Why I can't get input value in my javascript code

I can't get the value of selected Id.
Here's the html and javascript

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  <input id="input">
  <button id="button" type="button" name="button">Search</button>

  <script>
    const der = document.getElementById('input').value;

    document.getElementById('button').addEventListener('click',
      function() {
        alert(der);
      });
  </script>

</body>

</html>

I tested it on chrome, opera, and firefox. Nothing work. I have used varalso instead of const, that dont work too.
I want to get the input value of the Id I selected. I really can't see any problem in the code

A:

You need to move the assignment to der into the click handler. At present, der is being evaluated when the page is loaded, not when the button is clicked.
  document.getElementById('button').addEventListener('click',
  function(){
    const der = document.getElementById('input').value;
    alert(der);
  });


Q:

Anonymous methods vs. lambda expression

Can anyone provide a concise distinction between anonymous method and lambda expressions?
Usage of anonymous method:
private void DoSomeWork()
{
    if (textBox1.InvokeRequired)
    {
        //textBox1.Invoke((Action)(() => textBox1.Text = "test"));
        textBox1.Invoke((Action)delegate { textBox1.Text = "test"; });
    }
}

Is it only a normal lambda expression being cast to a strongly typed delegate or there is more of it undercover.
I'm well aware that a strongly typed delegate like follow
UpdateTextDelegate mydelegate = new UpdateTextDelegate(MethodName)

suffice as a parameter of type System.Delegate, but the idea of anonymous method is rather new to me.

A:

What is an anonymous method? Is it really anonymous? Does it have a name? All good questions, so let's start with them and work our way up to lambda expressions as we go along.
When you do this:
public void TestSomething()
{
    Test(delegate { Debug.WriteLine("Test"); });
}

What actually happens?
The compiler first decides to take the "body" of the method, which is this:
Debug.WriteLine("Test");

and separate out that into a method.
Two questions the compiler now has to answer:

Where should I put the method?
What should the signature of the method look like?

The second question is easily answered. The delegate { part answers that. The method takes no parameters (nothing between delegate and {), and since we don't care about its name (hence the "anonymous" part), we can declare the method as such:
public void SomeOddMethod()
{
    Debug.WriteLine("Test");
}

But why did it do all this?
Let's look at what a delegate, such as Action really is.
A delegate is, if we for a moment disregard the fact that delegates in .NET are actually linked list of multiple single "delegates", a reference (pointer) to two things:

An object instance
A method on that object instance

So, with that knowledge, the first piece of code could actually be rewritten as this:
public void TestSomething()
{
    Test(new Action(this.SomeOddMethod));
}

private void SomeOddMethod()
{
    Debug.WriteLine("Test");
}

Now, the problem with this is that the compiler has no way of knowing what Test actually does with the delegate it is given, and since one half of the delegate is a reference to the instance on which the method is to be called, this in the above example, we don't know how much data will be referenced.
For instance, consider if the above code was part of a really huge object, but an object that only live temporarily. Also consider that Test would store that delegate somewhere it would live for a long time. That "long time" would tie itself up to the life of that huge object as well, keeping a reference to that for a long time as well, probably not good.
So the compiler does more than just create a method, it also creates a class to hold it. This answers the first question, where should I put it?.
The code above can thus be rewritten as follows:
public void TestSomething()
{
    var temp = new SomeClass;
    Test(new Action(temp.SomeOddMethod));
}

private class SomeClass
{
    private void SomeOddMethod()
    {
        Debug.WriteLine("Test");
    }
}

That is, for this example, what an anonymous method is really all about.
Things get a bit more hairy if you start using local variables, consider this example:
public void Test()
{
    int x = 10;
    Test(delegate { Debug.WriteLine("x=" + x); });
}

This is what happens under the hood, or at least something very close to it:
public void TestSomething()
{
    var temp = new SomeClass;
    temp.x = 10;
    Test(new Action(temp.SomeOddMethod));
}

private class SomeClass
{
    public int x;

    private void SomeOddMethod()
    {
        Debug.WriteLine("x=" + x);
    }
}

The compiler creates a class, lifts all the variables that the method requires into that class, and rewrites all access to the local variables to be access to fields on the anonymous type.
The name of the class, and the method, are a bit odd, let's ask LINQPad what it would be:
void Main()
{
    int x = 10;
    Test(delegate { Debug.WriteLine("x=" + x); });
}

public void Test(Action action)
{
    action();
}

If I ask LINQPad to output the IL (Intermediate Language) of this program, I get this:
// var temp = new UserQuery+<>c__DisplayClass1();
IL_0000:  newobj      UserQuery+<>c__DisplayClass1..ctor
IL_0005:  stloc.0     // CS$<>8__locals2
IL_0006:  ldloc.0     // CS$<>8__locals2

// temp.x = 10;
IL_0007:  ldc.i4.s    0A
IL_0009:  stfld       UserQuery+<>c__DisplayClass1.x

// var action = new Action(temp.<Main>b__0);
IL_000E:  ldarg.0
IL_000F:  ldloc.0     // CS$<>8__locals2
IL_0010:  ldftn       UserQuery+<>c__DisplayClass1.<Main>b__0
IL_0016:  newobj      System.Action..ctor

// Test(action);
IL_001B:  call        UserQuery.Test

Test:
IL_0000:  ldarg.1
IL_0001:  callvirt    System.Action.Invoke
IL_0006:  ret

<>c__DisplayClass1.<Main>b__0:
IL_0000:  ldstr       "x="
IL_0005:  ldarg.0
IL_0006:  ldfld       UserQuery+<>c__DisplayClass1.x
IL_000B:  box         System.Int32
IL_0010:  call        System.String.Concat
IL_0015:  call        System.Diagnostics.Debug.WriteLine
IL_001A:  ret

<>c__DisplayClass1..ctor:
IL_0000:  ldarg.0
IL_0001:  call        System.Object..ctor
IL_0006:  ret

Here you can see that the name of the class is UserQuery+<>c__DisplayClass1, and the name of the method is <Main>b__0. I edited in the C# code that produced this code, LINQPad doesn't produce anything but the IL in the example above.
The less-than and greater-than signs are there to ensure that you cannot by accident create a type and/or method that matches what the compiler produced for you.
So that's basically what an anonymous method is.
So what is this?
Test(() => Debug.WriteLine("Test"));

Well, in this case it's the same, it's a shortcut for producing an anonymous method.
You can write this in two ways:
() => { ... code here ... }
() => ... single expression here ...

In its first form you can write all the code you would do in a normal method body. In its second form you're allowed to write one expression or statement.
However, in this case the compiler will treat this:
() => ...

the same way as this:
delegate { ... }

They're still anonymous methods, it's just that the () => syntax is a shortcut to getting to it.
So if it's a shortcut to getting to it, why do we have it?
Well, it makes life a bit easier for the purpose of which it was added, which is LINQ.
Consider this LINQ statement:
var customers = from customer in db.Customers
                where customer.Name == "ACME"
                select customer.Address;

This code is rewritten as follows:
var customers =
    db.Customers
      .Where(customer => customer.Name == "ACME")
      .Select(customer => customer.Address");

If you were to use the delegate { ... } syntax, you would have to rewrite the expressions with return ... and so on, and they'd look more funky. The lambda syntax was thus added to make life easier for us programmers when writing code like the above.
So what are expressions?
So far I have not shown how Test has been defined, but let's define Test for the above code:
public void Test(Action action)

This should suffice. It says that "I need a delegate, it is of type Action (taking no parameters, returning no values)".
However, Microsoft also added a different way to define this method:
public void Test(Expression<Func<....>> expr)

Note that I dropped a part there, the .... part, let's get back to that 1.
This code, paired with this call:
Test(() => x + 10);

will not actually pass in a delegate, nor anything that can be called (immediately). Instead, the compiler will rewrite this code to something similar (but not at all like) the below code:
var operand1 = new VariableReferenceOperand("x");
var operand2 = new ConstantOperand(10);
var expression = new AdditionOperator(operand1, operand2);
Test(expression);

Basically the compiler will build up an Expression<Func<...>> object, containing references to the variables, the literal values, the operators used, etc. and pass that object tree to the method.
Why?
Well, consider the db.Customers.Where(...) part above.
Wouldn't it be nice if, instead of downloading all customers (and all their data) from the database to the client, looping through them all, finding out which customer has the right name, etc. the code would actually ask the database to find that single, correct, customer at once?
That's the purpose behind expression. The Entity Framework, Linq2SQL, or any other such LINQ-supporting database layer, will take that expression, analyze it, pick it apart, and write up a properly formatted SQL to be executed against the database.
This it could never do if we were still giving it delegates to methods containing IL. It can only do this because of a couple of things:

The syntax allowed in a lambda expression suitable for an Expression<Func<...>> is limited (no statements, etc.)
The lambda syntax without the curly brackets, which tells the compiler that this is a simpler form of code

So, let's summarize:

Anonymous methods are really not all that anonymous, they end up as a named type, with a named method, only you do not have to name those things yourself
It's a lot of compiler magic under the hood that moves things around so that you don't have to
Expressions and Delegates are two ways to look at some of the same things
Expressions are meant for frameworks that wants to know what the code does and how, so that they can use that knowledge to optimize the process (like writing a SQL statement)
Delegates are meant for frameworks that are only concerned about being able to call the method

Footnotes:

The .... part for such a simple expression is meant for the type of return value you get from the expression. The () => ... simple expression ... only allows expressions, that is, something that returns a value, and it cannot be multiple statements. As such, a valid expression type is this: Expression<Func<int>>, basically, the expression is a function (method) returning an integer value.
Note that the "expression that returns a value" is a limit for Expression<...> parameters or types, but not of delegates. This is entirely legal code if the parameter type of Test is an Action:
Test(() => Debug.WriteLine("Test"));

Obviously, Debug.WriteLine("Test") doesn't return anything, but this is legal. If the method Test required an expression however, it would not be, as an expression must return a value.

A:

There is one subtle difference you should be aware of. Consider the following queries (using the proverbial NorthWind).
Customers.Where(delegate(Customers c) { return c.City == "London";});
Customers.Where(c => c.City == "London");

The first one uses an anonymous delegate and the second one uses a lambda expression. If you evaluate the results of both you will see the same thing. However, looking at the generated SQL, we'll see quite a different tale. The first generates
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [Customers] AS [t0]

Whereas the second generates
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [Customers] AS [t0]
WHERE [t0].[City] = @p0

Notice in the first case, the where clause is not passed to the database. Why is this? The compiler is able to determine that the lambda expression is a simple single-line expression which can be retained as an expression tree, whereas the anonymous delegate is not a lambda expression and thus not wrappable as an Expression<Func<T>>. As a result in the first case, the best match for the Where extension method is the one that extends IEnumerable rather than the IQueryable version which requires an Expression<Func<T, bool>>.
At this point, there's little use to the anonymous delegate. It's more verbose and less flexible. In general, I would recommend always using the lambda syntax over the anonymous delegate syntax and pick up parsability and syntactic terseness as well.


Q:

Add diffrenet href to some nodes in cytoscape.js

I set href for some nodes and it works fine but the other nodes opening blank page Is it possible make them without href and don´t open blank page?
I used this to make href  :
cy.nodes('[id = "start"]').data('href', 'https://js.cytoscape.org/');

cy.on('tap', 'node', function() {
  try {
    window.open(this.data('href'));
  } catch (e) {
    window.location.href = this.data('href');
  }
});

A:

Yes, listen for events that come from node[href], this means nodes that have href within their data set.
cy.on('tap', 'node[href]', function() {})

I'm not totally sure about this, but it should work.
If not, just add
if (!this.data('href')) return;

As the first line in your handler.


Q:

Run only one instance of a script running in the background at a time in ZSH / OS X

I have a script that runs in the background. It opens an SSH connection to a server and tails a file indefinitely. When I put my mac to sleep, the SSH connection is closed. Here is the script in question:
#!/bin/sh

(ssh <user>@<ip> -o PermitLocalCommand=no  \
 ": > .irssi/fnotify ; tail -f .irssi/fnotify " | \
 while read heading message; do                   \
 growlnotify -s -t "${heading}" -m "${message}";  \
 done)&

At that point, I have to run ps aux | grep ssh, find the right process and kill it manually; It's tedious. So I have a couple of questions and potential answers:

Is there a way to rename the process name of the script so that I can kill it by name everytime I run it again?
Otherwise, is there a way to store the pid of the script when I execute it and then kill it when I run it again?

The first solution is impossible I believe, but it's worth asking.
For the second solution, I did some research I went somewhere but not far enough... Here is what I have:
I managed to get the pid of the script itself, not the one of the particular SSH connection. But from what I saw, the pid of the script is always <pid of ssh connection> - 1.
So I need to add 1 to the pid of the script, and I couldn't manage to do that. But anyway, is that
a viable solution?
Otherwise, what are the alternative solutions please?

A:

You don't need to do any PID tracking, let the shell handle ssh disconnects in a loop.
#!/bin/sh
while true ; do
    ssh -o BatchMode=yes user@host '
        : > ~/.irssi/notify
        tail -f ~/.irssi/notify
    ' | while read -r title message ; do
        growlnotify -s -t "$title" -m "$message"
    done
    sleep 5  # retry timeout
done

Adjust user@host and retry timeout to taste, save in your path, chmod +x it, and run when convenient, like backgrounded from xinitrc/xsession or in a term if you want to watch output.
To guard against multiple instances you can prepend something like the following.
if [ -e /tmp/sshnotify.pid ] ; then
    read pid < /tmp/sshnotify.pid
    if kill -0 $pid > /dev/null 2>&1 ; then
        echo >&2 already running
        exit 1
    fi
fi
echo $$ > /tmp/sshnotify.pid


Q:

R: Package for English language wordlist

do you have a recommendation for a libary that offers extensive wordlists of english or other languages?
I have a vector of non-english words with eventually an english word sneaked in here and there. To remove these, I would need a library of english words to compare that to.
Thx

A:

Couple of options -
wordnet - https://cran.r-project.org/web/packages/wordnet/index.html
syn - https://github.com/ropenscilabs/syn


Q:

Hyperlinks are being overwritten in emails

I am sending out emails from my website using Zend_Mail and Send Grid. I have hyperlinks in the email that are being overwritten with what appears to be garbage by the time it gets to the user's inbox.
For example,
href="http://www.foo.com" is becoming href="http://email.foo.com/wf/click?upn=DSDRHSSBH2938TS".
I do not have this problem when I remove the 'http://' from the href. This is not a solution for me however, because links without 'http://' do not work in some email clients.
I checked the Zend Mail content and the links appear to be fine, so I am wondering if this is a problem with Send Grid or the email client. I have looked all over the web and have found very little information on this. I have seen some people with similar issues, but no one has been able to provide a real solution.
Has anyone seen anything like this? I'll be happy to provide more information if needed.

A:

It looks like Send Grid is re-writing the URLs for click tracking. Try disabling this feature in your Send Grid account. https://sendgrid.com/docs/Apps/click_tracking.html


Q:

All c# project was unloaded

I encountered this error

after cloned my project.
i tried to reload the project but it didn't work.
how to resolve this?

A:

i solved the problem, by matching my current sdk version in global.json
this are my procedure,

Result


Q:

Linear Subspace of a topological space

Let $X$ be a topological space. Show that the set $$C(X)=\{f:X \rightarrow \mathbb{R} : f \text{ is continuous}\}$$ is a linear subspace of all functions from $X$ to $\mathbb{R}$.
I am able to show that it is closed under multiplication but am unable to see how I could show the same under addition.

A:

Let $f$ and $g$ be continuous functions from $X$ to $\mathbb R$. Consider $\{x\in X: f(x)+g(x) <c\}$ where $c$ is  a real number. You can write this as $\bigcup_q \{x\in X: f(x)<q<g(x)-c\}$ where the union is over rational numbers $q$. Now write this sets as $\bigcup_q [f^{-1}(-\infty, q) \cap g^{-1} (q+c ,\infty)]$. It follows that $\{x\in X: f(x)+g(x) <c\}$ is open. Similarly $\{x\in X: f(x)+g(x) >c\}$ is open for any real number $c$. Taking intersection of sets of these two types you see that $(f+g)^{-1} (a,b)$ is open whenever $a<b$. Since any open set in $\mathbb R$ is a union of open intervals you see that inverse image of any open set under $f+g$ is open.


Q:

Strange behaviour when using Marshal.GetActiveObject("Outlook.Application")

In order to start outlook and wait until it's available via Interop I wrote the following Console app:
static Outlook.Application outlook;
static void Main(string[] args)
{
    Console.WriteLine("Enter Profile:");
    var profile = Console.ReadLine();

    var process = Process.GetProcessesByName("Outlook").FirstOrDefault();
    if (process == null)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("outlook.exe", $"/profile \"{profile}\""); // MK_E_UNAVAILABLE appears until I click in the console window
        // ProcessStartInfo startInfo = new ProcessStartInfo("outlook.exe"); // Works as expected
        process = Process.Start(startInfo);
    }

    while (outlook == null && !process.HasExited)
    {
        try
        {
            outlook = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
            break;
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
            outlook = null;
        }
        process.Refresh();
        Thread.Sleep(500);
    }

    if (outlook != null)
        Console.WriteLine($"Outlook is running.");

    Console.ReadKey();
}

I verified in task manager that console app is running under the same user as Outlook does (see here).
The output of the console app is:
Vorgang nicht verfügbar. (Ausnahme von HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))
Vorgang nicht verfügbar. (Ausnahme von HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))
Vorgang nicht verfügbar. (Ausnahme von HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))

This message gets repeated until I click into the console window or resize it. Then output changes to
Outlook is running.

This does only happen when starting outlook with the profile parameter. Without profile parameter the message Outlook is running. appears straight after I selected the profile in the Outlook profile dialog.
Can anybody explain what's the reason for this behaviour?

A:

Try to use WaitForInputIdle() to force the processing of your application to wait until the message loop has returned to the idle state. When a process with a user interface is executing, its message loop executes every time a Windows message is sent to the process by the operating system. The process then returns to the message loop. A process is said to be in an idle state when it is waiting for messages inside of a message loop. This state is useful, for example, when your application needs to wait for a starting process to finish creating its main window before the application communicates with that window. If a process does not have a message loop, WaitForInputIdle() throws an InvalidOperationException.
Also I'd suggest adding any delay before checking whether it is running or not.
Process.Start(startInfo);
Thread.Sleep(5000);

Another possible solution is to use COM Automation with the Logon method which allows specifying the profile name:
myNameSpace = Application.GetNamespace("MAPI");
myNameSpace.Logon("LatestProfile", Type.Missing , true, true);


Q:

check if something is an attribute or decorator in python

I want to wrap a model class of a legacy codebase. The model class has a dictionary with meta-information and properties that access that dictionary as well as attributes. I want to unify the access to meta information, properties, and attributes with the an_object[some_key] syntax using __getitem__. The problem is, that some of the properties have getters but not setters. So trying to check if an attribute exists (via hasattr) returns True, but then setting that attribute fails because there is no property defined.
How can I decide if I can set an attribute safely or if it is an property that I need to set in the meta-dictionary?

A:

You can detect if something is a property, by looking at the same attribute on the class:
class_attribute = getattr(type(instance), some_key, None)
if isinstance(class_attribute, property):
    # this is a property
    if class_attribute.fset is None:
        print "Read-only"

You can also test .fget and .fdel to test if the property has a getter and a deleter, respectively.
However, you can always catch the AttributeError exception to deal with the setter missing:
>>> class Foo(object):
...     @property
...     def bar(self):
...         return 'spam'
...
>>> f = Foo()
>>> class_attribute = getattr(type(f), 'bar', None)
>>> isinstance(class_attribute, property)
True
>>> class_attribute.fget
<function bar at 0x10aa8c668>
>>> class_attribute.fset is None
True
>>> try:
...     f.bar = 'baz'
... except AttributeError:
...     print 'Read-only'
...
Read-only


Q:

Field Pack not storing icon hex

I have a Field Pack Dropdown field for authors to select an icon. In the field settings I have the following options:
👀 : View
📝 : Compose
🔒 : Lock
🔓 : Unlock
🔑 : Key
📞 : Phone
✉ : Mail
💬 : Chat
👥 : Users
 : Location
 : Connection
“ : Quote
 : List
⚙ : Settings
📅 : Calendar

This shows up in the publish page as expected:
<select name="field_id_5">
    <option value="👀">View</option>
    <option value="📝">Compose</option>
    <option value="🔒">Lock</option>
    <option value="🔓">Unlock</option>
    <option value="🔑">Key</option>
    <option value="📞">Phone</option>
    <option value="✉">Mail</option>
    <option value="💬">Chat</option>
    <option value="👥">Users</option>
    <option value="">Location</option>
    <option value="">Connection</option>
    <option value="“">Quote</option>
    <option value="">List</option>
    <option value="⚙">Settings</option>
    <option value="📅">Calendar</option>
</select>

The problem is the field is not storing the data, and on the front-end calling the field outputs a null value.
Any ideas what the issue could be, or any workarounds I could try?

A:

I removed the'&#' characters from the dropdown options
👀 : View

has now become
x1F440; : View

and added those characters to my template output instead.
&#{standard_icon}

The field is storing the value as expected and the icon is being output fine in the template.


Q:

Asp.net Validation just working for one property

Following is my Model for Product
public class Product
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Please Enter Product Name")]
    [StringLength(100)]
    public string Name { get; set; }
    [Required(ErrorMessage = "Please Enter Short Desciption")]
    [StringLength(200)]
    .   // other properties
    .   // Removed for brevity
}

And following is my View code

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
       Html.Telerik().TabStrip()
           .Name("TabStrip")
           .Items(tabstrip =>
           {
               tabstrip.Add()
                   .Text("General")
                   .ContentHtmlAttributes(new { style = "height:700px" })
                   .Content(@<text>

                            @Html.LabelFor(model => model.Product.Name)

                            @Html.EditorFor(model => model.Product.Name)
                            @Html.ValidationMessageFor(model => model.Product.Name)

                            @Html.LabelFor(model => model.Product.ShortDescription)

                            @Html.TextAreaFor(model => model.Product.ShortDescription, new { cols = "50%", rows = "3" })
                            @Html.ValidationMessageFor(model => model.Product.ShortDescription)

                </text>);
           })
           .SelectedIndex(0)
           .Render();
}

Other than the Name property, validation isn't working.

A:

I found the answer to my problem. It's a bug or error in Asp.net MVC 3 as it is reported here : Unobtrusive Client Hooks Not Generated Via TextAreaFor For Nested Model Properties. This is the reason why the validations are aren't happening for ShortDescription in my case since i am using @Html.TextAreaFor.
Hope this is removed in MVC4