text:
Q: Prove that $1/x^2$ is not uniformly continuous on $(0,\infty)$ using $\varepsilon$-$\delta$ arguments I am trying to prove that $f(x) = 1/x^2$ is not uniformly continuous on $(0,\infty)$ using $\varepsilon$-$\delta$ arguments.
This is what I got so far.
Proof: Let $\varepsilon = 1$. For every $\delta>0$ take
$$c = \delta\, \text{ and }\, x = \frac{1}{\frac{1}{\delta} +\frac{\delta}{2}}.$$
Then
$$|x-c| = \frac{\delta^3}{\delta^2+2}<\delta.$$
But
$$|f(x) - f(c)| = \frac{1}{4}\left(\delta^2+4\right)\geq 1 = \varepsilon.$$
Therefore $f(x)=1/x^2$ is not uniformly continuous on $(0,\infty)$.
Is this a valid proof? Any advice would be appreciated. Thanks in advance. :)
Edit: I am trying to use part ii) from Bartle's Introduction to Real Analysis page 142:

A:
Claim: $f:(0,\infty)\to \Bbb{R}$ defined by $f(x)=\frac{1}{x^2}$ is
not uniformly continuous.

Preliminary:
$f$ is uniformly continuous if, for every $\epsilon>0$, there exists a $\delta>0$ such that for all $x,y\in (0,\infty)$ with $|x−y|<\delta$ implies $|f(x)−f(y)|<\epsilon$.

\begin{align}\forall\epsilon>0\space \exists \delta>0 \space \forall
   > x, y\in (0,\infty):|x-y|<\delta\implies |f(x) -f(y) |<\epsilon\end{align}

$f$ is not uniformly continuous if, there exists $\epsilon>0$ such that for all $\delta>0$ there exists two points  $x,y\in (0,\infty)$ with $|x−y|<\delta$ but $|f(x)−f(y)|\ge\epsilon$.

\begin{align}\exists\epsilon>0\space \forall \delta>0 \space
 \exists x, y\in (0,\infty):|x-y|<\delta\implies |f(x) -f(y)|\ge \epsilon\end{align}

Proof : Let $\delta>0$ be given. Then by Archimedean property of $\Bbb{R}$ choose
$N\in \Bbb{N}$ such that $\frac{1}{2N}<\delta$
Let $x=\frac{1}{N} $ and $y=\frac{1}{2N}$
Then $|x-y|=|\frac{1}{N} -\frac{1}{2N}|=\frac{1}{2N}<\delta$
$|f(x) -f(y) |=|\frac{1}{N^2} -\frac{1}{4N^2}|=\frac{3}{4N^2}$

$\exists \epsilon (=\frac{3}{4N^2}) >0 $ such that $\forall \delta>0$ there exists two points $x=\frac{1}{N}, y=\frac{1}{2N}\in(0, \infty) $ with $|x-y|<\delta$ but $|f(x) -f(y) |\ge \epsilon$
•To get strict inequality , choose $0<\epsilon <\frac{3}{4N^2}$ ( You have plenty choices! )

Alt:
$f: (X, d) \to (Y, d') $ is uniformly continuous iff $f$ preserve parallel sequences.
Two sequences $(x_n), (y_n) $ are called  parallel sequence in $X$ if $d'(f(x_n), f(y_n)) \to 0$ whenever $d(x_n, y_n) \to 0$

Now choose $x_n=\frac{1}{n} $ and $y_n=\frac{1}{2n}$
Then $|x_n-y_n|\to 0$ but $|f(x_n-f(y_n) |=3n^2\to\infty$
Hence $f$ is not uniformly continuous.
Comments: Your proof is also correct. $\forall\delta>0$ ,you need to find two points (doesn't matter whether those points depend on $\delta$ or not) which are atmost $\delta$ distance away but their images have distance at least $\epsilon$ for some fixed $\epsilon>0$.
So your proof is correct. But the above two proofs are somehow easier to execute. Isn't it?

A: Your reasoning is not valid since $x$ depends on $\delta$. In uniform continuity, the variables $x,y$ do not depend on anything, that is why it is uniform. An easy approach using sequences is as follows:
Take $x_n=\frac{1}{\sqrt{n+1}}$ and $y_n=\frac{1}{\sqrt n}$. Clearly $x_n-y_n\to 0$ as $n\to\infty$, but
$$\vert f(x_n)-f(y_n)\vert=1\not\to 0$$ as $n\to\infty$.


text:
Q: Is there a numeric version of SUBSTR in BigQuery? This may be a complete noob question. I have spent hours looking for a solution but haven't found one...
I am trying to capture the first digit of each number in a column of numbers. For example:
173563 = 1
247309 = 2
653638 = 6

etc
I know that I could do this using SUBSTR if the value were a string but that doesn't work for numbers. I have a work around but there must be a better way than how I'm currently doing it.
Any help would be much appreciated
with
-- Convert to string and get the first character
stage1 as (
SELECT
number
, SUBSTR(CAST(number AS STRING), 1, 1) AS cut_off
FROM my_table
),

-- Convert back to a numeric value
stage2 as (
SELECT
number
, CAST(cut_off AS NUMERIC) AS cut_off,
FROM stage1
)

select
number,
cut_off
from stage2

A: You can use below "trick"
with `project.dataset.table` as (
  select 173563 number union all
  select 247309 union all
  select 653638
)
select number, left('' || number, 1) cut_off
from `project.dataset.table`

with output

Obviously, such a trick allows you to use any string function to meet your needs

A: You can do this all in one expression:
CAST(LEFT(CAST(number AS STRING), 1) as int64)

If the length of the number is always 6 digits, you can use arithmetic:
FLOOR(number / 100000)

Or:
DIV(number, 100000)

redpajama_set_name: RedPajamaStackExchange


text:
Q: send bulk sms using gsm modem in java I wanted to develop application that can send bulk sms. i have no idea how to implement it.  I have app that can send only one sms by reading this web site . but I want to know how i can send bulk sms.please give me idea how can i do it?
Thanks in advance

A: Assuming you've gotten that module to work, adding a loop around the gsmModem.Sender call should send a specified amount of messages. I would suggest adding in a sleep method, as your modem probably won't be able to handle all of the AT commands at once.


text:
Q: Laravel 5.5 Eloquent groupBy on ManyToMany Relationship For example, I need take tags name and its not duplicate each categories
here my model
Post.php
class Posts extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function tags() : belongsToMany
    {
    return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
    }
}

Category.php
class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

Tag.php
class Tag extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

and here what I do.
Category::with(['posts.tags' => function($query){
        $query->groupBy('name'); // i need show tags name and group it, so its will not duplcate
    }])->get();

for $query->groupBy('name'); name is tags name.
example
Categpry A
|__Title A
   |__Tag A
   |__Tag B
   |__Tag C
   |__Tag D
|__Title B
   |__Tag A
   |__Tag D
   |__Tag E

the result must be Tag A, Tag B, Tag C, Tag D, Tag E i don't have an idea how to right now, any have a solution?...
thank you!


text:
Q: didEnterBackground in Kobold2d In Cocos2d I would implement - (void)applicationDidEnterBackground:(UIApplication *)application inside of the AppDelegate, but in Kobold2d (I haven't worked with it much) that is all handled by config.lua, which is great, but how do I handle these exit/enter/background state changes of the application?
Do I have to to override something, or is there some specific place? I'm not sure what the best practice is here and either I am having a lot of trouble finding a resource online.
Thanks!

A: You can simply add these methods to your project's AppDelegate class. AppDelegate derives from KKAppDelegate which implements the UIApplicationDelegate.
Make sure to call [super method] for every method since KKAppDelegate implements basic behavior and relies on receiving some of the UIApplicationDelegate methods.


text:
Q: ViewPager, TabHost and Fragments from android.support.v4. All together doesn't work I decided to create some small library which create awesome menu using ViewPager, Tabhost and FragmentActivity. So I have 3 small classes:

*

*Draw menu (drawing all xml things)
public class DrawAMKMenu extends FragmentActivity {

protected LinearLayout mLinearLayout;
protected static TabHost mTabHost;
protected static Context mContext;
protected ViewPager mViewPager;
protected RelativeLayout mMenuBar;
protected Resources res;
protected int screenwidth;

protected Drawable ThumbResource = null;
protected Drawable menuBg = null;
protected TabWidget tw;

/**
 * constructor
 * @param c
 * @param main_layout
 */
protected DrawAMKMenu(FragmentActivity fa, LinearLayout main_layout){
    mContext = fa.getApplicationContext();
    mLinearLayout = main_layout;
    res = fa.getResources();
    Display display = fa.getWindowManager().getDefaultDisplay();
    screenwidth = display.getWidth();

}

/**
 *Draw main LinearLayout
 */
protected void DrawMenu()
{
    mLinearLayout.removeAllViews();
    mLinearLayout.setBaselineAligned(true);
    mLinearLayout.setOrientation(LinearLayout.VERTICAL);
    mLinearLayout.addView(createTabHost());
}
/**
 * @return TabHost
 * draw the TabHost view
 */
protected TabHost createTabHost(){

    mTabHost = new TabHost(mContext);
    mTabHost.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

    mTabHost.addView(createTabContentLayout());
    mTabHost.addView(createViewPager());
    mTabHost.addView(createMenuBar());

    mTabHost.setTag("TabHost");
    SetupTabs(mTabHost);

    return mTabHost;
}
/**
 * Create FrameLayout for Content
 * @return FrameLayout
 */
protected FrameLayout createTabContentLayout(){
    /*Frame layout for Content*/
    FrameLayout fl = new FrameLayout(mContext);
    fl.setLayoutParams(new LinearLayout.LayoutParams(0,0,1));
    fl.setId(android.R.id.tabcontent);
    /*------------------------*/
    return fl;
}

/**
 * @return ViewPager
 * draw ViewPager element
 */
protected ViewPager createViewPager(){
    mViewPager = new ViewPager(mContext);
    mViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1));
    mViewPager.setBackgroundColor(Color.WHITE);
    mViewPager.setTag("viewpager");
    return mViewPager;
}

/**
 * @return RelativeLayout
 * draw Menu bar
 */
protected RelativeLayout createMenuBar(){
    /* Layout for Menu Bar */
    mMenuBar = new RelativeLayout(mContext);
    mMenuBar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    //mMenuBar.setGravity(Gravity.BOTTOM);

    /* ------------------ */

    /* Tab Widget*/
    tw =  new TabWidget(mContext);
    tw.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,0));
    tw.setOrientation(LinearLayout.HORIZONTAL);

    tw.setId(android.R.id.tabs);
    if(menuBg != null)
        tw.setBackgroundDrawable(menuBg);
    /*-----------*/

    /* Scroll bar for menu */
    HorizontalScrollView hsv = new HorizontalScrollView(mContext);
    hsv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,0));
    hsv.setScrollBarStyle(View.GONE);
    hsv.setFillViewport(true);
    /* ----------------- */

    //add tabWidget to HorizontalScrollView
    hsv.addView(tw);

    /*Seek Bar*/
    SeekBar sb = new SeekBar(mContext);
    sb.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    sb.setBackgroundColor(Color.TRANSPARENT);
    sb.setProgressDrawable(res.getDrawable(android.R.id.empty));

    if(ThumbResource!=null)
        sb.setThumb(ThumbResource);
    else
        sb.setThumb(res.getDrawable(android.R.id.empty));
    /*-------*/

    /*Frame layout for SeekBar*/
    FrameLayout fl = new FrameLayout(mContext);
    fl.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    fl.addView(sb);
    /*------------------------*/

    mMenuBar.addView(hsv);
    mMenuBar.addView(fl);
    return mMenuBar;

}

/**
 * Delete bottom strip from tabhost
 * @param tabHost
 */
protected void SetupTabs(TabHost tabHost) {

    Field mBottomLeftStrip;
    Field mBottomRightStrip;

    try {
        mBottomLeftStrip = tw.getClass().getDeclaredField("mBottomLeftStrip");
        mBottomRightStrip = tw.getClass().getDeclaredField("mBottomRightStrip");

        if (!mBottomLeftStrip.isAccessible()) {
            mBottomLeftStrip.setAccessible(true);
        }

        if (!mBottomRightStrip.isAccessible()) {
            mBottomRightStrip.setAccessible(true);
        }

        mBottomLeftStrip.set(tw,  res.getDrawable(Color.TRANSPARENT));
        mBottomRightStrip.set(tw, res.getDrawable(Color.TRANSPARENT));

    }
    catch (java.lang.NoSuchFieldException e) {
        // possibly 2.2
        try {
            Method stripEnabled = tw.getClass().getDeclaredMethod("setStripEnabled", boolean.class);
            stripEnabled.invoke(tw, false);
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    catch (Exception e) {}
}

}

*PagerAdapter class
public class PagerAdapter extends FragmentPagerAdapter

private List<Fragment> pFragments;

/**
 * @param fm
 * @param fragments
 */
public PagerAdapter(FragmentManager fm, List<Fragment> fr) {
    super(fm);
    this.pFragments = fr;
}

/* (non-Javadoc)
 * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
 */
@Override
public Fragment getItem(int position) {
    return this.pFragments.get(position);
}

/* (non-Javadoc)
 * @see android.support.v4.view.PagerAdapter#getCount()
 */
@Override
public int getCount() {
    return this.pFragments.size();
}
}

*Create menu class.
public  class AMKMenu extends DrawAMKMenu implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private PagerAdapter mPagerAdapter;
private Vector<Fragment> fragments;
private FragmentManager mFragmentManager;
private FragmentActivity mFragmentActivity;
private static HashMap<Integer, Class<?>> TabsClass;
private static HashMap<Integer, String> TabsTabName;
private static HashMap<Integer, Drawable> TabsIcon;

/**
 * CONSTRUCTOR
 * Create AMKMenu object to setup settings and
 * also initialize menu
 * @param c
 * @param main_layout
 * @param fm
 * @param screenWidth
 */
public AMKMenu(FragmentActivity fa, LinearLayout main_layout) {
    super(fa, main_layout);
    mFragmentActivity = fa;
    mFragmentManager = fa.getSupportFragmentManager();
    TabsClass = new HashMap<Integer, Class<?>>();
    TabsTabName = new HashMap<Integer, String>();
    TabsIcon = new HashMap<Integer, Drawable>();

}

/**
 * Final method to create menu
 * Use it after you setup all settings
 */
public void createMenu(){
    super.DrawMenu();
    initializeTabHost();
    intializeViewPager();

}
/**
 * A simple factory that returns dummy views to the Tabhost
 * @author Gavryschuk Anatoliy V.
 */
public class TabFactory implements TabContentFactory {

    private final Context fContext;

    /**
     * @param context
     */
    public TabFactory(Context context) {
        fContext = context;
    }

    /** (non-Javadoc)
     * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
     */
    public View createTabContent(String tag) {
        View v = new View(fContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }

}
/**
 * Initialize ViewPager
 */
protected void intializeViewPager() {
    fragments = new Vector<Fragment>();
    if(getTabsClass().size()>0)
    {
        for(int i=0;i<getTabsClass().size();i++)
        {
            fragments.add(Fragment.instantiate(mFragmentActivity, getTabsClass(i).getName()));
        }
    }

    setPagerAdapter(new PagerAdapter (mFragmentManager, fragments));
    mViewPager.setAdapter(getPagerAdapter());
    mViewPager.setOnPageChangeListener(this);
}
/**
 * Initialize the Tab Host
 */
protected void initializeTabHost() {
    if(getTabsClass().size()>0)
    {

        TabHost mTabHost = (TabHost) mLinearLayout.findViewWithTag("TabHost");
        mTabHost.setup();
        for(int i=0;i<getTabsClass().size();i++)
        {
            TabSpec tabSpec = mTabHost.newTabSpec(getTabsTabName(i));
            tabSpec.setIndicator(getTabsTabName(i), getTabsIcon(i));
            tabSpec.setContent(new TabFactory(mFragmentActivity));
            mTabHost.addTab(tabSpec);
        }

        mTabHost.setOnTabChangedListener(this);
        mTabHost.getTabWidget().setHorizontalScrollBarEnabled(false);

        for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
        {
            //mTabHost.getTabWidget().getChildAt(i).setLayoutParams(new LinearLayout.LayoutParams(65,65));
            mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(0);
        }

        //  mTabHost.setCurrentTab(0);
    }else
        return;
}...
}

after I use this library in this way
AMKMenu menu = new AMKMenu(this, (LinearLayout)findViewById(R.id.main_layout));

    menu.setMenuBg(getResources().getDrawable(R.drawable.menu_bg));
    menu.setCursor(getResources().getDrawable(R.drawable.new_cursor));

    menu.AddTab(Tab1Fragment.class, "tab1", getResources().getDrawable(R.drawable.f_icon));
    menu.AddTab(Tab2Fragment.class, "tab2", getResources().getDrawable(R.drawable.s_icon));
    menu.AddTab(Tab3Fragment.class, "tab3", getResources().getDrawable(R.drawable.t_icon));
    menu.createMenu();

I get error

java.lang.IllegalArgumentException: No new found for id for fragment

The problem is in intializeViewPager() method in AMKMenu class.
Please Somebody (Android guru)  help me what do I do wrong?
I hope I explained everything clear.

A: Hear is my solution for the (Tabs + Fragment + ViewPager) it is works for me as i wanted, hope that works for you as well
hear is the xml file
<LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="5" />

        <FrameLayout
            android:id="@+id/fragment_details"
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="4.3" />
    </LinearLayout>

hear is the code for MainActivity.java I'll post relevant code only so you'll have to manage it
public class MainActivity extends FragmentActivity implements
        DialogInterface.OnDismissListener, TabDataResponder {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        artistTab = getSupportActionBar().newTab().setText(
                R.string.tab_name_artist);
        albumTab = getSupportActionBar().newTab().setText(
                R.string.tab_name_album);
        songTab = getSupportActionBar().newTab().setText(
                R.string.tab_name_songs);

        map = new HashMap<String, Integer>();
        mViewPager = (ViewPager) findViewById(R.id.pager);
        FrameLayout deatil = (FrameLayout) findViewById(R.id.fragment_details);
        mDualPane = (deatil != null) && (deatil.getVisibility() == View.VISIBLE);
        mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);

        if (savedInstanceState != null) {
            flag = true;
            index = savedInstanceState.getInt("index");
        }

        setUpTabView();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("index", getSupportActionBar()
                .getSelectedNavigationIndex());
    }

    private void setUpTabView() {
        mTabsAdapter.addTab(artistTab, ArtistFragment.class, null);
        mTabsAdapter.addTab(albumTab, AlbumFragment.class, null);
        mTabsAdapter.addTab(songTab, SongFragment.class, null);
        getSupportActionBar().setSelectedNavigationItem(index);
    }

    public static class TabsAdapter extends FragmentPagerAdapter implements
            ViewPager.OnPageChangeListener, ActionBar.TabListener {

        private FragmentActivity mContext;
        private ActionBar mActionBar;
        private final ViewPager mViewPager;

        private final ArrayList<String> mTabs = new ArrayList<String>();
        private TabDataResponder responder;

        public TabsAdapter(FragmentActivity activity, ActionBar actionBar,
                ViewPager pager) {

            super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = actionBar;
            mViewPager = pager;

            // TabDataResponder is an interface which is implemented in MainActivity
            // You can find implementation @ the last

            responder = (TabDataResponder) activity;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);

            //I have used map to save state of the fragment
            map.put(SongFragment.TYPE_FRAGMENT.trim(), 0);
            map.put(AlbumFragment.TYPE_FRAGMENT.trim(), 0);
            map.put(ArtistFragment.TYPE_FRAGMENT.trim(), 0);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            mTabs.add(clss.getName());
            // mArgs.add(args);
            mActionBar.addTab(tab.setTabListener(this));
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            return Fragment
                    .instantiate(mContext, mTabs.get(position), /*
                                                                 * mArgs.get(
                                                                 * position)
                                                                 */null);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            Log.i(TAG, "PageSelected....");
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            Log.i(TAG, "ScrollSateChanged....");
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            mViewPager.setCurrentItem(tab.getPosition());
            String a = null;
            if (mDualPane) {
                a = mTabs.get(tab.getPosition());
                responder.loadData(a, map.get(a));
            }
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            Log.i(TAG, "Tab is released now....");
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        setUpTabView();

    }
//This interface must be call from fragment class
//@ the time of event you want to show detail
// pass the class name in the type argument using class.getName() method
    @Override
    public void loadData(String type, int index) {
        DetailFragment viewer = (DetailFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_details);
        if (mDualPane) {
            if (viewer == null || viewer.getShownIndex() != index
                    || viewer.getTypeFragment() != type) {

                DetailFragment df = DetailFragment.newInstance(index, type);
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_details, df)
                        .setTransition(
                                FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                        .commit();
                map.put(type.trim(), index);

            }

        } else {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, DetailActivity.class);
            intent.putExtra("index", index);
            intent.putExtra("type", type);
            startActivity(intent);
        }
    }
}

and hear is how i deal with detail fragment not very efficient but kind of working
public class DetailFragment extends Fragment{

    public static DetailFragment newInstance(int index, String  TYPE_FRAGMENT) {
        DetailFragment f = new DetailFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        args.putString("type", TYPE_FRAGMENT);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    public String getTypeFragment(){
        String a = getArguments().getString("type");
        return a;
    }

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

        //template is blank layout
        View view =  inflater.inflate(R.layout.template, container, false);
        if(getTypeFragment().equals(ArtistFragment.TYPE_FRAGMENT)){
            view = null;
            view = inflater.inflate(R.layout.artist_details, container, false);
            //....

        }
        else if(getTypeFragment().equals(AlbumFragment.TYPE_FRAGMENT)){

            //do's for album fragment
        }
        else if(getTypeFragment().equals(SongFragment.TYPE_FRAGMENT)){
            //do's for song fragment
        }
        return view;
    }

}

do not save the state of tab in their individual fragment it will conflict, we are already doing it hear
Hope It Helps


text:
Q: Ubuntu 18.04 KDE Dropbox issues I'm running Ubuntu 18.04. I installed the KDE desktop alongside the regular Gnome(-based) DE. Dropbox works fine in Gnome, but has two issues under KDE:

*

*No Dropbox badges in Dolphin, even after installing the Dolphin dropbox extension (from Dolphin's settings). Badges work fine in Nautilus.

*The notification icon in the panel is semi-functional: it's there, and changes as expected when Dropbox is syncing, but right-clicking on it and clicking on "Recent Files" does not display a list of the, er, most recently synced files.

These two issues combined mean that there is no way to be sure that all relevant files have been synced (short of opening the web client). Google says that the above are supposed to work. Any advice?
Note: the second issue (recents not showing) also occurs in Gnome if I move the panel to the bottom (e.g. using Dash to Dock or similar). So maybe the issue is that the Dropbox notifier really wants to be on a top panel, not a bottom panel.


text:
Q: Subset cases in which there were more than 3 observations in longitudinal data? Have a set of longitudinal data in which measures were repeatedly collected at various waves (see example of set up below. As this sort of data goes however, there was attrition, with some waves stopping before the study ended. However, my analysis has the assumption that each participant have at least 3 observations

ID
Wave
Score

1000
0
5

1000
1
4

1001
0
6

1001
1
6

1001
2
7

How would I subset only those IDs (subjects) that have at least 3 observations? I've looked into similar questions on stackoverflow but they do not seem to fit this specific issue.

A: Method 1
# set as data table
setDT(df)

# calculate no. of waves per ID
df[, no_of_waves := .N, ID]

# subset
df[no_of_waves >= 3]

Method 2
# calculate no. of waves per ID
df[, no_of_waves := max(Wave), ID]

# subset
df[no_of_waves >= 3]

A: Using base R, you could try this one-liner.
out <- with(df, df[ID %in% names(which(sapply(split(df, ID), nrow) > 2)), ])

Output
> out
    ID Wave Score
3 1001    0     6
4 1001    1     6
5 1001    2     7

Data
df <- data.frame(
  ID = unlist(mapply(rep, 1000:1001, 2:3)),
  Wave = c(0,1,0,1,2),
  Score = c(5,4,6,6,7)
)


text:
Q: Warping radar maps for overlay into Google Maps For a small project I'm looking to add various weather maps to overlay on Google Maps.  I've can pull several maps from various sources, however I also know that they are not in the right projection to just dump into Google Maps.
Unfortunately I'm not an expert in GIS.
From what I've been able to read, I can assume that the images I get from the radars are Gnomonic projection, and I can get a reasonably accurate Latitude and Longitude of they centre pixel of the map.  The scale of the map (in terms of distance for each concentric circle) is also published.
So far I've pieced together that I need to use goal-translate and gdalwarp to first locate the image, and then warp it into the EPSG:3857 projection that Google Maps uses.
I read someone else's question and the answers in:
Convert gnomonic projection to Mercator
Form there I see the steps as:
gdal_translate -a_srs "+proj=gnom +lat_0=[Centre Lat] +lon_0=[Centre Lon]" -a_ullr [EXTENTS] infile.png translated.png

to actually locate the image with a projection, and from there I can use
gdalwarp -overwrite -s_srs "+proj=gnom +lat_0=[Centre Lat] +lon_0=[Centre Lon]" -t_srs EPSG:3857 translated.png warped.png

My issue comes from that while I understand the basics of what I'm doing, I'm clueless as to what to use in the [EXTENTS].  I understand that they represent the coordinate edges of the image, but I don't know what units they are or how to get them.
I see that the person asking the question referenced cs2cs which looks useful and I can get information out of it, however I'm unsure of what values to put into it to get what I want.
To provide a concrete example:
I can fetch a radar image from Environment Canada.

From there I crop out the border and scale to the side, and get an image that is 478x478 px.  Form the published data I know that the centre pixel is at -113.3881 51.0264, and that the scale is 1 px/km.  Meaning that the mid points of the edges of the image are 239km from the centre.
From here I am reasonably sure that I need to go through gdal_translate to first locate the image, but I'm not sure what to use for extents.  I think cs2cs could help me, but I'm not sure what to provide it for the coordinates.
Can I generate these extents from the knowledge that the edges are 283km from the centre? (at least in the mid points, I know that doesn't apply to the corners)
Am I going down the correct rabbit hole at all?
Ultimately I would love to generate a pipeline that takes in:

*

*The image

*The lat/lon of the centre of the image

*The scale in km/px of the image

Warp the image to be suitable to display on Google Maps, preferably with the pipeline telling me what the lat/lon extents I need to use for Google Maps are.
Could anyone nudge me in the right direction?


text:
Q: Spring hibernate non column model variable In spring and hibernate I have a vehicle model. Now vehicles can have proposals on them and I want a variable in the vehicle model to represent the total proposals that have been made. I want it to be a variable as I serialize it and output it as JSON. Someone has suggested that instead of doing this I should do a seperate AJAX request to pull the total proposals for a vehicle. The issue is if I am listing a vehicle on a mobile application I will get like 30 ajax requests for one list. It does not make sense to me it makes sense to append the total proposals to the vehicle model.
Does anyone have any advice on which way to go about this? If you agree with storing it in the vehicle model even though it is not a column in the database can you give the best way to go about this thank you
Dan


text:
Q: How to use fetch to get the HTML source of a webpage in a firefox or chrome web extension? I am trying to use fetch to get the HTML source of https://smmry.com/ in a Chrome/Firefox web extension.
Here is my manifest.json
{

    "manifest_version": 2,
    "name": "To_Be_Done",
    "version": "1.0",

    "description": "To_Be_Done",

    "permissions": [
        "tabs",
        "*://*.smmry.com/*"
    ],

    "icons": {
        "48": "icons/border-48.png"
    },

    "browser_action": {
        "browser_style": true,
        "default_popup": "popup/choose_page.html",
        "default_icon": {
            "16": "icons/news-icon-16.png",
            "32": "icons/news-icon-32.png"
        }
    }
}

Whenever, my extension's button is clicked, I want to get the HTML source of smmry.com. However, I don't know how to implement the fetch() method to do this. I've read through the documentation but I am still confused.
Can anyone show an example?

A: I figured out how to do it. The following returns the html file of "https://smmry.com" as a string.
fetch('https://smmry.com/')
    .then((resp) => resp.text())
    .then(function (data) {
    })


text:
Q: Using OpenCV to get skeleton of an image I read an article talking about how to skeletonsise an image with OpenCV in C++.
http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/
Seems good. But I'm trying to use it in Unity with an asset called OpenCV for Unity (clone of OpenCV Java 3.1.0). So I try to port the code from C++ to C# and I failed. I tried to debug by writing out image. Turns out the image is entirely black.
BTW, my use case in white background, and the code is for black background I think, but I tested it with black background white shapes, still no luck.

FML, This is what I see after adding the imwrite line in the loop
Mat GetSkel (Texture2D srcTexture)
{
    Mat img = new Mat (srcTexture.height, srcTexture.width, CvType.CV_8UC1);
    Utils.texture2DToMat (srcTexture, img);
    Debug.Log ("img.ToString() " + img.ToString ());

    Imgproc.threshold (img, img, 127, 255, Imgproc.THRESH_BINARY);
    Mat skel = new Mat (srcTexture.height, srcTexture.width, CvType.CV_8UC1, new Scalar (0));
    Mat temp = new Mat();
    Mat eroded = new Mat();

    Mat element = Imgproc.getStructuringElement (Imgproc.MORPH_CROSS, new Size(3,3));

    bool done;
    do
    {
        Imgproc.erode(img, eroded, element);
        Imgproc.dilate(eroded, temp, element);
        Core.subtract(img, temp, temp);
        Core.bitwise_or(skel, temp, skel);
        eroded.copyTo(img);

        done = (Core.countNonZero(img) == 0);
    } while (!done);

    Imgcodecs.imwrite ("/Users/fung/Documents/FYP/Future/Assets/Future -fung/img.jpg", img);

    return img;

}

A: private void skeleton(Mat _img)
   {
       boolean done = false;
       Mat img = _img.clone();
       CvUtilsFX.showImage(img, "tresh_1");

       Mat imgGray = new Mat();
       Imgproc.cvtColor(img, imgGray, Imgproc.COLOR_BGR2GRAY);

       Mat tresh = new Mat();
       double thresh = Imgproc.threshold(imgGray, tresh, 100, 255, Imgproc.THRESH_BINARY_INV | Imgproc.THRESH_OTSU);
       CvUtilsFX.showImage(tresh, "tresh_1");

       Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(3,3));
       Mat eroded = new Mat();
       Mat temp = new Mat();
       Mat skel = new Mat (tresh.rows(), tresh.cols(), CvType.CV_8UC1, new Scalar (0));

       int size = _img.cols() * _img.rows();
       int zeros = 0;

       while(!done)
       {
           Imgproc.erode(tresh, eroded, element);
           Imgproc.dilate(eroded, temp, element);
           Core.subtract(tresh, temp, temp);
           Core.bitwise_or(skel, temp, skel);
           eroded.copyTo(tresh);

           zeros = size - Core.countNonZero(tresh);
           if(zeros == size)
               done = true;
       }
       CvUtilsFX.showImage(skel, "Skeleton");
   }

Image


text:
Q: How to sample data points for two variables that has highest (close to +1) or lowest (close to zero) correlation coefficient? Let's assume that we have N (N=212 in this case) number of datapoints for both variables A and B. I have to sample n (n=50 in this case) number of data points for A and B such that A and B should have the highest possible positive correlation coefficient or lowest correlation coefficient (close to zero)  for that sample set. Is there any easy way to do this (Please note that the sampling should be index-based i.e., if we select a ith datapoint then both A and B should be taken corresponding to that ith index)? Below is the sample dataframe (Coded in R but I am OK with any programming language):
df <- structure(list(A = c(1.37, 1.44, 1.51, 1.59, 1.67, 1.75, 1.82,1.9, 1.97, 2.05, 2.12, 2.19, 2.26, 2.33, 2.4, 2.47, 2.53, 2.6,  2.66, 2.72, 2.78, 2.84, 2.9, 2.95, 3.01, 3.05, 3.09, 3.13, 3.16,  3.18, 3.2, 3.21, 3.22, 3.22, 3.23, 3.23, 3.23, 3.22, 3.21, 3.2,  3.18, 3.15, 3.13, 3.1, 3.06, 3.03, 3, 2.98, 2.95, 2.92, 2.89,  2.86, 2.84, 2.81, 2.79, 2.76, 2.74, 2.71, 2.69, 2.67, 2.65, 2.62,  2.6, 2.58, 2.56, 2.55, 2.54, 2.53, 2.53, 2.53, 2.54, 2.55, 2.56, 2.58, 2.59, 2.61, 2.62, 2.64, 2.66, 2.68, 2.7, 2.72, 2.74, 2.76, 2.79, 2.82, 2.84, 2.88, 2.91, 2.94, 2.98, 3.02, 3.06, 3.1, 3.14, 3.19, 3.24, 3.29, 3.34, 3.39, 3.45, 3.5, 3.56, 3.61, 3.66, 3.71, 3.77, 3.82, 3.87, 3.91, 3.96, 4.01, 4.06, 4.11, 4.15, 4.2, 4.24, 4.28, 4.32, 4.35, 4.39, 4.42, 4.44, 4.47, 4.49, 4.51, 4.53, 4.54, 4.56, 4.57, 4.58, 4.59, 4.6, 4.61, 4.62, 4.63, 4.64, 4.65, 4.65, 4.66, 4.66, 4.66, 4.66, 4.65, 4.64, 4.63, 4.62, 4.61, 4.6, 4.58, 4.56, 4.54, 4.52, 4.5, 4.48, 4.45, 4.42, 4.39, 4.36, 4.32, 4.28, 4.23, 4.19, 4.14, 4.08, 4.03, 3.97, 3.91, 3.84, 3.78, 3.71, 3.64, 3.57, 3.5, 3.43, 3.36, 3.29, 3.22, 3.15, 3.08, 3, 2.93, 2.86, 2.78, 2.7, 2.63, 2.55, 2.47, 2.4, 2.32, 2.24, 2.16, 2.08, 2, 1.93, 1.85, 1.76, 1.68, 1.6, 1.53, 1.45, 1.38, 1.31, 1.24, 1.18, 1.11, 1.05, 0.99, 0.93, 0.88, 0.83, 0.78), B = c(1.44, 0.76, 0.43, 0.26, 0.69, 0.46, 0.07, 0.22, 0.38, 0.44, 0.37, 0.31, 0.48, 0.45, 0.86, 1.15, 1.13, 0.5, 0.39, 0.64, 0.71, 0.86, 0.45, 0.6, 0.29, 0.58, 0.24, 0.64, 0.61, 0.49, 0.53, 0.27, 0.03, 0.18, 0.25, 0.24, 0.2, 0.23, 0.3, 0.39, 0.32, 0.22, 0.18, 0.24, 0.2, 0.61, 0.12, 0.16, 0.29, 0.51, 0.48, 0.27, 0.28, 0.41, 0.48, 0.76, 0.45, 0.59, 0.55, 0.69, 0.46, 0.42, 0.42, 0.22, 0.34, 0.19, 0.11, 0.18, 0.33, 0.48, 0.91, 1.1, 0.32, 0.18, 0.09, NaN, 0.27, 0.31, 0.3, 0.27, 0.79, 0.43, 0.32, 0.48, 0.77, 0.32, 0.28, 0.4, 0.46, 0.69, 0.93, 0.71, 0.41, 0.3, 0.34, 0.44, 0.3, 1.03, 0.97, 0.35, 0.51, 1.21, 1.58, 0.67, 0.37, 0.04, 0.57, 0.67, 0.7, 0.47, 0.48, 0.38, 0.61, 0.8, 1.1, 0.39, 0.38, 0.48, 0.58, 0.55, 0.7, 0.7, 0.86, 0.61, 0.18, 0.9, 0.83, 0.9, 0.83, 0.61, 0.23, 0.22, 0.44, 0.41, 0.52, 0.71, 0.59, 0.9, 1.23, 1.56, 0.73, 0.69, 1.23, 1.28, 0.43, 0.97, 0.58, 0.44, 0.23, 0.46, 0.48, 0.22, 0.21, 0.66, 0.26, 0.55, 0.69, 0.84, 1.04, 0.83, 0.85, 0.63, 0.63, 0.17, 0.58, 0.66, 0.44, 0.53, 0.81, 0.63, 0.51, 0.15, 0.42, 0.77, 0.73, 0.87, 0.34, 0.51, 0.63, 0.05, 0.23, 0.87, 0.84, 0.39, 0.61, 0.89, 1.06, 1.08, 1.01, 1.05, 0.27, 0.79, 0.88, 1.34, 1.26, 1.42, 0.81, 1.46, 0.84, 0.54, 0.95, 1.42, 0.44, 0.73, 1.31, 1.75, 2.1, 2.36, 1.94, 2.31, 2.17, 2.35)), class = "data.frame", row.names = c(NA, -212L))

A: Perhaps there is a better way, but it seems to me that this is something that could be solved with a genetic algorithm. The following approach will return the correlation value (i.e. fitness) only if n genes/variables are "turned on"; otherwise, zero is returned.
I had to initialize the population with individuals with exactly 50 genes turned on to start the evolutionary process. The result is pretty high (r = 0.97) after 1142 generations, and no improvement is made over the last 50 generations.
# required libraries
library(GA)
library(memoise)

# original data
df <- structure(list(A = c(1.37, 1.44, 1.51, 1.59, 1.67, 1.75, 1.82,1.9, 1.97, 2.05, 2.12, 2.19, 2.26, 2.33, 2.4, 2.47, 2.53, 2.6,  2.66, 2.72, 2.78, 2.84, 2.9, 2.95, 3.01, 3.05, 3.09, 3.13, 3.16,  3.18, 3.2, 3.21, 3.22, 3.22, 3.23, 3.23, 3.23, 3.22, 3.21, 3.2,  3.18, 3.15, 3.13, 3.1, 3.06, 3.03, 3, 2.98, 2.95, 2.92, 2.89,  2.86, 2.84, 2.81, 2.79, 2.76, 2.74, 2.71, 2.69, 2.67, 2.65, 2.62,  2.6, 2.58, 2.56, 2.55, 2.54, 2.53, 2.53, 2.53, 2.54, 2.55, 2.56, 2.58, 2.59, 2.61, 2.62, 2.64, 2.66, 2.68, 2.7, 2.72, 2.74, 2.76, 2.79, 2.82, 2.84, 2.88, 2.91, 2.94, 2.98, 3.02, 3.06, 3.1, 3.14, 3.19, 3.24, 3.29, 3.34, 3.39, 3.45, 3.5, 3.56, 3.61, 3.66, 3.71, 3.77, 3.82, 3.87, 3.91, 3.96, 4.01, 4.06, 4.11, 4.15, 4.2, 4.24, 4.28, 4.32, 4.35, 4.39, 4.42, 4.44, 4.47, 4.49, 4.51, 4.53, 4.54, 4.56, 4.57, 4.58, 4.59, 4.6, 4.61, 4.62, 4.63, 4.64, 4.65, 4.65, 4.66, 4.66, 4.66, 4.66, 4.65, 4.64, 4.63, 4.62, 4.61, 4.6, 4.58, 4.56, 4.54, 4.52, 4.5, 4.48, 4.45, 4.42, 4.39, 4.36, 4.32, 4.28, 4.23, 4.19, 4.14, 4.08, 4.03, 3.97, 3.91, 3.84, 3.78, 3.71, 3.64, 3.57, 3.5, 3.43, 3.36, 3.29, 3.22, 3.15, 3.08, 3, 2.93, 2.86, 2.78, 2.7, 2.63, 2.55, 2.47, 2.4, 2.32, 2.24, 2.16, 2.08, 2, 1.93, 1.85, 1.76, 1.68, 1.6, 1.53, 1.45, 1.38, 1.31, 1.24, 1.18, 1.11, 1.05, 0.99, 0.93, 0.88, 0.83, 0.78), B = c(1.44, 0.76, 0.43, 0.26, 0.69, 0.46, 0.07, 0.22, 0.38, 0.44, 0.37, 0.31, 0.48, 0.45, 0.86, 1.15, 1.13, 0.5, 0.39, 0.64, 0.71, 0.86, 0.45, 0.6, 0.29, 0.58, 0.24, 0.64, 0.61, 0.49, 0.53, 0.27, 0.03, 0.18, 0.25, 0.24, 0.2, 0.23, 0.3, 0.39, 0.32, 0.22, 0.18, 0.24, 0.2, 0.61, 0.12, 0.16, 0.29, 0.51, 0.48, 0.27, 0.28, 0.41, 0.48, 0.76, 0.45, 0.59, 0.55, 0.69, 0.46, 0.42, 0.42, 0.22, 0.34, 0.19, 0.11, 0.18, 0.33, 0.48, 0.91, 1.1, 0.32, 0.18, 0.09, NaN, 0.27, 0.31, 0.3, 0.27, 0.79, 0.43, 0.32, 0.48, 0.77, 0.32, 0.28, 0.4, 0.46, 0.69, 0.93, 0.71, 0.41, 0.3, 0.34, 0.44, 0.3, 1.03, 0.97, 0.35, 0.51, 1.21, 1.58, 0.67, 0.37, 0.04, 0.57, 0.67, 0.7, 0.47, 0.48, 0.38, 0.61, 0.8, 1.1, 0.39, 0.38, 0.48, 0.58, 0.55, 0.7, 0.7, 0.86, 0.61, 0.18, 0.9, 0.83, 0.9, 0.83, 0.61, 0.23, 0.22, 0.44, 0.41, 0.52, 0.71, 0.59, 0.9, 1.23, 1.56, 0.73, 0.69, 1.23, 1.28, 0.43, 0.97, 0.58, 0.44, 0.23, 0.46, 0.48, 0.22, 0.21, 0.66, 0.26, 0.55, 0.69, 0.84, 1.04, 0.83, 0.85, 0.63, 0.63, 0.17, 0.58, 0.66, 0.44, 0.53, 0.81, 0.63, 0.51, 0.15, 0.42, 0.77, 0.73, 0.87, 0.34, 0.51, 0.63, 0.05, 0.23, 0.87, 0.84, 0.39, 0.61, 0.89, 1.06, 1.08, 1.01, 1.05, 0.27, 0.79, 0.88, 1.34, 1.26, 1.42, 0.81, 1.46, 0.84, 0.54, 0.95, 1.42, 0.44, 0.73, 1.31, 1.75, 2.1, 2.36, 1.94, 2.31, 2.17, 2.35)), class = "data.frame", row.names = c(NA, -212L))

# fitness function
fitfun <- function(x, data, n){
  if(sum(x) == n){ # only calculate correlation if n genes/variable are included
    incl <- which(x == 1)
    res <- unname(cor.test(x = df[incl,"A"], y = df[incl,"B"], method = "pearson")$estimate)
  }else{
    res <- 0 # otherwise return zero fitness
  }
  return(res)
}

# set-up initial population
popSize = 200 # population size
set.seed(1)
initPop <- matrix(0, nrow = popSize, ncol = nrow(df))
for(i in seq(nrow(initPop))){
  initPop[i,sample(x = nrow(df), size = 50)] <- 1
}
rowSums(initPop)

# Run genetic algorithm
fitfun <- memoise::memoise(f = fitfun) # use memoisation to record unique genetic solutions (may help with speed)
fit <- ga(type = "binary", nBits = nrow(df), fitness = fitfun, data = df,
  n = 50, popSize = popSize, maxiter = 1500, run = 200, seed = 1112,
  pmutation = 0.2, elitism = popSize*0.2,
  suggestions = initPop)
memoise::forget(f = fitfun)

# Result and plot
(incl <- which(fit@solution == 1)) # selected rows of df
fit@fitnessValue ; cor.test(x = df[incl,"A"], y = df[incl,"B"], method = "pearson")$estimate # double check (same)
plot(fit)

As per your comment on how to adjust the fitness function to target a specific correlation, see the example below. Since ga always maximizes fitness, you will need to flip the sign of the output (e.g. -sqrt((res-targ)^2) is the squared error to the target value).
# fitness function - correlation closest to target value
fitfun0 <- function(x, data, n, targ){
  if(sum(x) == n){ # only calculate correlation if n genes/variable are included
    incl <- which(x == 1)
    res <- unname(cor.test(x = df[incl,"A"], y = df[incl,"B"], method = "pearson")$estimate)
    res <- res
  }else{
    res <- 100
  }
  res <- -sqrt((res-targ)^2) # reverse sign since fitness is maximized
  return(res)
}

# set-up initial population
popSize = 200 # population size
set.seed(1)
initPop <- matrix(0, nrow = popSize, ncol = nrow(df))
for(i in seq(nrow(initPop))){
  initPop[i,sample(x = nrow(df), size = 50)] <- 1
}
rowSums(initPop)

# Run genetic algorithm
fitfun0 <- memoise::memoise(f = fitfun0) # use memoisation to record unique genetic solutions (may help with speed)
fit <- ga(type = "binary", nBits = nrow(df), fitness = fitfun0, data = df, targ = -0.1,
  n = 50, popSize = popSize, maxiter = 1500, run = 200, seed = 1112,
  pmutation = 0.2, elitism = popSize*0.2,
  suggestions = initPop)
memoise::forget(f = fitfun0)

# Result and plot
(incl <- which(fit@solution == 1)) # selected rows of df
cor.test(x = df[incl,"A"], y = df[incl,"B"], method = "pearson")$estimate # close to target
plot(fit)


text:
Q: Avoid polling database mysql entity framework This might look like a duplicate question, but I was not able to find an exact equivalent.
My setup is a Web API that has an api call that waits till a status in the database changes to "Complete". For this currently I am polling the database every 10 seconds. I would like to avoid polling, because the status change can happen at any time between 2 seconds to as late as 180 seconds.
I am stuck in between having very small poll times thus increasing the calls to the database and having longer poll times and thus reducing the performance of the API.
Here is what I am using,

*

*C# Web API 2

*Entity Framework 6

*MySQL 5.6.27

Any help on this is greatly appreciated.


text:
Q: Spring Boot: I am interested how an actual DispatcherServlet/Front Controller implementation looks like in code I am trying to go a bit more deeper in how a dispatcher servlet is actually auto implemented by spring boot.I know and understand the dispatcher servlet schema and how it routes the request to the respective controllers and handlers so i do not need that.I would actually like to see an actual code implementation of a dispatcher servlet.Where can i see this?
Since java spring is based on the servlets technology, i know that a Servlet class (implements HttpServlet) has only 1 of each http protocol equivalent methods (doPost,doGet,doPut,doDelete) available in the service method.That means you can only do 1 doGet/doPost etc... per servlet.If you need more , you need to create another servlet.You can of course also create an if/else inside the doPost/doGet etc to have more options , but you basically can only have one.
How is this transposing to a front servlet that can route to different classes that have N get/post request methods?
I would appreciate some code of the actual implementation if possible, thank you!
UPDATE:Just found what i needed by searching for DisparcherServlet source code!


text:
Q: Jquery detect element type in if I have the following JQuery http://jsfiddle.net/gg9xnkqq/1/
$(document).ready(function () {
    if( $('.one').hasClass('one') ){
        $('.one').css({ 'color' : '#f00' });
    }
});

and this HTML

dfv

dfv

dfv

dfv

dfv

dfv

dfv

dfv

oiuoiuioou

In the if statement, how can I detect if the type of the element with the class one is not body?
So all elements that are not body and have a certain class, will have their class changed.

A: Since there is only 1 body you can select the elements as follows $('body .one') that way it'll select all the elements with class one inside the body.

A: Use jQuery not()
$('.one').not('body').css({ 'color' : '#f00' });

This will

Remove elements from the set of matched elements.

Therefore, there is no need for the if

A: You could just use not():
$('.one').not('body').css({ 'color' : '#f00' });

Or :not():
$('.one:not("body")').css({ 'color' : '#f00' });

Or filter():
$('.one').filter(':not("body")').css({ 'color' : '#f00' });

Or:
$('.one').filter(function () {
    return $(this).not('body');
}).css({ 'color' : '#f00' });

What you don't need to do is:
if( $('.one').hasClass('one') ){
    $('.one').css({ 'color' : '#f00' });
}

Because if the elements didn't have the class of one they wouldn't have been selected by the selector comprising of the class-name one.
References:

*

*filter().

*:not() selector.

*not().


text:
Q: Can anyone please tell me the time complexities of these following two java codes (a) & (b) I'm confused with the time complexities of these two codes:
code 1:
I suppose its O(n^3)
void easy(in n, int x, inty)
{
    for(int i=0; i<n: ++i) { //o(n)
        if(x<y) {
            for(int k=0: k < n*n: ++k) { //o(n^2)
                System.out.println("k =" +k);
            }
        } else {
            System.out.println("i =" +i);
        }
    }
}

code 2:
void find(int n)
{
    for(int i=0; i<20; ++i) {   //o(1)
        for(int j=0: j<n; ++j) {   //o(n)
            for(int k=0; k<j; ++k)   //o(n)
                System.out.println("k =" +k);

            for(int m=0; m<i; ++m) //o(1)
                Systen.out.println("m =" +m);
        }
    }
}

I suppose its o(n^2)

A: In the first snippet you have an outer loop of n iterations. Then the body of that loop either performs n^2 operations (if x<y) or one operation (if x>=y). This means that the running time is either O(n) or O(n^3), depending on the values of x and y.
In the second snippet you have an outer loop with an i variable that doesn't depend on n. It goes from 1 to 20, which means you can count it as constant amount of time, so lets get rid of that loop.
We have the following loops remaining:
for(int j=0: j<n; ++j) {
    for(int k=0; k<j; ++k)
        System.out.println("k =" +k);

    for(int m=0; m<i; ++m)
        Systen.out.println("m =" +m);
}

Now the outer loop has n iterations. The second inner loop depends on i, which is constant, so that entire loop takes constant time.
The first inner loop takes O(n), since k goes from 0 to j, and j goes from 0 to n. Hence the total running time is O(n^2).


text:
Q: Spring Security 5.7 - How to return custom UserDetails I've seen a lot of examples where a user creates a custom UserDetailsService in order to override the loadUserByUsername method and return a custom implementation of a UserDetails object.
This was done previously with sth like this
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

Now with the new version I'm confused on how to do this
I created a Bean and used the JdbcUserDetailsManager, I can configure my custom queries for users and authorities tables
  @Bean
  public UserDetailsManager userDetailsManager(DataSource dataSource) {
    String usersByUsernameQuery = "select username, password, enabled from tbl_users where username = ?";
    String authsByUserQuery = "select username, authority from tbl_authorities where username = ?";

    JdbcUserDetailsManager userDetailsManager = new JdbcUserDetailsManager(dataSource);

    userDetailsManager.setUsersByUsernameQuery(usersByUsernameQuery);
    userDetailsManager.setAuthoritiesByUsernameQuery(authsByUserQuery);

    return userDetailsManager;
  }

but how to return a custom UserDetails object with an extra field, e.g. an email with the new version?

A: OK after many tries what I did was to remove completely JdbcUserDetailsManager stuff from my custom SecurityConfig class and I created a custom UserDetailsService and custom UserDetails class and it worked.
So security config class had no code regarding the authentication of the users.
I was very confused because I thought that somehow I had to create a @Bean inside the config class, implement the authentication myself and in general that all this authentication code had to be done inside the config class, but it worked with this approach.
@Service
public class MyCustomUserDetailsService implements UserDetailsService {

  @Autowired
  UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);

    if (user == null) {
      throw new UsernameNotFoundException("User Not Found with username: " + username);
    }
    return MyUserDetails.build(user);
  }
}

And the details class
public class MyUserDetails implements UserDetails {

  private String username;
  private String firstName;
  private String lastName;

  @JsonIgnore
  private String password;

  private Collection<? extends GrantedAuthority> authorities;

  public MyUserDetails(String username, String firstName, String lastName, String password,
      Collection<? extends GrantedAuthority> authorities) {
    this.username = username;
    this.firstName = firstName;
    this.lastName = lastName;
    this.password = password;
    this.authorities = authorities;
  }

  public static MyUserDetails build(User user) {
    List<GrantedAuthority> authorities = user.getRoles().stream()
        .map(role -> new SimpleGrantedAuthority(role.getAuthority()))
        .collect(Collectors.toList());

    return new MyUserDetails(
        user.getUsername(),
        user.getFirstName(),
        user.getLastName(),
        user.getPassword(),
        authorities);
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  @Override
  public String getPassword() {
    return password;
  }

  @Override
  public String getUsername() {
    return username;
  }

  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return true;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;
    MyUserDetails user = (MyUserDetails) o;

    return Objects.equals(username, user.username);
  }
}

Also check Spring Security Architecture


text:
Q: Creating a dynamically-sized multidimensional list in python I want to build a multi-dimensional list in Python where the number of the dimensions isn't known at the time of writing (development-time) but determined dynamically at runtime.
Example: If I want to create a n-dimensional lattice where each lattice point corresponds to a object I created.
Here i want to know the algorithm for varying n while the program runs.

A: Pure Python Solution:
n = 2
f = [[0.0 for _ in range(2)] for _ in range(3)]
f[0][0] = 8
print (f)

n = 3
f = [[[0.0 for _ in range(2)] for _ in range(3)] for _ in range(3)]
f[0][0][0] = 5
print (f)

numpy Solution:

Quickstart tutorial: array-creation

n = 2
f = np.zeros((2, 3,))

n = 3
f = np.zeros((2, 3, 3))

Output:
[[8, 0.0], [0.0, 0.0], [0.0, 0.0]]
     [[[5, 0.0], [0.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]]


text:
Q: How can I type a mapping of Object function values with TypeScript? I am trying to set up state in a monorepo application by composing reducers. Currently, all state is divided by domain, e.g.
type State = { fruit: FruitState, snacks: SnackState })

Each state domain contains some selectors. These selectors are defined in an encapsulated manner, e.g.
const selectApples = (state: FruitState) => state.apples;

We then have a web module which imports all the state domain selectors, grouping them by key and then wrapping them in a higher-order function to scope them into domain namespaces, e.g.
function scopeSelector<T extends keyof State>(
  scopeNamespace: T,
  selectors: { [selector: string]: Function }
) {
  return Object.keys(selectors).reduce((scoped, key) => ({
    ...scoped,
    [key]: (state: State) => selectors[key](state[scopeNamespace])
  }), {});
}

export const selectors = {
  fruits: scopeSelector('fruits', fruits.selectors),
  snacks: scopeSelector('snacks', snacks.selectors)
};

This code works at runtime - but produces TypeScript errors, e.g.
// Error: Property 'selectApples' does not exist on type '{}'.
const apples = selectors.fruits.selectApples(state);

I have tried using Ramda's map with the advanced typings from npm-ramda. This nearly worked, except the return result of any selector was a union of all selectors within its "scope".
I have set up a project on StackBlitz which demonstrates the problem.

A: TypeScript can't infer the return type of { [K in keyof typeof selector]: (state: RootState) => ReturnType<typeof selector[K]> }. Unfortunately inferring any types (or even defining them without requiring a cast) when using reduce to build an object is almost impossible.
That said, you can get the desired behavior with a bit of casting, and declaring the return type manually.
function scopeSelector<
  T extends keyof RootState,
  S extends { [selector: string]: (state: RootState[T]) => any }
>(
  scopeNamespace: T,
  selectors: S
): { [K in keyof S]: (state: RootState) => ReturnType<S[K]> } {
  return Object.keys(selectors).reduce((scoped, key) => ({
    ...scoped,
    [key]: (state: RootState) => selectors[key](state[scopeNamespace])
  }), {} as any);
}

Using {} as any removes any type safety in your reduce function, but you didn't have any in the first place, so I don't feel to bad about it.
Here's a StackBlitz so you can see it in action: Link

A: Yes, you can!
Type definition
Consider the following definition:
declare function scopeSelector<Namespace extends keyof RootState, SubSelectors extends Selectors<any, RootState[Namespace]>>(scope: Namespace, selectors: SubSelectors): Result<SubSelectors>;

Where:
type Selectors<K extends string = string, S = any> = {
  [index in K]: (state: S) => ValueOf<S>;
}

type Result<T> = {
  [K in keyof T]: (state: RootState) =>
    T[K] extends AnyFunction
      ? ReturnType<T[K]>
      : never;
}

type AnyFunction = (...args: any[]) => any;
type ValueOf<T> = T[keyof T];

Implementation
function scopeSelector<Namespace extends keyof RootState, SubSelectors extends Selectors<any, RootState[Namespace]>>(scope: Namespace, selectors: SubSelectors): Result<SubSelectors> {
  return Object.keys(selectors)
    .reduce<Result<SubSelectors>>(
      (accumulator, current) => ({
        ...accumulator,
        [current]: (state: RootState) => selectors[current](state[scope])
      }),
      {} as Result<SubSelectors>
    )
}


text:
Q: Log4j-2.6.2 Basic Configurator is not configuring the logging levels I was trying to implement a basic configurator via the following code
package com.myapp.loggingutilities;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class LoggingUtilitiesApplication {
    static Logger currentLogger = Logger.getLogger(LoggingUtilitiesApplication.class);

    public static void main(String[] args) {
        BasicConfigurator.configure();
        currentLogger.debug("Application Started here");
        LoggerUtilityModel bar = new LoggerUtilityModel();
        bar.doIt();
        currentLogger.debug("Application ended");

    }
}

The class def for bar is
package com.myapp.loggingutilities;
import org.apache.log4j.Logger;

public class LoggerUtilityModel {
    static Logger modelLogger = Logger.getLogger(LoggerUtilityModel.class);

    public void doIt() {
        modelLogger.debug("OPPS! DID IT AGAIN");
    }

}

I am using Log4j2 and the distribution was taken here. I am always getting the SLF4J bridge error when I have the Log4j-to-slf4j and implementation jars in build path:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
    at org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:59)

When I removed them, it was okay. But the log messages were not being printed
I thought BasicConfigurator ought to be configuring the root logger for DEBUG so all of my log statements should go through (i.e. anything on or above DEBUG level). But I cannot see any log messages on the console when I run the application. Something I have missed?

A: BasicConfigurator is a log4j 1.2 class and cannot be used to configure Log4j 2. Basically, everything in the org.apache.log4j package is Log4j 1.2 (old) and everything in the org.apache.logging.log4j namespace is for Log4j 2.
If you are interested in programmatic configuration of Log4j 2, please see the manual page. Personally I find the new simplified XML configuration file format easiest to work with.
The behavior you are seeing (only console logging at ERROR level) is Log4j 2's "default configuration", which is what it does if it can't find a configuration file and hasn't been manually configured.

A: The problem seems to be the LEVEL set for log4j2.6.2. As per Apache's Log4J-2.6.2 docs, all the default log messages are set for DEBUG.
Also, you CANNOT change the logging level using root logger. You need to change it per logger. Everything is defaulted to ERROR.


text:
Q: use not being recognized Class 'MailChimp' not found i am using this mailchimp-api according to the documentation i should just place
use \DrewM\MailChimp\MailChimp;

$MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');

directory structure

*

*index.php (this is where i call any library i use using use)

*composer.json

*vendor (this is the folder that contains all libraries from git and the autoload file)
-- drewm
--- mailchimp-api
---- src (this folder contains the Mailchimp.php that has namespace DrewM\MailChimp;)

*configs (config directory)
-- functions.php (this file contains the function for mailchimp)
now whenever i call this mailchimp() function i get

Fatal error: Uncaught Error: Class 'DrewM\MailChimp\MailChimp' not
  found

composer.json file
{
    "require": {
        "drewm/mailchimp-api": "^2.4",
        "ircmaxell/random-lib": "^1.2",
        "phpmailer/phpmailer": "^5.2"
    }
}

index.php
require_once './vendor/autoload.php';
require_once './config/functions.php';

functions.php
use \DrewM\MailChimp\MailChimp;
function mailchimp(){
    $MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');
    $result = $MailChimp->get('lists');
    print_r($result);
}

A: Probably the function class is not under the autoloader of Composer. You should add in the autoload section of the composer.json files as example:
"autoload": {
    "psr-0": { "": "./" },
    "files": ["configs/functions.php"]
}

And remove the require_once directive of functions.php from index.php
Hope this help

A: You need to include mailchimp in the functions.php
use \DrewM\MailChimp\MailChimp;
or you can use
function mailchimp(){
    $MailChimp = new \DrewM\MailChimp\MailChimp($apikey);
    $result = $MailChimp->get('lists');
    return $result;
}

and pass the $apikey in the class


text:
Q: Simulate map click on cesium entities I'm looking for a way to simulate mouse click on entity on cesium map, for automation tests using puppeteer or selenium..
or a way to convert cartesian2 or cartesian3 to a pixel xy position so I can click on the screen xy

A: Yes I've done it on a project
const scene = new Cesium.Viewer().scene;
const worldPos = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
const windowPosition = Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, worldPos);


text:
Q: sap.ui.table - FilterType on Column not working The filterType property of sap.ui.table.Column does not appear to work for me. Here is my code:

        abc}">

abc is containing a number as a string e.g. "10". The values are showing in the table so the bindings are correct.
Sorting also works but it does not respect the Integer type. I still get a String like sorting so that the entry "6" shows after "10" for an ascending sort. The column is even returning the filterType I set if I do sap.ui.getCore().byId("columnId").getFilterType(); What the heck is wrong here?
BR
Chris

A: It is working for the code snippet. You can click the column header to sort by descending or ascending and filter value.Please check.

A: To finally answer this: The filterType is NOT taken into account for sorting, no matter which view type you use. If you also think there should be a way to easily influence the sort logic you can support the issue here: https://github.com/SAP/openui5/issues/192


text:
Q: Jekyll rendering Markdown in _include not working I'm attempting to render some markdown within an _include file in my Jekyll site but for some reason I can't get it to work.  I'm trying 2 different methods, here is my markdown document
---
layout: post
title: "About"
description:
---
# This is a test

> pop

Here is my include file
<div class="tab">
    {% markdown about.markdown %}

    {% capture my-include %}{% include about.markdown %}{% endcapture %}
    {{ my-include | markdownify }}
</div>

As you can see, the first method I'm trying is using a plugin, shown below and sourced from here http://wolfslittlestore.be/2013/10/rendering-markdown-in-jekyll/, the second method is using markdownify,
=begin
  Jekyll tag to include Markdown text from _includes directory preprocessing with Liquid.
  Usage:
    {% markdown <filename> %}
  Dependency:
    - kramdown
=end
module Jekyll
  class MarkdownTag < Liquid::Tag
    def initialize(tag_name, text, tokens)
      super
      @text = text.strip
    end
    require "kramdown"
    def render(context)
      tmpl = File.read File.join Dir.pwd, "_includes", @text
      site = context.registers[:site]
      tmpl = (Liquid::Template.parse tmpl).render site.site_payload
      html = Kramdown::Document.new(tmpl).to_html
    end
  end
end
Liquid::Template.register_tag('markdown', Jekyll::MarkdownTag)

Unfortunately all it's doing (using both methods) is outputting the raw, unparsed markdown.
Any idea what I'm doing incorrectly?

A: Okay so I was mistaken, it does parse the markdown file, using both methods.  It's just that the produced styles do not match what I was expecting to see.  Plus it doesn't support the YAML front matter, so I removed that and tweaked my markdown file to look like I wanted it to originally.
One style that looks totally different is the Blockquote.  It's not the correct font, so that will be my style sheet that needs amending.


text:
Q: Upgrade failed Azure AKS from 1.8.1 to 1.8.6 Im trying to upgrade my Azure AKS cluster from version 1.8.1 to 1.8.6.
Deployment failed. Correlation ID: 09312a25-04f3-4e35-8f79-6b2337bb7f19. Operation failed with status: 200. Details: Resource state Failed
The output of command az aks upgrade --name myaks --resource-group myresourcegr --kubernetes-version 1.8.6
More output az aks show --name myaks --resource-group myresourcegr --output table
    Name     Location    ResourceGroup    KubernetesVersion    ProvisioningState    Fqdn
    -------  ----------  ---------------  -------------------  -------------------  -----------------------------------------
    myaks  westeurope  myresourcegr             1.8.6                Failed               myaks-81cf39b1.hcp.westeurope.azmk8s.io

Retrying the upgrade action I get always the same error
Edit
Output of command az aks get-versions -g myresourcegr -n myaks
{
  "agentPoolProfiles": [
    {
      "kubernetesVersion": "1.8.6",
      "name": null,
      "osType": "Linux",
      "upgrades": [
        "1.8.6"
      ]
    }
  ],
  "controlPlaneProfile": {
    "kubernetesVersion": "1.8.6",
    "name": null,
    "osType": "Linux",
    "upgrades": [
      "1.8.6"
    ]
  },
  "id": "/subscriptions/xxx-98ec-4db6-bfed-946d93a62a7c/resourcegroups/myresourcegr/providers/Microsoft.ContainerService/managedClusters/myaks/upgradeprofiles/default",
  "name": "default",
  "resourceGroup": "myresourcegr",
  "type": "Microsoft.ContainerService/managedClusters/upgradeprofiles"
}

A: When we consider for AKS upgrade, Always try with creating a new nodepool with the decided upgrade version to the cluster first and then drain the nodes of old nodepools . It will help you t identify the related issues and will be considered for the production upgrade process.


text:
Q: How do I fetch the value of selected value from drop down in PHP? Here's my drop down:
 <form name="form" method="POST" style="display:inline;">
            <select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;">
                 <option value="" disabled selected>Select Category</option>
            <?php
            $sth = $conn->prepare('Select name From category');
            $sth->execute();
            $data = $sth->fetchAll();
            foreach ($data as $row ){
                if($row['name']!="")
             echo ' <option id=\"CategoryName\" nameCategoryNameVendorName\" value="' .$row['name']. '">'.$row['name'].'</option>';
            }
            ?>
            </select>
     </form>

And I'm trying to access it using the following code:
if(!empty($_POST['category']))
     $category=$_POST['category'];

When I echo the value of $category, it returns null. Why is that? How can I get the value of the selected value from the drop down?

A: Hi In PHP we can submit form using a submit button or using javascript.
if you want to use only php you shoud add a submit button and check if that is posted then check for category like this.
        <form name="form" method="POST" style="display:inline;">
                    <select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;">
                         <option value="" disabled selected>Select Category</option>
                    <?php
                    $sth = $conn->prepare('Select name From category');
                    $sth->execute();
                    $data = $sth->fetchAll();
                    foreach ($data as $row ){
                        if($row['name']!="")
                     echo ' <option id=\"CategoryName\" nameCategoryNameVendorName\" value="' .$row['name']. '">'.$row['name'].'</option>';
                    }
                    ?>
                    </select>
    <input type="submit" name="submit" value="submit">
             </form>

<?php

    if(isset($_POST['submit'])){
         $category=$_POST['category'];}

or you can try javascript for  submission it will work on change of value in select box

    <form name="form" method="POST" style="display:inline;">
                <select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onchange="document.form.submit();">
                     <option value="" disabled selected>Select Category</option>
                <?php
                $sth = $conn->prepare('Select name From category');
                $sth->execute();
                $data = $sth->fetchAll();
                foreach ($data as $row ){
                    if($row['name']!="")
                 echo ' <option id=\"CategoryName\" nameCategoryNameVendorName\" value="' .$row['name']. '">'.$row['name'].'</option>';
                }
                ?>
                </select>
         </form>

<?php

if(!empty($_POST['category']))
     $category=$_POST['category'];

A: You need to use input type submit in form to get values in php
<form name="form" method="POST" style="display:inline;">
                <select name="category" id="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;">
                     <option value="" disabled selected>Select Category</option>
                <?php
                $sth = $conn->prepare('Select name From category');
                $sth->execute();
                $data = $sth->fetchAll();
                foreach ($data as $row ){
                    if($row['name']!="")
                 echo ' <option id="CategoryName" value="' .$row['name']. '">'.$row['name'].'</option>';
                }
                ?>
                </select>    <input type="submit" />
         </form>

    <?php
    if(!empty($_POST['category']))
         $category=$_POST['category'];
    print_r($category);
    ?>


text:
Q: How to add an attribute to an object at runtime in C#? I need to serialize any type of object. In order to serialize an object, it must have a Serializable attribute. So I need to add that attribute to any object at runtime. I think it's only possible by creating a new type using System.Reflection.
Here's a simple method that tests whether the object is serializable (has the Serializable attribute) or not.
bool IsObjectSerializable(object obj)
{
    try
    {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        // If it's not serializable (aka doesn't have the Serializable attribute) it will thrown an exception.
        formatter.Serialize(stream, obj);

        return true;
    }
    catch(SerializationException)
    {
        return false;
    }
}

I have a serializable and a non-serializable class:
[Serializable]
class SerializableTestObject
{
}

class TestObject
{
}

void Main()
{
    Console.WriteLine(IsObjectSerializable(new SerializableTestObject())); // prints true

    Console.WriteLine(IsObjectSerializable(new TestObject())); // prints false

    dynamic modifiedTestObject = AddAttributeToObject<SerializableAttribute>(new TestObject());
    Console.WriteLine(IsObjectSerializable(modifiedTestObject)); // should print true
}

What do I need to write in AddAttributeToObject?
I've done some research, but I found very little resources on this topic, and most people just say it's hard to do and stuff like that.


text:
Q: Form is not Submitted with Javascript I am working on a spring web application. In front end I am using JSP. I have a form (with id formToSubmit) in jsp -
<form:form id="formToSubmit" modelAttribute="jobForm" >

            Your Comments:

                (Required if you do not review the samples)

                <form:textarea id="newCommentsTextAreaId" path="newComments" rows="5" cols="50" />

                <input onclick="apprvRqstSbmt()"type="image" src="/images/buttons/approveBtn.png" />

                <input onclick="disApprvRqstSbmt()" type="image" src="/images/buttons/disApproveBtn.png" />

</form:form>

This form has two button - one for approve (with apprveBtn.png) and another for disapprove (with disApproveBtn.png). So I write some javascript to submit the form on button click -

When I click the disapprove button the form is submitted properly. But when I click on the approve button the form is not submitted properly. Can anyone help me why the form is not submitted properly?

A: Just removed the :form, I can't see why is it necessary.
Also, Thanks to Razib, except from the :form part which is unnecessary, you forgot to set the method to POST, so you can add it in the javascript part, or in the HTML. I did in both as you can see. You can use only one of them.

    function apprvRqstSbmt(){
        $("#formToSubmit").attr("method","POST");  //Razib solution
        $("#formToSubmit").attr("action","/some/url/to/submit");
        $("#formToSubmit").submit();
    }

    function disApprvRqstSbmt(){
        $("#formToSubmit").attr("method","POST");  //Razib solution
        $("#formToSubmit").attr("action","/some/url/to/submit");
        $("#formToSubmit").submit();
    }
    <form id="formToSubmit" modelAttribute="jobForm" method="POST" >

                Your Comments:

                    (Required if you do not review the samples)

                    <form:textarea id="newCommentsTextAreaId" path="newComments" rows="5" cols="50" />

                    <input onclick="apprvRqstSbmt()"type="image" src="/images/buttons/approveBtn.png" />

                    <input onclick="disApprvRqstSbmt()" type="image" src="/images/buttons/disApproveBtn.png" />

    </form>

JSFiddle: http://jsfiddle.net/6fp1ukzL/

A: I think you are missing the 'method' attribute in you javascript. You have to add attr("method", "POST") in your javascript. If I rewrite your code with my changes then it would be -

The disapprove button click working properly because the default method on form submit is 'GET'. Probably the disapprove button is throwing a get request.


text:
Q: Parsing XML for specific item using ElementTree I am making a request to the Salesforce merge API and getting a response like this:
xml_result = '<?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com">
    <soapenv:Header>
        <LimitInfoHeader>
            <limitInfo>
                <current>62303</current>
                <limit>2680000</limit><type>API REQUESTS</type></limitInfo>
        </LimitInfoHeader>
    </soapenv:Header>
    <soapenv:Body>
        <mergeResponse>
            <result>
                <errors>
                    <message>invalid record type</message>
                    <statusCode>INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY</statusCode>
                </errors>
                <id>003skdjf494244</id>
                <success>false</success>
           </result>
        </mergeResponse>
    </soapenv:Body>
</soapenv:Envelope>'

I'd like to be able to parse this response and if success=false, return the errors, statusCode, and the message text.
I've tried the following:
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml_result)

root.find('mergeResponse')
root.find('{urn:partner.soap.sforce.com}mergeResponse')
root.findtext('mergeResponse')
root.findall('{urn:partner.soap.sforce.com}mergeResponse')

...and a bunch of other variations of find, findtext and findall but I can't seem to get these to return any results.  Here's where I get stuck. I've tried to follow the ElementTree docs, but I don't understand how to parse the tree for specific elements.

A:
Element.find() finds the first child with a particular tag
  https://docs.python.org/2/library/xml.etree.elementtree.html#finding-interesting-elements

Since mergeResponse is a descendant, not a child, you should use XPath-syntax in this case:
root.find('.//{urn:partner.soap.sforce.com}mergeResponse')

will return your node. .// searches all descendants starting with the current node (in this case the root).


text:
Q: Can I use a remote user to log in into a remote SQL Server? Can I use the administrator user of a remote (no domain or anything like that) Windows Server to log in into the SQL Server running on that same machine? That would be, using the same credentials, user and password, as I use when I connect to that server with Remote Desktop.
Is there anything special I should do for that?
I'm talking about SQL Server 2008 and Windows Server 2008

A: If the username and password that you are logging into your local computer with, are the same as a username and password that exist on the SQL Server then yes.
If the username and/or password are different then no, you can't specify a Windows account and password when connecting using Windows Authentication.

A: As far as I could find, there's no way to use the Windows credentials to log into SQL Server.


text:
Q: Singleton Pattern in C
Possible Duplicate:
How to create a Singleton in C ?

Hello, if I have a structure definition as follows:
struct singleton
{
    char sharedData[256];
};

Can I impose the singleton pattern on instance variables of the above structure in C [not in C++]?

A: If you just forward declare your struct in the header file, it will be impossible for clients to create an instance of it. Then you can provide a getter function for your single instance.
Something like this:
.h:
#ifndef FOO_H
#define FOO_H

struct singleton;

struct singleton* get_instance();

#endif

.c:
struct singleton
{
    char sharedData[256];
};

struct singleton* get_instance()
{
    static struct singleton* instance = NULL;

    if (instance == NULL)
    {
        //do initialization here
    }

    return instance;
}

A: You can just declare:
char sharedData[256];

That's a global variable, no struct and singleton-antipattern needed.


text:
Q: How to call a python function in PySpark? I have a multiple files (CSV and XML) and I want to do some filters.
I defined a functoin doing all those filters, and I want to knwo how can I call it to be applicable for my CSV file?
PS: The type of my dataframe is: pyspark.sql.dataframe.DataFrame
Thanks in advance

A: For example, if you read in your first CSV files as df1 = spark.read.csv(..) and your second CSV file as df2 = spark.read.csv(..)
Wrap up all the multiple pyspark.sql.dataframe.DataFrame that came from CSV files alone into a list..
csvList = [df1, df2, ...]
and then,
for i in csvList:
    YourFilterOperation(i)

Basically, for every i which is pyspark.sql.dataframe.DataFrame that came from a CSV file stored in csvList, it should iterate one by one, go inside the loop and perform whatever filter operation that you've written.
Since you haven't provided any reproducible code, I can't see if this works on my Mac.


text:
Q: loop over columns for regression using purrr and caret I am trying to loop over regressions using purrr and caret, but I have trouble passing arguements.
# sample dataframe
foo <- data.frame(y1 = runif(10),
                  y2 = runif(10),
                  y3 = runif(10),
                  x1 = runif(10),
                  x2 = runif(10),
                  x3 = runif(10)
                  )

# list of dependent and independent variables
Yvars <- c("y1","y2","y3")
Xvars <- c("x1","x2","x3")

# library(caret)

# custom caret function to loop over vars
caretlm <- function(xvars, yvars, data) {
  set.seed(1123)
  lmFitTest <- train(x = eval(substitute(xvars)), y = eval(substitute(yvars)), data = data,
                     method = "lm",
                     trControl = trainControl(method = "cv")
  )
}

# library(purrr)

modellist_lm <- map2(xvars, yvars, ~caretlm(.x, .y, foo) )
# Error in eval(substitute(xvars)) : object '.x' not found

when I do not use eval and substitute, then I get another error
caretlm2 <- function(xvars, yvars, data) {
  set.seed(1123)
  lmFitTest <- train(x = xvars, y = yvars, data = data,
                     method = "lm",
                     trControl = trainControl(method = "cv")
  )
}

modellist_lm <- map2(xvars, yvars, ~caretlm2(.x, .y, foo) )

# Error: Please use column names for `x`

Please suggest if there are better methods or frameworks..

A: Not sure about the x, y method, but that function has a formula method which appears to me to be easier to work with (note that I changed Data to data)
caretlm <- function(xvars, yvars, data) {
  set.seed(1123)
  lmFitTest <- train(reformulate(xvars, yvars), data = foo,
                     method = "lm",
                     trControl = trainControl(method = "cv")
  )
}

modellist_lm <- map2(Xvars, Yvars, ~caretlm(.x, .y, foo))


text:
Q: How to rewrite url in .htaccess if the pointer is also a variable pointing the variable Rewrite in .htaccess for the URL:
http://localhost/name.php?**category**=$origin&gender=$gen&alpha=$alphabet
Written as:
RewriteRule ^name/([a-zA-Z]+)/([a-zA-Z]+)/([A-Z])/?$ name.php?category=$1&gender=$2&alpha=$3

to get URL as: http: //localhost/name/uk/girl/A
But how do I rewrite a URL in .htaccess file if the URL is:
http://localhost/name.php?**$category**=$origin&gender=$gen&alpha=$alphabet
Now the "category" also becomes a variable $category
variable category varies as: country or religion or language or anything else.