qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | This commit introduced the breaking change: <https://github.com/indutny/miller-rabin/commit/bb85f555974587a410a17173f0bc484133b53cb7>
The author of the library should fix it, but meanwhile you can:
1. Delete the existing `node_modules` folder
2. `npm install miller-rabin@1.1.1 --save-peer`
3. `npm install browserify` | Try zipping your existing node\_modules and package.json, then delete them.
You may need to 1st generate a new package.json using:
```
npm init
```
Then install browserify locally:
`npm install browserify`
Also, you'll have to install browserify globally:
```
npm install browserify -g
```
To zip on CMD or terminal refer to the following article:
[How to zip a file using cmd line?](https://stackoverflow.com/questions/18180060/how-to-zip-a-file-using-cmd-line) |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | This commit introduced the breaking change: <https://github.com/indutny/miller-rabin/commit/bb85f555974587a410a17173f0bc484133b53cb7>
The author of the library should fix it, but meanwhile you can:
1. Delete the existing `node_modules` folder
2. `npm install miller-rabin@1.1.1 --save-peer`
3. `npm install browserify` | There are details of a workaround list in the issues on the github page
[Error listing](https://github.com/substack/node-browserify/issues/1049)
To summarise the solution posted in the issue, you need to install miller-rabin@1.1.1 as a peer-dependency in your own project (npm install miller-rabin@1.1.1 --save-peer) that makes sure the bn.js@0.15 is used rather than the more recent version.
Hope that helps! |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | Had the same issue on Linux. Try running `npm update -g`
before installing browserify. This has worked for me. | Try zipping your existing node\_modules and package.json, then delete them.
You may need to 1st generate a new package.json using:
```
npm init
```
Then install browserify locally:
`npm install browserify`
Also, you'll have to install browserify globally:
```
npm install browserify -g
```
To zip on CMD or terminal refer to the following article:
[How to zip a file using cmd line?](https://stackoverflow.com/questions/18180060/how-to-zip-a-file-using-cmd-line) |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | Had the same issue on Linux. Try running `npm update -g`
before installing browserify. This has worked for me. | Recently found this issue on browserify's github.
<https://github.com/substack/node-browserify/issues/1049>
There is a workaround described. |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | Had the same issue on Linux. Try running `npm update -g`
before installing browserify. This has worked for me. | There are details of a workaround list in the issues on the github page
[Error listing](https://github.com/substack/node-browserify/issues/1049)
To summarise the solution posted in the issue, you need to install miller-rabin@1.1.1 as a peer-dependency in your own project (npm install miller-rabin@1.1.1 --save-peer) that makes sure the bn.js@0.15 is used rather than the more recent version.
Hope that helps! |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | In order to make the `workaround` work, you have to
1. Delete the existing `node_modules` folder.
2. `npm install miller-rabin@1.1.1 --save-peer`
3. `npm install browserify`
That works guaranteed. | Recently found this issue on browserify's github.
<https://github.com/substack/node-browserify/issues/1049>
There is a workaround described. |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | This commit introduced the breaking change: <https://github.com/indutny/miller-rabin/commit/bb85f555974587a410a17173f0bc484133b53cb7>
The author of the library should fix it, but meanwhile you can:
1. Delete the existing `node_modules` folder
2. `npm install miller-rabin@1.1.1 --save-peer`
3. `npm install browserify` | Recently found this issue on browserify's github.
<https://github.com/substack/node-browserify/issues/1049>
There is a workaround described. |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | In order to make the `workaround` work, you have to
1. Delete the existing `node_modules` folder.
2. `npm install miller-rabin@1.1.1 --save-peer`
3. `npm install browserify`
That works guaranteed. | Try zipping your existing node\_modules and package.json, then delete them.
You may need to 1st generate a new package.json using:
```
npm init
```
Then install browserify locally:
`npm install browserify`
Also, you'll have to install browserify globally:
```
npm install browserify -g
```
To zip on CMD or terminal refer to the following article:
[How to zip a file using cmd line?](https://stackoverflow.com/questions/18180060/how-to-zip-a-file-using-cmd-line) |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | Recently found this issue on browserify's github.
<https://github.com/substack/node-browserify/issues/1049>
There is a workaround described. | There are details of a workaround list in the issues on the github page
[Error listing](https://github.com/substack/node-browserify/issues/1049)
To summarise the solution posted in the issue, you need to install miller-rabin@1.1.1 as a peer-dependency in your own project (npm install miller-rabin@1.1.1 --save-peer) that makes sure the bn.js@0.15 is used rather than the more recent version.
Hope that helps! |
27,743,113 | I create a project with the NavigationDrawerFragment, and I set the fragments for the menu. Switching between menus fragments are working. But now I create an imageview on one of the fragments. and I want that when you click on the imageview it changes fragment just like the menu.
MainActivity.java
```
package com.****.****;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new news_Fragment();
break;
case 1:
objFragment = new heroes_Fragment();
break;
case 2:
objFragment = new game_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
heroes\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class heroes_Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
public View trac(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.trac_layout, container, false);
}
}
```
heroes\_layout.xml
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/header_bg">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignWithParentIfMissing="false"
android:id="@+id/tableLayout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/icontrac"
android:src="@drawable/icon_portrait_trac"
android:layout_column="0"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:clickable="true"
android:onClick="trac"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconreap"
android:src="@drawable/icon_portrait_reap"
android:layout_column="1"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iconwid"
android:src="@drawable/icon_portrait_wid"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</TableRow>
</TableLayout>
</RelativeLayout>
```
trac\_Fragment.java
```
package com.****.****;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Calvin on 27/12/2014.
*/
public class trac_Fragment extends Fragment {
}
}
```
I want that when you click on the imageview (trac) it changes fragment. As if we change activity.
And sorry for my English.
I tried to use trac() methode but the apps crash | 2015/01/02 | [
"https://Stackoverflow.com/questions/27743113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4412515/"
] | Recently found this issue on browserify's github.
<https://github.com/substack/node-browserify/issues/1049>
There is a workaround described. | Try zipping your existing node\_modules and package.json, then delete them.
You may need to 1st generate a new package.json using:
```
npm init
```
Then install browserify locally:
`npm install browserify`
Also, you'll have to install browserify globally:
```
npm install browserify -g
```
To zip on CMD or terminal refer to the following article:
[How to zip a file using cmd line?](https://stackoverflow.com/questions/18180060/how-to-zip-a-file-using-cmd-line) |
25,648,704 | I am getting trouble trying to delete a pointer that is owned by a vector. In my application I have a QListView, and I store new items based on a vector of pointers. This is the declaration:
```
private:
vector<QStandardItem *> item;
QStandardItemModel* model = new QStandardItemModel();
```
I simplified it, but it is an attribute of a class. To add new items I use this code:
```
this->item.push_back(new QStandardItem());
for (unsigned long i = 0; i != this->item.size(); ++i) {
this->item[i]->setCheckable( true );
this->item[i]->setCheckState( Qt::Checked );
this->item[i]->setText( "Current " + QString::number(i) );
this->model->setItem( i, this->item[i] );
ui->listView->setModel( model );
}
```
This works just fine. Now I am trying to add a delete button which deletes the current index on the QListView. This is the code I made so far:
```
QModelIndex index = ui->listView->currentIndex();
int deleteIndex = index.row();
this->model->removeRow(deleteIndex);
delete this->item[deleteIndex];
this->item.erase(this->item.begin() + deleteIndex);
```
For what I searched on StackOverflow, the line
```
delete this->item[deleteIndex];
```
should work, but I am getting an application crash every time I press the delete button. Without that line the button works fine, the problem is that I am not deallocating the memory used by that item.
EDIT: I already made a question related to the same problem.
[[Error using Qt and unique pointers](https://stackoverflow.com/questions/25631923/error-using-qt-and-unique-pointers][1])
Now I am wondering if I am trying to delete the pointer two times, and thats why I am getting the error. The problem is that my knowledge about c++ and qt is not very high. | 2014/09/03 | [
"https://Stackoverflow.com/questions/25648704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3758543/"
] | You're actually deleting a second time the `QStandardItem` that was at this index. Indeed, as you can see in the following extract from the Qt doc of the [`QStandardItemModel`'s function `setItem`](http://qt-project.org/doc/qt-5/qstandarditemmodel.html#setItem)
>
> Sets the item for the given row and column to item. **The model takes ownership of the item**. If necessary, the row count and column count are increased to fit the item. **The previous item at the given location (if there was one) is deleted.**
>
>
>
the `QStandardItemModel` manages any `QStandardItem` you would pass it, and thus you should never try to delete these.
As a rule of thumb, when you're unsure, check the Qt documentation for any function where you pass a `QObject`. If it says it take ownership, then never delete it. | As far as I know, Qt is managing the lifetime of the objects through a parent-child relationship and automatically deletes children. This was at least the case Qt while I was using it. Considering that, I think there is no need for manual memory management here because the item will be deleted by Qt. |
20,285,562 | Why this perl code is giving output "True"?
```
$bar = "\\";
if ($bar =~ /[A-z]/){
print "True";
} else {
print "False";
}
```
Shouldn't it return false? | 2013/11/29 | [
"https://Stackoverflow.com/questions/20285562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503870/"
] | Because \ is between A-z. See table below, 92 is between 65 and 122. Try [A-Z].
```
0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel
8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si
16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb
24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us
32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 '
40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 /
48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7
56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ?
64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G
72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O
80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W
88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _
96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g
104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o
112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w
120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del
```
Use the following command to see ASCII chart:
```
man ascii
``` | ```
$bar =~ /[A-z]/;
```
is not same as
```
$bar =~ /[A-Z]/;
```
Check all chars between `A` and `z`:
```
perl -le 'print map chr, ord("A") .. ord("z")'
```
---
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
``` |
20,285,562 | Why this perl code is giving output "True"?
```
$bar = "\\";
if ($bar =~ /[A-z]/){
print "True";
} else {
print "False";
}
```
Shouldn't it return false? | 2013/11/29 | [
"https://Stackoverflow.com/questions/20285562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503870/"
] | ```
$bar =~ /[A-z]/;
```
is not same as
```
$bar =~ /[A-Z]/;
```
Check all chars between `A` and `z`:
```
perl -le 'print map chr, ord("A") .. ord("z")'
```
---
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
``` | Becauase you've written `[A-z]`:
See: <http://perldoc.perl.org/perlrecharclass.html>
```
[a-z] # Matches a character that is a lower case ASCII letter.
```
Try `[A-Z]` for uppercase, or `[a-zA-Z]` for both upper and lower case |
20,285,562 | Why this perl code is giving output "True"?
```
$bar = "\\";
if ($bar =~ /[A-z]/){
print "True";
} else {
print "False";
}
```
Shouldn't it return false? | 2013/11/29 | [
"https://Stackoverflow.com/questions/20285562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503870/"
] | Because \ is between A-z. See table below, 92 is between 65 and 122. Try [A-Z].
```
0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel
8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si
16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb
24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us
32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 '
40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 /
48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7
56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ?
64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G
72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O
80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W
88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _
96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g
104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o
112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w
120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del
```
Use the following command to see ASCII chart:
```
man ascii
``` | Becauase you've written `[A-z]`:
See: <http://perldoc.perl.org/perlrecharclass.html>
```
[a-z] # Matches a character that is a lower case ASCII letter.
```
Try `[A-Z]` for uppercase, or `[a-zA-Z]` for both upper and lower case |
9,742,752 | I am trying to add a second pager to my slideshows in 1/3 > format so if there are 3 slides it shows how many slides and what slide your on and if you want to move forward you just click the arrow. It has to be simple but I can't find any examples out there. Here is what I have so far:
```
$(function() {
$('.slideshow').each(function() {
var $nav = $('<div class="nav"></div>').insertAfter(this);
var $nav2 = $('<div class="nav2"></div>').insertBefore(this);
$('<div class="caption"> </div>').insertAfter($nav);
$(this).cycle({
fx: 'fade',
speed: 300,
timeout: 0,
pager: $nav,
after: onAfter
});
});
function onAfter(curr, next, opts) {
var src = ' ';
if (next.src)
src = next.src.match(/([a-zA-Z0-9\.]+$)/)[1];
$(curr).parent().nextAll('div.caption:first').html(src);
}
```
Any ideas?
**UPDATE:**
Thanks, Jeff Lamb...I tried that and its almost there. Because I have 2 slideshows on one page the navs are superimposing on one another so if I go forward on one both of the captions change. I tried just changing class names but it still superimposes. What am I missing here? Here is my updated code:
```
$(function() {
$('.slideshow').each(function() {
var $nav = $('<div class="nav"></div>').insertAfter(this);
var $nav2 = $('<div class="nav2"></div>').insertBefore(this);
$('<div class="caption"> </div>').insertBefore($nav);
$('<div class="caption2"> </div>').insertAfter($nav2);
$('.next').click(function() {
$('.slideshow').cycle('next');
});
$('.next2').click(function() {
$('.two').cycle('next');
});
$(this).cycle({
fx: 'fade',
speed: 300,
timeout: 0,
pager: $nav,
after: onAfter
});
});
function onAfter() {
$('.caption').html('<h3>' + (parseInt($(this).index())+1) + ' / ' + $(".slideshow div").length + '</h3>');
}
function onAfter() {
$('.caption2').html('<h3>' + (parseInt($(this).index())+1) + ' / ' + $(".two div").length + '</h3>');
}
```
I do want the option of adding a 3rd slideshow if needed. Here is my HTML:
```
<div class="slideshow-container">
<h2>CASE STUDIES</h2>
<input type="button" class="next" value=">" />
<div class="slideshow">
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Jorge<br/>
<strong>Pensi</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Designer<br/>
<strong>Two</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
</div>
</div>
<div class="slideshow-container">
<h2>OUR DESIGNERS</h2>
<input type="button" class="next2" value=">" />
<div class="slideshow two">
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Jorge<br/>
<strong>Pensi</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Designer<br/>
<strong>Two</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9742752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130990/"
] | If you click the dropdown on your MainPage.xaml.cs you will see methods that are greyed out, these are the methods that you are looking for. If you have another partial class based on your MainPage they will be visible there also.
 | Should be in YourProject\obj\x86\Debug\MainWindow.g.cs |
9,742,752 | I am trying to add a second pager to my slideshows in 1/3 > format so if there are 3 slides it shows how many slides and what slide your on and if you want to move forward you just click the arrow. It has to be simple but I can't find any examples out there. Here is what I have so far:
```
$(function() {
$('.slideshow').each(function() {
var $nav = $('<div class="nav"></div>').insertAfter(this);
var $nav2 = $('<div class="nav2"></div>').insertBefore(this);
$('<div class="caption"> </div>').insertAfter($nav);
$(this).cycle({
fx: 'fade',
speed: 300,
timeout: 0,
pager: $nav,
after: onAfter
});
});
function onAfter(curr, next, opts) {
var src = ' ';
if (next.src)
src = next.src.match(/([a-zA-Z0-9\.]+$)/)[1];
$(curr).parent().nextAll('div.caption:first').html(src);
}
```
Any ideas?
**UPDATE:**
Thanks, Jeff Lamb...I tried that and its almost there. Because I have 2 slideshows on one page the navs are superimposing on one another so if I go forward on one both of the captions change. I tried just changing class names but it still superimposes. What am I missing here? Here is my updated code:
```
$(function() {
$('.slideshow').each(function() {
var $nav = $('<div class="nav"></div>').insertAfter(this);
var $nav2 = $('<div class="nav2"></div>').insertBefore(this);
$('<div class="caption"> </div>').insertBefore($nav);
$('<div class="caption2"> </div>').insertAfter($nav2);
$('.next').click(function() {
$('.slideshow').cycle('next');
});
$('.next2').click(function() {
$('.two').cycle('next');
});
$(this).cycle({
fx: 'fade',
speed: 300,
timeout: 0,
pager: $nav,
after: onAfter
});
});
function onAfter() {
$('.caption').html('<h3>' + (parseInt($(this).index())+1) + ' / ' + $(".slideshow div").length + '</h3>');
}
function onAfter() {
$('.caption2').html('<h3>' + (parseInt($(this).index())+1) + ' / ' + $(".two div").length + '</h3>');
}
```
I do want the option of adding a 3rd slideshow if needed. Here is my HTML:
```
<div class="slideshow-container">
<h2>CASE STUDIES</h2>
<input type="button" class="next" value=">" />
<div class="slideshow">
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Jorge<br/>
<strong>Pensi</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Designer<br/>
<strong>Two</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
</div>
</div>
<div class="slideshow-container">
<h2>OUR DESIGNERS</h2>
<input type="button" class="next2" value=">" />
<div class="slideshow two">
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Jorge<br/>
<strong>Pensi</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Designer<br/>
<strong>Two</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9742752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130990/"
] | If you click the dropdown on your MainPage.xaml.cs you will see methods that are greyed out, these are the methods that you are looking for. If you have another partial class based on your MainPage they will be visible there also.
 | When Ctrl Key Pressed Click on Class name (MainPage for this instance) and you will see list of other partials. Not for just Silverlight projects.
Its a good way extending a class I think. When you manage well.
 |
9,742,752 | I am trying to add a second pager to my slideshows in 1/3 > format so if there are 3 slides it shows how many slides and what slide your on and if you want to move forward you just click the arrow. It has to be simple but I can't find any examples out there. Here is what I have so far:
```
$(function() {
$('.slideshow').each(function() {
var $nav = $('<div class="nav"></div>').insertAfter(this);
var $nav2 = $('<div class="nav2"></div>').insertBefore(this);
$('<div class="caption"> </div>').insertAfter($nav);
$(this).cycle({
fx: 'fade',
speed: 300,
timeout: 0,
pager: $nav,
after: onAfter
});
});
function onAfter(curr, next, opts) {
var src = ' ';
if (next.src)
src = next.src.match(/([a-zA-Z0-9\.]+$)/)[1];
$(curr).parent().nextAll('div.caption:first').html(src);
}
```
Any ideas?
**UPDATE:**
Thanks, Jeff Lamb...I tried that and its almost there. Because I have 2 slideshows on one page the navs are superimposing on one another so if I go forward on one both of the captions change. I tried just changing class names but it still superimposes. What am I missing here? Here is my updated code:
```
$(function() {
$('.slideshow').each(function() {
var $nav = $('<div class="nav"></div>').insertAfter(this);
var $nav2 = $('<div class="nav2"></div>').insertBefore(this);
$('<div class="caption"> </div>').insertBefore($nav);
$('<div class="caption2"> </div>').insertAfter($nav2);
$('.next').click(function() {
$('.slideshow').cycle('next');
});
$('.next2').click(function() {
$('.two').cycle('next');
});
$(this).cycle({
fx: 'fade',
speed: 300,
timeout: 0,
pager: $nav,
after: onAfter
});
});
function onAfter() {
$('.caption').html('<h3>' + (parseInt($(this).index())+1) + ' / ' + $(".slideshow div").length + '</h3>');
}
function onAfter() {
$('.caption2').html('<h3>' + (parseInt($(this).index())+1) + ' / ' + $(".two div").length + '</h3>');
}
```
I do want the option of adding a 3rd slideshow if needed. Here is my HTML:
```
<div class="slideshow-container">
<h2>CASE STUDIES</h2>
<input type="button" class="next" value=">" />
<div class="slideshow">
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Jorge<br/>
<strong>Pensi</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Designer<br/>
<strong>Two</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
</div>
</div>
<div class="slideshow-container">
<h2>OUR DESIGNERS</h2>
<input type="button" class="next2" value=">" />
<div class="slideshow two">
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Jorge<br/>
<strong>Pensi</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
<div> <img src="images/jorge-pensi.png" width="278" height="270" />
<h1>Designer<br/>
<strong>Two</strong></h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</div>
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9742752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130990/"
] | When Ctrl Key Pressed Click on Class name (MainPage for this instance) and you will see list of other partials. Not for just Silverlight projects.
Its a good way extending a class I think. When you manage well.
 | Should be in YourProject\obj\x86\Debug\MainWindow.g.cs |
1,004,191 | With twitter being down today I was thinking about how to best handle calls to an API when it is down. If I am using CURL to call their api how do I cause the script to fail quickly and handle the errors so as not to slow down the application? | 2009/06/16 | [
"https://Stackoverflow.com/questions/1004191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105008/"
] | I wrote a [blog post](http://www.joshclarkson.net/blog/file-uploads-in-a-hidden-iframe-using-jquery/) about doing this with jQuery to upload a file using a hidden iframe. Here's the code:
Here is the HTML for the form:
```
<div id="uploadform">
<form id="theuploadform">
<input type="hidden" id="max" name="MAX_FILE_SIZE" value="5000000" >
<input id="userfile" name="userfile" size="50" type="file">
<input id="formsubmit" type="submit" value="Send File" >
</form>
```
The DIV in which to allow jQuery to create the iframe you can hide it with a little CSS:
```
<div id="iframe" style="width:0px height:0px visibility:none">
</div>
```
The DIV in which to show the results of the callback:
```
<div id="textarea">
</div>
```
The jQuery code:
```
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#formsubmit").click(function() {
var userFile = $('form#userfile').val();
var max = $('form#max').val();
var iframe = $( '<iframe name="postframe" id="postframe" class="hidden" src="about:none" />' );
$('div#iframe').append( iframe );
$('#theuploadform').attr( "action", "uploader.php" )
$('#theuploadform').attr( "method", "post" )
$('#theuploadform').attr( "userfile", userFile )
$('#theuploadform').attr( "MAX_FILE_SIZE", max )
$('#theuploadform').attr( "enctype", "multipart/form-data" )
$('#theuploadform').attr( "encoding", "multipart/form-data" )
$('#theuploadform').attr( "target", "postframe" )
$('#theuploadform').submit();
//need to get contents of the iframe
$("#postframe").load(
function(){
iframeContents = $("iframe")[0].contentDocument.body.innerHTML;
$("div#textarea").html(iframeContents);
}
);
return false;
});
});
</script>
```
I used a php app like this uploader.php to do something with the file:
```
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$maxfilesize = $_POST[MAX_FILE_SIZE];
if ($maxfilesize > 5000000) {
//Halt!
echo "Upload error: File may be to large.<br/>";
exit();
}else{
// Let it go
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
print('File is valid, and was successfully uploaded. ');
} else {
echo "Upload error: File may be to large.<br/>";
}
chmod($uploadfile, 0744);
?>
```
There's more there than you need, but it illustrates the concept in jQuery. | I don't have the code handy but my team accomplished this purely in Javascript. As I recall it went something like this:
```
function postToPage() {
var iframe = document.getElementById('myIFrame');
if (iframe) {
var newForm = '<html><head></head><body><form...> <input type="hidden" name="..." value="..." /> </form><script type=\"text/javascript\">document.forms[0].submit();</scrip' + 't></body></html>';
iframe.document.write(newForm); //maybe wrong, find the iframe's document and write to it
}
}
``` |
215,849 | I am trying to export regions of interest in google map as geotiff. I know google earth has option to save image as jpeg.
Are there any tools to obtain a part of image from google maps with its world file or as geotiff?
Is there any way to do that with python? | 2016/10/28 | [
"https://gis.stackexchange.com/questions/215849",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/48497/"
] | [Google don't like copying or saving](https://developers.google.com/maps/terms) of their map/earth products. So I doubt it is possible within their API.
However it is possible to get a georeferenced gtiff of google maps imagery for a limited area through Qgis:
1. Use google street within the Openlayers plugin
2. Zoom to the area you want
3. Go to project -> Save as image and choose tif
4. Open the image, provide the correct projection info (EPSG: 3857)
5. Right click the image in the layers panel -> save as Gtiff
This is limited to the area within the map canvas, but if imagery for a larger area is needed, it can be repeated several times and the images tiled. But depending on your intended use this may be contravening the google terms of service. | [Downloading images from Google Maps is against the Terms of Service.](https://gis.stackexchange.com/questions/69962/download-google-map-tiles-images)
You can, however, embed maps using Google Maps APIs. See: [Google Static Maps Developer Guide](https://developers.google.com/maps/documentation/static-maps/intro) |
638,225 | I have formatted a flash drive and thus needed to unmount the device.
Is there a way to trigger automount via command line after formatting was finished ?
(I know I can just reinsert a USB flash drive, but that seems like a cheap shot ;)
And manually mounting seems a bit cumbersome as one needs to mkdir the mount directory manually.) | 2013/08/29 | [
"https://superuser.com/questions/638225",
"https://superuser.com",
"https://superuser.com/users/247896/"
] | ```
/usr/bin/udisks --mount /dev/sdc1
```
worked for me. This seems to be what is invoked by gnome according to <https://help.ubuntu.com/community/AutomaticallyMountPartitions>. | I think you need to run
```
sudo partprobe
```
to re-scan all devices for partitions and filesystems. On my Xubuntu 12.04 (debian-based), this also triggers automount. |
638,225 | I have formatted a flash drive and thus needed to unmount the device.
Is there a way to trigger automount via command line after formatting was finished ?
(I know I can just reinsert a USB flash drive, but that seems like a cheap shot ;)
And manually mounting seems a bit cumbersome as one needs to mkdir the mount directory manually.) | 2013/08/29 | [
"https://superuser.com/questions/638225",
"https://superuser.com",
"https://superuser.com/users/247896/"
] | ```
/usr/bin/udisks --mount /dev/sdc1
```
worked for me. This seems to be what is invoked by gnome according to <https://help.ubuntu.com/community/AutomaticallyMountPartitions>. | Here my solution on Ubuntu 18.04:
```
udisksctl mount -b {device}
``` |
27,416,200 | I am posting because I have encountered a problem with one script that I am trying to develop .
What I am trying to create is a gallery that receives it's images from Instagram. In order to accomplish this two tasks I've found two plugins that fits my needs , but I am unable to fusion them both.
I'm relatively new to Jquery , and I do not understand why the script that I'm trying to run only affects one part of the code.
This example gallery has two fundamental parts :
1)Pre-loaded by the developer :
```
<div class="content-primary">
<ul class="iGallery" id="iGallery">
<li>
<a href="http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/10817900_1528499780732950_533530016_n.jpg">
<img src="http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/10817900_1528499780732950_533530016_s.jpg">
<li><a class="ui-link" href="http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/10831784_752863841449953_2058216615_n.jpg"><img src="http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/10831784_752863841449953_2058216615_s.jpg"></a></li></ul>
</a>
</li>
</ul>
```
And , the ones that are added dynamically thanks to the instagram api :
```
<script type="text/javascript">
(function() {
var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];
s.type = 'text/javascript';
s.async = true;
s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto';
t.parentNode.insertBefore(s, t);
})();
/* ]]> */
function createPhotoElement(photo) {
var innerHtml;
innerHtml= $('<img>')
.attr('src', photo.images.thumbnail.url);
innerHtml = $('<a>')
.attr('href', photo.images.standard_resolution.url)
.append(innerHtml)
.append(innerHtml)
.addClass( "ui-link" );
return $('<li>')
.append(innerHtml);
}
function didLoadInstagram(event, response) {
var that = this;
$.each(response.data, function(i, photo) {
$(that).append(createPhotoElement(photo));
});
}
$(document).ready(function() {
var clientId = 'baee48560b984845974f6b85a07bf7d9';
$('.iGallery').on('didLoadInstagram', didLoadInstagram);
$('.iGallery').instagram({
hash: 'usa123',
count: 1,
clientId: clientId
});
});
</script>
```
Well , the main problem is that the part that handles the gallery seems to read only the part added manually , but not the ones that comes thanks to the instagram api .
I'm pretty sure that my problem is related to the time that the script is loaded , since the script changes some atributes of the images like `href to data-href` , but I've tried to pre-load that information , and I received the same results.
In order to give a visual idea of my problem , I have the script in codepen :
<http://codepen.io/anon/pen/XJdbZR>

And , this is the idea I have that tells me that only the per-loaded information is being modified by the script

I appreciate any kind of help or hint. Thanks | 2014/12/11 | [
"https://Stackoverflow.com/questions/27416200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4072618/"
] | There are many different [CoNLL](http://ifarm.nl/signll/conll/) formats since CoNLL is a different shared task each year. The format for CoNLL 2009 is described [here](http://ufal.mff.cuni.cz/conll2009-st/task-description.html). Each line represents a single word with a series of tab-separated fields. `_`s indicate empty values. [Mate-Parser's manual](https://mate-tools.googlecode.com/files/shortmanual.pdf) says that it uses the first 12 columns of CoNLL 2009:
```
ID FORM LEMMA PLEMMA POS PPOS FEAT PFEAT HEAD PHEAD DEPREL PDEPREL
```
The definition of some of these columns come from earlier shared tasks (the [CoNLL-X format](https://web.archive.org/web/20160814191537/http://ilk.uvt.nl/conll/#dataformat) used in 2006 and 2007):
* `ID` (index in sentence, starting at 1)
* `FORM` (word form itself)
* `LEMMA` (word's lemma or stem)
* `POS` (part of speech)
* `FEAT` (list of morphological features separated by |)
* `HEAD` (index of syntactic parent, 0 for `ROOT`)
* `DEPREL` (syntactic relationship between `HEAD` and this word)
There are variants of those columns (e.g., `PPOS` but not `POS`) that start with `P` indicate that the value was automatically predicted rather a gold standard value.
**Update:** There is now a [CoNLL-U](http://universaldependencies.github.io/docs/format.html) data format as well which extends the CoNLL-X format. | As update to @dmcc's answer:
* CoNLL is the conventional name for TSV formats in NLP (TSV - tab-separated values, i.e., CSV with `<TAB>` as separator)
* It originates from a series of shared tasks organized at the Conferences of Natural Language Learning (hence the name)
* Not all of these tasks use "CoNLL" formats, some tasks had JSON or XML formats
* There are "CoNLL" formats that developed independently from CoNLL, most notably CoNLL-U
* CoNLL formats differ in the choice and order of columns
In CoNLL formats,
* every word (token) is represented in one line.
* every sentence is separated from the next by an empty line
* every column represents one annotation
* every word in a sentence has the same number of columns (in some formats: every word in the corpus has the same number of columns)
* an annotation is a string value about a particular word
* annotations that span over multiple words sometimes use special notations, e.g., round brackets (indicating begin and end of a phrase) or the IOBES-annotation (e.g., B-NP: begin of NP, I-NP: in the middle of NP, E-NP: end of NP, S-NP: NP begins and ends at the current word, O: no NP annotation)
* some CoNLL formats have one or multiple columns of numerical identifiers as the first column, the next column after these (or the first if there are no IDs) usually contains the WORD
* the ID of the first word in the sentence is 1. If no ID column is provided, the ID is the number of preceding words within the sentence plus 1.
* in dependency syntax, grammatical relations hold between words, the dependent is marked for the HEAD (= ID of the parent word) and the EDGE/DEP[endency] (= grammatical relation), both in separate columns
* if a word in dependency syntax does not have a parent (i.e., it is the syntactic root), set its HEAD to 0
Be careful when working with tools or libraries that claim to support (some) "CoNLL format". Different CoNLL formats have different order of columns and the developer might not be aware of that. So, it is likely that they don't work as expected if they get data from another (or unspecified) CoNLL format.
For converting between different CoNLL formats, you can consider using CoNLL-RDF (<https://github.com/acoli-repo/conll-rdf>), resp., CoNLL-Transform (<https://github.com/acoli-repo/conll-transform>) (Disclaimer: Developed by my lab.) |
1,294,568 | I have a data set that looks like the table shown on the left. The data has 3 columns, ranked by values in column 3; column 1 is the index of the row in the ranking; column 2 is the 'category' assigned to that row.
I am not sure if this is a 'single series' or 'two data series' problem... but I would like to draw a chart where, each value in column 3 is shown as a point on the chart referenced to the left Y-axis, but the shape of that point should be determined based on the label next to that value, in column 2.
Can I do this using scatter point chart/point-only-line chart? I tried to do this but it plots all points on the chart with the same shape, I am not sure how to use column 2 to change the shape of the points..
I would be grateful for any advice!
Many thanks in advance
[](https://i.stack.imgur.com/uPxI9.png)
***UPDATE***
I followed bandersnatch's 2nd suggestion and have got quite close to it but I still have some problems.
Testing on the dummy data it works perfectly. but when working on the real data, it appears that those empty cells are considered as a '0' value and as you can see on this screenshot below, these are plotted as well and making an incorrect chart:
[](https://i.stack.imgur.com/QugQl.png)
I am not sure how to fix this? I already made sure that empty cells are shown as 'gap', see screenshot below. I have shared my data file for anybody interested to play with, at:
<https://drive.google.com/file/d/1L32urXmkYoA0WZDSXTuBS_UMM3a__bMn/view?usp=sharing>
[](https://i.stack.imgur.com/G6LqI.png)
Thanks again | 2018/02/13 | [
"https://superuser.com/questions/1294568",
"https://superuser.com",
"https://superuser.com/users/872269/"
] | You *could* edit and change the marker style for just those two points. But that causes some difficulties with the labels in the legend.
A better solution is to arrange your data table as shown below. That causes Excel to plot the data as two separate series, and then you can format the two series separately as you wish.
[](https://i.stack.imgur.com/74jVo.png)
EDIT: If the data is generated by formulas, and you want to skip plotting a point, for example where the blank cells are in the table above, have the formula return NA(). The formula might look like this:
=IF([some condition],[some value],NA())
This puts #N/A into the cell, and the chart ignores the point. See my recent tutorial [Plot Blank Cells and #N/A in Excel Charts](https://peltiertech.com/plot-blank-cells-na-in-excel-charts/) for more details. | I was able to do this as a single series scatter plot, 1st column vs. 3rd column, where I set the markers of the series to 'None'.
To get the correct markers I used data labels where the label contained the value from the second column. I placed the labels on the 'Center' position. For the second column I replaced the A and B by appropriate shapes from the Wingdings font.
Note: also in the graph then you need to set the font of the labels to Wingdings.
Note 2: If you want to keep the A's and B's also, you could make a 4th column where you create the label based on the A/B column with a simple IF statement (=IF(B1="A","l","n") -- "l" and "n" in wingdings font are circles and squares)
A two-series will also work without the trick with the labels but then you need to rearrange your data such that you have uninterrupted sections of A's and B's. |
1,294,568 | I have a data set that looks like the table shown on the left. The data has 3 columns, ranked by values in column 3; column 1 is the index of the row in the ranking; column 2 is the 'category' assigned to that row.
I am not sure if this is a 'single series' or 'two data series' problem... but I would like to draw a chart where, each value in column 3 is shown as a point on the chart referenced to the left Y-axis, but the shape of that point should be determined based on the label next to that value, in column 2.
Can I do this using scatter point chart/point-only-line chart? I tried to do this but it plots all points on the chart with the same shape, I am not sure how to use column 2 to change the shape of the points..
I would be grateful for any advice!
Many thanks in advance
[](https://i.stack.imgur.com/uPxI9.png)
***UPDATE***
I followed bandersnatch's 2nd suggestion and have got quite close to it but I still have some problems.
Testing on the dummy data it works perfectly. but when working on the real data, it appears that those empty cells are considered as a '0' value and as you can see on this screenshot below, these are plotted as well and making an incorrect chart:
[](https://i.stack.imgur.com/QugQl.png)
I am not sure how to fix this? I already made sure that empty cells are shown as 'gap', see screenshot below. I have shared my data file for anybody interested to play with, at:
<https://drive.google.com/file/d/1L32urXmkYoA0WZDSXTuBS_UMM3a__bMn/view?usp=sharing>
[](https://i.stack.imgur.com/G6LqI.png)
Thanks again | 2018/02/13 | [
"https://superuser.com/questions/1294568",
"https://superuser.com",
"https://superuser.com/users/872269/"
] | A better solution would be to:
1. Create an Excel Data Table from your existing data.
2. Create a Pivot Table from your Data Table (which will update as you add rows to your Data Table).
3. Create your chart from the Pivot Table (which will also update as you add rows to your Data Table). | I was able to do this as a single series scatter plot, 1st column vs. 3rd column, where I set the markers of the series to 'None'.
To get the correct markers I used data labels where the label contained the value from the second column. I placed the labels on the 'Center' position. For the second column I replaced the A and B by appropriate shapes from the Wingdings font.
Note: also in the graph then you need to set the font of the labels to Wingdings.
Note 2: If you want to keep the A's and B's also, you could make a 4th column where you create the label based on the A/B column with a simple IF statement (=IF(B1="A","l","n") -- "l" and "n" in wingdings font are circles and squares)
A two-series will also work without the trick with the labels but then you need to rearrange your data such that you have uninterrupted sections of A's and B's. |
1,294,568 | I have a data set that looks like the table shown on the left. The data has 3 columns, ranked by values in column 3; column 1 is the index of the row in the ranking; column 2 is the 'category' assigned to that row.
I am not sure if this is a 'single series' or 'two data series' problem... but I would like to draw a chart where, each value in column 3 is shown as a point on the chart referenced to the left Y-axis, but the shape of that point should be determined based on the label next to that value, in column 2.
Can I do this using scatter point chart/point-only-line chart? I tried to do this but it plots all points on the chart with the same shape, I am not sure how to use column 2 to change the shape of the points..
I would be grateful for any advice!
Many thanks in advance
[](https://i.stack.imgur.com/uPxI9.png)
***UPDATE***
I followed bandersnatch's 2nd suggestion and have got quite close to it but I still have some problems.
Testing on the dummy data it works perfectly. but when working on the real data, it appears that those empty cells are considered as a '0' value and as you can see on this screenshot below, these are plotted as well and making an incorrect chart:
[](https://i.stack.imgur.com/QugQl.png)
I am not sure how to fix this? I already made sure that empty cells are shown as 'gap', see screenshot below. I have shared my data file for anybody interested to play with, at:
<https://drive.google.com/file/d/1L32urXmkYoA0WZDSXTuBS_UMM3a__bMn/view?usp=sharing>
[](https://i.stack.imgur.com/G6LqI.png)
Thanks again | 2018/02/13 | [
"https://superuser.com/questions/1294568",
"https://superuser.com",
"https://superuser.com/users/872269/"
] | You *could* edit and change the marker style for just those two points. But that causes some difficulties with the labels in the legend.
A better solution is to arrange your data table as shown below. That causes Excel to plot the data as two separate series, and then you can format the two series separately as you wish.
[](https://i.stack.imgur.com/74jVo.png)
EDIT: If the data is generated by formulas, and you want to skip plotting a point, for example where the blank cells are in the table above, have the formula return NA(). The formula might look like this:
=IF([some condition],[some value],NA())
This puts #N/A into the cell, and the chart ignores the point. See my recent tutorial [Plot Blank Cells and #N/A in Excel Charts](https://peltiertech.com/plot-blank-cells-na-in-excel-charts/) for more details. | A better solution would be to:
1. Create an Excel Data Table from your existing data.
2. Create a Pivot Table from your Data Table (which will update as you add rows to your Data Table).
3. Create your chart from the Pivot Table (which will also update as you add rows to your Data Table). |
58,244,999 | I have been trying to specific access a nested property of req.body the output however is always undefined
the code is as follows
```
let dataRecieved = JSON.stringify(req.body);
console.log(dataRecieved);
let refCode = dataRecieved["refferal"];
```
and the output in the terminal is
```
{"name":"","phone":"","emailid":"","refferal":"gg","time":"Sat Oct 05 2019 08:14:07 GMT+0530 (India Standard Time)"}
undefined
```
the second undefined is when i ask for the refferal object of req.body | 2019/10/05 | [
"https://Stackoverflow.com/questions/58244999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12167200/"
] | ***When you push the value to same array during loop***, you end up in ***infinite loop***, create a temp array push value to it, in the end add it to `this`
```js
const a = [1, 2, 3, 4, 5];
//this is the what I tried
Array.prototype.multiply = function() {
let newArr = []
for (const m of this) {
newArr.push(m * m)
}
this.push(...newArr)
}
a.multiply();
console.log(a);
```
That being said you should not override the `prototype` simply use a function and pass the parameters
```js
const a = [1, 2, 3, 4, 5];
function multiply(arr) {
return [...arr, ...arr.map(a => a * a)]
}
console.log(multiply(a));
``` | Pushing a new value into an array in the middle of a `for ... of` loop creates an infinite loop as the loop includes the new values. You can use `forEach` instead as that ignores the new values added:
```js
const a = [1, 2, 3, 4, 5];
Array.prototype.multiply = function() {
this.forEach(v => this.push(v*v));
}
a.multiply(); //this should not be changed
console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25] (expected output)
``` |
8,831,824 | This is the query generated by Mongomapper:
```
MONGODB mydatabase['users'].find({:name=>"bob"}).limit(-1)
```
But this is not valid in the mongo console since the correct syntax is
```
db.users.find({:name=>"bob"}).limit(-1)
```
If I just use the generated one, I got this error in the console
```
Thu Jan 12 03:01:23 ReferenceError: mydatabase is not defined (shell):1
```
Is there any way to make it correct? This causes my rails application broken. | 2012/01/12 | [
"https://Stackoverflow.com/questions/8831824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304319/"
] | You can't use symbols in the MongoDB console as they are ruby and not javascript :-) Try this:
```
db.users.find({name: "bob"}).limit(-1)
``` | It is not mongodb's issue. 406 is pretty much relating to the controller call.
I need to use:
```
render :json => @user
```
rather than
```
respond_to
``` |
14,112,340 | I am using the Opus iMacros add-on with Internet Explorer. The following Macro takes a variable from the first line of my excel CSV File and performs a search on a website. The search results from the website may be anywhere from 10 to 200 records, which are grouped 20 per page (1-10 pages). The macro then extracts each page to a text file for future reference.
```
SET !ERRORIGNORE YES
SET !EXTRACT_TEST_POPUP NO
TAB T=1
TAB CLOSEALLOTHERS
SET !DATASOURCE 7Digits.csv
SET !DATASOURCE_Columns 1
SET !DATASOURCE_LINE {{!LOOP}}
'Login
URL GOTO=https://SomeWebsite.com/login
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:form1 ATTR=NAME:USER_NAME CONTENT=ABC123
TAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:form1 ATTR=NAME:PASSWORD CONTENT=XXX
'set search criteria on multiple search page
TAG POS=1 TYPE=TEXTAREA FORM=NAME:form1 ATTR=NAME: NUMBER CONTENT={{!COL1}}
TAG POS=1 TYPE=INPUT:IMAGE FORM=NAME:form1 ATTR=ID:SEARCH
‘Extract results and SAVE
TAG POS=1 TYPE=A ATTR=TXT:1
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:2
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:3
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:4
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:5
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:6
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:7
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:8
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:9
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
TAG POS=1 TYPE=A ATTR=TXT:10
TAG POS=2 TYPE=TABLE ATTR=TXT:*location* EXTRACT=TXT
SAVEAS TYPE=txt FOLDER=* FILE=mytable_{{!NOW:yymmdd_hhnnss}}
'END
```
My challenge is to figure out a way to cancel the “`SAVEAS`” if there are less than 10 pages of search results. For instance, if the search only returns 60 results, the Macro only needs to perform the `SAVEAS` command 3 times (20 x 3). How can I move to the next `{{!LOOP}}` without saving the same text file 7 more times?
I have tried the “`!FAIL_ON_ALL_NAVIGATEERRORS`” command, but the macro stops entirely. I would like to move to the next record instead of stopping the macro. | 2013/01/01 | [
"https://Stackoverflow.com/questions/14112340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1093827/"
] | Use [`request.get_json()`](http://flask.pocoo.org/docs/latest/api/#flask.Request.get_json) and set `force` to `True`:
```
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(request.get_json(force=True))
```
From the documentation:
>
> By default this function will only load the json data if the mimetype is `application/json` but this can be overridden by the *force* parameter.
>
>
> Parameters:
>
>
> * **force** – if set to *True* the mimetype is ignored.
>
>
>
For older Flask versions, < 0.10, if you want to be forgiving and allow for JSON, always, you can do the decode yourself, explicitly:
```
from flask import json
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(json.loads(request.data))
``` | the `request` object already has a method `get_json` which can give you the json regardless of the content-type if you execute it with `force=True` so your code would be something like the following:
```
@menus.route('/', methods=["PUT", "POST"])
def new():
return jsonify(request.get_json(force=True))
```
in fact, the flask documentation says that `request.get_json` should be used instead of `request.json`: <http://flask.pocoo.org/docs/api/?highlight=json#flask.Request.json> |
74,657,605 | In Python I can do something like:
```py
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
```
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for `postfix`. It needs to be calculated. (which is why I can't just have a default value).
In C++ I reached for std::optional and tried:
```cpp
std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) {
if (!postfix.has_value()) { postfix.emplace("2") };
return name + postfix;
}
```
I'm now aware that this won't work because `std::optional<T&>` is not a thing in C++. I'm fine with that.
But now what mechanism should I use to achieve the following:
* Maintain the benefits of const T&: no copy and don't modify the original.
* Don't have to make some other `postfix_` so that I have the optional one and the final one.
* Don't have to overload.
* Have multiple of these optional parameters in one function signature. | 2022/12/02 | [
"https://Stackoverflow.com/questions/74657605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4391249/"
] | You do this with two functions:
```
std::string add_postfix(const std::string& name, const std::string& postfix) {
// whatever
}
std::string add_default_postfix(const std::string& name) {
return add_postfix(name, "2");
}
```
Or, if you're into overloading, you can write the second one as an overload by naming it `add_postfix`. | You simply can write:
```
std::string add_postfix(const std::string& name, const std::string& postfix = "default value")
{
return name + postfix;
}
``` |
74,657,605 | In Python I can do something like:
```py
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
```
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for `postfix`. It needs to be calculated. (which is why I can't just have a default value).
In C++ I reached for std::optional and tried:
```cpp
std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) {
if (!postfix.has_value()) { postfix.emplace("2") };
return name + postfix;
}
```
I'm now aware that this won't work because `std::optional<T&>` is not a thing in C++. I'm fine with that.
But now what mechanism should I use to achieve the following:
* Maintain the benefits of const T&: no copy and don't modify the original.
* Don't have to make some other `postfix_` so that I have the optional one and the final one.
* Don't have to overload.
* Have multiple of these optional parameters in one function signature. | 2022/12/02 | [
"https://Stackoverflow.com/questions/74657605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4391249/"
] | One possibility is to use a `std::string const*` (a non-constant pointer to a `const std::string`) as a function argument.
```cpp
std::string add_postfix(const std::string& name, std::string const* postfix = nullptr)
{
std::string derivedSuffix;
if(!postfix)
{
derivedSuffix = some_computation(name);
postfix = &derivedSuffix;
}
return name + *postfix;
}
```
Some care is required with the details here. `derivedSuffix` needs to be an object that lasts at least as long as the pointer `postfix` refers to it. Therefore it cannot be contained entirely within the `if(!postfix)` block, because if it did then using `*postfix` outside of it would be invalid. There's technically still a bit of overhead here where we create an empty `std::string` even when `postfix` isn't `nullptr`, but we never have to make a copy of a `std::string` with actual values in it. | You simply can write:
```
std::string add_postfix(const std::string& name, const std::string& postfix = "default value")
{
return name + postfix;
}
``` |
74,657,605 | In Python I can do something like:
```py
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
```
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for `postfix`. It needs to be calculated. (which is why I can't just have a default value).
In C++ I reached for std::optional and tried:
```cpp
std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) {
if (!postfix.has_value()) { postfix.emplace("2") };
return name + postfix;
}
```
I'm now aware that this won't work because `std::optional<T&>` is not a thing in C++. I'm fine with that.
But now what mechanism should I use to achieve the following:
* Maintain the benefits of const T&: no copy and don't modify the original.
* Don't have to make some other `postfix_` so that I have the optional one and the final one.
* Don't have to overload.
* Have multiple of these optional parameters in one function signature. | 2022/12/02 | [
"https://Stackoverflow.com/questions/74657605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4391249/"
] | You do this with two functions:
```
std::string add_postfix(const std::string& name, const std::string& postfix) {
// whatever
}
std::string add_default_postfix(const std::string& name) {
return add_postfix(name, "2");
}
```
Or, if you're into overloading, you can write the second one as an overload by naming it `add_postfix`. | With your usage, [`value_or`](https://en.cppreference.com/w/cpp/utility/optional/value_or) seems to do the job:
```
std::string add_postfix(const std::string& name,
const std::optional<std::string>& postfix)
{
return name + postfix.value_or("2");
}
```
If you really want `optional<T&>`, `optional<reference_wrapper<T>>` might do the job.
```
std::string add_postfix(const std::string& name,
const std::optional<std::reference_wrapper<const std::string>>& postfix)
{
#if 1
const std::string postfix_ = "2";
return name + postfix.value_or(postfix_).get();
#else // or
return name + (postfix.has_value() ? postfix->get() : "2");
#endif
}
```
[Demo](https://godbolt.org/z/rbxooGfrY) |
74,657,605 | In Python I can do something like:
```py
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
```
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for `postfix`. It needs to be calculated. (which is why I can't just have a default value).
In C++ I reached for std::optional and tried:
```cpp
std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) {
if (!postfix.has_value()) { postfix.emplace("2") };
return name + postfix;
}
```
I'm now aware that this won't work because `std::optional<T&>` is not a thing in C++. I'm fine with that.
But now what mechanism should I use to achieve the following:
* Maintain the benefits of const T&: no copy and don't modify the original.
* Don't have to make some other `postfix_` so that I have the optional one and the final one.
* Don't have to overload.
* Have multiple of these optional parameters in one function signature. | 2022/12/02 | [
"https://Stackoverflow.com/questions/74657605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4391249/"
] | One possibility is to use a `std::string const*` (a non-constant pointer to a `const std::string`) as a function argument.
```cpp
std::string add_postfix(const std::string& name, std::string const* postfix = nullptr)
{
std::string derivedSuffix;
if(!postfix)
{
derivedSuffix = some_computation(name);
postfix = &derivedSuffix;
}
return name + *postfix;
}
```
Some care is required with the details here. `derivedSuffix` needs to be an object that lasts at least as long as the pointer `postfix` refers to it. Therefore it cannot be contained entirely within the `if(!postfix)` block, because if it did then using `*postfix` outside of it would be invalid. There's technically still a bit of overhead here where we create an empty `std::string` even when `postfix` isn't `nullptr`, but we never have to make a copy of a `std::string` with actual values in it. | You do this with two functions:
```
std::string add_postfix(const std::string& name, const std::string& postfix) {
// whatever
}
std::string add_default_postfix(const std::string& name) {
return add_postfix(name, "2");
}
```
Or, if you're into overloading, you can write the second one as an overload by naming it `add_postfix`. |
74,657,605 | In Python I can do something like:
```py
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
```
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for `postfix`. It needs to be calculated. (which is why I can't just have a default value).
In C++ I reached for std::optional and tried:
```cpp
std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) {
if (!postfix.has_value()) { postfix.emplace("2") };
return name + postfix;
}
```
I'm now aware that this won't work because `std::optional<T&>` is not a thing in C++. I'm fine with that.
But now what mechanism should I use to achieve the following:
* Maintain the benefits of const T&: no copy and don't modify the original.
* Don't have to make some other `postfix_` so that I have the optional one and the final one.
* Don't have to overload.
* Have multiple of these optional parameters in one function signature. | 2022/12/02 | [
"https://Stackoverflow.com/questions/74657605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4391249/"
] | One possibility is to use a `std::string const*` (a non-constant pointer to a `const std::string`) as a function argument.
```cpp
std::string add_postfix(const std::string& name, std::string const* postfix = nullptr)
{
std::string derivedSuffix;
if(!postfix)
{
derivedSuffix = some_computation(name);
postfix = &derivedSuffix;
}
return name + *postfix;
}
```
Some care is required with the details here. `derivedSuffix` needs to be an object that lasts at least as long as the pointer `postfix` refers to it. Therefore it cannot be contained entirely within the `if(!postfix)` block, because if it did then using `*postfix` outside of it would be invalid. There's technically still a bit of overhead here where we create an empty `std::string` even when `postfix` isn't `nullptr`, but we never have to make a copy of a `std::string` with actual values in it. | With your usage, [`value_or`](https://en.cppreference.com/w/cpp/utility/optional/value_or) seems to do the job:
```
std::string add_postfix(const std::string& name,
const std::optional<std::string>& postfix)
{
return name + postfix.value_or("2");
}
```
If you really want `optional<T&>`, `optional<reference_wrapper<T>>` might do the job.
```
std::string add_postfix(const std::string& name,
const std::optional<std::reference_wrapper<const std::string>>& postfix)
{
#if 1
const std::string postfix_ = "2";
return name + postfix.value_or(postfix_).get();
#else // or
return name + (postfix.has_value() ? postfix->get() : "2");
#endif
}
```
[Demo](https://godbolt.org/z/rbxooGfrY) |
7,023,981 | How does one change file access permissions?
```
f = open('test','w')
f.close()
```
Defaults access permissions: 10600 | 2011/08/11 | [
"https://Stackoverflow.com/questions/7023981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/853863/"
] | You can use [os.chmod](http://docs.python.org/library/os.html#os.chmod)
```
os.chmod(path, mode)
```
You probably want to use an octal integer literal, like 0777 for the mode. | Use [os.chmod(path, mode)](http://docs.python.org/library/os.html#os.chmod) |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | It certainly is not pointless, you can have another thread that has a reference to the object containing the above code doing
```
synchronized(foo) {
foo.wait();
}
```
in order to be woken up when something happens. Though, in many cases it's considered good practice to synchronize on an internal/private lock object instead of `this`.
However, *only* doing a .notify() within the synchronization block could be quite wrong - you usually have some work to do and notify when it's done, which in normal cases also needs to be done atomically in regards to other threads. We'd have to see more code to determine whether it really is wrong. | This is generally not a anti-pattern, if you still want to use intrinsic locks. Some may regard this as an anti pattern, as the new explicit locks from `java.util.concurrent` are more fine grained.
But your code is still valid. For instance, such code can be found in a blocking queue, when an blocking operation has succeeded and another waiting thread should be notified. Note however that concurrency issues are highly dependent on the usage and the surrounding code, so your simple snippet is not that meaningful. |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | This is perfectly fine. According to the [Java 6 `Object#notify()` api documentation](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29):
>
> This method should only be called by a thread that is the owner of this object's monitor.
>
>
> | This is generally not a anti-pattern, if you still want to use intrinsic locks. Some may regard this as an anti pattern, as the new explicit locks from `java.util.concurrent` are more fine grained.
But your code is still valid. For instance, such code can be found in a blocking queue, when an blocking operation has succeeded and another waiting thread should be notified. Note however that concurrency issues are highly dependent on the usage and the surrounding code, so your simple snippet is not that meaningful. |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | If that is all that is in the synchonized block then it *is* an antipattern, the point of synchronizing is to do something within the block, setting some condition, then call `notify` or `notifyAll` to wake up one or more waiting threads.
When you use wait and notify you have to use a condition variable, see [this Oracle tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html):
>
> Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
>
>
>
You shouldn't assume you received a notification just because a thread exited from a call to Object#wait, for multiple reasons:
* When calling the version of wait that takes a timeout value there's no way to know whether wait ended due to receiving a notification or due to timing out.
* You have to allow for the possibility that a Thread can wake up from waiting without having received a notification (the "spurious wakeup").
* The waiting thread that receives a notification still has to reacquire the lock it gave up when it started waiting, there is no atomic linking of these two events; in the interval between being notified and reacquiring the lock another thread can act and possibly change the state of the system so that the notification is now invalid.
* You can have a case where the notifying thread acts before any thread is waiting so that the notification has no effect. Assuming one thread will enter a wait before the other thread will notify is dangerous, if you're wrong the waiting thread will hang indefinitely.
So a notification by itself is not good enough, you end up guessing about whether a notification happened when the wait/notify API doesn't give you enough information to know what's going on. Even if other work the notifying thread is doing doesn't require synchronization, updating the condition variable does; there should at least be an update of the shared condition variable in the synchronized block. | This is generally not a anti-pattern, if you still want to use intrinsic locks. Some may regard this as an anti pattern, as the new explicit locks from `java.util.concurrent` are more fine grained.
But your code is still valid. For instance, such code can be found in a blocking queue, when an blocking operation has succeeded and another waiting thread should be notified. Note however that concurrency issues are highly dependent on the usage and the surrounding code, so your simple snippet is not that meaningful. |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | It certainly is not pointless, you can have another thread that has a reference to the object containing the above code doing
```
synchronized(foo) {
foo.wait();
}
```
in order to be woken up when something happens. Though, in many cases it's considered good practice to synchronize on an internal/private lock object instead of `this`.
However, *only* doing a .notify() within the synchronization block could be quite wrong - you usually have some work to do and notify when it's done, which in normal cases also needs to be done atomically in regards to other threads. We'd have to see more code to determine whether it really is wrong. | The Java API documentation for [Object.notify()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29) states that the method "should only be called by a thread that is the owner of this object's monitor". So the use could be legitimate depending upon the surrounding context. |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | It certainly is not pointless, you can have another thread that has a reference to the object containing the above code doing
```
synchronized(foo) {
foo.wait();
}
```
in order to be woken up when something happens. Though, in many cases it's considered good practice to synchronize on an internal/private lock object instead of `this`.
However, *only* doing a .notify() within the synchronization block could be quite wrong - you usually have some work to do and notify when it's done, which in normal cases also needs to be done atomically in regards to other threads. We'd have to see more code to determine whether it really is wrong. | This is perfectly fine. According to the [Java 6 `Object#notify()` api documentation](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29):
>
> This method should only be called by a thread that is the owner of this object's monitor.
>
>
> |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | It certainly is not pointless, you can have another thread that has a reference to the object containing the above code doing
```
synchronized(foo) {
foo.wait();
}
```
in order to be woken up when something happens. Though, in many cases it's considered good practice to synchronize on an internal/private lock object instead of `this`.
However, *only* doing a .notify() within the synchronization block could be quite wrong - you usually have some work to do and notify when it's done, which in normal cases also needs to be done atomically in regards to other threads. We'd have to see more code to determine whether it really is wrong. | If that is all that is in the synchonized block then it *is* an antipattern, the point of synchronizing is to do something within the block, setting some condition, then call `notify` or `notifyAll` to wake up one or more waiting threads.
When you use wait and notify you have to use a condition variable, see [this Oracle tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html):
>
> Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
>
>
>
You shouldn't assume you received a notification just because a thread exited from a call to Object#wait, for multiple reasons:
* When calling the version of wait that takes a timeout value there's no way to know whether wait ended due to receiving a notification or due to timing out.
* You have to allow for the possibility that a Thread can wake up from waiting without having received a notification (the "spurious wakeup").
* The waiting thread that receives a notification still has to reacquire the lock it gave up when it started waiting, there is no atomic linking of these two events; in the interval between being notified and reacquiring the lock another thread can act and possibly change the state of the system so that the notification is now invalid.
* You can have a case where the notifying thread acts before any thread is waiting so that the notification has no effect. Assuming one thread will enter a wait before the other thread will notify is dangerous, if you're wrong the waiting thread will hang indefinitely.
So a notification by itself is not good enough, you end up guessing about whether a notification happened when the wait/notify API doesn't give you enough information to know what's going on. Even if other work the notifying thread is doing doesn't require synchronization, updating the condition variable does; there should at least be an update of the shared condition variable in the synchronized block. |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | This is perfectly fine. According to the [Java 6 `Object#notify()` api documentation](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29):
>
> This method should only be called by a thread that is the owner of this object's monitor.
>
>
> | The Java API documentation for [Object.notify()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29) states that the method "should only be called by a thread that is the owner of this object's monitor". So the use could be legitimate depending upon the surrounding context. |
7,613,027 | I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
```
synchronized (this) {
this.notify();
}
```
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7613027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74815/"
] | If that is all that is in the synchonized block then it *is* an antipattern, the point of synchronizing is to do something within the block, setting some condition, then call `notify` or `notifyAll` to wake up one or more waiting threads.
When you use wait and notify you have to use a condition variable, see [this Oracle tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html):
>
> Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
>
>
>
You shouldn't assume you received a notification just because a thread exited from a call to Object#wait, for multiple reasons:
* When calling the version of wait that takes a timeout value there's no way to know whether wait ended due to receiving a notification or due to timing out.
* You have to allow for the possibility that a Thread can wake up from waiting without having received a notification (the "spurious wakeup").
* The waiting thread that receives a notification still has to reacquire the lock it gave up when it started waiting, there is no atomic linking of these two events; in the interval between being notified and reacquiring the lock another thread can act and possibly change the state of the system so that the notification is now invalid.
* You can have a case where the notifying thread acts before any thread is waiting so that the notification has no effect. Assuming one thread will enter a wait before the other thread will notify is dangerous, if you're wrong the waiting thread will hang indefinitely.
So a notification by itself is not good enough, you end up guessing about whether a notification happened when the wait/notify API doesn't give you enough information to know what's going on. Even if other work the notifying thread is doing doesn't require synchronization, updating the condition variable does; there should at least be an update of the shared condition variable in the synchronized block. | The Java API documentation for [Object.notify()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29) states that the method "should only be called by a thread that is the owner of this object's monitor". So the use could be legitimate depending upon the surrounding context. |
73,312 | A possible solution to [my other question](https://android.stackexchange.com/questions/73244/secure-boot-while-still-being-able-to-keep-up-with-nightlies) related to this.
Having root access, what's there to prevent me from manually flashing a custom recovery from my running operating system? If my bootloader is locked, can I still do:
```
dd if=openrecovery-twrp-2.7.0-deb.img of=/dev/block/platform/msm_sdcc.1/by-name/recovery
```
If so, then I'd be able to flash a custom recovery from inside of a running Android operating system, bypassing a locked bootloader. I suppose if someone has root access to a running operating system, you're pretty much hosed anyway, but would this at least in theory work?
Can I use something similar to the above command to flash a recovery in a live, running Android device? | 2014/06/17 | [
"https://android.stackexchange.com/questions/73312",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/2829/"
] | In response to my own question: yes, you can flash a custom recovery from a running OS. The recovery, since it isn't mounted, should be fine to write:
```
dd if=openrecovery-twrp-2.7.0-deb.img of=/dev/block/platform/msm_sdcc.1/by-name/recovery
```
You run the above at your own risk and I accept no responsibility for what you do with this.
Do note, however, that if you have a locked bootloader, it will prevent booting because it will see that the recovery's signature is bad. | A 'newer' and free (and in my opinion the best so far) root app is Flashify.
It can flash kernels and recoveries from your phone. Additionally it can download the images for you, too.
<https://play.google.com/store/apps/details?id=com.cgollner.flashify> |
73,312 | A possible solution to [my other question](https://android.stackexchange.com/questions/73244/secure-boot-while-still-being-able-to-keep-up-with-nightlies) related to this.
Having root access, what's there to prevent me from manually flashing a custom recovery from my running operating system? If my bootloader is locked, can I still do:
```
dd if=openrecovery-twrp-2.7.0-deb.img of=/dev/block/platform/msm_sdcc.1/by-name/recovery
```
If so, then I'd be able to flash a custom recovery from inside of a running Android operating system, bypassing a locked bootloader. I suppose if someone has root access to a running operating system, you're pretty much hosed anyway, but would this at least in theory work?
Can I use something similar to the above command to flash a recovery in a live, running Android device? | 2014/06/17 | [
"https://android.stackexchange.com/questions/73312",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/2829/"
] | A 'newer' and free (and in my opinion the best so far) root app is Flashify.
It can flash kernels and recoveries from your phone. Additionally it can download the images for you, too.
<https://play.google.com/store/apps/details?id=com.cgollner.flashify> | Actually I have tried this on around 3-5 occassions(and it has always worked, for some reason).
What I did was I download recovery in img format (or if it was zip I manually extracted it to get the img file). Then renamed file from whatever name to `recovery.img`
Then I went to `system/etc` and deleted existing recovery.img and copied the new one downloaded above. Then set permissions to rw-r-r or 755.
This has quite greatly worked for me. Again, *I am not taking any responsibility here*. Feel free to backup and check ;) |
73,312 | A possible solution to [my other question](https://android.stackexchange.com/questions/73244/secure-boot-while-still-being-able-to-keep-up-with-nightlies) related to this.
Having root access, what's there to prevent me from manually flashing a custom recovery from my running operating system? If my bootloader is locked, can I still do:
```
dd if=openrecovery-twrp-2.7.0-deb.img of=/dev/block/platform/msm_sdcc.1/by-name/recovery
```
If so, then I'd be able to flash a custom recovery from inside of a running Android operating system, bypassing a locked bootloader. I suppose if someone has root access to a running operating system, you're pretty much hosed anyway, but would this at least in theory work?
Can I use something similar to the above command to flash a recovery in a live, running Android device? | 2014/06/17 | [
"https://android.stackexchange.com/questions/73312",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/2829/"
] | In response to my own question: yes, you can flash a custom recovery from a running OS. The recovery, since it isn't mounted, should be fine to write:
```
dd if=openrecovery-twrp-2.7.0-deb.img of=/dev/block/platform/msm_sdcc.1/by-name/recovery
```
You run the above at your own risk and I accept no responsibility for what you do with this.
Do note, however, that if you have a locked bootloader, it will prevent booting because it will see that the recovery's signature is bad. | Actually I have tried this on around 3-5 occassions(and it has always worked, for some reason).
What I did was I download recovery in img format (or if it was zip I manually extracted it to get the img file). Then renamed file from whatever name to `recovery.img`
Then I went to `system/etc` and deleted existing recovery.img and copied the new one downloaded above. Then set permissions to rw-r-r or 755.
This has quite greatly worked for me. Again, *I am not taking any responsibility here*. Feel free to backup and check ;) |
2,036,024 | $\sum\_{n=0}^{\infty} \frac{1}{\sqrt{n^2 + n}}$
Is there an elementary way to show that this *diverges*? | 2016/11/29 | [
"https://math.stackexchange.com/questions/2036024",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384153/"
] | Hint:
$$\frac1{\sqrt{n^2+n}}>\frac1{n+1}$$ | You have
$$\frac{1}{\sqrt{n^2+n}}\sim \frac 1n.$$
So by comparaison to Riemann example, this series diverges. |
50,879,151 | How to get previous friday in SQL Server?
Here is the code I have so far:
```
select (7 -datePart(dw, getdate()+3)) +1
``` | 2018/06/15 | [
"https://Stackoverflow.com/questions/50879151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5635467/"
] | Use mod like this:
```
declare @date datetime = getdate()
declare @dow int = datepart(dw,@date)
declare @mod int = @dow % 7 +1
select cast(dateadd(d,-@mod ,@date) as date)
``` | If your week starts on Sunday, then here's a one-liner:
```
SELECT DATEADD(WEEK
,DATEDIFF(WEEK, '1900-01-05', DATEADD(DAY, 6 - DATEPART(DAY, GETDATE()) - 1, GETDATE()))
,'1900-01-05') AS [Last Friday]
```
The query counts the number of weeks since 1900-01-05 (which is a Friday) to today's date minus 1 week. This number of weeks is added to 1900-01-05 to get the previous week's Friday. |
50,879,151 | How to get previous friday in SQL Server?
Here is the code I have so far:
```
select (7 -datePart(dw, getdate()+3)) +1
``` | 2018/06/15 | [
"https://Stackoverflow.com/questions/50879151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5635467/"
] | Use mod like this:
```
declare @date datetime = getdate()
declare @dow int = datepart(dw,@date)
declare @mod int = @dow % 7 +1
select cast(dateadd(d,-@mod ,@date) as date)
``` | Try this
select convert(varchar(10), DATEADD(DD, -1 - DATEPART(DW, CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, GETDATE())))
),CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, GETDATE())))),101)
It will give you previous friday of every week |
40,995,032 | I have an idea for a code style for writing specific kinds of numerical algorithms where you write your algorithm purely in data-layout agnostic fashion.
i.e. All of your functions take (one or more) scalar arguments, and return (through a pointer) one or more scalar return values. So, for example, if you have a function that takes a 3d float vector, instead of taking a struct with three members, or float[3] xyz, you take float x, float y, float z.
The idea is that you can change the layout of your input and output data, i.e. you can play with struct of array vs. array of struct data layout, tiled layouts for cache efficiency, SIMD vs. multicore granularity, etc... WITHOUT having to rewrite all of your code for all combinations of data layouts.
The strategy has some obvious downsides:
* You can't use for loops inside your functions to make your code more compact
* Your functions need more parameters in their signatures
...but those are palatable if your arrays are short and it saves you having to rewrite your code a bunch of times to make it fast.
But in particular, I am worried that compilers might not be able to take stuff like x+=a; y+=b; z+=c; w+=d and autovectorize it into a single SIMD vector add, in the case where you want to do SIMD at the bottom of your call stack, as opposed to doing SIMD at the top of a stack of inlined functions.
Are clang and/or gcc able to "re-roll" manually unrolled loops in C and/or C++ code (probably after functions are inlined) and generate vectorized machine code? | 2016/12/06 | [
"https://Stackoverflow.com/questions/40995032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139802/"
] | I wrote some code to do a trivial test of my idea:
```
// Compile using gcc -O4 main.c && objdump -d a.out
void add4(float x0, float x1, float x2, float x3,
float y0, float y1, float y2, float y3,
float* out0, float* out1, float* out2, float* out3) {
// Non-inlined version of this uses xmm registers and four separate
// SIMD operations
*out0 = x0 + y0;
*out1 = x1 + y1;
*out2 = x2 + y2;
*out3 = x3 + y3;
}
void sub4(float x0, float x1, float x2, float x3,
float y0, float y1, float y2, float y3,
float* out0, float* out1, float* out2, float* out3) {
*out0 = x0 - y0;
*out1 = x1 - y1;
*out2 = x2 - y2;
*out3 = x3 - y3;
}
void add4_then_sub4(float x0, float x1, float x2, float x3,
float y0, float y1, float y2, float y3,
float z0, float z1, float z2, float z3,
float* out0, float* out1, float* out2, float* out3) {
// In non-inlined version of this, add4 and sub4 get inlined.
// xmm regiesters get re-used for the add and subtract,
// but there is still no 4-way SIMD
float temp0,temp1,temp2,temp3;
// temp= x + y
add4(x0,x1,x2,x3,
y0,y1,y2,y3,
&temp0,&temp1,&temp2,&temp3);
// out = temp - z
sub4(temp0,temp1,temp2,temp3,
z0,z1,z2,z3,
out0,out1,out2,out3);
}
void add4_then_sub4_arrays(const float x[4],
const float y[4],
const float z[4],
float out[4])
{
// This is a stand-in for the main function below, but since the arrays are aguments,
// they can't be optimized out of the non-inlined version of this function.
// THIS version DOES compile into (I think) a bunch of non-aligned moves,
// and a single vectorized add a single vectorized subtract
add4_then_sub4(x[0],x[1],x[2],x[3],
y[0],y[1],y[2],y[3],
z[0],z[1],z[2],z[3],
&out[0],&out[1],&out[2],&out[3]
);
}
int main(int argc, char **argv)
{
}
```
Consider the generated assembly for add4\_then\_sub4\_arrays:
```
0000000000400600 <add4_then_sub4_arrays>:
400600: 0f 57 c0 xorps %xmm0,%xmm0
400603: 0f 57 c9 xorps %xmm1,%xmm1
400606: 0f 12 06 movlps (%rsi),%xmm0
400609: 0f 12 0f movlps (%rdi),%xmm1
40060c: 0f 16 46 08 movhps 0x8(%rsi),%xmm0
400610: 0f 16 4f 08 movhps 0x8(%rdi),%xmm1
400614: 0f 58 c1 addps %xmm1,%xmm0
400617: 0f 57 c9 xorps %xmm1,%xmm1
40061a: 0f 12 0a movlps (%rdx),%xmm1
40061d: 0f 16 4a 08 movhps 0x8(%rdx),%xmm1
400621: 0f 5c c1 subps %xmm1,%xmm0
400624: 0f 13 01 movlps %xmm0,(%rcx)
400627: 0f 17 41 08 movhps %xmm0,0x8(%rcx)
40062b: c3 retq
40062c: 0f 1f 40 00 nopl 0x0(%rax)
```
The arrays aren't aligned, so there are a lot more move ops than ideal, and I'm not sure what that xor is doing in there, but there is indeed one 4-way add and one 4-way subtract as desired.
So the answer is that gcc has at least ~some ability to pack scalar floating point operations back into SIMD operations.
Update: Tighter code with both `gcc-4.8 -O3 -march=native main.c && objdump -d a.out`:
```
0000000000400600 <add4_then_sub4_arrays>:
400600: c5 f8 10 0e vmovups (%rsi),%xmm1
400604: c5 f8 10 07 vmovups (%rdi),%xmm0
400608: c5 f0 58 c0 vaddps %xmm0,%xmm1,%xmm0
40060c: c5 f8 10 0a vmovups (%rdx),%xmm1
400610: c5 f8 5c c1 vsubps %xmm1,%xmm0,%xmm0
400614: c5 f8 11 01 vmovups %xmm0,(%rcx)
400618: c3 retq
400619: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
```
and with `clang-4.0 -O3 -march=native main.c && llvm-objdump -d a.out`:
```
add4_then_sub4_arrays:
4005e0: c5 f8 10 07 vmovups (%rdi), %xmm0
4005e4: c5 f8 58 06 vaddps (%rsi), %xmm0, %xmm0
4005e8: c5 f8 5c 02 vsubps (%rdx), %xmm0, %xmm0
4005ec: c5 f8 11 01 vmovups %xmm0, (%rcx)
4005f0: c3 ret
4005f1: 66 66 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 nopw %cs:(%rax,%rax)
``` | Your concern is correct. No compiler is going to autovectorize those 4 adds. It's simply not worth it, considering the inputs aren't contiguous and aligned. The cost of gathering arguments into a SIMD register are much higher than the saving of a vector addition.
Of course, the reason the compiler can't use an aligned streaming load is because you passed the arguments as scalars. |
29,166,701 | Till now I solved most of my problems/questions by myself, simply searching for already existing threads...unfortunately this did not work for my current problem, so I thought I give it a try:
I am new to VBA and just recently started programming some useful marcos to automate/simplify slide development on PowerPoint 2007.
In one of them, I am trying to add shapes to a slide with a predefined bullet list. All works fine, except of getting the indentation of the bullets right. I'm not sure which code to use...
What I want to do is on the one hand define the space between bullet and text and on the other hand set the indentation before the bullet for the different levels of the bullet list.
I would really appreciate your help or any links to threads that adress this problem.
Code developed so far see below:
```
Sub PhaseWiz1Row2Phases()
Dim sld As Slide
Dim SlideIndex As Integer
Dim row1 As Shape
'###Only apply command to currentlty viewed slide###
'set the index number of the currently viewed slide as the variable "SlideIndex"
SlideIndex = ActiveWindow.View.Slide.SlideIndex
'set sld as the current slide
Set sld = ActivePresentation.Slides(SlideIndex)
'###Add and configure shapes to currently viewed slide###
'add first column to the currently viewed slide
Set row1 = sld.Shapes.AddShape(msoShapeRectangle, _
Left:=35.999, Top:=195.587, Width:=308.971, Height:=120)
'configure column
row1.Fill.Visible = msoFalse
row1.Line.Visible = msoTrue
row1.Line.Weight = 1#
row1.Line.ForeColor.RGB = RGB(0, 40, 104)
'Add and configure text
row1.TextFrame.TextRange.Text = "Headline" _
+ Chr$(CharCode:=13) + "Text" + Chr$(CharCode:=13) + "Text" _
+ Chr$(CharCode:=13) + "Text" + Chr$(CharCode:=13) + "Text"
row1.TextFrame.TextRange.Font.Size = 14
row1.TextFrame.TextRange.Font.Name = "Verdana"
row1.TextFrame.TextRange.ParagraphFormat.Alignment = ppAlignLeft
row1.TextFrame.VerticalAnchor = msoAnchorTop
row1.TextFrame.TextRange.Paragraphs(3).IndentLevel = 2
row1.TextFrame.TextRange.Paragraphs(4).IndentLevel = 3
row1.TextFrame.TextRange.Paragraphs(5).IndentLevel = 4
With row1.TextFrame.TextRange.Characters(1, 8)
.Font.Color.RGB = RGB(0, 174, 239)
.Font.Bold = msoTrue
End With
With row1.TextFrame.TextRange.Characters(9, 16)
.Font.Color.RGB = RGB(0, 40, 104)
.Font.Bold = msoFalse
End With
With row1.TextFrame.TextRange.Characters(10, 0)
.ParagraphFormat.Bullet.Character = 8226
.ParagraphFormat.Bullet.RelativeSize = 0.7
End With
With row1.TextFrame.TextRange.Characters(15, 0)
.ParagraphFormat.Bullet.Character = 45
.ParagraphFormat.Bullet.RelativeSize = 1.2
'.Paragraphs(3).IndentLevel = 2
End With
With row1.TextFrame.TextRange.Characters(20, 0)
.ParagraphFormat.Bullet.Character = 43
'.Paragraphs(3).IndentLevel = 2
End With
With row1.TextFrame.TextRange.Characters(25, 0)
.ParagraphFormat.Bullet.Character = 46
End With
```
End Sub | 2015/03/20 | [
"https://Stackoverflow.com/questions/29166701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4693949/"
] | I know I am a bit late but I just had a similar problem and it was driving me crazy.
To answer your question " ...I am trying to figure it out, where I am creating an issue"... The error is being created at
```
$ffs = imagecreatefromjpeg($image);
```
This error came from executing this line of code, when uploading an image jpg and then working with it with the PHP GD2 Library
I followed the solution in the link below and it solved my issue.
<http://anvilstudios.co.za/blog/2010/02/23/imagecreatefromjpeg-gd-jpeg-library-reports-unrecoverable-error/>
I hope somebody will find this useful and save some time. Kudos to Nico from anvilstudios
**Update**
For those who cant access the link here is the code
```
$file_tempname = null;
if (is_uploaded_file($FILE['tmp_name'])) {
$file_tempname = $FILE['tmp_name'];
}
else{
exit('Wrong file type');
}
$file_dimensions = getimagesize($file_tempname);
$file_type = strtolower($file_dimensions['mime']);
if ($file_type=='image/jpeg'||$file_type=='image/pjpeg'){
if(imagecreatefromjpeg($file_tempname)){
$ffs = imagecreatefromjpeg($file_tempname);
return $ffs;
}
}
``` | the solution I found is the following:
```
$file_dimensions = getimagesize($_SERVER['DOCUMENT_ROOT'] . $fileUrl);
$ImageType = strtolower($file_dimensions['mime']);
switch(strtolower($ImageType))
{
case 'image/png':
$img_r = imagecreatefrompng($_SERVER['DOCUMENT_ROOT'] . $fileUrl);
break;
case 'image/jpeg':
$img_r = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'] . $fileUrl);
break;
default:
die('Unsupported File!'); //output error
}
``` |
7,463,377 | I recently had a stack overflow exception in my .NET app (asp.net website), which I know because it showed up in my EventLog. I understand that a StackOverflow exception cannot be caught or handled, but is there a way to log it before it kills your application? I have 100k lines of code. If I knew the stack trace, or just part of the stack trace, I could track down the source of the infinite loop/recursion. But without any helpful diagnostic information, it looks like it'll take a lot of guess-and-test.
I tried setting up an unhandled exception handler on my app domain (in global.asax), but that didn't seem to execute, which makes sense if a stack overflow is supposed to terminate and not run any catch/finally blocks.
Is there any way to log these, or is there some secret setting that I can enable that will save the stack frames to disk when the app crashes? | 2011/09/18 | [
"https://Stackoverflow.com/questions/7463377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197605/"
] | Your best bet is to use [ADPlus](http://msdn.microsoft.com/en-us/library/ff537953.aspx).
The Windows NT Kernel Debugging Team has a nice [blog post](http://blogs.msdn.com/b/ntdebugging/archive/2009/05/18/capturing-adplus-clr-crashes.aspx) on how to catch CLR exceptions with it. There are a lot of details on that there about different configuration options for it.
ADPlus will monitor the application. You can specify that it run in [crash mode](http://msdn.microsoft.com/en-us/library/ff539318.aspx) so you can tell ADPlus to take a memory dump right as the StackOverflowException is happening.
Once you have a memory dump, you can use WinDbg and a managed debugging extension like [Psscor](http://www.microsoft.com/download/en/details.aspx?id=21255) to see what was going on during the stack overflow. | You could try logging messages at key points in your application and take out the part where the flow of log messages break.
Then, try and replicate it with that section of code using unit tests.
The only way to get a trace for a stack overflow error that I know of is to have an intermediary layer taking snapshots of the running code and writing that out. This always has a heavy performance impact. |
7,463,377 | I recently had a stack overflow exception in my .NET app (asp.net website), which I know because it showed up in my EventLog. I understand that a StackOverflow exception cannot be caught or handled, but is there a way to log it before it kills your application? I have 100k lines of code. If I knew the stack trace, or just part of the stack trace, I could track down the source of the infinite loop/recursion. But without any helpful diagnostic information, it looks like it'll take a lot of guess-and-test.
I tried setting up an unhandled exception handler on my app domain (in global.asax), but that didn't seem to execute, which makes sense if a stack overflow is supposed to terminate and not run any catch/finally blocks.
Is there any way to log these, or is there some secret setting that I can enable that will save the stack frames to disk when the app crashes? | 2011/09/18 | [
"https://Stackoverflow.com/questions/7463377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197605/"
] | Your best bet is to use [ADPlus](http://msdn.microsoft.com/en-us/library/ff537953.aspx).
The Windows NT Kernel Debugging Team has a nice [blog post](http://blogs.msdn.com/b/ntdebugging/archive/2009/05/18/capturing-adplus-clr-crashes.aspx) on how to catch CLR exceptions with it. There are a lot of details on that there about different configuration options for it.
ADPlus will monitor the application. You can specify that it run in [crash mode](http://msdn.microsoft.com/en-us/library/ff539318.aspx) so you can tell ADPlus to take a memory dump right as the StackOverflowException is happening.
Once you have a memory dump, you can use WinDbg and a managed debugging extension like [Psscor](http://www.microsoft.com/download/en/details.aspx?id=21255) to see what was going on during the stack overflow. | Very wise to ask about StackOverFlowException on StackOverflow :)
AFAIK, about the only thing you can do is get a dump on a crash. The CLR is going to take you down unless you host your own CLR.
A related question on getting a dump of IIS worker process on crash:
* [Getting IIS Worker Process Crash dumps](https://stackoverflow.com/questions/53435/getting-iis-worker-process-crash-dumps)
Here's a couple other SO related threads:
* [How to print stack trace of StackOverflowException](https://stackoverflow.com/questions/2591406/how-to-print-stack-trace-of-stackoverflowexception)
* [C# catch a stack overflow exception](https://stackoverflow.com/questions/1599219/c-catch-a-stack-overflow-exception)
Hope these pointers help. |
12,234,193 | I am calling a function named edit from an onclick event as follows.
```
<script type="text/javascript">
$(document).ready(function () {
...
$.each(data, function (key, val) {
...
var td11 = $('<input type="button" value="Edit" onclick="edit();" />')
.attr("name",val.Id);
$(tr2).append(td11);
$(table1).append(tr2);
});
$("#cers").append(table1);
```
The function is defined outside the $.each loop, inside $(document).ready, as follows
```
function edit() {
alert("Id ");
}
```
When i click on Edit button, Chrome shown error : Uncaught ReferenceError: edit is not defined.
No other errors. | 2012/09/02 | [
"https://Stackoverflow.com/questions/12234193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385490/"
] | Running svnserve with -d -r can be a solution:
<http://blog.dbtracer.org/2010/01/20/porting-subversion-git-with-error/> | From [here](https://github.com/nirvdrum/svn2git/issues/69):
>
> I had the same problem, happens when an error occurs (i missed some authors in the authors file) in the middle of the process. I solved it by removing the directory in where you executed svn2git, recreate it and execute it again. Still this isn't a solution and this issue needs to be fixed.
>
>
> |
12,234,193 | I am calling a function named edit from an onclick event as follows.
```
<script type="text/javascript">
$(document).ready(function () {
...
$.each(data, function (key, val) {
...
var td11 = $('<input type="button" value="Edit" onclick="edit();" />')
.attr("name",val.Id);
$(tr2).append(td11);
$(table1).append(tr2);
});
$("#cers").append(table1);
```
The function is defined outside the $.each loop, inside $(document).ready, as follows
```
function edit() {
alert("Id ");
}
```
When i click on Edit button, Chrome shown error : Uncaught ReferenceError: edit is not defined.
No other errors. | 2012/09/02 | [
"https://Stackoverflow.com/questions/12234193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385490/"
] | The problem is that you are accessing this file locally and using different formats for your original svn repo and the git instance that is migrating from svn to git (most likely your git is behind your svn repo version) - instead try running the migration through an svn server - try starting up an svn server with
`svnserve.exe -d -r /path/to/repo`
and then try your import again using:
`git.exe svn init -s "svn://localhost/repo_name"`
The problem is not your permissions, but a mismatch of versions | From [here](https://github.com/nirvdrum/svn2git/issues/69):
>
> I had the same problem, happens when an error occurs (i missed some authors in the authors file) in the middle of the process. I solved it by removing the directory in where you executed svn2git, recreate it and execute it again. Still this isn't a solution and this issue needs to be fixed.
>
>
> |
12,234,193 | I am calling a function named edit from an onclick event as follows.
```
<script type="text/javascript">
$(document).ready(function () {
...
$.each(data, function (key, val) {
...
var td11 = $('<input type="button" value="Edit" onclick="edit();" />')
.attr("name",val.Id);
$(tr2).append(td11);
$(table1).append(tr2);
});
$("#cers").append(table1);
```
The function is defined outside the $.each loop, inside $(document).ready, as follows
```
function edit() {
alert("Id ");
}
```
When i click on Edit button, Chrome shown error : Uncaught ReferenceError: edit is not defined.
No other errors. | 2012/09/02 | [
"https://Stackoverflow.com/questions/12234193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385490/"
] | Running svnserve with -d -r can be a solution:
<http://blog.dbtracer.org/2010/01/20/porting-subversion-git-with-error/> | The problem is that you are accessing this file locally and using different formats for your original svn repo and the git instance that is migrating from svn to git (most likely your git is behind your svn repo version) - instead try running the migration through an svn server - try starting up an svn server with
`svnserve.exe -d -r /path/to/repo`
and then try your import again using:
`git.exe svn init -s "svn://localhost/repo_name"`
The problem is not your permissions, but a mismatch of versions |
26,814,081 | ```
string = c("Hello-", "HelloA", "Helloa")
grep("Hello$[A-z]", string)
```
I wish to find the indices of the strings in which the next character after the word "Hello" is a letter (case insensitive). The code above doesn't work, but I would like grep() to return indices 2 and 3 since those words have a letter after "Hello" | 2014/11/08 | [
"https://Stackoverflow.com/questions/26814081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3391549/"
] | Use Positive lookahead
```
> string = c("Hello-", "HelloA", "Helloa")
> grep('Hello(?=[A-Za-z])', string, perl=T)
[1] 2 3
```
`(?=[A-Za-z])` this positive lookahead asserts that the character following the string `Hello` must be a letter.
**OR**
```
> grep('Hello[A-Za-z]', string)
[1] 2 3
```
Add a `$` in the regex if there is only one letter following the string `Hello`. `$` Asserts that we are at the end.
```
> grep('Hello[A-Za-z]$', string)
[1] 2 3
> grep('Hello(?=[A-Za-z]$)', string, perl=T)
[1] 2 3
``` | The "$" is the symbol for the end of the string, so you need to remove.
```
string = c("Hello-", "HelloA", "Helloa")
grep("Hello[A-z]", string)
#[1] 2 3
?regex # to my memory of the "alpha" version of the character class
grep("Hello[[:alpha:]]", string)
#[1] 2 3
```
The second one is preferable because "A-z" can be ambiguous or misleading in locales where that is not a correct definition of the collation order of characters for "alphabetic". |
8,835,413 | >
> **Possible Duplicate:**
>
> [Difference between DOMContentLoaded and Load events](https://stackoverflow.com/questions/2414750/difference-between-domcontentloaded-and-load-events)
>
>
>
Whats the difference between
```
window.addEventListener("load", load, false);
```
and
```
document.addEventListener("DOMContentLoaded", load, false);
```
? | 2012/01/12 | [
"https://Stackoverflow.com/questions/8835413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/579421/"
] | * `DOMContentLoaded` - the whole document (HTML) has been loaded.
* `load` - the whole document and its resources (e.g. images, iframes, scripts) have been loaded. | DOMContentLoaded awaits only for HTML and scripts to be loaded.
window.onload and iframe.onload triggers when the page is fully loaded with all dependent resources including images and styles.
Here is more details you can find <http://javascript.info/tutorial/onload-ondomcontentloaded> |
13,293,607 | If I use this:
```
mCamera.rotateY(45);
mCamera.getMatrix(mMatrix);
mMatrix.preTranslate(-pivotX, -pivotY);
mMatrix.postTranslate(pivotX + centerX, pivotY + centerY);
```
And do:
```
canvas.drawBitmap(bitmap, mMatrix, null);
```
Then the drawn picture will be taller and slimmer and the matrix will be nicely applied to the whole picture. Now, is there any way to calculate the rotated size? I want to fit the image by scaling it and now when I rotate it some of the top and bottom is clipped because of the parent's constraints. Thanks!
EDIT:
What I am going to do is spin the image and the range for rotateY will be from 0 to 90. | 2012/11/08 | [
"https://Stackoverflow.com/questions/13293607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1663253/"
] | Well, you could easily let the matrix map the corners of your bitmap and then calculate the bounds, as the mapped corners will be the max / min for x and y coordinate. Maybe you can do it without too many `if` clauses :)
**Edit:**
Check out
```
RectF r = new RectF(/*your bitmap's corners*/);
matrix.mapRect(r);
```
That way you should get `r`'s new size. | If you stick to 45° then Pythagoras is the key |
44,243,853 | I have couple of file with same name, and I wanted to get the latest file
[root@xxx tmp]# ls -t1 abclog\*
abclog.1957
abclog.1830
abclog.1799
abclog.1742
I can accomplish that by executing below command.
[root@xxx tmp]# ls -t1 abclog\*| head -n 1
abclog.1957
But when I am trying to execute the same in python , getting error :
>
>
> >
> >
> > >
> > > subprocess.check\_output("ls -t1 abclog\* | head -n 1",shell=True)
> > > ls: cannot access abclog\*: No such file or directory
> > > ''
> > >
> > >
> > >
> >
> >
> >
>
>
>
Seems it does not able to recognize '\*' as a special parameter. How can I achieve the same ? | 2017/05/29 | [
"https://Stackoverflow.com/questions/44243853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377271/"
] | I think you are asking for open resource(`Ctrl`+`Shift`+`R`) not open type(`Ctrl`+`Shift`+`T`).
IMHO there is no way to filter out **types** by their paths, as because same type(ex Enum/Inner class) may exist in different Java classes.
Yes. You can filter out resources by project/folder path. Refer this answer <https://stackoverflow.com/a/39568618/1391924> | Open Resource and Open Type both let You use *Working Sets*.
So You can define a WS per project or whatever makes sense for You and use the one You need at the given moment.
You can choose the WS directly in the modal dialog. |
211,303 | I want to count the number of rows with duplicate ids
My current code is
```
SET @x=1;
SELECT
c.id,
so.trans_id,
IF(c.id = c.id, @x + 1, @x) as count_t
FROM customer c
LEFT JOIN sales_order so
```
Current Result
```
+-----+----------+----------+
| id | trans_id | count_t |
+-----+----------+----------+
| 101 | 100001 | 2 |
| 101 | 100059 | 2 |
| 101 | 100061 | 2 |
| 102 | 100030 | 2 |
| 102 | 100035 | 2 |
| 102 | 100090 | 2 |
| 103 | 100005 | 2 |
| 103 | 100115 | 2 |
+-----+----------+----------+
```
Desired Result
```
+-----+----------+----------+
| id | trans_id | count_t |
+-----+----------+----------+
| 101 | 100001 | 1 |
| 101 | 100059 | 2 |
| 101 | 100061 | 3 |
| 102 | 100030 | 1 |
| 102 | 100035 | 2 |
| 102 | 100090 | 3 |
| 103 | 100005 | 1 |
| 103 | 100115 | 2 |
+-----+----------+----------+
```
SQL Version:
MySQL 5.6.32-78.1
---
**UPDATE:**
I added a **nested query** and a **GROUP BY** function to my code but it doesn't seem to count properly.
My NEW code is
```
SELECT
id,
time,
next_time,
(SELECT COUNT(1) FROM ecms.customer c1
LEFT JOIN ecms.sales_order so1 ON so1.customer_id = c1.id
WHERE c1.id = t.id AND so1.date_created <= t.time) as count_t
FROM(
SELECT
c.id,
so.date_created as time,
(
SELECT
MIN(so1.date_created)
FROM ecms.customer c1
LEFT JOIN ecms.sales_order so1 ON so1.customer_id = c1.id
WHERE c1.id = c.id
AND so1.date_created > so.date_created
AND IF((TIME_TO_SEC(TIMEDIFF(so1.date_created,
so.date_created))/360)>=60,1,0)=1
) as next_time
FROM ecms.customer c
LEFT JOIN ecms.sales_order so ON so.customer_id = c.id
LEFT JOIN ecms.sales_order_item soi ON soi.sales_order_id = so.id
LEFT JOIN ecms.product p ON p.id = soi.product_id
LEFT JOIN ecms.history h ON h.transaction_id = so.transaction_id
GROUP BY c.id, next_time
) as t
WHERE id = 7941
```
Sample Result would be
```
+-----+----------+-----------+----------+
| id | time | next_time | count_t |
+-----+----------+-----------+----------+
| 7941 | 100001 | 100061 | 1 |
| 7941 | 100061 | 100121 | 4 |
| 7941 | 100121 | 100181 | 7 |
| 7941 | 100181 | 100241 | 8 |
| 7941 | 100241 | 100301 | 16 |
| 7941 | 100301 | 100361 | 21 |
| 7941 | 100361 | 100421 | 45 |
| 7941 | 100421 | NULL | 69 |
+------+---------+-----------+----------+
```
Sample Result Desired
```
+-----+----------+-----------+----------+
| id | time | next_time | count_t |
+-----+----------+-----------+----------+
| 7941 | 100001 | 100061 | 1 |
| 7941 | 100061 | 100121 | 2 |
| 7941 | 100121 | 100181 | 3 |
| 7941 | 100181 | 100241 | 4 |
| 7941 | 100241 | 100301 | 5 |
| 7941 | 100301 | 100361 | 6 |
| 7941 | 100361 | 100421 | 7 |
| 7941 | 100421 | NULL | 8 |
+------+---------+-----------+----------+
``` | 2018/07/04 | [
"https://dba.stackexchange.com/questions/211303",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/154178/"
] | That's not a bug. That's 'move to standard'.
Do not fix this problem by change server's SQL Mode. Fix it by altering the queries which uses partial `GROUP BY` expressions.
Details can be read in [MySQL Handling of GROUP BY](https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html). | You should add it to your config file, for example: /etc/my.cnf:
```
sql_mode='...'
```
Do note that this is not a bug, this is the way it is supposed to work. By disabling this check you risk getting indeterministic answers from your queries. A small example:
```
create table t (x int not null, y int not null, z int not null);
insert into t (x,y,z) values (1,1,2),(1,2,3);
```
What would be the result of:
```
select x,y,max(z) from t group by x
```
? MAX(z) in the group x is 3. What value should y have, 1 or 2? This would be logically valid if y were functionally dependent on x, but in this case, there is neither a constraint that guarantees it nor data that conforms to it. |
60,362 | My requirement is to add two binary numbers, say "1001" and "0101" as `binary1` and `binary2`.
```
Partial Class Default2
Inherits System.Web.UI.Page
Dim carry As Boolean = False ' Boolean variable to hold the carry if occured
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim binary1 As String = TextBox1.Text 'First binary number
Dim binary2 As String = TextBox2.Text 'Second binary number
Dim result As String = "" 'to store the result
For i As Integer = Len(binary1 ) - 1 To 0 Step -1
result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function
Next
If carry = True Then
result = "1" & result 'if a carry remains add it to the MSB
End If
MsgBox(rslt) 'Display the result
End Sub
Public Function bin_add(b1 As Boolean, b2 As Boolean) As String'Function which performs the addition of each single bits form the two inputs which is passed from the calling function
Dim result As Boolean
If b1 AndAlso b2 = True Then 'both values are 1/true
If carry = True Then
result = True
carry = True
Else
result = False
carry = True
End If
ElseIf b1 = False And b2 = False Then 'Both are 0/false
If carry = True Then
result = carry
carry = False
Else
result = False
carry = False
End If
Else
If carry = True Then
result = False
carry = True
Else
result = True
carry = False
End If
End If
If result = True Then
Return "1" 'return 1 for Boolean true
Else
Return "0" 'return 0 for Boolean false
End If
End Function
Private Function getbyte(s As String, ByVal place As Integer) As String'Function for getting each individual letters from the input string. i got it from net.
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function
End Class
```
**Notes:**
* It gives good results for me only if the no. of digits in both numbers are the same.
**Question:**
How can I improve the code? Especially, how can I reduce the length of code? | 2014/08/18 | [
"https://codereview.stackexchange.com/questions/60362",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/51382/"
] | For now, let's ignore the fact that there are easier ways to add binary numbers. There are other issues with this code.
---
>
>
> ```
> Inherits System.Web.UI.Page
>
> ```
>
>
Why is code that adds binary numbers inheriting from a UI class? There's no need for this. Separate the concerns and create a module for this code instead.
---
`carry` is scoped to the class level. This is a symptom of problems in this code.
>
>
> ```
> Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
> Dim binary1 As String = TextBox1.Text 'First binary number
> Dim binary2 As String = TextBox2.Text 'Second binary number
> Dim result As String = "" 'to store the result
> For i As Integer = Len(binary1 ) - 1 To 0 Step -1
> result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function
> Next
> If carry = True Then
> result = "1" & result 'if a carry remains add it to the MSB
> End If
> MsgBox(rslt) 'Display the result
> End Sub
>
> ```
>
>
Getting the values from the UI makes sense, but then you loop over `bin_add`, which obviously doesn't actually add anything, or you wouldn't need to loop or have a class variable. All of this logic should happen inside of `bin_add`.
`bin_add` should take in two strings, handle all of the logic, and return a single string representing the output. While I'm at it, methods should have PascalCased verb-noun names. This method should be called `AddBinary` and I will refer to it as such for the rest of the review.
As I said earlier, I wouldn't expect a Function that adds binary numbers to take in Boolean values. I would rather it actually take in a byte and overload the method to handle string representation, but I'm lazy and you don't seem to need all that.
Putting it all together, the signature line
>
>
> ```
> Public Function bin_add(b1 As Boolean, b2 As Boolean) As String
>
> ```
>
>
Should look like this.
```
Public Function AddBinary(value1 as String, value2 as String) As String
```
Implementing this change will be left as an exercise for the reader. | Once the user input is validated to be ones or zeros in the textboxes the conversion / addition is simple. Using the OP's input parameters:
```
'verify user input as a binary digit
For Each c As Char In TextBox1.Text
If Not (c = "0"c OrElse c = "1"c) Then
Stop 'not a binary digit - error handling needed
Exit Sub
End If
Next
For Each c As Char In TextBox2.Text
If Not (c = "0"c OrElse c = "1"c) Then
Stop 'not a binary digit - error handling needed
Exit Sub
End If
Next
'http://msdn.microsoft.com/en-us/library/1k20k614%28v=vs.110%29.aspx
Dim num1 As Integer = Convert.ToInt32(TextBox1.Text, 2)
Dim num2 As Integer = Convert.ToInt32(TextBox2.Text, 2)
Dim answer As Integer = num1 + num2
```
One of the overloads to Convert.ToInt32 accepts a base(radix) to be used in the conversion. |
40,592,103 | I am new in OpenGL. I created an OpenGL object and display it on the screen. I wan to ask how to get the position of the OpenGL object ?
Because I want to detect whether the OpenGL object is being collided with others objects or not.
So, how do I get the position (point x, point y) of the OpenGL object in Android. | 2016/11/14 | [
"https://Stackoverflow.com/questions/40592103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600150/"
] | First, you are violating the [DRY principle](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Instead of having separate variables for each set of products, store each of them in a sort of dictionary structure such as an object.
This would be my **first revision**.
```
var dict = {
a: ["V1-1: 1/4-4 900-4500#", "V1-1 Light-Weight Compact Solution", "V1-2: 1/2-36 150-600#","V1-3: 1/2-2, 150-600#","V1-4: 4-36 900-4500#"],
b: ['NexTech® R Series Valves','NexTech® E Series Valves','TrunTech® Valves', 'PulseJet Valves'],
c: ['Coking Isolation Valves','Coking Switch Valves'],
d: ['Three-Way Valves','Four-Way Valves'],
e: ['IsoTech®'],
f: ['Xactrol® Mark I Valves', 'Xactrol® Mark II Valves', 'Xactrol® Mark III Valves'],
g: ['PulseJet Valves','Ecopack®'],
h: ['AbrasoCheck® Slurry Check Valves', 'AbrasoTech® Slurry Ball Valves'],
i: ['Electronic Relief Valves'],
j: ['ValvXpress® Automated Valve Packages'],
k: ['Acid Injection Valves'],
l: ['Double Block-and-Bleed Valves'],
m: ['Turbine Bypass System'],
n: ['Check Valves'],
o: ['ValvXpress®','EcoPack®','ValvPerformance Testing®','Slurry Valves','Acid Injection Valves','Double Block-and-bleed Valves','Rhinoite® Hardfacing','Switch Valves','HVOF RiTech®','Cryogenic Valves']
};
$(function() {
// attach an 'change' event handler
// THEN trigger the event handler to call the function from the start
$('#cat').change(populateSelect).trigger('change');
});
function populateSelect() {
// this refers to the current element
// get the selected value
var cat = this.value;
// always a good idea to cache your element that you will be re-using (maybe move it outside the function too)
var items = $('#item');
items.html('');
// check if there are products associated with the selected value
if (dict.hasOwnProperty(cat)) {
// show products
dict[cat].forEach(function(product) {
items.append('<option>' + product + '</option>');
});
}
}
```
Now, in terms of your actual problem. We can modify the arrays, so that it also includes a url. You could have arrays of arrays for simplicity e.g.
>
> a: [["V1-1: 1/4-4 900-4500#", "url"], ["V1-1 Light-Weight Compact
> Solution", "url"], ...]
>
>
>
or arrays of objects for readability e.g.
>
> a: [{ name: "V1-1: 1/4-4 900-4500#", url: "url" }, { name: "V1-1
> Light-Weight Compact Solution", url: "url"}, ...]
>
>
>
So here's my **second revision** using arrays of objects. (I shorten the dictionary just to show illustration).
```
var dict = {
a: [
{
name: "V1-1: 1/4-4 900-4500#",
url: "http://www.bing.com"
},
{
name: "V1-1 Light-Weight Compact Solution",
url: "http://www.google.com"
},
{
name: "V1-2: 1/2-36 150-600#",
url: "http://www.yahoo.com"
},
],
b: [
{
name: 'NexTech® R Series Valves',
url: 'http://www.nike.com'
},
{
name: 'NexTech® E Series Valves',
url: 'http://www.walmart.com'
}
],
c: [{
name: 'Coking Isolation Valves',
url: 'http://www.adidas.com'
}],
};
$(function() {
// cache element so that you don't re-search the DOM multiple times
var $items = $('#item');
$('#cat').change(populateSelect).trigger('change');
$('#goto').click(redirectToURL);
// place the functions within the document.ready so that they have access to the cached elements
function populateSelect() {
$items.html('');
if (dict.hasOwnProperty(this.value)) {
dict[this.value].forEach(function(product) {
// you can store the URL in HTML5-data attribute to use it later
$items.append('<option data-url="' + product.url + '">' + product.name +'</option>');
});
}
}
function redirectToURL() {
// get the URL from the selected option's data-url and redirect to it
window.location.href = $items.find(':selected').data('url');
}
});
```
Technically, you are not "submitting" a form but just "redirecting" -- so I would not use a submit button but just an ordinary button.
```
<input type="button" id="goto" value="submit">
```
Below is a [demo](http://codepen.io/anon/pen/KNMWBa) of the final revision. You'll have to fix the dictionary. | You can pass these selected values to a product page using the markup you already have, just add an action to the form
```
<form action="yourpageurl" method="get">
```
You need to write your product page to dynamically show whatever information is necessary or redirect based on the parameters passed through. As we have selected the get method above, the parameters would be passed as part of a query string (part of the url) but you could also use POST. |
40,592,103 | I am new in OpenGL. I created an OpenGL object and display it on the screen. I wan to ask how to get the position of the OpenGL object ?
Because I want to detect whether the OpenGL object is being collided with others objects or not.
So, how do I get the position (point x, point y) of the OpenGL object in Android. | 2016/11/14 | [
"https://Stackoverflow.com/questions/40592103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600150/"
] | First, you are violating the [DRY principle](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Instead of having separate variables for each set of products, store each of them in a sort of dictionary structure such as an object.
This would be my **first revision**.
```
var dict = {
a: ["V1-1: 1/4-4 900-4500#", "V1-1 Light-Weight Compact Solution", "V1-2: 1/2-36 150-600#","V1-3: 1/2-2, 150-600#","V1-4: 4-36 900-4500#"],
b: ['NexTech® R Series Valves','NexTech® E Series Valves','TrunTech® Valves', 'PulseJet Valves'],
c: ['Coking Isolation Valves','Coking Switch Valves'],
d: ['Three-Way Valves','Four-Way Valves'],
e: ['IsoTech®'],
f: ['Xactrol® Mark I Valves', 'Xactrol® Mark II Valves', 'Xactrol® Mark III Valves'],
g: ['PulseJet Valves','Ecopack®'],
h: ['AbrasoCheck® Slurry Check Valves', 'AbrasoTech® Slurry Ball Valves'],
i: ['Electronic Relief Valves'],
j: ['ValvXpress® Automated Valve Packages'],
k: ['Acid Injection Valves'],
l: ['Double Block-and-Bleed Valves'],
m: ['Turbine Bypass System'],
n: ['Check Valves'],
o: ['ValvXpress®','EcoPack®','ValvPerformance Testing®','Slurry Valves','Acid Injection Valves','Double Block-and-bleed Valves','Rhinoite® Hardfacing','Switch Valves','HVOF RiTech®','Cryogenic Valves']
};
$(function() {
// attach an 'change' event handler
// THEN trigger the event handler to call the function from the start
$('#cat').change(populateSelect).trigger('change');
});
function populateSelect() {
// this refers to the current element
// get the selected value
var cat = this.value;
// always a good idea to cache your element that you will be re-using (maybe move it outside the function too)
var items = $('#item');
items.html('');
// check if there are products associated with the selected value
if (dict.hasOwnProperty(cat)) {
// show products
dict[cat].forEach(function(product) {
items.append('<option>' + product + '</option>');
});
}
}
```
Now, in terms of your actual problem. We can modify the arrays, so that it also includes a url. You could have arrays of arrays for simplicity e.g.
>
> a: [["V1-1: 1/4-4 900-4500#", "url"], ["V1-1 Light-Weight Compact
> Solution", "url"], ...]
>
>
>
or arrays of objects for readability e.g.
>
> a: [{ name: "V1-1: 1/4-4 900-4500#", url: "url" }, { name: "V1-1
> Light-Weight Compact Solution", url: "url"}, ...]
>
>
>
So here's my **second revision** using arrays of objects. (I shorten the dictionary just to show illustration).
```
var dict = {
a: [
{
name: "V1-1: 1/4-4 900-4500#",
url: "http://www.bing.com"
},
{
name: "V1-1 Light-Weight Compact Solution",
url: "http://www.google.com"
},
{
name: "V1-2: 1/2-36 150-600#",
url: "http://www.yahoo.com"
},
],
b: [
{
name: 'NexTech® R Series Valves',
url: 'http://www.nike.com'
},
{
name: 'NexTech® E Series Valves',
url: 'http://www.walmart.com'
}
],
c: [{
name: 'Coking Isolation Valves',
url: 'http://www.adidas.com'
}],
};
$(function() {
// cache element so that you don't re-search the DOM multiple times
var $items = $('#item');
$('#cat').change(populateSelect).trigger('change');
$('#goto').click(redirectToURL);
// place the functions within the document.ready so that they have access to the cached elements
function populateSelect() {
$items.html('');
if (dict.hasOwnProperty(this.value)) {
dict[this.value].forEach(function(product) {
// you can store the URL in HTML5-data attribute to use it later
$items.append('<option data-url="' + product.url + '">' + product.name +'</option>');
});
}
}
function redirectToURL() {
// get the URL from the selected option's data-url and redirect to it
window.location.href = $items.find(':selected').data('url');
}
});
```
Technically, you are not "submitting" a form but just "redirecting" -- so I would not use a submit button but just an ordinary button.
```
<input type="button" id="goto" value="submit">
```
Below is a [demo](http://codepen.io/anon/pen/KNMWBa) of the final revision. You'll have to fix the dictionary. | I think that I would take this approach. Store an array of objects, each of which contain the product name and the appropriate url for that product. Then (assuming you are using a form) you can change the action of form to the value of the selected option.
Side notes: It's recommended to use the bracket notation (`[]`) instead of `new Array()`. You can read more about this [here](https://stackoverflow.com/a/1800603/6069012) and at other sources. Also, since your `cat` will only ever be one value when you're in the `populatSelect` function, you should use the `if..else if..else if..` structure. In the case of a match, you will leave the `if..else if` expression completely, saving time. Whereas if you kept `if..if..if..`, you would have to evaluate all of them even if you found a match right away.
**EDIT**: You should definitely follow the concepts that some of the other answers are using (namely using a dictionary, which will allow you to retrieve the correct category without all the `if` checks).
```
var cats = {
a: [
{ product: 'V1-1: 1/4-4 900-4500#', url: '<product url>' },
{ product: 'V1-1 Light-Weight Compact Solution', url: '<product url>' },
{ product: 'V1-2: 1/2-36 150-600#', url: '<product url>' },
{ product: 'V1-3: 1/2-2, 150-600#', url: '<product url>' },
{ product: 'V1-4: 4-36 900-4500#', url: '<product url>' }
],
b: [
{ product: 'NexTech® R Series Valves', url: '<product url>'},
{ product: 'NexTech® E Series Valves', url: '<product url>' },
{ product: 'TrunTech® Valves', url: '<product url>' },
{ product: 'PulseJet Valves', url: '<product url>' }
],
// same for the rest of your categories
};
populateSelect();
$(function() {
$('#cat').change(function(){
populateSelect();
});
});
function populateSelect(){
var cat = $('#cat').val();
$('#item').html('');
appendProducts(cats[cat]);
}
function appendProducts(arr) {
arr.forEach(function(t) {
$('#item').append('<option value="' + t.url + '">'+ t.product +'</option>');
});
}
$('form').submit(function() {
this.action = $('select').find(':selected').val();
});
``` |
25,657 | Found a sentence,
>
> 人間の身体能力は吸血鬼の**7分の1**しかありません
>
>
>
Is this how you write ratios in Japanese? | 2015/07/13 | [
"https://japanese.stackexchange.com/questions/25657",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/10345/"
] | Not exactly (as several have commented). This is how you talk about *fractions* in Japanese:
>
> 7分の1 → 1/7
>
>
>
Literally, you can think about it as 'one part of seven'. It is not a ratio, i.e. 'one part to seven parts', as that equates to 1/8. | Yes.
>
> n / m = n : m
>
>
>
is written
>
> m分のn,
>
>
>
where "m" and "n" are positive integers.
BTW, is
>
> 人間の身体能力は、吸血鬼の身体能力の7分の1しかありません
>
>
>
more acceptable for you?
**\* added \***
I just learned that the notation n : m confuses some people.
Here is what Hans Lundmark pointed out to me in regard of the usage of n : m. I hope this helps to resolve their confusion.
>
> You have good historical reasons for interpreting n:m as n/m.
>
>
> From <http://jeff560.tripod.com/operation.html>:
>
>
> The colon (:) was used in 1633 in a text entitled Johnson Arithmetik; In two Bookes (2nd ed.: London, 1633). However Johnson only used the symbol to indicate fractions (for example three-fourths was written 3:4); he did not use the symbol for division "dissociated from the idea of a fraction" (Cajori vol. 1, page 276).
>
>
> Gottfried Wilhelm Leibniz (1646-1716) used : for both ratio and division in 1684 in the Acta eruditorum (Cajori vol. 1, page 295).
>
>
>
As for the said excerpt, it reads "The (average?) physical ability of humankind is one-seventh of that of vampire."
**\* added (again) \***
In view of the *established* usage as described in <http://www.bradford.ac.uk/wimba-files/msu-course/media/ratio%20teaching%20new.pdf> , the assertion by @Earthliŋ
>
> n : m is usually the notation for "n parts in (n+m) parts vs. m parts in (n+m) parts", so 1:7 would correspond to 1/8 and 7/8
>
>
>
should read
>
> In the context that something is to be divided into n : m, it can be considered as "n parts in (n+m) parts vs. m parts in (n+m) parts", so 1:7 can be specified as the pair (1/8, 7/8) if needed.
>
>
> |
25,657 | Found a sentence,
>
> 人間の身体能力は吸血鬼の**7分の1**しかありません
>
>
>
Is this how you write ratios in Japanese? | 2015/07/13 | [
"https://japanese.stackexchange.com/questions/25657",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/10345/"
] | Not exactly (as several have commented). This is how you talk about *fractions* in Japanese:
>
> 7分の1 → 1/7
>
>
>
Literally, you can think about it as 'one part of seven'. It is not a ratio, i.e. 'one part to seven parts', as that equates to 1/8. | Yes, 「7分の1」 means same as 1:7 mathematically.
1:7 = (1/8):(7/8) = (1/8)/(7/8) = (1/8)x(8/7) = 8/56 = 1/7
However, in Japan, kids are taught that 1:7 is 「[比]{ひ}」 and 1/7 is 「[分数]{ぶんすう}」. I guess that 「比」 is translated as "ratios", and 「分数」 is translated as "fractions" generally. So, Japanese people tend to think that 1/7 is not a ratio, maybe.
In English, both 1:7 and 1/7 can be read "one to seven", right? And both 1:7 and 1/7 are called "ratio" in some cases, maybe? (Sorry, if my knowledge about English is wrong.) But in Japanese, each of them has its own way to be read.
>
> 1:7 is read 「[1]{いち}[対]{たい}[7]{なな}」.
>
>
>
>
> 1/7 is read 「[7]{なな}[分]{ぶん}の[1]{いち}」.
>
>
>
There are other ways to express proportions in Japanese. For example,
>
> 1/10 is read 「[1]{いち}[割]{わり}」 = 10%
>
>
> 2/10 is read 「[2]{に}[割]{わり}」 = 20%
>
>
>
Which word should be used is up to the situation and context.
If your "ratio" means both 1:7 and 1/7, I would answer that there are several ways to write ratio in Japanese, and 「7分の1」 is one of them. So, yes. |
62,216,682 | Suppose we have the following class:
```py
from __future__ import annotations
class BaseSwallow:
# Can't get the ref to `BaseSwallow` at runtime
DerivedSwallow = NewType('DerivedSwallow', BaseSwallow)
def carry_with(self, swallow: DerivedSwallow):
self.carry()
swallow.carry()
def carry(self):
pass
class AfricanSwallow(BaseSwallow): pass
godOfSwallows = BaseSwallow()
africanSwallow = AfricanSwallow()
africanSwallow.carry_with(godOfSwallows) # Should fail at static typing
```
I want to enforce that `carry_with` should only be called with instances of classes **derived from** `BaseSwallow`, so I use `NewType` to do that [like the doc says](https://docs.python.org/3/library/typing.html#distinct).
However, `NewType` needs a reference to the base class object to work, and I don't have access to that at runtime. Before runtime, I have "access" to `BaseSwallow` thanks to the `annotations` module but it will still fail when running.
I'm aware that using an Abstract Base Class for `BaseSwallow` is the best thing to do here in most cases, but I can't do that [for various reasons](https://stackoverflow.com/q/59638421/5989906).
Any idea ? | 2020/06/05 | [
"https://Stackoverflow.com/questions/62216682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5989906/"
] | I don't think there's a way to express "all subclasses of `T` excluding `T`" using type annotations. If you have a fixed set of subclasses you could use a `Union` type to capture them all, but that's probably not what you want. I think [Sam's answer](https://stackoverflow.com/a/62220325/4909228) is your best bet: just use the `BaseSwallow` base class instead of crafting a complicated type to rule out the base class itself.
Also, I think you misunderstood the usage for `NewType`. `NewType` is used to create an alias of a type that requires explicit conversion. For example:
```py
URL = NewType('URL', str)
def download(url: URL): ...
link_str = "https://..." # inferred type is `str`
link_url = URL(link_str) # inferred type is `URL`
download(link_str) # type error
download(link_url) # correct
```
---
**Edit:** If you don't mind a little bit of overhead, you can achieve this with an additional level of inheritance. Create a subtype of `BaseSwallow` (named `Swallow` for convenience), and have all the derived classes inherit `Swallow` instead of `BaseSwallow`. This way, you can annotate the `carry_with` method using the `Swallow` type:
```py
class BaseSwallow:
def carry_with(self, swallow: 'Swallow'): # string as forward reference
self.carry()
swallow.carry()
def carry(self):
pass
class Swallow(BaseSwallow): pass # dummy class to serve as base
class AfricanSwallow(Swallow): pass
godOfSwallows = BaseSwallow()
africanSwallow = AfricanSwallow()
africanSwallow.carry_with(godOfSwallows) # mypy warns about incompatible types
``` | can you just mark `carry` as an [`abstractmethod`](https://docs.python.org/3/library/abc.html#abc.abstractmethod)? for example, something like:
```
import abc
class BaseSwallow:
def carry_with(self, swallow: BaseSwallow) -> None:
self.carry()
swallow.carry()
@abc.abstractmethod
def carry(self) -> None:
raise NotImplementedError('implementation of carry needed')
```
derived classes could then implement the method, but because the base class didn't attempts to instantiate it would cause type checking to fail saying that `BaseSwallow` is an abstract class due to missing attribute `carry` |
2,830,707 | i need to get images from a webpage source.
i can use cfhttp method get and use htmleditformat() to read the html from that page, now i need to loop through the content to get all image url's(src)
can i use rematch() or refind() etc... and if yes how??
please help!!!!!
if im not clear i can try to clarify.. | 2010/05/13 | [
"https://Stackoverflow.com/questions/2830707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270737/"
] | [It can be very difficult to reliably parse html with regex.](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) | Use a browser and jQuery to 'query' out all the img tag from the DOM might be easier... |
2,830,707 | i need to get images from a webpage source.
i can use cfhttp method get and use htmleditformat() to read the html from that page, now i need to loop through the content to get all image url's(src)
can i use rematch() or refind() etc... and if yes how??
please help!!!!!
if im not clear i can try to clarify.. | 2010/05/13 | [
"https://Stackoverflow.com/questions/2830707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270737/"
] | Here's a function that will probably trip up on a lot of bad cases, but might work if you just need something quick and dirty.
```
<cffunction name="getSrcAttributes" access="public" output="No">
<cfargument name="pageContents" required="Yes" type="string" default="" />
<cfset var continueSearch = true />
<cfset var cursor = "" />
<cfset var startPos = 0 />
<cfset var finalPos = 0 />
<cfset var images = ArrayNew(1) />
<cfloop condition="continueSearch eq true">
<cfset cursor = REFindNoCase("src\=?[\""\']", arguments.pageContents, startPos, true) />
<cfif cursor.pos[1] neq 0>
<cfset startPos = (cursor.pos[1] + cursor.len[1]) />
<cfset finalPos = REFindNoCase("[\""\'\s]", arguments.pageContents, startPos) />
<cfset imgSrc = Mid(arguments.pageContents, startPos, finalPos - startPos) />
<cfset ArrayAppend(images, imgSrc) />
<cfelse>
<cfset continueSearch = false />
</cfif>
</cfloop>
<cfreturn images>
</cffunction>
```
Note: I can't verify at the moment that this code works. | Use a browser and jQuery to 'query' out all the img tag from the DOM might be easier... |
52,654,797 | I am working with django and using angularjs. I made a request which responded with an object containing the name, price and date this input was modified.
My html has the following `{{price_level.modified }}` providing me with `2018-01-16T10:15:34.401839Z`.
Here is the data that I am getting when I console.log the data
`created: "2017-06-02T05:01:17.803045Z"
fs_charge: 10
id: 595
locked: false
modified: "2018-02-06T07:36:21.517414Z"
moq: 30
moq_price: 60` | 2018/10/04 | [
"https://Stackoverflow.com/questions/52654797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9766402/"
] | Your result appears to be a string in YYYY-mm-dd format with time, so just slice it.
```
{{price_level.modified[:10] }}
``` | If you just want `YYYY-MM-DD` you could do a substring from position 0 through 9.
Example in Python `dateStr[:10]` |
71,500 | The majority of primates have really thick nails, though not as broad or flat as humans'. However, marmosets have 18 claws, and only their big toes have nails. What differences in evolutionary pressures caused this? And how does the structural relationship between marmosets' germinal matrices and their distal phalanxes differ from other primates, so they can grow claws? | 2018/03/18 | [
"https://biology.stackexchange.com/questions/71500",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/41155/"
] | Since marmosets and tamarins are considered the most primitive primates, we can't assume that evolutionary pressure led to the development of claws. Rather, it's accepted that claws disappeared as primates adapted to an arboreal lifestyle. So the question is really "Why did marmosets not completely lose their claws?"
The clues to the answer lie in their unusually large incisors and disgestive system. The marmoset occupies an evolutionary niche where they rely heavily (20-70% of total diet) on exudates (sap, resin, etc.) from trees. Their claws, and incisors allow them to claw/chew holes in the bark to get at the exudates, while a specially adapted large intestine allows them to digest this food. The advantage of exudates is they are not seasonal, offering the marmoset a relatively stable year-round food supply.
Other primates enjoyed the evolutionary benefits of tool use by losing their claws and gaining opposable thumbs (which marmosets don't have). I've come across no papers that describe a different phlange structure for marmosets and other primates, and there doesn't necessarily need to be one.
Most of this information came from the University of Wisconsin's Primate Research Center:
<http://pin.primate.wisc.edu/factsheets/entry/common_marmoset>
Edited to add (since I can't comment): One way to deduce how different features evolved is to look at phylogenetic trees. There are many out there, but I pulled this one from J.R. Roede et al. *Redox Biology* 1 (2013) 387-393.
[](https://i.stack.imgur.com/vEv4A.png)
If you look at this simple tree, you'll see that marmosets diverged from humans on a time frame where it's possible they kept their claws instead of reacquiring this trait (it would be unusual, but not impossible, for this to happen). One thing you can do is dive deeper into the phylogeny, square this up with how primate hands evolved, and see if the split of marmosets from the rest of the primates happened when nails began to evolve. | Ill try and research this later and add references, it's a bit of a draft version while im on laptop in the car, A good place to think but not to write and surf from!
It's probably best viewed as a vestigial trait, made redundant by monkey's prehensile grasp, and related to their strong social and hierarchical behaviour. Indeed the flat nails seem to be a progressive arrival transitioning from lemures/aye-ayes to larger prehensile primates.
Humans have the most vestigial nails, to protect the fingers and for fine fingertip manipulation, and earlier mammals and non-prehensile herbivores find advantage of pointy nails for grasping bark and defense, to decorticate husks rinds, to dig, and other tasks.
We can imagine if nails had become reduced vestigial tools in a different way to what they did, imagine that they had tapered into bulbous tips
We can consider other alternatives that could have evolved, but the flat shape seems most fitting for a finger protection and versatility.
Also consider that large monkeys are belligerent, for example baboons which are very fierce, and monkeys that have sharp teeth which they can use in combat. If they had claws to do demonstrative fighting, it may be less beneficial for the group, and nails would generally discourage the mostly demonstrative social competition which is found in most social and rutting creatures. It demonstrates the contrast of vestigial carnivorous traits of some primates compared to the herbivorous organs of the largest ones.
With regards to the structure, perhaps it's best to check other mammals fingernails to see that it's only a small proportional and dimensional change.
Conical nails require a different shaped matrix which doesn't fit on top of fingertips for grooming and find dexterity, to alight with the bone, the nail matrix surrounds the top of the finger bone, so it's easy to broaden and thin out.
It's matrix cells that generate keratin which is not structurally affixed to the bone, which means it can regenerate efficiently, while it has structural weakness for lifting bodyweight. For carnivores, the stress on the nail is reduced by the cutting edge. The structural difference is not very pronounced. web resources for primate nail anatomy aren't abundant but you can find trees of primate hand anatomy. |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | Triggers are included in the implicit transaction required for insert, update, and delete statements. Because you are connecting to a linked server within a transaction, SQL Server promotes it to a Distributed Transaction.
You'll need to configure MSDTC, you can either open MMC and load the MSDTC plugin or use the following script to open inbound and outbound transactions.
<https://technet.microsoft.com/en-us/library/cc731495.aspx>
```
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccess
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessTransactions
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessInbound
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessOutbound
PAUSE
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccess /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessTransactions /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessInbound /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessOutbound /t REG_DWORD /d 1
PAUSE
net stop MSDTC
net start MSDTC
PAUSE
``` | My issue was resolved by disabling a conflicting service/driver. I disabled all of my HP services (HP App Helper, HP CASL, HP System Info), and now it works fine. |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | Triggers are included in the implicit transaction required for insert, update, and delete statements. Because you are connecting to a linked server within a transaction, SQL Server promotes it to a Distributed Transaction.
You'll need to configure MSDTC, you can either open MMC and load the MSDTC plugin or use the following script to open inbound and outbound transactions.
<https://technet.microsoft.com/en-us/library/cc731495.aspx>
```
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccess
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessTransactions
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessInbound
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessOutbound
PAUSE
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccess /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessTransactions /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessInbound /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessOutbound /t REG_DWORD /d 1
PAUSE
net stop MSDTC
net start MSDTC
PAUSE
``` | I ran into the same error, however it wasn't as simple as the Distributed Transaction Coordinator service from not running. I received a driver update automatically through windows that was causing issues with COM+ and not allowing MSDTC to communicate properly even though the MSDTC service was running. In my case, it was an issue with HP hotkey drivers but in researching I found other reports of issues with audio drivers from other manufacturers causing this as well.
To check to see if you have a similar issue, launch Component Services (dcomcnfg.exe), then expand Component Services > Computers > My Computer, from here click on 'COM+ Applications' to see if an error will pop-up with "COM+ unable to talk to Microsoft Distributed Transaction Coordinator" or there will be a red error over the icon for My Computer in the navigation.
The fix for me was to disable the 'HP Hotkey Service" and "HotKeyServiceUWP" services. Once those were disable, MSDTC immediately started working. |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | I ran into the same error, however it wasn't as simple as the Distributed Transaction Coordinator service from not running. I received a driver update automatically through windows that was causing issues with COM+ and not allowing MSDTC to communicate properly even though the MSDTC service was running. In my case, it was an issue with HP hotkey drivers but in researching I found other reports of issues with audio drivers from other manufacturers causing this as well.
To check to see if you have a similar issue, launch Component Services (dcomcnfg.exe), then expand Component Services > Computers > My Computer, from here click on 'COM+ Applications' to see if an error will pop-up with "COM+ unable to talk to Microsoft Distributed Transaction Coordinator" or there will be a red error over the icon for My Computer in the navigation.
The fix for me was to disable the 'HP Hotkey Service" and "HotKeyServiceUWP" services. Once those were disable, MSDTC immediately started working. | I was having the same issue but for Azure SQL. (Just posting this here in case someone is having same issue with Azure SQL.)
It was because of the application intent being set with the readonly option (ApplicationIntent=ReadOnly) when connecting to the Azure SQL DB with Read Scale Out option enabled in Azure.
For a quick fix, we removed the ApplicationIntent=ReadOnly configuration from the application.
For a better idea about this along with the proper solution please follow the below link:
<https://techcommunity.microsoft.com/t5/azure-database-support-blog/lesson-learned-173-msdtc-on-server-xxxxx-is-unavailable/ba-p/2376529> |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | 'Distributed Transaction Coordinator' service was not running, So started service and changed service type to automatic too. | Recently this appeared as an issue on my work machine (Win 10, MSSQL 2016 SP2 Express). I do not have linked servers. This appeared from nothing. The MSDTC service is running, MSSQL works fine using the Mgmt Studio. However my .NET 4.7.1 Unit test app refuse to connect with the database with that "MSDTC on server '...' is unavailable" error.
The temporal workaround I found is to add "Enlist=False;" at the end of the connection string to avoid using MSDTC at all for the connection.
The source for this solution is a comment under this topic: <https://learn.microsoft.com/en-us/archive/blogs/distributedservices/intermittent-error-msdtc-on-server-servername-is-unavailable> |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | In my case, the service was **stopped**. solution: need to turn the MSDTC service on
1. go to **Services**. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
2. Find the service called '**Distributed Transaction Coordinator**' and
RIGHT CLICK (on it and select) > **Start**.
3. make this service to run **Automatically** for solving this issue permanently | Triggers are included in the implicit transaction required for insert, update, and delete statements. Because you are connecting to a linked server within a transaction, SQL Server promotes it to a Distributed Transaction.
You'll need to configure MSDTC, you can either open MMC and load the MSDTC plugin or use the following script to open inbound and outbound transactions.
<https://technet.microsoft.com/en-us/library/cc731495.aspx>
```
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccess
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessTransactions
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessInbound
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessOutbound
PAUSE
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccess /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessTransactions /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessInbound /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessOutbound /t REG_DWORD /d 1
PAUSE
net stop MSDTC
net start MSDTC
PAUSE
``` |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | 'Distributed Transaction Coordinator' service was not running, So started service and changed service type to automatic too. | I was having the same issue but for Azure SQL. (Just posting this here in case someone is having same issue with Azure SQL.)
It was because of the application intent being set with the readonly option (ApplicationIntent=ReadOnly) when connecting to the Azure SQL DB with Read Scale Out option enabled in Azure.
For a quick fix, we removed the ApplicationIntent=ReadOnly configuration from the application.
For a better idea about this along with the proper solution please follow the below link:
<https://techcommunity.microsoft.com/t5/azure-database-support-blog/lesson-learned-173-msdtc-on-server-xxxxx-is-unavailable/ba-p/2376529> |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | In my case, the service was **stopped**. solution: need to turn the MSDTC service on
1. go to **Services**. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
2. Find the service called '**Distributed Transaction Coordinator**' and
RIGHT CLICK (on it and select) > **Start**.
3. make this service to run **Automatically** for solving this issue permanently | Powershell solution:
```
Get-Service -Name MSDTC | Set-Service -StartupType Automatic
``` |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | In my case, the service was **stopped**. solution: need to turn the MSDTC service on
1. go to **Services**. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
2. Find the service called '**Distributed Transaction Coordinator**' and
RIGHT CLICK (on it and select) > **Start**.
3. make this service to run **Automatically** for solving this issue permanently | Recently this appeared as an issue on my work machine (Win 10, MSSQL 2016 SP2 Express). I do not have linked servers. This appeared from nothing. The MSDTC service is running, MSSQL works fine using the Mgmt Studio. However my .NET 4.7.1 Unit test app refuse to connect with the database with that "MSDTC on server '...' is unavailable" error.
The temporal workaround I found is to add "Enlist=False;" at the end of the connection string to avoid using MSDTC at all for the connection.
The source for this solution is a comment under this topic: <https://learn.microsoft.com/en-us/archive/blogs/distributedservices/intermittent-error-msdtc-on-server-servername-is-unavailable> |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | Triggers are included in the implicit transaction required for insert, update, and delete statements. Because you are connecting to a linked server within a transaction, SQL Server promotes it to a Distributed Transaction.
You'll need to configure MSDTC, you can either open MMC and load the MSDTC plugin or use the following script to open inbound and outbound transactions.
<https://technet.microsoft.com/en-us/library/cc731495.aspx>
```
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccess
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessTransactions
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessInbound
REG QUERY "HKLM\Software\Microsoft\MSDTC\Security" /v NetworkDtcAccessOutbound
PAUSE
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccess /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessTransactions /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessInbound /t REG_DWORD /d 1
REG ADD "HKLM\Software\Microsoft\MSDTC\Security" /f /v NetworkDtcAccessOutbound /t REG_DWORD /d 1
PAUSE
net stop MSDTC
net start MSDTC
PAUSE
``` | I was having the same issue but for Azure SQL. (Just posting this here in case someone is having same issue with Azure SQL.)
It was because of the application intent being set with the readonly option (ApplicationIntent=ReadOnly) when connecting to the Azure SQL DB with Read Scale Out option enabled in Azure.
For a quick fix, we removed the ApplicationIntent=ReadOnly configuration from the application.
For a better idea about this along with the proper solution please follow the below link:
<https://techcommunity.microsoft.com/t5/azure-database-support-blog/lesson-learned-173-msdtc-on-server-xxxxx-is-unavailable/ba-p/2376529> |
29,414,250 | I get this weird error on SQL Server. And I cannot find solution in older posts.
I have this procedure:
```
create proc _upJM_SyncAll_test
as
begin
DECLARE @SQLString nvarchar(max)
set @SQLString = N'
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setitemprices'') where acSubject not in (select acSubject from _uvJM_SetSubj)
DELETE FROM OPENQUERY([LOCAL_MYSQL],''SELECT acSubject FROM _utjm_setsubj'') where acSubject not in (select acSubject from _uvJM_SetSubj)
update a
set acName2 = b.acName2,
acName3 = b.acName3,
acAddress = b.acAddress,
acPost = b.acPost,
acPostName = b.acPostName,
acCountry = b.acCountry,
acVATCodePrefix = b.acVATCodePrefix,
acCode = b.acCode,
anDaysForPayment = b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where 1=1
and ( isnull(a.acName2,'''') <> isnull(b.acName2,'''') OR
isnull(a.acName3,'''') <> isnull(b.acName3,'''') OR
isnull(a.acAddress,'''') <> isnull(b.acAddress,'''') OR
isnull(a.acPost,'''') <> isnull(b.acPost,'''') OR
isnull(a.acPostName,'''') <> isnull(b.acPostName,'''') OR
isnull(a.acCountry,'''') <> isnull(b.acCountry,'''') OR
isnull(a.acVATCodePrefix,'''') <> isnull(b.acVATCodePrefix,'''') OR
isnull(a.acCode,'''') <> isnull(b.acCode,'''') OR
isnull(a.anDaysForPayment,'''') <> isnull(b.anDaysForPayment,'''')
)
insert into OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') (acSubject, acName2, acName3, acAddress, acPost, acPostName, acCountry, acVATCodePrefix, acCode, anDaysForPayment)
select b.acSubject, b.acName2, b.acName3, b.acAddress, b.acPost, b.acPostName, b.acCountry, b.acVATCodePrefix, b.acCode, b.anDaysForPayment
from OPENQUERY([LOCAL_MYSQL],''SELECT * FROM _utjm_setsubj'') a right join _uvJM_SetSubj b on (a.acSubject = b.acSubject)
where a.acSubject is null '
EXECUTE sp_executesql @SQLString;
end
```
When I run procedure in management studio like this:
```
exec dbo._upJM_SyncAll_test
```
everything is OK. I get no error, sync is working just fine.
But when I put execute in trigger like this:
```
create trigger _utrJM_SetSubj on tHE_SetSubj after insert, update, delete
as
begin
exec dbo._upJM_SyncAll_test
end
```
I get this error:
>
> Msg 8501, Level 16, State 3, Procedure \_upJM\_SyncAll\_test, Line 54
>
> MSDTC on server 'server' is unavailable.
>
>
>
Procedure \_upJM\_SyncAll\_test has only 39 lines... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29414250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3185532/"
] | In my case, the service was **stopped**. solution: need to turn the MSDTC service on
1. go to **Services**. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
2. Find the service called '**Distributed Transaction Coordinator**' and
RIGHT CLICK (on it and select) > **Start**.
3. make this service to run **Automatically** for solving this issue permanently | I was having the same issue but for Azure SQL. (Just posting this here in case someone is having same issue with Azure SQL.)
It was because of the application intent being set with the readonly option (ApplicationIntent=ReadOnly) when connecting to the Azure SQL DB with Read Scale Out option enabled in Azure.
For a quick fix, we removed the ApplicationIntent=ReadOnly configuration from the application.
For a better idea about this along with the proper solution please follow the below link:
<https://techcommunity.microsoft.com/t5/azure-database-support-blog/lesson-learned-173-msdtc-on-server-xxxxx-is-unavailable/ba-p/2376529> |
42,736,765 | I have an assignment to create an ArrayList of employees, to provide a menu to add, find, and delete employee records. I successfully managed to implement all the functions on my own, but there is a small problem. When I use the find or delete option, the correct record is found or deleted properly but the code goes through the array list of elements and prints out employee not found till the correct record is found, this is unnecessary as it should only print the found record. I have limited experience with coding and I am writing my own code from scratch, please help me with this.
[enter image description here](https://i.stack.imgur.com/oJvQH.png)
I'VE ATTACHED MY CODE AND THE OUTPUT!
```js
else if (choice.equals("4")) {
System.out.println("Enter Name: ");
String fName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String fJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(fName) && myEList.get(i).getJob().equals(fJob)) {
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
} else {
System.out.print("Employee not found!");
}
}
} else if (choice.equals("5")) {
System.out.println("Enter Name: ");
String dName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String dJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(dName) && myEList.get(i).getJob().equals(dJob)) {
System.out.println("Employee record removed succesfully!");
myEList.remove(i);
} else {
System.out.print("Employee not found!");
}
}
}
```
This is the Output
Enter Option: 4
Enter Name: arjun
Enter Job Name: tester
Searching...
Employee not found!
Employee not found!
Employee found!
Name: arjun Job Name: tester Weekly Pay: 1200.0 | 2017/03/11 | [
"https://Stackoverflow.com/questions/42736765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6836874/"
] | ```
else
{
System.out.print("Employee not found!");
}
```
This has to be AFTER the for loops are over. You need a found flag. If after the loop is false then print the message | Remove this block of code
```
else
{
System.out.print("Employee not found!");
}
```
It should work fine after that.
---
**EDIT**
This is off topic but when you ask question next time remember to post image of output rather than typing it or posting a link.
And also avoid writing about your coding experience. Just be straight to the point. It just increases the size of question unnecessarily. :) |
42,736,765 | I have an assignment to create an ArrayList of employees, to provide a menu to add, find, and delete employee records. I successfully managed to implement all the functions on my own, but there is a small problem. When I use the find or delete option, the correct record is found or deleted properly but the code goes through the array list of elements and prints out employee not found till the correct record is found, this is unnecessary as it should only print the found record. I have limited experience with coding and I am writing my own code from scratch, please help me with this.
[enter image description here](https://i.stack.imgur.com/oJvQH.png)
I'VE ATTACHED MY CODE AND THE OUTPUT!
```js
else if (choice.equals("4")) {
System.out.println("Enter Name: ");
String fName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String fJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(fName) && myEList.get(i).getJob().equals(fJob)) {
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
} else {
System.out.print("Employee not found!");
}
}
} else if (choice.equals("5")) {
System.out.println("Enter Name: ");
String dName = myScanner.nextLine();
System.out.println("Enter Job Name: ");
String dJob = myScanner.nextLine();
for (int i = 0; i < myEList.size(); i++) {
if (myEList.get(i).getName().equals(dName) && myEList.get(i).getJob().equals(dJob)) {
System.out.println("Employee record removed succesfully!");
myEList.remove(i);
} else {
System.out.print("Employee not found!");
}
}
}
```
This is the Output
Enter Option: 4
Enter Name: arjun
Enter Job Name: tester
Searching...
Employee not found!
Employee not found!
Employee found!
Name: arjun Job Name: tester Weekly Pay: 1200.0 | 2017/03/11 | [
"https://Stackoverflow.com/questions/42736765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6836874/"
] | 1. Create a variable to track if employee not found before the loops
2. In the if statements sent it to false if found.
3. At the end of the loop check if it is true. Then print the message "Employee not found"
See the sample below
```
boolean notFound = true;
for(int i=0;i<myEList.size();i++)
{
if(myEList.get(i).getName().equals(fName)&&myEList.get(i).getJob().equals(fJob))
{
System.out.println("Employee found!");
System.out.println(myEList.get(i).toString());
notFound = false;
break;
}
}
if(notFound)
System.out.print("Employee not found!");
``` | Remove this block of code
```
else
{
System.out.print("Employee not found!");
}
```
It should work fine after that.
---
**EDIT**
This is off topic but when you ask question next time remember to post image of output rather than typing it or posting a link.
And also avoid writing about your coding experience. Just be straight to the point. It just increases the size of question unnecessarily. :) |
15,194,896 | I want to load the image from url, as well as the text show in below the image. Like this,

1. Alignment on ImageView & TextView, here is my code but doesn't shows the desired layout
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FFFF"
android:padding="0.1dp">
<TextView android:text="@string/widgetUrl"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:layout_gravity="center_vertical"
android:textColor="#000000">
</TextView>
<TextView android:text="@string/widgetTitle"
android:id="@+id/widgetTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:layout_gravity="center_vertical"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textColor="#ffffff">
</TextView>
<ImageView android:id="@+id/widgetBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:src="@drawable/ic_launcher"
android:layout_gravity="center_vertical">
</ImageView>
</LinearLayout>
```
2. How to load the image from web and display on the layout in java code? Below is my widget provider code:
```
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Log.i(WIDGETTAG, "onUpdate");
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Log.i(WIDGETTAG, "updating widget[id] " + appWidgetId);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
/* View setup */
views.setInt(R.id.widgetTitle, "setBackgroundColor", Color.argb(150, 0, 0, 0));
Intent intent = new Intent(context, ChopInkService.class);
intent.setAction(ChopInkService.UPDATE_IMAGE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widgetBackground, pendingIntent);
Log.i(WIDGETTAG, "pending intent set");
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
```
3. What is the job for **Service** and **AppWidgetProvider**?
* Load image from url is the job of **service** or **AppWidgetProvider**?
* View setup should put in **service** or **AppWidgetProvider**?
4. How can I redirect user to play store when user tapped on the widget?
Thanks in advanced. I'm a newbie, apologize that if I asked a stupid question. | 2013/03/04 | [
"https://Stackoverflow.com/questions/15194896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898931/"
] | **Available Widget views & Layout**
A **widget** is restricted in the View classes it can use. As layouts you can use the **FrameLayout, LinearLayout** and **RelativeLayout** classes. As views you can use AnalogClock, Button, Chromometer, ImageButton, ImageView, ProgressBar and TextView.
As of Android 3.0 more views are available: **GridView, ListView, StackView, ViewFlipper and AdapterViewFlipper.** This adapter Views require that you define a collection view widget which is described later in this tutorial.
The only interaction that is possible on the Views of a Widget is via on OnClickListener. This OnClickListener can be registered on a widget and is triggered by the user.
**AppWidgetProvider**
Your **BroadcastReceiver** typically extends the **AppWidgetProvider** class.
The AppWidgetProvider class implements the **onReceive()** method, extracts the required information and calls the following widget lifecycle methods.
As you can add several instances of a widget to the homescreen you have lifecycle methods which are called only for the first instance added / removed to the homescreen and others which are called for every instance of your widget.
**Lifecycle of Widget**
**onEnabled()** -Called the first time an instance of your widget is added to the homescreen
**onDisabled()** -Called once the last instance of your widget is removed from the homescreen.
**onUpdate()** -Called for every update of the widget. Contains the ids of appWidgetIds for which an update is needed. Note that this may be all of the AppWidget instances for this provider, or just a subset of them, as stated in the methods JavaDoc. For example if more than one widget is added to the homescreen, only the last one changes (until reinstall).
**onDeleted()** -Widget instance is removed from the homescreen
All long running operations in these methods should be performed in a service, as the execution time for a broadcast receiver is limited. Using asynchronous processing in the onReceive() method does not help as the system can kill the broadcast process after his onReceive() method.
For more details about widget check [How to create widget in Android?](http://www.vogella.com/articles/AndroidWidgets/article.html)
[Tutorial1](http://kasperholtze.com/android/how-to-make-a-simple-android-widget/)
[Tutorial2](http://code.google.com/p/android-sky/) | Hi you can check this **[tutorial](https://code.google.com/p/url-image-widget/)** for Loading Image from URL (Http) .
Try the following code :
URL Image widget provider class
```
public class URLImageAppWidgetProvider extends AppWidgetProvider {
public static String TAG = "URLImageWidget";
public static class Size_1_1 extends URLImageAppWidgetProvider {}
public static class Size_1_2 extends URLImageAppWidgetProvider {}
public static class Size_1_4 extends URLImageAppWidgetProvider {}
public static class Size_2_2 extends URLImageAppWidgetProvider {}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
SharedPreferences urls = context.getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
for (int id : appWidgetIds) {
String url = urls.getString("url_" + id, "");
update(context, appWidgetManager, id, url);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
SharedPreferences urls = context.getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
SharedPreferences.Editor urls_editor = urls.edit();
for (int id : appWidgetIds) {
urls_editor.remove("url_" + id);
}
urls_editor.commit();
}
public static void update(final Context context, final AppWidgetManager appWidgetManager, final int id, final String url) {
new Thread() {
public void run() {
Bitmap img = getBitmapFromUrl(url);
if (img != null) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setImageViewBitmap(R.id.img, img);
appWidgetManager.updateAppWidget(id, views);
}
}
}.start();
}
private static Bitmap getBitmapFromUrl(final String url) {
try {
return BitmapFactory.decodeStream(((java.io.InputStream)new java.net.URL(url).getContent()));
} catch (Exception e) {
return null;
}
}
}
```
Here is URL Image widget Configuration class
```
public class URLImageAppWidgetConfiguration extends Activity {
private int id;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configuration);
setResult(RESULT_CANCELED);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
id = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (id == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
}
public void addWidget(View v) {
SharedPreferences urls = getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
SharedPreferences.Editor urls_editor = urls.edit();
String url = ((TextView) findViewById(R.id.url)).getText().toString();
if (!url.startsWith("http://")) url = "http://" + url;
urls_editor.putString("url_" + id, url);
urls_editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
URLImageAppWidgetProvider.update(this, appWidgetManager, id, url);
setResult(RESULT_OK,
new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
);
finish();
}
}
``` |
15,194,896 | I want to load the image from url, as well as the text show in below the image. Like this,

1. Alignment on ImageView & TextView, here is my code but doesn't shows the desired layout
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FFFF"
android:padding="0.1dp">
<TextView android:text="@string/widgetUrl"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:layout_gravity="center_vertical"
android:textColor="#000000">
</TextView>
<TextView android:text="@string/widgetTitle"
android:id="@+id/widgetTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:layout_gravity="center_vertical"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textColor="#ffffff">
</TextView>
<ImageView android:id="@+id/widgetBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:src="@drawable/ic_launcher"
android:layout_gravity="center_vertical">
</ImageView>
</LinearLayout>
```
2. How to load the image from web and display on the layout in java code? Below is my widget provider code:
```
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Log.i(WIDGETTAG, "onUpdate");
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Log.i(WIDGETTAG, "updating widget[id] " + appWidgetId);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
/* View setup */
views.setInt(R.id.widgetTitle, "setBackgroundColor", Color.argb(150, 0, 0, 0));
Intent intent = new Intent(context, ChopInkService.class);
intent.setAction(ChopInkService.UPDATE_IMAGE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widgetBackground, pendingIntent);
Log.i(WIDGETTAG, "pending intent set");
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
```
3. What is the job for **Service** and **AppWidgetProvider**?
* Load image from url is the job of **service** or **AppWidgetProvider**?
* View setup should put in **service** or **AppWidgetProvider**?
4. How can I redirect user to play store when user tapped on the widget?
Thanks in advanced. I'm a newbie, apologize that if I asked a stupid question. | 2013/03/04 | [
"https://Stackoverflow.com/questions/15194896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898931/"
] | **Available Widget views & Layout**
A **widget** is restricted in the View classes it can use. As layouts you can use the **FrameLayout, LinearLayout** and **RelativeLayout** classes. As views you can use AnalogClock, Button, Chromometer, ImageButton, ImageView, ProgressBar and TextView.
As of Android 3.0 more views are available: **GridView, ListView, StackView, ViewFlipper and AdapterViewFlipper.** This adapter Views require that you define a collection view widget which is described later in this tutorial.
The only interaction that is possible on the Views of a Widget is via on OnClickListener. This OnClickListener can be registered on a widget and is triggered by the user.
**AppWidgetProvider**
Your **BroadcastReceiver** typically extends the **AppWidgetProvider** class.
The AppWidgetProvider class implements the **onReceive()** method, extracts the required information and calls the following widget lifecycle methods.
As you can add several instances of a widget to the homescreen you have lifecycle methods which are called only for the first instance added / removed to the homescreen and others which are called for every instance of your widget.
**Lifecycle of Widget**
**onEnabled()** -Called the first time an instance of your widget is added to the homescreen
**onDisabled()** -Called once the last instance of your widget is removed from the homescreen.
**onUpdate()** -Called for every update of the widget. Contains the ids of appWidgetIds for which an update is needed. Note that this may be all of the AppWidget instances for this provider, or just a subset of them, as stated in the methods JavaDoc. For example if more than one widget is added to the homescreen, only the last one changes (until reinstall).
**onDeleted()** -Widget instance is removed from the homescreen
All long running operations in these methods should be performed in a service, as the execution time for a broadcast receiver is limited. Using asynchronous processing in the onReceive() method does not help as the system can kill the broadcast process after his onReceive() method.
For more details about widget check [How to create widget in Android?](http://www.vogella.com/articles/AndroidWidgets/article.html)
[Tutorial1](http://kasperholtze.com/android/how-to-make-a-simple-android-widget/)
[Tutorial2](http://code.google.com/p/android-sky/) | see this.
[How to create android app with app widget in single application](https://stackoverflow.com/questions/15038385/how-to-create-android-app-with-app-widget-in-single-application)
This is helpful for you if you find out any problem then let me know. |
46,109,017 | I want to user `substr` in an 'if-statement' in mysql.
for example...
```
if(substr(member, 1, 2 ) = 'A1','one','two') as member
```
When I use substr in the 'select-statement', the result is good.
But the above query will cause an error.
>
> Can not 'substr' be used in an 'if-statement'?
>
>
>
Is there any other way?
===============================
member field value = 'A1/B1/C1/D1' or 'A2/B2/C2/D2' or 'A1/B2/C2/D1'........
A1,B1,C1,D1 = yes , A2,B2,C2,D2 = no
I would like to change this as follows.
member1
answerA = yes
answerB = yes
answerC = yes
answerD = yes
member2
answerA = no
answerB =no
answerC =no
answerD =no
member3
answerA = yes
answerB =no
answerC =yes
answerD =no | 2017/09/08 | [
"https://Stackoverflow.com/questions/46109017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6759208/"
] | you can try `$parent`.
you can access the parent scope as follows
```
//This assigns the RESULT of login() to $scope.test
$scope.test= $scope.$parent.login();
``` | If I understand the question correctly, I believe you need to assign `var vm = $scope.LoginCtrl = this`. This is so the ng-click has the correct method to fire, as it currently isn't assigned to the login function. |
46,109,017 | I want to user `substr` in an 'if-statement' in mysql.
for example...
```
if(substr(member, 1, 2 ) = 'A1','one','two') as member
```
When I use substr in the 'select-statement', the result is good.
But the above query will cause an error.
>
> Can not 'substr' be used in an 'if-statement'?
>
>
>
Is there any other way?
===============================
member field value = 'A1/B1/C1/D1' or 'A2/B2/C2/D2' or 'A1/B2/C2/D1'........
A1,B1,C1,D1 = yes , A2,B2,C2,D2 = no
I would like to change this as follows.
member1
answerA = yes
answerB = yes
answerC = yes
answerD = yes
member2
answerA = no
answerB =no
answerC =no
answerD =no
member3
answerA = yes
answerB =no
answerC =yes
answerD =no | 2017/09/08 | [
"https://Stackoverflow.com/questions/46109017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6759208/"
] | you can try `$parent`.
you can access the parent scope as follows
```
//This assigns the RESULT of login() to $scope.test
$scope.test= $scope.$parent.login();
``` | You should use the controllerAs syntax to give an alias to each controller. You can then call any method as follows:
```
alias.method()
```
The method you are calling must be in scope. e.g. where a controller is nested in another, the child controller has access to the parents methods. |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What you need to do is:
1. create `www` folder in the same folder as `server.R` and `ui.R`
2. put javascript file into `www` folder.
3. put `tags$head(tags$script(src="hoge.js"))` in UI.
The folder looks like:
```
├── server.R
├── ui.R
└── www
└── hoge.js
```
The `ui.R` is something like
```
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min = 1,
max = 1000,
value = 500)
),
mainPanel(
plotOutput("distPlot"),
tags$head(tags$script(src="hoge.js"))
)
))
```
and `server.R`
```
library(shiny)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
})
```
Note that these are templates generated by Rstudio.
Now `head` of html looks like:
```
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
... snip ...
<script src="shared/slider/js/jquery.slider.min.js"></script>
<script src="hoge.js"></script>
</head>
``` | ```
└──shiny
├── server.R
├── ui.R
└── www
├── stylesheet.css
└── js
└── hoge.js
```
ui.R
====
Either one of them will work
```
1. tags$head(HTML("<script type='text/javascript' src='js/hoge.js'></script>"))
2. HTML('<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="js/hoge.js"></script>
</head>')
``` |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What you need to do is:
1. create `www` folder in the same folder as `server.R` and `ui.R`
2. put javascript file into `www` folder.
3. put `tags$head(tags$script(src="hoge.js"))` in UI.
The folder looks like:
```
├── server.R
├── ui.R
└── www
└── hoge.js
```
The `ui.R` is something like
```
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min = 1,
max = 1000,
value = 500)
),
mainPanel(
plotOutput("distPlot"),
tags$head(tags$script(src="hoge.js"))
)
))
```
and `server.R`
```
library(shiny)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
})
```
Note that these are templates generated by Rstudio.
Now `head` of html looks like:
```
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
... snip ...
<script src="shared/slider/js/jquery.slider.min.js"></script>
<script src="hoge.js"></script>
</head>
``` | Another way is to use:
```
includeScript("mapManipulator.js"),
``` |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What you need to do is:
1. create `www` folder in the same folder as `server.R` and `ui.R`
2. put javascript file into `www` folder.
3. put `tags$head(tags$script(src="hoge.js"))` in UI.
The folder looks like:
```
├── server.R
├── ui.R
└── www
└── hoge.js
```
The `ui.R` is something like
```
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min = 1,
max = 1000,
value = 500)
),
mainPanel(
plotOutput("distPlot"),
tags$head(tags$script(src="hoge.js"))
)
))
```
and `server.R`
```
library(shiny)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
})
```
Note that these are templates generated by Rstudio.
Now `head` of html looks like:
```
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
... snip ...
<script src="shared/slider/js/jquery.slider.min.js"></script>
<script src="hoge.js"></script>
</head>
``` | Another option not discussed yet is that you just delete the ui.R file entirely, and then code the entire thing as a custom HTML file. Details here <https://shiny.rstudio.com/articles/html-ui.html>
In this article, the default HTML form elements are automatically used as inputs in server.R, but you can also build custom input (or output) elements for shiny with this guide <https://shiny.rstudio.com/articles/building-inputs.html> |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What you need to do is:
1. create `www` folder in the same folder as `server.R` and `ui.R`
2. put javascript file into `www` folder.
3. put `tags$head(tags$script(src="hoge.js"))` in UI.
The folder looks like:
```
├── server.R
├── ui.R
└── www
└── hoge.js
```
The `ui.R` is something like
```
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("New Application"),
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min = 1,
max = 1000,
value = 500)
),
mainPanel(
plotOutput("distPlot"),
tags$head(tags$script(src="hoge.js"))
)
))
```
and `server.R`
```
library(shiny)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
})
```
Note that these are templates generated by Rstudio.
Now `head` of html looks like:
```
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
... snip ...
<script src="shared/slider/js/jquery.slider.min.js"></script>
<script src="hoge.js"></script>
</head>
``` | My preferred way is like this:
ui.R:
```
extendShinyjs(script = "app.js", functions = c("alerta")),
```
app.js:
```
shinyjs.alerta = function(text){
alert(text);
}
```
server.R
```
js$alerta("alerta alerta antifascista")
```
You can also include code like this:
ui.R after library imports:
```
jsCode <- "shinyjs.alerta = function(text){alert(text);}"
```
ui.R inside fluidPage:
```
extendShinyjs(text = jsCode, functions = c("alerta")),
```
the call from server.R would be the same |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Another way is to use:
```
includeScript("mapManipulator.js"),
``` | ```
└──shiny
├── server.R
├── ui.R
└── www
├── stylesheet.css
└── js
└── hoge.js
```
ui.R
====
Either one of them will work
```
1. tags$head(HTML("<script type='text/javascript' src='js/hoge.js'></script>"))
2. HTML('<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="js/hoge.js"></script>
</head>')
``` |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
└──shiny
├── server.R
├── ui.R
└── www
├── stylesheet.css
└── js
└── hoge.js
```
ui.R
====
Either one of them will work
```
1. tags$head(HTML("<script type='text/javascript' src='js/hoge.js'></script>"))
2. HTML('<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="js/hoge.js"></script>
</head>')
``` | Another option not discussed yet is that you just delete the ui.R file entirely, and then code the entire thing as a custom HTML file. Details here <https://shiny.rstudio.com/articles/html-ui.html>
In this article, the default HTML form elements are automatically used as inputs in server.R, but you can also build custom input (or output) elements for shiny with this guide <https://shiny.rstudio.com/articles/building-inputs.html> |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
└──shiny
├── server.R
├── ui.R
└── www
├── stylesheet.css
└── js
└── hoge.js
```
ui.R
====
Either one of them will work
```
1. tags$head(HTML("<script type='text/javascript' src='js/hoge.js'></script>"))
2. HTML('<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="js/hoge.js"></script>
</head>')
``` | My preferred way is like this:
ui.R:
```
extendShinyjs(script = "app.js", functions = c("alerta")),
```
app.js:
```
shinyjs.alerta = function(text){
alert(text);
}
```
server.R
```
js$alerta("alerta alerta antifascista")
```
You can also include code like this:
ui.R after library imports:
```
jsCode <- "shinyjs.alerta = function(text){alert(text);}"
```
ui.R inside fluidPage:
```
extendShinyjs(text = jsCode, functions = c("alerta")),
```
the call from server.R would be the same |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Another way is to use:
```
includeScript("mapManipulator.js"),
``` | Another option not discussed yet is that you just delete the ui.R file entirely, and then code the entire thing as a custom HTML file. Details here <https://shiny.rstudio.com/articles/html-ui.html>
In this article, the default HTML form elements are automatically used as inputs in server.R, but you can also build custom input (or output) elements for shiny with this guide <https://shiny.rstudio.com/articles/building-inputs.html> |
23,599,278 | How can I go out of the currect directory and access the test.php file?
I have tried the following:
```
realpath(__dir__.'../test.php');
realpath(__dir__.'./test.php');
```
But it does not work!
Also could you please let me know what is the difference between ./ and ../ ?
UPDATED:
The following lines give the following results:
```
echo(__dir__.'\tests.php');
echo "<br/>";
echo(__dir__.'..\tests.php');
echo "<br/>";
echo(realpath(__dir__.'..\tests.php'));
echo "<br/>";
echo "hi";
die();
Result:
C:\xampp\htdocs\proj1\includes\tests.php
C:\xampp\htdocs\proj1\includes..\tests.php
hi
```
So whay the third one is empty?
Thanks | 2014/05/12 | [
"https://Stackoverflow.com/questions/23599278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Another way is to use:
```
includeScript("mapManipulator.js"),
``` | My preferred way is like this:
ui.R:
```
extendShinyjs(script = "app.js", functions = c("alerta")),
```
app.js:
```
shinyjs.alerta = function(text){
alert(text);
}
```
server.R
```
js$alerta("alerta alerta antifascista")
```
You can also include code like this:
ui.R after library imports:
```
jsCode <- "shinyjs.alerta = function(text){alert(text);}"
```
ui.R inside fluidPage:
```
extendShinyjs(text = jsCode, functions = c("alerta")),
```
the call from server.R would be the same |
22,966,279 | Is there a possibility where I can make a button on which when I click, the contents directly get shared on facebook without showing our user the share prompt dialog box?
I referred it online and found that its possible through mobile devices:
<http://www.mindfiresolutions.com/How-to-post-message-on-your-facebook-wall-without-using-Facebook-dialog-Box-1419.php>
The question is can we make some sort of ajax call and get this done on web apps.
We used Following code
```
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'My app ID', /*Your APP ID*/
'secret' => 'My Secret ID', /*Your APP Secret Key*/
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
}
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => 'www.google.com'
/* 'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'*/
)
);
?>
```
But its returns : " Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action throw in file"
Any help would be highly appreciated.
Thanks in advance. | 2014/04/09 | [
"https://Stackoverflow.com/questions/22966279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2368690/"
] | Of course you can using the Graph API. On the button click you just have to make a `\POST` call to `/me/feed`.
Learn more about publishing a feed via Graph API and what all parameters are available [here](https://developers.facebook.com/docs/graph-api/reference/user/feed/#publish).
Permission required: `publish_stream`
Using **PHP SDK:**
```
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => '{link}',
'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'
)
);
```
Direct **HTTP** Request-
```
POST /me/feed
Host: graph.facebook.com
message=This+is+a+test+message
...
```
You can check your calls in [Graph API Explorer](http://graph.facebook.com/tools/explorer)
---
**Edit:**
To ask for the required permissions:
```
$params = array(
'scope' => 'publish_stream'
);
$login_url = $facebook->getLoginUrl($params);
```
You can read more about permissions [here](https://developers.facebook.com/docs/facebook-login/permissions/). | Try this way: <https://developers.facebook.com/docs/reference/php/>
When coding the wep app, you only have to provide the App Id and the App Secret, then you should have to specify the content to be posted.
You should try also the Javascript Facebook SDK, you'll find it here: <https://developers.facebook.com/docs/javascript> or you could go further and try the C# SDK, this one is a little bit more complex, but you will be able to do so much more.
Have fun coding!!! |
22,966,279 | Is there a possibility where I can make a button on which when I click, the contents directly get shared on facebook without showing our user the share prompt dialog box?
I referred it online and found that its possible through mobile devices:
<http://www.mindfiresolutions.com/How-to-post-message-on-your-facebook-wall-without-using-Facebook-dialog-Box-1419.php>
The question is can we make some sort of ajax call and get this done on web apps.
We used Following code
```
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'My app ID', /*Your APP ID*/
'secret' => 'My Secret ID', /*Your APP Secret Key*/
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
}
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => 'www.google.com'
/* 'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'*/
)
);
?>
```
But its returns : " Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action throw in file"
Any help would be highly appreciated.
Thanks in advance. | 2014/04/09 | [
"https://Stackoverflow.com/questions/22966279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2368690/"
] | Of course you can using the Graph API. On the button click you just have to make a `\POST` call to `/me/feed`.
Learn more about publishing a feed via Graph API and what all parameters are available [here](https://developers.facebook.com/docs/graph-api/reference/user/feed/#publish).
Permission required: `publish_stream`
Using **PHP SDK:**
```
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => '{link}',
'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'
)
);
```
Direct **HTTP** Request-
```
POST /me/feed
Host: graph.facebook.com
message=This+is+a+test+message
...
```
You can check your calls in [Graph API Explorer](http://graph.facebook.com/tools/explorer)
---
**Edit:**
To ask for the required permissions:
```
$params = array(
'scope' => 'publish_stream'
);
$login_url = $facebook->getLoginUrl($params);
```
You can read more about permissions [here](https://developers.facebook.com/docs/facebook-login/permissions/). | Just go to <https://developers.facebook.com/docs/opengraph/>
Review it and place what kind of share you want.
This is the long process to be handle so. you need to study it. |
9,958,357 | Lets say I have 3 domains "example.com", "example.net", and "example.org".
I also have a VPS running Ubuntu 11.04 32bit with Apache, MySQL, PHP5, ProFTPd and Webmin.
Sally owns example.com and has her home at:
>
> /home/sally
>
>
>
Joe owns example.net and has his home at:
>
> /home/joe
>
>
>
Dave owns example.org and has his home at:
>
> /home/dave
>
>
>
My Questions are:
1. How can I get them from not accessing each others directories, more specifically others websites files.
2. How can I let Apache read from the directories if each of their websites are at
>
> ~/htdocs/example.*\**/
>
>
>
Many thanks. | 2012/03/31 | [
"https://Stackoverflow.com/questions/9958357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305351/"
] | You need to use an `Array` instead an `Object` there. Like
```
var myThings = {
thing1: [
['24-04-12', '90'],
['25-04-12', '90'],
['26-04-12', '90']
],
thing2: [
['24-04-12', '10'],
['25-04-12', '30'],
['26-04-12', '210']
]
}
```
Now since `thing1` and `thing2` are `Arrays` you can just use `Array.prototype.push` to push new `Arrays` into that `Array`.
```
Object.keys( myThings ).forEach(function( thing ) {
myThings[ thing ].push( ['01-01-12', '42'] );
});
```
That code would add `['01-01-12', '42']` to all current `things` in that object.
Disclaimer: The above code contains ES5. You need a browser which supports that or a Shim to emulate | I'd do:
```
//create your array dynamically
var array1 = [['24-04-12', '90'],
['25-04-12', '90'],
['26-04-12', '90'] ];
var myThings = {
thing1: array1
,
thing2: array1
}
```
This way, the properties of your object are arrays. |
9,958,357 | Lets say I have 3 domains "example.com", "example.net", and "example.org".
I also have a VPS running Ubuntu 11.04 32bit with Apache, MySQL, PHP5, ProFTPd and Webmin.
Sally owns example.com and has her home at:
>
> /home/sally
>
>
>
Joe owns example.net and has his home at:
>
> /home/joe
>
>
>
Dave owns example.org and has his home at:
>
> /home/dave
>
>
>
My Questions are:
1. How can I get them from not accessing each others directories, more specifically others websites files.
2. How can I let Apache read from the directories if each of their websites are at
>
> ~/htdocs/example.*\**/
>
>
>
Many thanks. | 2012/03/31 | [
"https://Stackoverflow.com/questions/9958357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305351/"
] | You need to use an `Array` instead an `Object` there. Like
```
var myThings = {
thing1: [
['24-04-12', '90'],
['25-04-12', '90'],
['26-04-12', '90']
],
thing2: [
['24-04-12', '10'],
['25-04-12', '30'],
['26-04-12', '210']
]
}
```
Now since `thing1` and `thing2` are `Arrays` you can just use `Array.prototype.push` to push new `Arrays` into that `Array`.
```
Object.keys( myThings ).forEach(function( thing ) {
myThings[ thing ].push( ['01-01-12', '42'] );
});
```
That code would add `['01-01-12', '42']` to all current `things` in that object.
Disclaimer: The above code contains ES5. You need a browser which supports that or a Shim to emulate | Instead of your inner items being objects, you should make them arrays. Objects must exist in key-value pairs, which does not make sense for your usage. Arrays are also key-value pairs, but the key is simply the index number.
```
var myThings = {
thing1: [ // thing1 is now an array of arrays
['24-04-12', '90'],
['25-04-12', '90'],
['26-04-12', '90']
],
thing2: [ // thing2 is now an array of arrays
['24-04-12', '10'],
['25-04-12', '30'],
['26-04-12', '210']
]
}; // don't forget this semicolon...
```
You would then access the inner-most values like this:
```
myThings.thing1[0][1]; // gives you back '90'
myThings.thing2[2][0]; // gives you back '210'
```
If you want to iterate over the `myThings` object, use a [for...in loop](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in). If you want to iterate over any of the interior arrays, use a [regular for loop](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for). As long as you [do NOT use for...in on the arrays](https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) :) |
9,958,357 | Lets say I have 3 domains "example.com", "example.net", and "example.org".
I also have a VPS running Ubuntu 11.04 32bit with Apache, MySQL, PHP5, ProFTPd and Webmin.
Sally owns example.com and has her home at:
>
> /home/sally
>
>
>
Joe owns example.net and has his home at:
>
> /home/joe
>
>
>
Dave owns example.org and has his home at:
>
> /home/dave
>
>
>
My Questions are:
1. How can I get them from not accessing each others directories, more specifically others websites files.
2. How can I let Apache read from the directories if each of their websites are at
>
> ~/htdocs/example.*\**/
>
>
>
Many thanks. | 2012/03/31 | [
"https://Stackoverflow.com/questions/9958357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305351/"
] | I'd do:
```
//create your array dynamically
var array1 = [['24-04-12', '90'],
['25-04-12', '90'],
['26-04-12', '90'] ];
var myThings = {
thing1: array1
,
thing2: array1
}
```
This way, the properties of your object are arrays. | Instead of your inner items being objects, you should make them arrays. Objects must exist in key-value pairs, which does not make sense for your usage. Arrays are also key-value pairs, but the key is simply the index number.
```
var myThings = {
thing1: [ // thing1 is now an array of arrays
['24-04-12', '90'],
['25-04-12', '90'],
['26-04-12', '90']
],
thing2: [ // thing2 is now an array of arrays
['24-04-12', '10'],
['25-04-12', '30'],
['26-04-12', '210']
]
}; // don't forget this semicolon...
```
You would then access the inner-most values like this:
```
myThings.thing1[0][1]; // gives you back '90'
myThings.thing2[2][0]; // gives you back '210'
```
If you want to iterate over the `myThings` object, use a [for...in loop](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in). If you want to iterate over any of the interior arrays, use a [regular for loop](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for). As long as you [do NOT use for...in on the arrays](https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) :) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.