text:
Q: WebDriver - wait for element using Java I'm looking for something similar to waitForElementPresent to check whether element is displayed before I click it. I thought this can be done by implicitWait, so I used the following:
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

and then click by
driver.findElement(By.id(prop.getProperty(vName))).click();

Unfortunately, sometimes it waits for the element and sometimes not. I looked for a while and found this solution :
for (int second = 0;; second++) {
    Thread.sleep(sleepTime);
    if (second >= 10)
        fail("timeout : " + vName);
    try {
        if (driver.findElement(By.id(prop.getProperty(vName))).isDisplayed())
            break;
    } catch (Exception e) {
        writeToExcel("data.xls", e.toString(), parameters.currentTestRow, 46);
    }
}
driver.findElement(By.id(prop.getProperty(vName))).click();

And it waited all right, but before timing out it had to wait 10 times 5, 50 seconds. A bit much. So I set the implicitly wait to 1sec and all seemed fine until now. Because now some things wait 10s before timeout but some other things time out after 1s.
How do you cover the waiting for element present/visible in your code? Any hint is appreciable.

A: We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force
Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

A: This is how I do it in my code.
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.
See also:

*

*org.openqa.selenium.support.ui.ExpectedConditions for similar shortcuts for various wait scenarios.

*org.openqa.selenium.support.ui.WebDriverWait for its various constructors.

A: You can use Explicit wait or Fluent Wait
Example of Explicit Wait -
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));

Example of Fluent Wait -
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("about_me"));
 }
});

Check this TUTORIAL for more details.

A: Above wait statement is a nice example of Explicit wait.
As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).
By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.


text:
Q: Android ActionBar always null I have an activity with a navigation drawer that flicks between fragments. Nothing special.
However what I want is the action bar to appear at the top of the activity. The issue is that I keep getting a nullpointerexception for the Actionbar.
I've tried answers from the following pages:
getActionBar returns null
getActionBar() returns Null (AppCompat-v7 21)
None of these have worked so I thought I'd submit my own question with my own code.
MainActivity.java
package com.jampez.smalltalk;

import com.jampez.smalltalk.fragments.HomeFragment;
import com.jampez.smalltalk.fragments.MessageFragment;
import com.jampez.smalltalk.fragments.PreferencesFragment;
import com.jampez.smalltalk.fragments.SettingsFragment;
import com.jampez.smalltalk.helper.SessionManager;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends FragmentActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private String[] items;
    int selectedPosition;
    private SessionManager session;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    getActionBar().setTitle("");

    // Session manager
    session = new SessionManager(getApplicationContext());

    if (!session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    items = getResources().getStringArray(R.array.menus);
    // Getting reference to the DrawerLayout
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.drawer_list);

    /* Creating an ArrayAdapter to add items to mDrawerList */
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, items);
    mDrawerList.setAdapter(adapter);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer,
            R.string.drawer_open) {

        /* Called when drawer is closed */
        public void onDrawerClosed(View view) {
            //Put your code here
        }

        /* Called when a drawer is opened */
        public void onDrawerOpened(View drawerView) {
            //Put your code here
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Enabling Home button
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    // Setting item click listener for the listview mDrawerList
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectedPosition = position;

            /* Replace fragment content */
            displayView(position);

           /* Closing the drawer */
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    });

    /* Setting default fragment */
    selectedPosition = 0;
    displayView(0);
}

private void displayView(int position) {
    // update the main content by replacing fragments
    android.app.Fragment fragment = null;
    Log.i("position", position+"");
    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;
    case 1:
        fragment = new MessageFragment();
        break;
    case 2:
        fragment = new PreferencesFragment();
        break;
    case 3:
        fragment = new SettingsFragment();
        break;
    case 4:
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
        break;
    case 5:
        String url = "http://www.example.com";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
        break;
        default:
            break;
    }

    if (fragment != null) {

        android.app.FragmentManager fragmentManager = getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);

        //setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}
}

activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@android:style/Theme.WithActionBar" >

<!-- The main content view -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- The navigation drawer list-->
<ListView
    android:id="@+id/drawer_list"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#111"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

HomeFragment.java
package com.jampez.smalltalk.fragments;

import com.jampez.smalltalk.R;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class HomeFragment extends Fragment {

public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    //getActivity().getActionBar().setTitle(R.string.home);

    return rootView;
}
}

fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e5e5e5"
android:orientation="vertical" >

<TextView
    android:id="@+id/home_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:layout_gravity="start|center_vertical"
    android:text="@string/home"/>
</LinearLayout>

Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jampez.smalltalk"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="23" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<application
    android:name=".app.AppController"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".LoginActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize|stateHidden" >
    </activity>
    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />
</application>

styles.xml
<resources>

<!--
    Base application theme, dependent on API level. This theme is replaced
    by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!--
        Theme customizations available in newer API levels can go in
        res/values-vXX/styles.xml, while customizations related to
        backward-compatibility can go here.
    -->

</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
     <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@color/white</item>
</style>

<style name="MyActionButtonOverflow"     parent="android:style/Widget.Holo.ActionButton.Overflow">
<item name="android:color">@color/white</item>
</style>

 <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">#25a0da</item>
</style>

Logcat Output
11-08 19:17:38.618: E/AndroidRuntime(6347): FATAL EXCEPTION: main
11-08 19:17:38.618: E/AndroidRuntime(6347): Process: com.jampez.smalltalk, PID: 6347
11-08 19:17:38.618: E/AndroidRuntime(6347): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jampez.smalltalk/com.jampez.smalltalk.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.ActivityThread.access$900(ActivityThread.java:172)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.os.Handler.dispatchMessage(Handler.java:102)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.os.Looper.loop(Looper.java:145)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.ActivityThread.main(ActivityThread.java:5832)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at java.lang.reflect.Method.invoke(Native Method)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at java.lang.reflect.Method.invoke(Method.java:372)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
11-08 19:17:38.618: E/AndroidRuntime(6347): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
11-08 19:17:38.618: E/AndroidRuntime(6347):     at com.jampez.smalltalk.MainActivity.onCreate(MainActivity.java:37)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.Activity.performCreate(Activity.java:6221)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
11-08 19:17:38.618: E/AndroidRuntime(6347):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
11-08 19:17:38.618: E/AndroidRuntime(6347):     ... 10 more

A: *First of all include this dependency in your gradle file
compile 'com.android.support:appcompat-v7:22.2.0'

*You should extend your activity to AppCompactActivity and start using toolbar instead of ActionBar.
*This is how you use Toolbar in your MainActivity
public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;

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

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

*this is how to add toolbar in your activity_main.xml
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

*your theme should look something like this styles.xml
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

make sure you add this style name in your manifest for your application.
*It will be better if you use v4.app.Fragment rather than using Fragment.
*this is how you should set title from your Fragment class
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.home);

Refer this clear Tutorial which will surely help you setting up material Navigation drawer.
If you want to quickly start off without much pain then you can try integrating this third party library.

A: If you are not getting a ActionBar at all, like visualy, try to rewrite your Activity so you are able to use AppCompatActivity. This thread suggests to use ActionbarActivity instead of FragmentActivity. Since ActionbarActivity is deprecated, AppCompatActivity should work just fine.
For the Nullpointer issue:
Always be consistent with what you are using. If you decide to use AppCompat, make sure you are extending AppCompatActivity. Double check all imports - you might be using the normal Fragment instead of the AppCompat version.
Check your styles and make sure to use AppCompat parents instead of holo ones. That also includes your Actionbar. Instead of Widget.Holo.Light.ActionBaruse parent="@style/Widget.AppCompat.Light.ActionBar".
Always call getSupportActionBarinstead of getActionBar(). Sometimes it might even be neccessary to cast the Activity you are getting with getActivity() in a Fragment to AppCompatActivity to be sure you are getting the right one: ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("");.

A: Ok so none of the answers posted have given me much success. I have however managed to get the action bar displayed but with somewhat limited functionality.
The first thing I did was to replace the appcompat_v7 library with android-support-v7-appcompat. Doing this allows me to call the action bar using getActionBar().
The limitation come with trying to control aspects of the action bar. I can set the title and icon fine but if I try to use ActionBarDrawerToggle I get a NullPointerException. I also noticed that tapping on the action bar does nothing when normally it opens the drawer.

A: Did you try to put getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
in your onCreate() method? It helped me once. Also try changing theme to Holo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Absolute path for images that work on localhost and server For including php files I use
if ( !defined('ABSPATH') ) define('ABSPATH', str_replace("core/","",dirname(__FILE__) . '/'));

As my config file is kept in core I have to remove the folder it is in.
Now this works for including php files as it gives the correct file path,and it also works on the server.
But it will not work on the following line
<link rel="stylesheet" href="css/raw/style/site.css" media="screen"/>

As this needs a url instead of a file path.
Also the same for images, you need a url for these also.
After searching stack overflow people have said to use the document root and all this, but document root is only ever good on the server.
Locally I use wampserver and I have many different webpages in different folders so document root is no good. Also I write all my webpages locally before uploading. The absolute path has to work locally and on the server.
I can't use a fixed path either. As I have many versions of a website. Whenever I update a website I create a new folder and number it. So constantly changing a fixed path is not going to work.
Most of my webpages use relative paths because I haven't come up with a good solution to absolute paths here.
So what is the best solution for absolute path urls which work on localhost and on the server?
PS. I know there are posts on stack overflow which answer this question, but none are giving the answer I want. Most say define a local and server address, but I use multiple folders so this won't work for me.

A: I have finally found the answer which works on localhost and on the server.
function getCurrentURL()
{
    $currentURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    $currentURL .= $_SERVER["SERVER_NAME"];

    if($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443")
    {
        $currentURL .= ":".$_SERVER["SERVER_PORT"];
    }

        $currentURL .= $_SERVER["REQUEST_URI"];
    return $currentURL;
}

I run it in my config with this
if(!isset($_SESSION['ABSURL'])) $_SESSION['ABSURL']=getCurrentURL();

I found the answer on this site
http://hayageek.com/php-get-current-url/


text:
Q: Is quantum field theory impredicative? We define a field as a physical quantity assigned to each point in spacetime. In turn, spacetime is often defined or understood as "all there is," where there are fields.
So logically I wonder whether or not this is an impredicative theory, i.e. self-referential/circular?

A: Short answer: No, it is not an impredicative theory.
Longer answer: Either if you take the Wightman axioms, or the Algebraic approach, the theories of quantum fields are perfectly defined theories within ZFC. Essentially, you can see a quantum field theory as a noncommutative probability theory (that is actually true for any quantum theory). Such theory is described by an algebra of observables (random variables) that should at least contain the Weyl C* algebra of canonical commutation relations. The Weyl C* algebra is characterized by an underlying infinite dimensional real symplectic vector space that specifies the nature of the quantum field(s) considered. In suitable representations (e.g. the Fock representation for free theories) it is possible to define the self-adjoint generators of the Weyl operators, that are the so-called quantum fields. There is one quantum field for each vector of the real symplectic vector space. Therefore it is often convenient to see the quantum fields as maps from the symplectic vector space to the self-adjoint operators. These maps are called operator-valued distributions. However, as usual distributions, they cannot be evaluated at single points of the spacetime, but they make sense only as "global" objects acting on "test functions" (i.e. vectors in the symplectic space).


text:
Q: Too much space after `\start...` I have this file:
\newdimen\cslhangindent
\cslhangindent=1.5em
\definestartstop [cslreferences] [
        before={%
        \setupnarrower[left=\cslhangindent]
        \startnarrower[left]%
        \setupindenting[-\leftskip,yes,first]%
        \indentation%
      },
      after=\stopnarrower,
    ]

\starttext

\section{Some title}

\input ward

\section{References}

\startcslreferences

\dorecurse{10}{\dorecurse{10}{This is a Test. }\par}

\stopcslreferences

\stoptext

The skip after the \section{References} is bigger than after \section{Some title}. Why is that? If I delete the empty line after \startcslreferences, the skips are identical.
Is there a way to take care of this through \definestartstop?

A: The problem is the \indentation statement which immediately forces the indentation box to be placed, but you only want the indentation when the paragraph is started, so instead use \doindentation.
\definemeasure[cslhangindent][1.5em]
\definestartstop
  [cslreferences]
  [before={%
     \setupnarrower[left=\measure{cslhangindent}]
     \startnarrower[left]%
     \setupindenting[-\leftskip,yes,first]%
     \doindentation%
   },
   after=\stopnarrower]

\starttext

\section{Some title}

\input ward

\section{References}

\startcslreferences

\dorecurse{10}{\dorecurse{10}{This is a Test. }\par}

\stopcslreferences

\stoptext


text:
Q: Creating a function that will handle objects with common properties Take this as an example
I have trimmed this example for readability and you may not find the use of this concept here.
class Teacher()
{
 public Name {get; set;}
 public Salt {get; set;}
 public Department{get; set;}
}

class Student()
{
 public Name {get; set;}
        public Salt {get; set;}
 public Section{get; set;}
}

public string GetEncryptedName(object Person)
{
 //return encrypted name based on Name and Salt property
 return encrypt(object.Salt,object.Name)
}

callig the function
GetEncryptedName(Teacher)
GetEncryptedName(Student)

How do you implement this kind of stuff?

A: You need to implement a common interface / base class in both Teacher and Student:
interface IPerson {
    string Name {get;set;}
    string Salt {get;set;}
}

class Teacher : IPerson...

class Student : IPerson...

public string GetEncryptedName(IPerson person)
{
 //return encrypted name based on Name and Salt property
 return encrypt(person.Salt,person.Name)
}

That way you can call GetEncryptedName when any object that implements the IPerson interface and is guaranteed to implement the Name and Salt properties

A: Here is one approach. Have both Teacher and Student inherit from a base class, let's call it Person.  This Person class will have two properties, Name and Salt, and it can also have a public method called GetEncryptedName(), which will keep your implementation organized in a single place.

A: You need an Interface that both classes implement. Then you can pass the GetEncryptedName() method an interface.
interface IPerson
{
 string Name {get; set;}
 string Salt {get; set;}
 string Section {get; set;}
}

class Teacher : IPerson
{
 public Name {get; set;}
 public Salt {get; set;}
 public Section{get; set;}
 public Department{get; set;}
}

class Student : IPerson
{
 public Name {get; set;}
 public Salt {get; set;}
 public Section{get; set;}
}

public string GetEncryptedName(IPerson person)
{
 //return encrypted name based on Name and Salt property
 return encrypt(person.Salt,person.Name)
}

Here is the MSDN reference to interfaces: interface (C# Reference)

A: you could define an interface that both the Teacher and Student clases implement. Something like:
That is what I would do.
interface IEncryptionInfoProvider
{
    Name {get; set;}
    Salt {get; set;}
}

If you do not wish to define this interface, you would have to use reflection to get the values of the properties by name.
There are plenty of examples, info on the web on this topic.
http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257


text:
Q: how to display a custom list data on the app page in flutter
1[https://i.stack.imgur.com/yI2Cp.png">]1
i have tried this code to retrieve data from subcollection of the same name(userProducts) stored in many firebase documents.How do i display this data in a container on the app page ? I tried using listiew.builder but it doesnt work.
The first function
 static List<products> finalProductsList = [] ;
  productsList() async
  {
    List list_of_products = await Firestore.instance.collection("products")
        .getDocuments()
        .then((val) => val.documents);
    for (int i=0; i<list_of_products.length; i++)
    {
      Firestore.instance.collection("products").document(
          list_of_products[i].documentID.toString()).collection("userProducts").snapshots().listen(CreateListofProducts);
    }
  }

Second function
 CreateListofProducts(QuerySnapshot snapshot)async
  {
    var docs = snapshot.documents;
    for (var Doc in docs)
    {
      finalProductsList.add(products.fromFireStore(Doc));
    }
    }

CourseModel
class products {
  final String prodId;
  final String ownerId;
  final String username;
  final String price;
  final String productname;
  final String details;
  final String color;
  final String composition;
  final String washandcare;
  final String sizeandfit;
  final String shopmediaUrl;
  final String id;
  final dynamic likes;
  products({ this.prodId,
    this.ownerId,
    this.username,
    this.price,
    this.details,
    this.productname,
    this.color,
    this.composition,
    this.washandcare,
    this.sizeandfit,
    this.shopmediaUrl,
    this.id,
    this.likes,});

  factory products.fromFireStore(DocumentSnapshot doc)
  {
    Map data = doc.data ;
    return products(
      prodId: doc['prodId'],
      ownerId: doc['ownerId'],
      username: doc['username'],
      price: doc['price'],
      productname: doc['productname'],
      details: doc['details'],
      shopmediaUrl: doc['shopmediaUrl'],
      color:doc['color'],
      composition:doc['composition'],
      washandcare:doc['washandcare'],
      sizeandfit:doc['sizeandfit'],
      likes: doc['likes'],
    );

A: SO if i understand you, you want to get data on multiple collections on multiple documents?
If so... you should use collecionGroup, you can learn how to use here, make sure to adjust your firestore rules.


text:
Q: Copying files from bundle to Libraries folder (IOS10, Swift3, xcode 8.2) Here is my code for copying the folder from bundle to libraries.
    let library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
    let bundle = Bundle.main.path(forResource: "MYFOLDER", ofType: "")!

    let fileManager = FileManager.default
    do
    {
        try fileManager.copyItem(atPath: bundle, toPath: library.path)
        print("NO CATCH")
    }
    catch
    {
            print(error)
    }

I get this error:

Error Domain=NSCocoaErrorDomain Code=516 ""MYFOLDER" couldn't be copied to "CBE6D212-8827-423B-AEC8-6830EED0EC5C" because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/Users/Joshua/Library/Developer/CoreSimulator/Devices/84EF61E3-6739-47D1-A0AE-1215B89D0CE7/data/Containers/Bundle/Application/C357EB0E-6719-464B-8DC9-513E5E7F83E1/Heffy.app/MYFOLDER, NSUserStringVariant=(
      Copy
  ), NSFilePath=/Users/Joshua/Library/Developer/CoreSimulator/Devices/84EF61E3-6739-47D1-A0AE-1215B89D0CE7/data/Containers/Bundle/Application/C357EB0E-6719-464B-8DC9-513E5E7F83E1/Heffy.app/MYFOLDER, NSDestinationFilePath=/Users/Joshua/Library/Developer/CoreSimulator/Devices/84EF61E3-6739-47D1-A0AE-1215B89D0CE7/data/Containers/Data/Application/CBE6D212-8827-423B-AEC8-6830EED0EC5C/Library, NSUnderlyingError=0x797878e0 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}

**BUT I CHECKED IT DOES NOT EXIST IN THE LIBRARY FOLDER*

A: As per your error, file is already existing. try this code and check
  let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("NewFolder")?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
    print("FILE AVAILABLE")
} else {
    print("FILE NOT AVAILABLE")
}

A: So I got pissed so I closed Xcode. Closed my browser. Turn my machine off and turned it on. Guess what not it works........ Thanks for the help TinuDahiya I appreciate it ^__^V.


text:
Q: WPF View not binding unless I switch view before I'm trying to dev a WPF app which displays 3 views that we can switch using a side menu.
The first View displays articles. I've tried this view in another project on its own and it works just fine.
My issue:
The problem is that when I use it in my navigation (with the exact same code) the Images or Titles won't appear unless I click on another view first then click back.
Here's my current code:
Model: (Article)
    public class Article : INotifyPropertyChanged
    {
        int id;
        string title;
        string link;
        BitmapImage image;

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public Article(int id, string title, string link, BitmapImage image)
        {
            Id = id;
            Title = title;
            Link = link;
            Image = image;
        }

        public int Id
        {
            get => id;
            set { if (value != id) { id = value; NotifyPropertyChanged(); } }
        }

        public string Title
        {
            get => title;
            set { if (value != title) { title = value; NotifyPropertyChanged(); } }
        }

        public string Link
        {
            get => link;
            set { if (value != link) { link = value; NotifyPropertyChanged(); } }
        }

        public BitmapImage Image
        {
            get => image;
            set { if (value != image) { image = value; NotifyPropertyChanged(); } }
        }
    }

ViewModel: (ArticlesViewModel)
public class ArticlesViewModel : INotifyPropertyChanged
    {
        Article[] articles;

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public AccueilViewModel()
        {
            loadArticle();
        }

        public Article[] Articles
        {
            get => articles;
            set { if (value != articles) { articles = value; NotifyPropertyChanged(); } }
        }

         private async void loadArticle()
        {
            var client = new WordPressClient(App.WordpressLink);

            try
            {
                var asychArticles = GetArticles(client);
                await asychArticles;
                var articles = asychArticles.Result;

                int i = 0;
                int a;

                foreach (WordPressPCL.Models.Post p in articles)
                {
                    a = p.FeaturedMedia.Value;

                    var media = GetMedia(client, a);
                    await media;

                    BitmapImage bimage = App.getImage(media.Result.SourceUrl);

                    articleImg[i].Source = bimage;
                    articleTitle[i].Content = p.Title.Rendered.ToUpper();
                    articleLink[i] = p.Link;

                    i++;
                    if (i == 4) break;
                }
            }
            catch (System.Net.Http.HttpRequestException e)
            {

            }
        }
        static async Task<IEnumerable<WordPressPCL.Models.Post>> GetArticles(WordPressClient client)
        {
            var posts = await client.Posts.GetAll();
            return posts;
        }
        static async Task<WordPressPCL.Models.MediaItem> GetMedia(WordPressClient client, int number)
        {
            var media = await client.Media.GetByID(number);
            return media;
        }
    }

View: (ArticlesView)
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="10*"/>
            <RowDefinition Height="5*"/>
        </Grid.RowDefinitions>

        <Grid Name="Article1" Grid.Row="0" Margin="10,10,10,10" DataContext="{Binding Articles[0]}">
            <Grid.RowDefinitions>
                <RowDefinition Height="5*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>

            <Image Name="Image1" Grid.Row="0" Stretch="UniformToFill" Source="{Binding Image}"/>
            <Button Name="Titre1" Grid.Row="1" Content="{Binding Title}"/>

        </Grid>

        <Grid Grid.Row="1">

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Grid Name="Article2" Grid.Column="0"  Margin="10,10,10,10" DataContext="{Binding Articles[1]}">
                <Grid.RowDefinitions>
                    <RowDefinition Height="5*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>

                <Image Name="Image2" Grid.Row="0" Stretch="UniformToFill" Source="{Binding Image}"/>
                <Button Name="Titre2" Grid.Row="1" Content="{Binding Title}"/>

            </Grid>

            <Grid Name="Article3" Grid.Column="1"  Margin="10,10,10,10" DataContext="{Binding Articles[2]}">
                <Grid.RowDefinitions>
                    <RowDefinition Height="5*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>

                <Image Name="Image3" Grid.Row="0" Stretch="UniformToFill" Source="{Binding Image}"/>
                <Button Name="Titre3" Grid.Row="1" Content="{Binding Title}"/>

            </Grid>

            <Grid Name="Article4" Grid.Column="2" Margin="10,10,10,10" DataContext="{Binding Articles[3]}">
                <Grid.RowDefinitions>
                    <RowDefinition Height="5*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>

                <Image Name="Image4" Grid.Row="0" Stretch="UniformToFill" Source="{Binding Image}"/>
                <Button Name="Titre4" Grid.Row="1" Content="{Binding Title}"/>

            </Grid>

        </Grid>
    </Grid>

MainWindow.xaml:
<Window.Resources>

        <DataTemplate x:Name="ArticlesViewTemplate" DataType="{x:Type viewmodels:ArticlesViewModel}">
            <views:ArticlesView DataContext="{Binding}"/>
        </DataTemplate>
        <DataTemplate x:Name="Feature2ViewTemplate" DataType="{x:Type viewmodels:Feature2ViewModel}">
            <views:Feature2View DataContext="{Binding}"/>
        </DataTemplate>
        <DataTemplate x:Name="Feature3ViewTemplate" DataType="{x:Type viewmodels:Feature3ViewModel}">
            <views:Feature3View DataContext="{Binding}"/>
        </DataTemplate>

</Window.Resources>
<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="4*" />
        </Grid.ColumnDefinitions>

        <Grid Grid.Column="0">
            <StackPanel Grid.Row="1" VerticalAlignment="Top" Margin="20,20,20,0">
                <Button Content="Articles" Click="F1Button_Click"/>
                <Button Content="F2" Click="F2Button_Click"/>
                <Button Content="F3" Click="F3Button_Click"/>
            </StackPanel>
        </Grid>

        <ContentControl Grid.Column="1" Content="{Binding}"/>
    </Grid>

MainWindow.xaml.cs:
public partial class MainWindow : Window
    {
        ArticlesViewModel avm;
        Feature2ViewModel f2vm;
        Feature3ViewModel f3vm;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void F1Button_Click(object sender, RoutedEventArgs e)
        {
            if (avm == null) avm = new AccueilViewModel();
            DataContext = avm;
        }

        private void F2Button_Click(object sender, RoutedEventArgs e)
        {
            if (f2vm == null) f2vm = new CatalogueViewModel();
            DataContext = f2vm;
        }

        private void F3Button_Click(object sender, RoutedEventArgs e)
        {
            if (f3vm == null) f3vm = new MesFormationsViewModel();
            DataContext = f3vm;
        }
    }

To sum up:

*

*Click on Articles -> Nothing is displayed

*Click on F2 then Articles -> Nothing is displayed

*Click on Articles then F2 then Articles -> Images and Titles correctly displayed!

Any ideas on where the problem might be coming from? Thank you.

A: So the problem seemed to be coming from the fact that I was using an array. At the start the DataContext was null so the images and titles even though they were loaded in the modelview were not displayed on the view.
The problem was fixed by using an ObservableCollection instead of the array. If I understood correctly, NotifyPropertyChanged() is apparently not notifying the view when the array is at first null.(?)


text:
Q: Can't view JRebel Config Center I have used JRebel and Eclipse Juno for some time, but now it seems broken. If I try to open the JRebel Config Centre or any other view related to JRebel I only get: "JRebel Config Centre view can only be opened in the JRebel Config Centre perspective!"
I don't know if it's related, but my license got obsolete last week and I replaced the old license file with a new one a few days ago. I know it worked before I updated the license I don't know though if it has worked afterwards.

A: Still not really sure what the problem was. But after the second uninstall/reinstall from the marketplace the problem dissapeared and everything is back to normal again.

A: You have two options of getting to the Config Centre:

*

*Help -> JRebel Config Centre

*Open Perspective -> JRebel Config Centre

A: Will you please try below mentioned two options & let me know if you are able to view the config center?
1] Windows->Preferences->JRebel->Jrebel Config Center
2] Windows->Show View->Other->Jrebel Config Center

A: After getting error mentioned in question I was able to get back Jrebel config center by resetting it to default settings, closing and opening it one more time.


text:
Q: SignalR server closes connection immediately when the client connects I want to use SignalR in a project to send reboot messages to devices, but I can not. So I decided to start a new solution only for testing purposes with the same results:
SocketException (0x80004005): An existing connection was forcibly closed by the remote host
I am using Visual Studio Professional 2017 with .NET 4.7.2, and these are the steps I followed:

*

*I create a new solution with ASP.NET Web App project named SignalRServer, using Indentity for authentication.

*I create new folder named SignalR and add new item > SignalR Hub Class (v2). I named it SignalRHub:

public class SignalRHub : Hub
{
    public void Reboot()
    {
        Clients.All.reboot();
    }
    public void Hello()
    {
        Clients.All.hello();
    }
    public override Task OnConnected()
    {
        Debug.WriteLine($"[SERVER] {this.Context.ConnectionId} connected");
        return base.OnConnected();
    }
    public override Task OnReconnected()
    {
        Debug.WriteLine($"[SERVER] {this.Context.ConnectionId} reconnected");
        return base.OnReconnected();
    }
    public override Task OnDisconnected(bool stopCalled)
    {
        Debug.WriteLine($"[SERVER] {this.Context.ConnectionId} disconnected");
        return base.OnDisconnected(stopCalled);
    }
}

*In Startup.cs file:

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }

Server implementation is done. After that, the client:

*I add a new WPF project named SignalRClient.

*I add Microsoft.AspNet.SignalR.Client package using Nuget.

*I change MainWindow.xaml:

<Window x:Class="SignalRClient.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SignalRClient"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="400" Loaded="Window_Loaded">
    <Grid>
        <Button VerticalAlignment="Center" HorizontalAlignment="Center" Padding="5" Content="Send message!" Click="Button_Click"/>
    </Grid>
</Window>

*And finally I change MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    private IHubProxy signalRHubProxy;

    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Window_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var hubConnection = new HubConnection("http://localhost:54475/"))
            {
                this.signalRHubProxy = hubConnection.CreateHubProxy("SignalRHub");
                this.signalRHubProxy.On("Hello", this.HelloMessageReceived);
                this.signalRHubProxy.On("Reboot", this.RebootMessageReceived);
                ServicePointManager.DefaultConnectionLimit = 10;
                await hubConnection.Start();
                Debug.WriteLine($"[CLIENT] Connected to hub");
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine($"[CLIENT] {exception.Message}");
        }
    }

    private void HelloMessageReceived()
    {
        Console.WriteLine("[CLIENT] Hello message received");
    }
    private void RebootMessageReceived()
    {
        Console.WriteLine("[CLIENT] Reboot message received");
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await this.signalRHubProxy.Invoke("Hello", new { });
    }
}

The client is done too. Now I run the web app first, and when the home page is loaded I run the WPF app (Debug > Start new instance). This is the output:
[SERVER] b3f11c77-6bfc-416a-914b-f2573f0cc42c connected
[CLIENT] Connected to hub
[SERVER] b3f11c77-6bfc-416a-914b-f2573f0cc42c disconnected
SignalRClient.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details.  ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.WebSockets.WebSocketConnectionStream.WebSocketConnection.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.DelegatedStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<>n__1(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<WriteAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<SendFrameAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.<Process>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__51.MoveNext()
   at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<>c.<<CloseAsync>b__13_0>d.MoveNext() in /_/src/Microsoft.AspNet.SignalR.Core/Owin/WebSockets/WebSocketHandler.cs:line 114
The thread 0x4b44 has exited with code 0 (0x0).
The thread 0x5560 has exited with code 0 (0x0).

I can see that the client connects to the server, but the connection is immediately closed. I don't know if I am forgetting a step. I stopped the firewall with the same result. Do you know how can I solve the problem?

A: It seems like using statement is the reason as it disposes created HubConnection object at the end of try block which leads to websocket closing.
You may consider removing using statement and saving hubConnection as a field or property to call hubConnection.Stop() later to disconnect.


text:
Q: *pointer was nullptr* error in C programming I have a serious problame.
at the line **c = (int*)malloc(size1 * sizeof(int*));
the compiler gives me this error which I don't really know what it says.

Unhandled exception thrown: read access violation.
c was nullptr. occurred

I don't know what I'm doing wrong..
I initialize every pointer like this.
void BuildMatrix(int ***, int, int);
void FreeMatrix(int ***, int);
void PrintMatrix(int **, int, int);
int **MultiplyMatrixes(int **, int**, int, int, int);

int main() {
    int **matrix1 = NULL, **matrix2 = NULL, **matrix3 = NULL;
    int * newCol = NULL;
    int size1, size2, size3, newRow;

    printf("-How many rows in the first matrix?: ");
    scanf("%d", &size1);
    printf("-How many columns in the first matrix and second?[size2, size3]: ");
    scanf("%d %d", &size2, &size3);  /*size2 = rows of matrix2.*/

    /*Build both matrices*/
    printf("-First matrix input.\n");
    BuildMatrix(&matrix1, size1, size2);
    PrintMatrix(matrix1, size1, size2);
    printf("-Second matrix input.\n");
    BuildMatrix(&matrix2, size2, size3);
    PrintMatrix(matrix2, size2, size3);

    /*Combine the 2 matrices to a new matrix*/
    matrix3 = MultiplyMatrixes(matrix1, matrix2, size1, size2, size3);
    FreeMatrix(&matrix2, size2); //Free the second matrix

    printf("\n-Multiplied matrix: \n");
    PrintMatrix(matrix3, size1, size3);

    FreeMatrix(&matrix3, size1);
    FreeMatrix(&matrix1, size1);
}
void BuildMatrix(int *** pMat, int row, int col) {
    int i, j;
    (*pMat) = (int **)malloc(row * sizeof(int*));
    if (*pMat == NULL) {
        free(pMat);
        printf("*Not enough RAM.\nTerminating.\n");
        exit(1);
    }
    for (i = 0; i < row; i++) {
        (*pMat)[i] = (int *)malloc(col * sizeof(int*));
        if ((*pMat)[i] == NULL) {
            printf("*Not enough RAM.\nTerminating.\n");
            FreeMatrix(pMat, row);
            exit(1);
        }
        for (j = 0; j < col; j++) {
            printf("-Enter %d element in %d row: ", j + 1, i + 1);
            scanf("%d", &(*pMat)[i][j]);
        }
        printf("\n");
    }
    //FreeMatrix(pMat, row);
}
void PrintMatrix(int ** pMat, int row, int col) {
    for (int i = 0; i < row; ++i) {
        for (int j = 0; j < col; ++j) {
            printf("%d ", pMat[i][j]);
        }
        printf("\n");
    }
}
int** MultiplyMatrixes(int ** a, int ** b, int size1, int size2, int size3) {
    int i, j, k, **c = NULL;
    **c = (int*)malloc(size1 * sizeof(int*));
    if (c == NULL) {
        free(*c);
        printf("*Not enough RAM.\nTerminating.\n");
        exit(1);
    }
    for (i = 0; i < size1; i++) {

        for (j = 0; j < size3; j++) {
            c[i] = (int *)malloc(size3 * sizeof(int));
            if (c[i] == NULL) {
                printf("*Not enough RAM.\nTerminating.\n");
                FreeMatrix(&c, size1);
                exit(1);
            }
            for (k = 0; k < size2; k++) {
                c[i][j] += (a[i][k] * b[k][j]);
            }
        }
    }
    return c;
}

A: (*pMat)[i] = (int *)malloc(col * sizeof(int*));

will be
(*pMat)[i] = malloc(col * sizeof(int));

You have allocated space for col number of int* where you are reading int-s.
Also
**c = (int*)malloc(size1 * sizeof(int*));

will be
c = malloc(size1 * sizeof(int*));

Otherwise you were trying to dereference NULL value which triggered the error you got.
Also the loop will be
for (i = 0; i < size1; i++) {
    c[i] = malloc(size3 * sizeof(int));
    if (c[i] == NULL) {
        printf("*Not enough RAM.\nTerminating.\n");
        FreeMatrix(&c, size1);
        exit(1);
    }

    for (j = 0; j < size3; j++) {
        c[i][j]=0;
        for (k = 0; k < size2; k++) {
            c[i][j] += (a[i][k] * b[k][j]);
        }
    }
}

Don't cast the return value of malloc.


text:
Q: async function with decorators got class prototype as target I'm trying to get decorate async function using decorator.
when I decorate static function, I got target as class it self.

But when I decorate async function, I got target as class prototype.
I don't understand, someone please help on this, thanks.

// run with babel-node
function de(param) {
  return (target, key, descriptor) => {
    if (descriptor && descriptor.value) {
      console.log('-------------------');
      descriptor.value();
    }
  }
}

class A {
  classVar = 'var';

  @de('a')
  static aa() {
    console.log('aaa');
  }

  @de('b')
  async bb() {
    var b = 'bbb';
    await new Promise((resolve, reject) => {
      setTimeout(resolve, 3000);
    });
    console.log(b);
  }
}


text:
Q: How to change aspect ratio of photos taken using AVFoundation? I am using AVFoundation to take pictures instead of UIImagePicker due to how customizable the user interface presented to the user can be. When using it the aspect ratio that the picture is saved as is the same as the iPhone's video feed. What I want to happen is to have the pictures saved in the same aspect ratio as normal pictures are.
The way that I am currently approaching this is to overlay a black bar in the excess preview display and then just crop the photo after saving it as an image.
However, this feels very crude. I assume that it is a common thing to use the AVFoundation as a way of taking photos and so I assume I must be missing something!
I have used this example code. And I have read through the AVFoundation documentation but can only assume that I am missing a function. I have also read through similar questions to this which describe the process by which I might go about cropping images, but that isn't really my concern.
On the other hand, if there is no standard way to do this, please do let me know so that I can stop worrying that I am approaching it in a convoluted way.
Also, I am using Objective-C so if answers contain code, please could you use the same language?


text:
Q: Determine which records errored during an ExecuteNonQuery action I am attempting to perform a mass "upsert" in a SQL Server 2008 database by using a temporary table and a MERGE command. First, I am loading all the data from a list object into a DataTable. I then create a temp table in the SQL database, load the data in that table, and then call MERGE on the temp table and the target table.
I'm using the ExecuteNonQuery() method of a SqlCommand object to call the MERGE. The problem is, this will only tell me the total amount of records added but will not specify which ones.
Is there a method or technique where I can programmatically determine which records erred during the transaction? Below is the method I'm using.
    private static string insertCommand =
        "INSERT (ChannelCode, DrmTerrDesc, IndDistrnId, StateCode, ZipCode, EndDate, EffectiveDate, LastUpdateId, LastUpdateDate, ErrorCodes, Status) " +
        "VALUES(Source.ChannelCode, Source.DrmTerrDesc, Source.IndDistrnId, Source.StateCode, Source.ZipCode, Source.EndDate, Source.EffectiveDate, Source.LastUpdateId, Source.LastUpdateDate, Source.ErrorCOdes, Source.Status)";

    private static string updateCommand = "UPDATE SET Target.ChannelCode = Source.ChannelCode, Target.DrmTerrDesc = Source.DrmTerrDesc, Target.IndDistrnId = Source.IndDistrnId," +
                                                "Target.StateCode = Source.StateCode, Target.ZipCode = Source.ZipCode, Target.EndDate = Source.EndDate, Target.EffectiveDate = Source.EffectiveDate," +
                                                "Target.LastUpdateId = Source.LastUpdateId, Target.LastUpdateDate = Source.LastUpdateDate, Target.ErrorCodes = Source.ErrorCodes," +
                                                "Target.Status = Source.Status ";

    public static void Update(List<ZipCodeTerritory> updates, Dictionary<ZipCodeTerritory, string> errorList)
    {
        try
        {
            //Load updates into datatable
            DataTable table = LoadData(updates, true);

            //Script to create temp table
            string tmpTable =   "CREATE TABLE [dbo].[ZipCodeTerritoryTemp]( " +
                                "[ChannelCode] [char](1) NOT NULL, " +
                                "[DrmTerrDesc] [nvarchar](30) NOT NULL, " +
                                "[IndDistrnId] [char](3) NULL, " +
                                "[StateCode] [char](3) NOT NULL, " +
                                "[ZipCode] [char](9) NULL, " +
                                "[EndDate] [date] NOT NULL, " +
                                "[EffectiveDate] [date] NOT NULL, " +
                                "[LastUpdateId] [char](8) NULL, " +
                                "[LastUpdateDate] [date] NULL, " +
                                "[Id] [int] NULL, " +
                                "[ErrorCodes] [varchar](255) NULL, " +
                                "[Status] [char](1) NULL)";

            using (SqlConnection connection = new SqlConnection(connString))
            {
                connection.Open();

                //Create temp table
                SqlCommand cmd = new SqlCommand(tmpTable, connection);
                cmd.ExecuteNonQuery();

                try
                {

                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                    {
                        //Write to temp table
                        bulkCopy.DestinationTableName = "ZipCodeTerritoryTemp";
                        bulkCopy.WriteToServer(table);

                        //Merge changes in temp table with ZipCodeTerritory
                        string mergeSql = "merge ZipCodeTerritory as Target " +
                                          "using ZipCodeTerritoryTemp as Source " +
                                          "on " +
                                          "Target.Id = Source.Id " +
                                          "when matched then " +
                                          updateCommand +
                                          "when not matched then " +
                                          insertCommand + ";";

                        cmd.CommandText = mergeSql;
                        int results = cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    //Drop temp table
                    SqlCommand final = new SqlCommand("DROP TABLE [dbo].[ZipCodeTerritoryTemp]", connection);
                    final.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            string msg = ex.Message;
        }
    }


text:
Q: Jquery por algum motivo não grava todas as variáreis Galera tenho esse Jquery que grava todas essas variaveis de um formulário em  asp.net mvc.
Meu problema é que ele não esta gravando todas as variáveis. Ele grava aproximadamente a metade. Ele esta parando em estado_civil_proprietario. Alguém sabe me dizer se esse tipo de Jquery tem limitação quanto a capacidade de variáveis?
function SalvarCliente() {
debugger;
//Segurado
var nome_segurado = $("#Nome_Segurado").val();
var email_segurado = $("#Email_Segurado").val();
var telefone_segurado = $("#Telefone_Segurado").val();
var cpf_segurado = $("#CPF_Segurado").val();
var data_nasc_segurado = $("#Data_Nasc_Segurado").val();
var sexo_segurado = $("#Sexo_Segurado:checked").val();

var estado_civil_segurado = $("#Estado_Civil_Segurado option:selected").text();
//Veículo
var uso_veiculo = $("#Uso_Veiculo option:selected").text();
var Marca = $("#MarcaId option:selected").text();
var Modelo = $("#ModeloId option:selected").text();
var Versao = $("#VersaoId option:selected").text();
var ano_fabricacao = $("#Ano_Fabricacao").val();
var ano_modelo = $("#Ano_Modelo").val();
var zero_km = $("#Zero_Km:checked").val();
var num_portas = $("#Num_Portas:checked").val();
var combustivel = $("#Combustivel option:selected").text();
var alarme = $("#Alarme:checked").val();
var anticolisao = $("#Anticolisao:checked").val();
var possui_veiculo = $("#Possui_Veiculo:checked").val();
var placa = $("#Placa").val();
var estado = $("#Estado option:selected").text();
//Proprietário
var confirm_prorietario = $("#Confirm_Proprietario:checked").val();
var nome_proprietario = $("#Nome_Proprietario").val();
var tipo_pessoa_proprietario = $("#quote_policyholder_owner_kind_cd:checked").val();
var cpf_proprietario = $("#quote_policyholder_attributes_owner_attributes_cpf").val();
var cnpj_proprietario = $("#quote_policyholder_attributes_owner_attributes_cnpj").val();
var data_nasc_proprietario = $("#Data_Nasc_Proprietario").val();
var sexo_proprietario = $("#Sexo_Proprietario").val();
var estado_civil_proprietario = $("#Estado_Civil_Proprietario option: selected").text();
var relacao_proprietario = $("#Relacao_Proprietario option: selected").text();
var confirm_condutor = $("#Confirm_Condutor:checked").val();
var relacao_condutor = $("#Relacao_Condutor option: selected").text();
var nome_condutor = $("#Nome_Condutor").val();
var cpf_condutor = $("#CPF_Condutor").val();
var data_nasc_condutor = $("#Data_Nasc_Condutor").val();
var sexo_condutor = $("#Sexo_Condutor:checked").val();
var estado_civil_condutor = $("#Estado_Civil_Condutor option: selected").text();
var profissao_condutor = $("#Profissao_Condutor").val();
var primeira_habilitação = $("#Primeira_Habilitação").val();
//Análise de Risco
var residencia = $("#Residencia option: selected").text();
var cep = $("#CEP").val();
var cep_veiculo = $("#CEP_Veiculo:checked").val();
var cep_veiculo_noite = $("#CEP_Veiculo_Noite").val();
var mais_veiculo_residencia = $("#Mais_Veiculo_Residencia option: selected").text();
var garagem = $("#Garagem:checked").val();
var km_uso = $("#Km_Uso option: selected").text();
var escola = $("#escola:checked").val();
var trabalho = $("#Trabalho:checked").val();
var residentes_entre17a25 = $("#Residentes_Entre17a25:checked").val();
var adicionar_condutor = $("#Adicionar_Condutor:checked").val();
var nome_condutor_adicional = $("#Nome_Condutor_Adicional").val();
var sexo_condutor_adicional = $("#Sexo_Condutor_Adicional:checked").val();
var relacao_condutor_adicional = $("#Relacao_Condutor_Adicional option: selected").text();
//Finalizando
var possui_seguro = $("#Possui_Seguro:checked").val();
var forma_contato = $("#Forma_Contato:checked").val();
var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr = $('form[action="/Cliente/Create"] input[name="__RequestVerification"]').val();

var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;

var url = "/Cliente/Create";
$.ajax({
    url: url
    , type: "POST"
    , datatype: "json"
    , headers: headersadr
    , data: {
        Id: 0,
        Nome_Segurado: nome_segurado,
        Email_Segurado: email_segurado,
        Telefone_Segurado: telefone_segurado,
        CPF_Segurado: cpf_segurado,
        Data_Nasc_Segurado: data_nasc_segurado,
        Sexo_Segurado: sexo_segurado,
        Estado_Civil_Segurado: estado_civil_segurado,
        Uso_Veiculo: uso_veiculo, MarcaId: Marca,
        ModeloId: Modelo, VersaoId: Versao,
        Ano_Fabricacao: ano_fabricacao,
        Ano_Modelo: ano_modelo,
        Zero_Km: zero_km,
        Num_Portas: num_portas,
        Combustivel: combustivel,
        Alarme: alarme,
        Anticolisao: anticolisao,
        Possui_Veiculo: possui_veiculo,
        Placa: placa,
        Estado: estado,
        Confirm_Proprietario: confirm_prorietario,
        Nome_Proprietario: nome_proprietario,
        quote_policyholder_owner_kind_cd_1: tipo_pessoa_proprietario,
        quote_policyholder_attributes_owner_attributes_cpf: cpf_proprietario,
        CNPJ_Proprietario: cnpj_proprietario,
        Data_Nasc_Proprietario: data_nasc_proprietario,
        Sexo_Proprietario: sexo_proprietario,
        Estado_Civil_Proprietario: estado_civil_proprietario,
        Relacao_Proprietario: relacao_proprietario,
        Confirm_Condutor: confirm_condutor,
        Relacao_Condutor: relacao_condutor,
        Nome_Condutor: nome_condutor,
        CPF_Condutor: cpf_condutor,
        Data_Nasc_Condutor: data_nasc_condutor,
        Sexo_Condutor: sexo_condutor,
        Estado_Civil_Condutor: estado_civil_condutor,
        Profissao_Condutor: profissao_condutor,
        Primeira_Habilitação: primeira_habilitação,
        Residencia: residencia,
        CEP: cep,
        CEP_Veiculo: cep_veiculo,
        CEP_Veiculo_Noite: cep_veiculo_noite,
        Mais_Veiculo_Residencia: mais_veiculo_residencia,
        Garagem: garagem,
        Km_Uso: km_uso,
        Escola: escola,
        Trabalho: trabalho,
        Residentes_Entre17a25: residentes_entre17a25,
        Adicionar_Condutor: adicionar_condutor,
        Nome_Condutor_Adicional: nome_condutor_adicional,
        Sexo_Condutor_Adicional: sexo_condutor_adicional,
        Relacao_Condutor_Adicional: relacao_condutor_adicional,
        Possui_Seguro: possui_seguro,
        Forma_Contato: forma_contato,
        __RequestVerificationToken: token
    }
    , success: function (data) {
        if (data.Resultado > 0) {

        }
    }
});

}
Seque o codigo em C# da minha controller que manda as variáveis para o db:
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Cliente cliente)
    {
      if (ModelState.IsValid)
      {

        db.Clientes.Add(cliente);
        db.SaveChanges();

      }

        return Json(new { Resultado = cliente.Id }, JsonRequestBehavior.AllowGet);

    }


text:
Q: STS 3.7.1 unable to add Dependencies to classpath on Import maven project I updated STS and when imported project using Import->Existing Maven projects I'm unable to add Maven Dependencies to classpath. I click on Project -> Properties -> Java Build Path -> Add Library -> Maven... STS says to me 'Use 'Maven project settings' to configure dependency resolution'. But nothing there, only active profile selection, which gives nothing.
Seems like STS team completely broke import and I need to create new project and move src files there.
version: 3.7.1.RELEASE
Update:
I mean I can add dependencies to pom, but cant add them to classpath.

A: They fixed this in 3.7.2.RELEASE. Click Maven->Update Project and all dependencies will be automatically added to classpath.

A: Open the pom.xml file. It would open in a tabbed form editor. See the "Dependecies" tab in the editor.


text:
Q: Can I create public/permanent files from Xamarin App? I'm making an App where I need to create CSV files with data I need to load in a software in a Windows machine. I want to connect an Android Device via USB to a computer and get the file from there. Is there any way I can create a file that's visible for a computer?
From what I've found you can only create cache files and files only visible to the app (neither my PC or the File Manager on the phone can see them).
I thought about creating a service in the network and send the data to that and create the file in the server but that would add more failing points and of course is more work, besides sometimes the app could be running in parts where the Wifi doesn't get to it and would mean I would have to do a temporal file and somehow upload it when it connects back, so not practical at all.

A: Of course you can create files and folders on external storage of the android device, which is publicly accessible. Refer to this guide.
Note: You need to get permission WRITE_EXTERNAL_STORAGE to write and READ_EXTERNAL_STORAGE to read from device's external storage.


text:
Q: NSNumberFormatter format currency not working I have a number formatter:
let currencyFormatter:NSNumberFormatter = NSNumberFormatter()
        currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        currencyFormatter.currencyCode = "$"

Set it for label:
cell.ValueLabel.text = currencyFormatter.stringFromNumber(product.price)

And get 100.00 instead of 100.00$

A: You have to set currencySymbol instead of currencyCode
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.currencySymbol = "$"
currencyFormatter.stringFromNumber(100)  // $100.00"

else
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.currencyCode = "USD"
currencyFormatter.stringFromNumber(100)  // $100.00"


text:
Q: Python streaming std(in/out/err) to another process I have a python process running "in the background".  It's a subprocess.Popen() call started in a totally different process.  As I've implemented it so far, the two processes are using multiprocessing.connections.(Listener|Client) to communicate with eachother.  But I'm open to any way to accomplish the following.
What I want to do is have the "listener" background process use std(in|out|err) as if they've come from the "client" process.  Streaming is important so that io isn't read into memory but is read and written efficiently but also to avoid blocking on the listener process.  I guess that means I need a lower-level access or some sort of async/threading/multiprocessing solution.  That's what I'm unclear on how do to.  For example:
while True:  # TODO
    conn = listener.accept()
    try:
        callable_, args, kw = conn.recv()
        callable_(*args, **kw)

The question is how to allow callable_ to execute streaming to/from std(in|out|err) efficiently and without blocking.  The listener is also long-running, and I'm trying to support arbitrary python code that does from sys import std(in|out|err) at listener module import time will still see std(in|out|err) as if from the client. I can do setup (modifying/replacing sys.std(in|out|err)?) at listener startup before anything else is impored.
Is there a good way to stream this io transparently such that after initial setup the code being run by the listener process can be arbitrary and can treat std(in|out|err) normally without blocking, etc.?  Preferably without creating new processes since the goal is to reduce process overhead, though using multiple processes on the client end is preferable since the client is thin.  Similarly, if I have to loop over reads/writes of segments of bytes from std(in|out|err) to accomplish effective streaming it would be best to do it in the client.

A: I'm not entirely sure I understand the question, but have you looked into using select with pipes/sockets to avoid blocking?   I'm a bit vague on the other req that it "not be read into memory."


text:
Q: $_SESSION login script: not validating users in SQL database My database setup is like so:
create database if not exists shop;
use shop;
create table if not exists users(
 id serial primary key,
 username varchar(20),
 password char(20));

create table if not exists admins(
 id serial primary key,
 username varchar(20),
 password char(20));

insert into admins values(null, 'admin', SHA('touch'));

and my main problem exists with the login_process page.
<?php
 $username = $_POST['username'];
 $password = $_POST['password'];

 $db=mysqli_connect("localhost","root","","shop")or die(mysqli_error($db));
 $q="select * from admins where username='$username' and password=SHA('$password')";
 $results=mysqli_query($db, $q)or die(mysqli_error($db));
 if(mysqli_num_rows($results) > 0)
 {
  session_start();
  $_SESSION['username']=$username;
  header("Location:index.php");
  exit(0);
 }
 else
 {
   header("Location:login.php");
   exit(0);
 }
?>

When the page tries to validate my admin, instead of the location heading to index.php, it instead stays on login.php and the admin credentials never validate. The same problem persists in my login and register process pages with their respective roles.

A: MySQL's SHA function return 40 hex digits string. The password field need to handle 40 characters to make SHA works.

A: Address the issues by following
type session_start on the login page & declare $_SESSION variables as ''
$q="select * from admins where username='$username' and password=SHA('$password')";
echo this query & run on backend,see if it returns data?
So if the above query returns data then sure redirection will be on index page


text:
Q: What is the difference between local disk and remote disk in the Profile Overview? I have executed a Snowflake query and the Profile output looks like this:

What is the difference between the Local Disk IO and Remote Disk IO? What is happening at each level?

A: 'Local Disk' IO refers to processing blocked by local disk access (i.e. local to the worker nodes of the virtual warehouse), whereas 'Remote Disk IO' refers to the processing time blocked by remote disk access.
In essence, when the amount of memory available on the underline EC2 instance running each of the virtual warehouse nodes is not enough, the query processing engine starts spilling the data to the local disks or remote disks if the local disks are not sufficient.
The Snowflake documentation is self-explanatory:

*

*'Analyzing Queries Using Query Profile > Execution Time'

*'Analyzing Queries Using Query Profile > Queries Too Large to Fit in Memory'

A: Remote disk is reading data from the database, not "spilling". Local Disk I/O is local disk usage that is part of normal processing. Spilling occurs when the warehouse can't fit all the data into memory and local disk cache.
In you example, neither is "spilling". Remote disk I/O is reading from the database.
You can improve performance of this query by using the next larger warehouse size; data will fit most likely fit in memory, eliminating most of the local storage.
"Spilling" will be shown in the profile with the word "Spilling".

A: Because all of the data doesn't necessarily fit in memory. You can think of it much like virtual memory on the server with pages swapped to local disk due to memory limitation.. If you increase the warehouse one size, you should see the local disk I/0 decline by about 50%.

A: I agree with #3, from the screenshot, we can't determine if the spillage actually happened, since it shows up as a separate section in the query profile. So, I would think that local I/O is the data that has already been read from the remote storage, and remote I/O is directly reading it from the storage layer, and hence it takes much longer. On the second execution of the same query/against the same table, the query should show local I/O.


text:
Q: How to mathematically express in a payoff matrix that "not losing" isn't the equivalent of winning My uncle was watching a documentary on the revolutionary war and one of the historians said, "Washington realized he didn't need to win the war, he only needed to not lose it." Is it possible to express in a pay off matrix that losing is not the antonym to winning?

A: The easiest way of doing this is saying that there are 2 levels of the game. Let $p_1$ and $p_2$ be two players, let $A$ be a finite set of all possible outcomes and let $f_1,f_2$ be a correspondent payoff matrix. Based on the outcome $A$, we determine new "meta" outcomes:
$$
  S_1 = \{f_1>f_2\},\; S_0 = \{f_1 = f_2\} = \{\text{draw}\}, \;S_2 = \{f_2>f_1\}.
$$
Now, the final result of the game is evaluated not based on the first-level-payoffs $f_1,f_2$, but on the second-layer ones $u_1$ and $u_2$ which in your case are given by:
$$
  u_1(S_1) = u_1(S_0) = 1, \;u_1(S_2) = -1.
$$
That means, the in the final count the player $p_1$ wants to avoid the loss in the first layer, but both the win and the draw in the first layer he considers as a final win.
P.S. this is highly informal, but seems to fit the question.


text:
Q: ifelse function, running one step by step is fine,but doesn't work in whole I wanna extract the date from a string. When I run it step by step, it works great as below
as.Date(strptime(substr("44132219721105202X",7,14),format="%Y%m%d"))
[1] "1972-11-05"

But I wanna use it in ifelse function, because I have a column strings to do that. But it doesn't work.
ifelse(nchar("44132219721105202X", type = "bytes", allowNA = FALSE, keepNA = NA)==18,as.Date(strptime(substr("44132219721105202X",7,14),format="%Y%m%d")),"44132219721105202X")


text:
Q: Angular2 beta14 Typescript routerLink binding error I'm trying to create a wizard using Angular2's router. Angular2 suggests to have a main bootstrap file, which will bootstrap all the app components. Since i'm not able to do a SPA, i would like each page to bootstrap it's own components.
I get the following error about routerLink when i run the application:
"EXCEPTION: Template parse errors:
Can't bind to 'routerLink' since it isn't a known native property ("For="#wizard of Wizards" [selected]="SelectedWizard == wizard" [value]="wizard.name" [ERROR ->][routerLink]="'' + wizard.path + ''">{{wizard.name}}
        "
Here is my page component:
/// <reference path="angular2/typings/browser.d.ts" />
/// <reference path="angular2/core.d.ts" />
/// <reference path="angular2/router.d.ts" />

import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';

import {Wizard1} from './wizard1';
import {Wizard2} from './wizard2';
import {Step1} from './step1';
import {Step2} from './step2';
import {Step3} from './step3';
import {Step4} from './step4';
import {Step5} from './step5';

@Component({
    selector: 'page',
    template:
'

    <select (change)="setSelectedWizard($event.target.value)">
        <option *ngFor="#wizard of Wizards" [selected]="SelectedWizard == wizard" [value]="wizard.name" [routerLink]="'' + wizard.path + ''">{{wizard.name}}</option>
    </select>
    <wizard1>
        <step1>

First!

        </step1>
        <step2>

Second!

        </step2>
        <step3>

Third!

        </step3>
        <step4>

Fourth!

        </step4>

            <button type="button" value="Next" [class]="(SelectedStepIndex == Steps.length) ? 'btn btn-primary hidden' : 'btn btn-default'" (click)="next()" [routerLink]="['' + Steps[SelectedStepIndex] + '']">Next</button>

        <router-outlet></router-outlet>
    </wizard1>
    <wizard2>
        <step1>

First!

        </step1>
        <step5>

Fifth!

        </step5>

            <button type="button" value="Next" [class]="(SelectedStepIndex == Steps.length) ? 'btn btn-primary hidden' : 'btn btn-default'" (click)="next()" [routerLink]="['' + Steps[SelectedStepIndex] + '']">Next</button>

        <router-outlet></router-outlet>
    </wizard2>
    <router-outlet></router-outlet>

'
})
export class Page {
    Wizards = [{name: 'wizard1', path:'/wizard1'}, {name: 'wizard2', path: '/wizard2'}];
    SelectedWizard = this.Wizards[0];

    setSelectedWizard(value) {
       this.SelectedWizard = value;
    }
}

bootstrap(Page, [ROUTER_PROVIDERS]);
bootstrap(Wizard1, [ROUTER_PROVIDERS]);
bootstrap(Wizard2, [ROUTER_PROVIDERS]);
bootstrap(Step1);
bootstrap(Step2);
bootstrap(Step3);
bootstrap(Step4);
bootstrap(Step5);

Wizard1
/// <reference path="angular2/core.d.ts" />
/// <reference path="angular2/router.d.ts" />

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_PROVIDERS} from 'angular2/router';

@RouteConfig([
    { path: '/wizard1', name: 'wizard1', component: Wizard1 }
])
@Component({
    selector: 'wizard1',
    template:`<div><ng-content></ng-content></div>`
})
export class Wizard1 {
    Steps = ['/Step1', '/Step2', '/Step3', '/Step4'];
    SelectedStepIndex = 0;

    next() {
        ++this.SelectedStepIndex;
    }
}

Wizard2
/// <reference path="angular2/core.d.ts" />
/// <reference path="angular2/router.d.ts" />

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_PROVIDERS} from 'angular2/router';

@RouteConfig([
    { path: '/wizard2', name: 'wizard2', component: Wizard2 }
])
@Component({
    selector: 'wizard2',
    template:`<div><ng-content></ng-content></div>`
})
export class Wizard2 {
    Steps = ['/Step1', '/Step5'];
    SelectedStepIndex = 0;

    next() {
        ++this.SelectedStepIndex;
    }
}

All steps are similar to this, in their own .ts files
/// <reference path="angular2/core.d.ts" />
/// <reference path="angular2/router.d.ts" />

import {Component} from 'angular2/core';
import {RouteConfig} from 'angular2/router';

@RouteConfig([
    { path: '/Step1', name: 'Step1', component: Step1 }
])
@Component({
    selector: 'step1',
    template: `<div><ng-content></ng-content></div>`
})
export class Step1 {

}

What is going on? why isn't this working?
Environment

*

*Visual Studio 2015 update 1

*ASP.NET 5 and MVC 6

*DNX 4.5.1 and 5.0

*Angular2 Typescript

A: You are missing ROUTER_DIRECTIVES is missing to import on Page components & directives option of ComponentMetaData, that is the reason why angular doesn't understand routerLink & routerOutlet directive on page. Do include below line
import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router';

Then obviously inject ROUTER_DIRECTIVES in that component directives option
@Component({
    selector: 'page',
    //....
    //other options
    //....
    directives: [ROUTER_DIRECTIVES]
})

I'm not sure why you did bootstrap you application multiple times? Ideally there should be only one main-component, other component will child of it.

A: Add ROUTER_DIRECTIVES to your component providers:
@Component({directives: [ROUTER_DIRECTIVES]})


text:
Q: Geometric race line - 90 degree angular curve I am in a process of solving the race curve by driving from outside to inside for $90˚$ curves. I'm trying to solve it with Pythagoras but somehow my theory seems to be flawed. Wolfphram alpha gives error and my calculator seems to give very low results for R2:

This gives:
$$(R2-R1)^2 = (R2-R1-W)^2 + (R2-R1-W)^2$$
I know there is another solution on this website, but I would like to know where I am wrong.
Thanks in advance!

A: Ok so you should have
$\begin{align*}
(R_2-R_1)^2&=2(R_2-R_1-W)^2\\R_2-R_1&=\sqrt2(R_2-R_1-W)\\0&=(\sqrt2-1)(R_2-R_1)-\sqrt2W\\R_2&=R_1+\frac{\sqrt2}{\sqrt2-1}W\end{align*}$


text:
Q: Pandas - Return rows that only contain integers From a whole DataFrame, i picked a specific column.
Once I have this column (which is of type object) i want to return all the rows that have integers only.
Consider the following DataFrame.
Fruits     Vegetable

Apple      Corn
123        Potatoe

subDf=df["Fruits"]

What can i use on subDf so that it returns all rows that contain only integers?
(In this case "123")

A: You may use str.contains here:
subDf = df[df["Fruits"].str.contains(r'^\d+$')]

str.contains uses the following regular expression, which means:
^    from the start of the Fruits value
\d+  match one or more digits (integer only)
$    end of the value


text:
Q: Disable ElasticSearch logs in Liferay 7 I've started using Liferay v7, and am getting a lot of the following log messages:
17:14:12,265 WARN  [elasticsearch[Mirage][management][T#1]][decider:157] [Mirage] high disk watermark [90%] exceeded on [fph02E6ISIWnZ5cxWw_mow][Mirage][/Users/randy/FasterPayments/src/eclipse/com.rps.portal/com.rps.portal.backoffice/bundles/data/elasticsearch/indices/LiferayElasticsearchCluster/nodes/0] free: 46gb[9.9%], shards will be relocated away from this node

To be honest, I'd rather not spend time learning about ElasticSearch right now, is it possible to simply disable ElasticSearch within Liferay 7 dev environment?  Or other action to remove these log messages?

A: Go to Control Panel / Configuration / System Settings / Foundation / Elasticsearch.
Under "Additional Configurations" enter
cluster.routing.allocation.disk.threshold_enabled: True
cluster.routing.allocation.disk.watermark.low: 30gb
cluster.routing.allocation.disk.watermark.high: 20gb

or whatever are appropriate values for your system (there is value in being warned that the disk is almost full).
Save & Restart (the values seem not to be picked up at runtime).

A: Liferay needs an index/search engine, say ElasticSearch or SOLR. It defaults to ElasticSearch in DXP. It makes no sense disabling it.
The warnings tell you you've reached your configured disk shared allocation. You can change this settings in your elasticSearch.yml (cluster.routing.allocation.disk.watermark.high).
If your logs annoy you, you can change your logging settings. Not sure If it's still valid in DXP, but have a look at https://dev.liferay.com/es/discover/deployment/-/knowledge_base/6-2/liferays-logging-system.


text:
Q: What are the main bottlenecks to know about Java portability? Java is known to be portable; "compile once, run anywhere".  I know this is often true because I have many times deployed jar or war without any cross-platform troubles.  Still, I am left wondering if this is always true.
For example, Swing applications look different between different OS platforms. Also, JDK-1.7 is still a preview release for Mac OS X.
So, what are the common problems that prove that Java applications are not entirely cross platform?

A: Swing is platform-dependent to a certain extent.  In addition to the widget themes being different, as you noted, we've had Swing-based applications where the layout is different from platform to platform.  There was also another group I worked in that had some widgets not even show up on certain platforms.
I'm not sure how big a problem this is though, because I'm not sure how much Swing is used anymore.  Eclipse's SWT seems to be a lot more platform-independent, so it seems that Java + GUI doesn't necessarily imply non-portability.
Also, any Java code that uses the operating system or makes assumptions about the underlying platform will naturally be less portable, for reasons including (but not limited to):

*

*case (in)sensitivity of the filesystem

*newline characters

*threads/processes

(Many of these can be easily handled by Java APIs -- System.getProperty("line.separator");).

As a counterpart to the saying you mentioned, some of the more experienced programmers in my group say that Java is "write once, test everywhere".


text:
Q: What is the View Generating of EF After I read Performance Considerations. I Have something not understand.

Before the Entity Framework can execute a query against a conceptual model or save changes to the data source, it must generate a set of local query views to access the database. Because of the high cost of generating these views, you can pre-generate the views and add them to the project at design-time.

My first question is Does it means everytime before executing a query EF will generate views for it ?
Second questions is  What is the view? What is it used for ? Thanks


text:
Q: ActiveModel::ForbiddenAttributesError in Devise::RegistrationsController#create I am getting this
ActiveModel::ForbiddenAttributesError in Devise::RegistrationsController#create

error when i used devise gem
error in console is
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"kwJU2b47XvXj9hNV1HAdttW/rvetDepAVCn+jPvndy8=", "user"=>{"email"=>"nagarajureddy@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}

Completed 500 Internal Server Error in 1ms
 ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):  activemodel (4.1.0) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'

Please  any one help me

A: Add this in your application controller and restart the server, It's because of Strong Parameters in Rails4.
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, password_confirmation)  }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:email, :password, password_confirmation) }
  end


text:
Q: Random Number Seed 4321 SPSS I have a question where I need to use a random number seed 4321 to create a random sample with a normal distribution on SPSS. Does this just mean that I need to use the RV.NORMAL like usual or is seed 4321 something different?

A: There is no need to specify a seed unless you want to produce the exact same "random" numbers in the future


text:
Q: scipy sparse matrix: Index out of range I want to run textrank against a large corpus (just my dev env is using 17K sentences)
Hence I have used scipy dok_matrix. However, when assigning the first value to my sparse matrix (i.e., similarity_matrix[1][0]), I get the following error, despite seeing in pycharm debug that my dok_matrix is of size 17K by 17k.
IndexError: row index (1) out of range
What have I done wrong?
 def _score_generator(self, sentences, sentence_vectors):
    sentence_count = len(sentences)
    similarity_matrix = dok_matrix((sentence_count, sentence_count), dtype=np.float32)
    for i in range(len(sentences)):
        for j in range(len(sentences)):
            if i != j:
                similarity_matrix[i][j] = cosine_similarity(sentence_vectors[i].reshape(1, 100), sentence_vectors[j].reshape(1, 100))[0, 0]

    nx_graph = nx.from_scipy_sparse_matrix(similarity_matrix)
    scores = nx.pagerank(nx_graph)
    return scores

A: simple:
similarity_matrix[i,j]
I'll leave it here in case anyone else ends up making the same cognitive slip as I did


text:
Q: Overwrite nested z-index I have an overlay which should be on top of everything. The problem is that the overlay is inside a content-wrapper that has a z-index defined. This can't be changed. The logo has a z-index defined as well. This too, can't be changed.
I've made a Fiddle which shows the issue. Can this be done with pure CSS? My other idea is to move the overlay with Javascript, but all the CSS is currently also nested, so I need to change lots of CSS if I do so.

A: Do something like this, when you click on 'btn' toggle some class to '.overlay', like this\
 $("button").on("click", function() {
    $(".overlay").toggle();
   $('.content').toggleClass('z-1000');
});

in your CSS:
.content.z-1000{
  z-index:1000;
}

hope this works for you. working fiddle


text:
Q: Java event handling with a delay import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JPanel;
import javax.swing.Timer;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

/**
 * A simple demonstration application showing how to create a pie chart using
 * data from a {@link DefaultPieDataset}.
 */
public class PieChartDemo1 extends ApplicationFrame implements ChartMouseListener {
private JFreeChart chart;
private PiePlot plot;
private int angle=270;
private static double explodePercent = 0.99;
private static long count=0;
/**
 * Default constructor.
 *
 * @param title  the frame title.
 */
public PieChartDemo1(String title) {
    super(title);
           this.chart = ChartFactory.createPieChart(
            "Pie Chart Demo 1",  // chart title
            createDataset(),             // data
            true,               // include legend
            true,
            false
        );

        this.plot = (PiePlot) chart.getPlot();
        this.plot.setSectionOutlinesVisible(false);
        this.plot.setNoDataMessage("No data available");
        this.plot.setBackgroundAlpha(0.2f);
        this.plot.setBackgroundPaint(Color.WHITE);
        this.plot.setExplodePercent("One",.99);
        this.angle=270;
        ChartPanel chartpanel = new ChartPanel(chart, false, false, false, false,      false);
        chartpanel.setVisible(true);
    chartpanel.addChartMouseListener(this);
    chartpanel.setPreferredSize(new Dimension(500, 270));
    setContentPane(chartpanel);
}

/**
 * Creates a sample dataset.
 *
 * @return A sample dataset.
 */
private static PieDataset createDataset() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("One", new Double(43.2));
    dataset.setValue("Two", new Double(10.0));
    dataset.setValue("Three", new Double(27.5));
    dataset.setValue("Four", new Double(17.5));
    dataset.setValue("Five", new Double(11.0));
    dataset.setValue("Six", new Double(19.4));
    return dataset;
}

/**
 * Creates a chart.
 *
 * @param dataset  the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart3D(
        "Pie Chart Demo 1",  // chart title
        dataset,             // data
        true,               // include legend
        true,
        false
    );

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setSectionOutlinesVisible(false);
    plot.setNoDataMessage("No data available");
    plot.setBackgroundAlpha(0.2f);
    return chart;

}

/**
 * Creates a panel for the demo (used by SuperDemo.java).
 *
 * @return A panel.
 */
public static JPanel createDemoPanel() {
    JFreeChart chart = createChart(createDataset());
    ChartPanel chartpanel = new ChartPanel(chart, false, false, false, false, false);
    chartpanel.setVisible(true);
    chartpanel.setPreferredSize(new Dimension(500, 270));
    return new JPanel();
}

/**
 * Starting point for the demonstration application.
 *
 * @param args  ignored.
 */
public static void main(String[] args) {

    PieChartDemo1 demo = new PieChartDemo1("Pie Chart Demo 1");
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
}

public void chartMouseClicked(ChartMouseEvent chartmouseevent)
{
ChartEntity chartentity = chartmouseevent.getEntity();
if (chartentity != null){
    this.plot.setStartAngle(angle);
    this.angle=angle+5;
    this.plot.setStartAngle(angle);
    this.plot.setExplodePercent("One", .8);
    System.out.println("Mouse clicked: " + chartentity.toString());
}
else
System.out.println("Mouse clicked: null entity.");
}

public void chartMouseMoved(ChartMouseEvent chartmouseevent)
{
int i = chartmouseevent.getTrigger().getX();
int j = chartmouseevent.getTrigger().getY();
ChartEntity chartentity = chartmouseevent.getEntity();
if (chartentity != null)
{
    //this.plot.setStartAngle(angle);
//this.angle=angle-5;
//this.plot.setStartAngle(angle);
    System.out.println("Explode Percent is "+plot.getExplodePercent("One"));
    Rotator rotator=new Rotator(plot);
    rotator.setInitialDelay(10000000);
    rotator.setDelay(100000000);

    rotator.start();
   //System.out.println("Mouse moved: " + i + ", " + j + ": " + chartentity.toString());
}
//else
//System.out.println("Mouse moved: " + i + ", " + j + ": null entity.");
}

static class Rotator extends Timer   {

    /** The plot. */
    private PiePlot plot;

    /** The angle. */

    private int X,Y;

    /**
     * Constructor.
     *
     * @param plot  the plot.
     */
    Rotator(final PiePlot plot) {
        super(100,null);
        this.plot = plot;

        while(count<999999999&&explodePercent>=0){
        if(explodePercent>0)
        explodePercent=explodePercent-.0001;
        else
        explodePercent=explodePercent+.0001;
        plot.setExplodePercent("One", explodePercent);
        count++;
        }

    }
}

}
The above code is used to create a chart and I have to develop something like amcharts link
I tried using Timer but the events are not getting delayed irrespective of the delay I use.Can anyone help me in getting the delay? This has nothing to with Jcharts though.This is purely event handling.

A: Your mouse event handler is never releasing the CPU.  The Rotator is not causing the thread to sleep so the whole delay happens as soon as the mouse event is handled.

A: you are doing the logic that your timer listener should be performing in the constructor of your Rotator.  this way you immediately perform the action without the delay.  you also dont  have anything that is listening for timer events.
instead, you should have your PieChartDemo implement ActionListener and have it do your timer processing:
 public void actionPerformed(ActionEvent actionevent) {
   //you can test if the event has come in from the timer
   if (actionevent.getSource() == myTimer) {
    while(count<999999999&&explodePercent>=0){
      if(explodePercent>0)
         explodePercent=explodePercent-.0001;
      else
         explodePercent=explodePercent+.0001;
      getPlot().setExplodePercent("One", explodePercent);
     count++;
    }
   }
 }

or something like that.
you will also need to pass in your ActionListener to the constructor:
old:
 Rotator(final PiePlot plot) {
    super(100,null);   // this passes a null listener to the timer object

new:
 Rotator(final PiePlot plot, ActionListener listener) {
    super(100, listener); // this will pass in the listener, which will then get timer updates, delayed as you have specified.

here is a good tutorial on swing timers