问:
<input type="file"> not working in webview
So I am a HTML/CSS developer in a noob stage. Im trying to build a simple webview app for my website. Now while i got a project from github for webview it seems that the "File Upload" doesnt work in webview but works like a charm in browser. Help me please. Also if the app's whole intention is just converting website into android app and if you think there is a project on github that can be easy for my purpose (file upload in webview) then you can give me the link to it! Thanks!

My MainActivity.java:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    private WebView mWebView;

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

        mWebView = (WebView) findViewById(R.id.activity_main_webview);

        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Use remote resource
        // mWebView.loadUrl("http://example.com");

        // Stop local links and redirects from opening in browser instead of WebView
        // mWebView.setWebViewClient(new MyAppWebViewClient());

        // Use local resource
        mWebView.loadUrl("file:///android_asset/www/index.html");
    }

    // Prevent the back-button from closing the app
    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @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);
    }
}```

答:
As per your expectation, I think you want to enable heavy task in your WebView. For that you need to enable ChromeClient,

```<code>mWebView.setWebChromeClient(new MyWebViewClient());
</code>```

And your MyWebViewClient class will be,

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

        mWebView = (WebView) findViewById(R.id.activity_main_webview);

        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyWebViewClient());    // HERE

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Use remote resource
        // mWebView.loadUrl("http://example.com");

        // Stop local links and redirects from opening in browser instead of WebView
        // mWebView.setWebViewClient(new MyAppWebViewClient());

        class MyWebViewClient extends WebChromeClient {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        }

        // Use local resource
        mWebView.loadUrl("file:///android_asset/www/index.html");
    }
</code>```

Body:
As per your expectation, I think you want to enable heavy task in your WebView. For that you need to enable ChromeClient,

mWebView.setWebChromeClient(new MyWebViewClient());

And your MyWebViewClient class will be,

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

        mWebView = (WebView) findViewById(R.id.activity_main_webview);

        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyWebViewClient());    // HERE

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Use remote resource
        // mWebView.loadUrl("http://example.com");

        // Stop local links and redirects from opening in browser instead of WebView
        // mWebView.setWebViewClient(new MyAppWebViewClient());

        class MyWebViewClient extends WebChromeClient {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        }

        // Use local resource
        mWebView.loadUrl("file:///android_asset/www/index.html");
    }


来源: stackexchange

问:
Trouble with PasteSpecial Transpose
I have written a macro to create a variable number of worksheets based on a list in worksheet "ProjList".  Each sheet is named at the time of creation. I am trying to copy the values in some of the cells (Columns A-D) from "ProjList" to the new sheets.  I've successfully done it with with a paste command, but I want the data transposed.

I have written:

```<code>Sub AddWorkSheets()
    Dim RowNumb As Long
    Dim LastRow As Integer
    LastRow = Worksheets("ProjList").Cells(Worksheets("ProjList").Rows.Count, "D").End(xlUp).Row

    For RowNumb = 2 To LastRow
        Sheets("ProjList").Activate
        Worksheets("ProjList").Range("A" & RowNumb, "D" & RowNumb).Copy
        Sheets.Add
        ActiveSheet.Name = Worksheets("ProjList").Cells(RowNumb, 4).Value
        ActiveSheet.Move After:=Sheets(ActiveWorkbook.Sheets.Count)
        ActiveSheet.Range("D1").PasteSpecial Paste:=xlPasteValues, transpose:=True
    Next RowNumb
End Sub
</code>```

I get a

RunTime Error 1004: PasteSpecial method of range class failed.

The first worksheet gets created, but the macro fails at the PasteSpecial line.

Any help is much appreciated.

Thank you!

答:
Try This:

```<code>ActiveSheet.Range("D1").Resize(, 4).PasteSpecial Paste:=xlPasteValues, transpose:=True
</code>```

try this code bellow:

```<code>Sub AddWorkSheets()
    Dim RowNumb As Long
    Dim LastRow As Integer
    LastRow = Worksheets("ProjList").Cells(Worksheets("ProjList").Rows.Count, "D").End(xlUp).Row

    For RowNumb = 2 To LastRow
        Sheets("ProjList").Activate
        Sheets.Add
        ActiveSheet.Name = Worksheets("ProjList").Cells(RowNumb, 4).Value
        ActiveSheet.Move After:=Sheets(ActiveWorkbook.Sheets.Count)
        ActiveSheet.Range("D1").Resize(, 4) = Application.WorksheetFunction.Transpose(Worksheets("ProjList").Range("A" & RowNumb, "D" & RowNumb))
    Next RowNumb
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Trouble with PasteSpecial Transpose

Body:
I have written a macro to create a variable number of worksheets based on a list in worksheet "ProjList".  Each sheet is named at the time of creation. I am trying to copy the values in some of the cells (Columns A-D) from "ProjList" to the new sheets.  I've successfully done it with with a paste command, but I want the data transposed.

I have written:

Sub AddWorkSheets()
    Dim RowNumb As Long
    Dim LastRow As Integer
    LastRow = Worksheets("ProjList").Cells(Worksheets("ProjList").Rows.Count, "D").End(xlUp).Row

    For RowNumb = 2 To LastRow
        Sheets("ProjList").Activate
        Worksheets("ProjList").Range("A" & RowNumb, "D" & RowNumb).Copy
        Sheets.Add
        ActiveSheet.Name = Worksheets("ProjList").Cells(RowNumb, 4).Value
        ActiveSheet.Move After:=Sheets(ActiveWorkbook.Sheets.Count)
        ActiveSheet.Range("D1").PasteSpecial Paste:=xlPasteValues, transpose:=True
    Next RowNumb
End Sub

I get a

RunTime Error 1004: PasteSpecial method of range class failed.

The first worksheet gets created, but the macro fails at the PasteSpecial line.

Any help is much appreciated.

Thank you!

Body:
Try This:

ActiveSheet.Range("D1").Resize(, 4).PasteSpecial Paste:=xlPasteValues, transpose:=True

try this code bellow:

Sub AddWorkSheets()
    Dim RowNumb As Long
    Dim LastRow As Integer
    LastRow = Worksheets("ProjList").Cells(Worksheets("ProjList").Rows.Count, "D").End(xlUp).Row

    For RowNumb = 2 To LastRow
        Sheets("ProjList").Activate
        Sheets.Add
        ActiveSheet.Name = Worksheets("ProjList").Cells(RowNumb, 4).Value
        ActiveSheet.Move After:=Sheets(ActiveWorkbook.Sheets.Count)
        ActiveSheet.Range("D1").Resize(, 4) = Application.WorksheetFunction.Transpose(Worksheets("ProjList").Range("A" & RowNumb, "D" & RowNumb))
    Next RowNumb
End Sub


问:
How to create navigation bar item in the custom Navigation Bar in iPhone?
I have created one custom view and added a web view as subview of that custom view. And i have created one navigation bar in programmatically. Now i want to create one Left or Right navigation bar buttons in that view.

```<code>navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

navigBar.tintColor = [UIColor blackColor];

[self.view addSubview:navigBar];

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonSystemItemAction target:self action:@selector(homeButtonAction)];

navigBar.rightBarButtonItem = homeButton; // it's not supports
</code>```

How can i create navigation bar item in the custom navigation bar?, i want to remove the custom view. So please Help me out!

Thanks.

答:
See http://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationItem_Class/Reference/UINavigationItem.html

You would invoke methods to self.navigationItem.

ContentLicense: CC BY-SA 2.5

Body:
I have created one custom view and added a web view as subview of that custom view. And i have created one navigation bar in programmatically. Now i want to create one Left or Right navigation bar buttons in that view.

navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

navigBar.tintColor = [UIColor blackColor];

[self.view addSubview:navigBar];

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonSystemItemAction target:self action:@selector(homeButtonAction)];

navigBar.rightBarButtonItem = homeButton; // it's not supports

How can i create navigation bar item in the custom navigation bar?, i want to remove the custom view. So please Help me out!

Thanks.


问:
How to avoid promise nesting
I have a feeling I'm doing an overkill nesting in the following simple function, which simply reads a value from one location and writes it to another location.

Is there a way to simplify it somehow?

```<code>exports.myFunc = functions.database.ref('...').onCreate(event => {
    const list_id = event.params.list_id;
    return new Promise(function(resolve, reject){
        event.data.adminRef.root.child('lists').child(list_id).child('owner').once('value').then(function(snap){
            const owner_id = snap.val();
            if (owner_id != null) {
                event.data.adminRef.root.child('users').child(owner_id).child('whatever').child('whatever2').set(true)
                    .then(function() {
                        resolve();
                    },
                    function(err) {
                        reject();
                    }
                )
            } else {
                reject();
            }
        });
    });
})
</code>```

答:
You don't need a new promise if you have existing promises to work with.  You can return promises from then to continue chaining.

```<code>exports.myFunc = functions.database.ref('...').onCreate(event => {
    const list_id = event.params.list_id;
    return event.data.adminRef.root.child('...').once('value')
    .then(function(snap){
        const owner_id = snap.val();
        if (owner_id != null) {
            return event.data.adminRef.root.child('...').set(true)
        } else {
            return Promise.reject('error message')
        }
    });
})
</code>```

Title: How to avoid promise nesting

Body:
I have a feeling I'm doing an overkill nesting in the following simple function, which simply reads a value from one location and writes it to another location.

Is there a way to simplify it somehow?

exports.myFunc = functions.database.ref('...').onCreate(event => {
    const list_id = event.params.list_id;
    return new Promise(function(resolve, reject){
        event.data.adminRef.root.child('lists').child(list_id).child('owner').once('value').then(function(snap){
            const owner_id = snap.val();
            if (owner_id != null) {
                event.data.adminRef.root.child('users').child(owner_id).child('whatever').child('whatever2').set(true)
                    .then(function() {
                        resolve();
                    },
                    function(err) {
                        reject();
                    }
                )
            } else {
                reject();
            }
        });
    });
})

Body:
You don't need a new promise if you have existing promises to work with.  You can return promises from then to continue chaining.

exports.myFunc = functions.database.ref('...').onCreate(event => {
    const list_id = event.params.list_id;
    return event.data.adminRef.root.child('...').once('value')
    .then(function(snap){
        const owner_id = snap.val();
        if (owner_id != null) {
            return event.data.adminRef.root.child('...').set(true)
        } else {
            return Promise.reject('error message')
        }
    });
})


问:
Convert string to date not same in swift 3
Why? i convert string to date, input not same output?</p>

```<code>Input:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
dateLahir = formatter.date(from: "2017-10-05")
print("date: \(dateLahir)")

Output:
date: 2017-10-04
</code>```

答:
In Swift 3
Convert Date to String

```<code>class func convertDateToString(_ dateStr: String?, fromDateFormat currentFormat: String, toDateFormat newFormat: String) -> String? {

    if dateStr == nil {
        return nil
    }

    let formatter:DateFormatter = DateFormatter()
    formatter.dateFormat = currentFormat
    let date = formatter.date(from: dateStr!)

    if date == nil {
        return ""
    }

    formatter.dateFormat = newFormat
    let newStr: String = formatter.string(from: date!)

    return newStr
}
</code>```

Convert string to Date

```<code>class func convertStringToDate(_ strDate: String, dateFormat: String) -> Date? {
    let formatter: DateFormatter = DateFormatter()
    formatter.dateFormat = dateFormat
    formatter.timeZone = TimeZone.autoupdatingCurrent

    let date = formatter.date(from: strDate)

    return date;
}
</code>```

Body:
Why? i convert string to date, input not same output?

Input:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
dateLahir = formatter.date(from: "2017-10-05")
print("date: \(dateLahir)")

Output:
date: 2017-10-04

Body:
In Swift 3
Convert Date to String

class func convertDateToString(_ dateStr: String?, fromDateFormat currentFormat: String, toDateFormat newFormat: String) -> String? {

    if dateStr == nil {
        return nil
    }

    let formatter:DateFormatter = DateFormatter()
    formatter.dateFormat = currentFormat
    let date = formatter.date(from: dateStr!)

    if date == nil {
        return ""
    }

    formatter.dateFormat = newFormat
    let newStr: String = formatter.string(from: date!)

    return newStr
}

Convert string to Date

class func convertStringToDate(_ strDate: String, dateFormat: String) -> Date? {
    let formatter: DateFormatter = DateFormatter()
    formatter.dateFormat = dateFormat
    formatter.timeZone = TimeZone.autoupdatingCurrent

    let date = formatter.date(from: strDate)

    return date;
}


问:
SearchView with multiple fragments using viewpager in android
I want to implement SearchView with multiple fragments present in a viewPager. All fragemnts contains lists and I want to filter those lists and create a new ListView which has categorization of results based upon which fragment it belongs to.

But my searchView is not working with one fragment.

Here is my main activity:

```<code>package com.codeon.directory;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import com.codeon.directory.fragments.FiveFragment;
import com.codeon.directory.fragments.FourFragment;
import com.codeon.directory.fragments.OneFragment;
import com.codeon.directory.fragments.SixFragment;
import com.codeon.directory.fragments.ThreeFragment;
import com.codeon.directory.fragments.TwoFragment;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Nikhil Jain on 21-Sep-15.
 */
public class TabEffect extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    public String pic[] = {"1","2","3","1","2","3","1","2","3","1","2","3","1","2","3"};
    public String state[] = {"A","B","C"};
    public String city[] = {"P","Q","R"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tablayout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.tab, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        Bundle bundle = new Bundle();
        bundle.putStringArray("pic", pic);
        bundle.putStringArray("district", city);
        bundle.putStringArray("state", state);
        adapter.addFragment(new OneFragment(), "ONE FRAGMENT", bundle);
        adapter.addFragment(new TwoFragment(), "TWO FRAGMENT", bundle);
        adapter.addFragment(new ThreeFragment(), "THREE FRAGMENT", bundle);
        adapter.addFragment(new FourFragment(), "FOUR FRAGMENT", bundle);
        adapter.addFragment(new FiveFragment(), "FIVE FRAGMENT", bundle);
        adapter.addFragment(new SixFragment(), "SIX FRAGMENT", bundle);
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

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

        public void addFragment(Fragment fragment, String title, Bundle args) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
            fragment.setArguments(args);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}
</code>```

This is my first fragment :

```<code>package com.codeon.directory.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.codeon.directory.R;
import com.codeon.directory.RecyclerAdapter;
import com.codeon.directory.customadapters.Listitems_new;

import java.util.ArrayList;

/**
 * Created by Nikhil Jain on 21-Sep-15.
 */
public class OneFragment extends Fragment {

    ListView list;
    private ArrayAdapter<String> listAdapter ;

    public OneFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView rootView = (RecyclerView) inflater.inflate(R.layout.fragment_one, container, false);
        // Inflate the layout for this fragment
        Bundle extras = getArguments();
        String pic[] = extras.getStringArray("pic");
        String state[] = extras.getStringArray("state");
        Log.e("VALUE",pic[0]+pic[1]+pic[2]);

        rootView.setLayoutManager(new LinearLayoutManager(rootView.getContext()));
        //listAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, pic);
        rootView.setAdapter(new RecyclerAdapter(pic));
        return rootView;
    }
}
</code>```

My SearchActivity:

```<code>package com.codeon.directory;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
  * Created by Nikhil Jain on 21-Sep-15.
*/
public class SearchActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    // Get the intent, verify the action and get the query
    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        doMySearch(query);
        Log.e("QUERY", query);
    }
}

private void doMySearch(String query) {

}
}
</code>```

This is my AndroidManifest.xml:

```<code><activity
        android:name=".TabEffect"
        android:label="@string/tablayout"
        android:theme="@style/AppTheme" >
    </activity>
    <activity android:name=".SearchActivity" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data android:name="android.app.searchable"
            android:resource="@layout/searchable"/>
    </activity>
</code>```

This is my Searchable layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<searchable
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
</code>```

For simple, I want to implement searchView like in Whatsapp.

答:
I got my fragments have list with one Searchview working by using following code..
Place the code in each fragment where you want to

```<code> @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser)
    {
       search_bar.setOnQueryTextListener(this);
        if(listAdapter!=null)
            listAdapter.getFilter().filter(search_bar.getQuery());
    }
}
</code>```

Screenshots:

Body:
I want to implement SearchView with multiple fragments present in a viewPager. All fragemnts contains lists and I want to filter those lists and create a new ListView which has categorization of results based upon which fragment it belongs to.

But my searchView is not working with one fragment.

Here is my main activity:

package com.codeon.directory;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import com.codeon.directory.fragments.FiveFragment;
import com.codeon.directory.fragments.FourFragment;
import com.codeon.directory.fragments.OneFragment;
import com.codeon.directory.fragments.SixFragment;
import com.codeon.directory.fragments.ThreeFragment;
import com.codeon.directory.fragments.TwoFragment;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Nikhil Jain on 21-Sep-15.
 */
public class TabEffect extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    public String pic[] = {"1","2","3","1","2","3","1","2","3","1","2","3","1","2","3"};
    public String state[] = {"A","B","C"};
    public String city[] = {"P","Q","R"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tablayout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.tab, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        Bundle bundle = new Bundle();
        bundle.putStringArray("pic", pic);
        bundle.putStringArray("district", city);
        bundle.putStringArray("state", state);
        adapter.addFragment(new OneFragment(), "ONE FRAGMENT", bundle);
        adapter.addFragment(new TwoFragment(), "TWO FRAGMENT", bundle);
        adapter.addFragment(new ThreeFragment(), "THREE FRAGMENT", bundle);
        adapter.addFragment(new FourFragment(), "FOUR FRAGMENT", bundle);
        adapter.addFragment(new FiveFragment(), "FIVE FRAGMENT", bundle);
        adapter.addFragment(new SixFragment(), "SIX FRAGMENT", bundle);
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

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

        public void addFragment(Fragment fragment, String title, Bundle args) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
            fragment.setArguments(args);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

This is my first fragment :

package com.codeon.directory.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.codeon.directory.R;
import com.codeon.directory.RecyclerAdapter;
import com.codeon.directory.customadapters.Listitems_new;

import java.util.ArrayList;

/**
 * Created by Nikhil Jain on 21-Sep-15.
 */
public class OneFragment extends Fragment {

    ListView list;
    private ArrayAdapter<String> listAdapter ;

    public OneFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView rootView = (RecyclerView) inflater.inflate(R.layout.fragment_one, container, false);
        // Inflate the layout for this fragment
        Bundle extras = getArguments();
        String pic[] = extras.getStringArray("pic");
        String state[] = extras.getStringArray("state");
        Log.e("VALUE",pic[0]+pic[1]+pic[2]);

        rootView.setLayoutManager(new LinearLayoutManager(rootView.getContext()));
        //listAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, pic);
        rootView.setAdapter(new RecyclerAdapter(pic));
        return rootView;
    }
}

My SearchActivity:

package com.codeon.directory;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
  * Created by Nikhil Jain on 21-Sep-15.
*/
public class SearchActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    // Get the intent, verify the action and get the query
    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        doMySearch(query);
        Log.e("QUERY", query);
    }
}

private void doMySearch(String query) {

}
}

This is my AndroidManifest.xml:

<activity
        android:name=".TabEffect"
        android:label="@string/tablayout"
        android:theme="@style/AppTheme" >
    </activity>
    <activity android:name=".SearchActivity" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data android:name="android.app.searchable"
            android:resource="@layout/searchable"/>
    </activity>

This is my Searchable layout:

<?xml version="1.0" encoding="utf-8"?>
<searchable
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>

For simple, I want to implement searchView like in Whatsapp.

Body:
I got my fragments have list with one Searchview working by using following code..
Place the code in each fragment where you want to

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser)
    {
       search_bar.setOnQueryTextListener(this);
        if(listAdapter!=null)
            listAdapter.getFilter().filter(search_bar.getQuery());
    }
}

Screenshots:


问:
How to initialise a mongokitten server globally in a swift file other than the main.swift file?
I use mongodb to store all data of my mac application.So I use Mongokitten library as the interface between the db and my app. Inorder to connect to db initially and maintain the connection throughout the time when application is running I need to establish a one time connection to db. But I'm not able to initialise the server globally in the swift file.What i do is connect to the server each time a operation(insertion, updation, deletion, read) is performed.This causes the connection to the server to be lost once when these operations are executed over a limit and causes my application to hang. Can anyone please help me find a solution to make the server connection only once for throughout running of application?</p>

答:
I found the answer.Implicitly unwrap the server variable and assign value to server on checking server connection.
For reference follow the link :https://swiftmodules.com/planteam/mongokitten</p>


问:
draggable droppable with sortable
we trying to integrate multiple drggable and droppable. we are using sortable for ease of clone functionality in this scenario. draggable once dropped need to be draggable again.

how do we limit sortable to receive only one element and revert to original if more than one dropped onto it.

look like out and over functions of sortable are misbehaving in that case.

commented line code is for disabling dropping second element on sortable. which is not working as expected.

Two issues when you enable my commented code:

draggable clone not reverting to original place after moving out of droppable.

draggable element moved from one droppable to another reverting to draggable's original place.

For a demonstration, see this jsfiddle

script:

```<code>//  jQuery.noConflict();

jQuery( document ).ready(function() { init();});
function init() {

  var mouse_button = false;
  jQuery('.ui-draggable').live({
      mousedown: function () {
          mouse_button = true;
      },
      mouseup: function () {

          if (jQuery(this).attr('data-pos') == 'out' && jQuery(this).attr('data-id')) {
              var p = jQuery('#' + jQuery(this).attr('data-id'));
              var offset = p.offset();
              jQuery(this).hide();
              jQuery(this).animate({ left: offset.left, top: offset.top, width: jQuery(this).width, height: jQuery(this).height }, 100, function () {
                  jQuery(this).remove();
                  $( ".ui-droppable" ).each(function() {
                    if($(this).children().length == 0) {
                      $( this ).removeClass("dontDrop");
                    }
                  });
                  //if(p[0].hasAttribute("draggable"))
                  p.draggable("enable");

             //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
             //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));

              });
          }
          mouse_button = false;
      },
      mouseout: function () {
          if (mouse_button) {
              mouse_button = false;
          }
      }

  });

    jQuery( '.ui-draggable' ).draggable( {
      cursor: 'move',
      helper: 'clone',
      connectToSortable: ".ui-droppable",
      revert: function (event, ui) {
        }
    } );

    jQuery(".ui-droppable").sortable({
        cursor: "move",
        connectWith: ".ui-droppable",
        receive: function (event, ui) {

        if($(this).children().length >= 1) {

            $(this).children().addClass('filled');
            $(this).addClass('dontDrop');

            $( ".ui-droppable" ).each(function() {
              if($(this).children().length == 0) {
                $( this ).removeClass("dontDrop");
              }
            });
       //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
       //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));
        }else {
            $(this).children().removeClass('filled');
        }
        if (jQuery(this).data().sortable.currentItem) {
                jQuery(this).data().sortable.currentItem.attr('data-id', jQuery(ui.item).attr("id"));
               // if(jQuery(ui.item)[0].hasAttribute("draggable"))
                jQuery(ui.item).draggable("disable");
            }

        },
        out: function (event, ui) {  if (ui.helper) { ui.helper.attr('data-pos', 'out'); } },
        over: function (event, ui) { ui.helper.attr('data-pos', 'in'); }
    });

  }
</code>```

答:
Determining when to revert may be best done in .draggable() using revert: function(){}.

Function: A function to determine whether the element should revert to its start position. The function must return true to revert the element.

You can do this:

```<code>  jQuery('.ui-draggable').draggable({
    cursor: 'move',
    helper: 'clone',
    connectToSortable: ".ui-droppable",
    revert: function(item) {
      if (!item) {
        return true;
      } else {
        if (item.hasClass("dontDrop")) {
          return true;
        }
      }
      return false;
    }
  });
</code>```

the revert function is passed false if the draggable item is not accepted. For example, if it is dropped on something that is not a target. If the draggable item is accepted, a jQuery Object is passed back.

See more: jQueryUI sortable,draggable revert event

The logic is a little confusing. If what is passed back is false, we return true to revert letting draggable revert the item to it's position. If what is passed back is not false, then it's an object we can test. If the target is "full", we revert. Otherwise we do not revert.

Sortable still wants add the item for some reason. May need to adjust to update and clear out any items that are not class "filled".

Fiddle: https://jsfiddle.net/Twisty/7mmburcx/32/

Title: draggable droppable with sortable

Body:
we trying to integrate multiple drggable and droppable. we are using sortable for ease of clone functionality in this scenario. draggable once dropped need to be draggable again.

how do we limit sortable to receive only one element and revert to original if more than one dropped onto it.

look like out and over functions of sortable are misbehaving in that case.

commented line code is for disabling dropping second element on sortable. which is not working as expected.

Two issues when you enable my commented code:

draggable clone not reverting to original place after moving out of droppable.

draggable element moved from one droppable to another reverting to draggable's original place.

For a demonstration, see this jsfiddle

script:

//  jQuery.noConflict();

jQuery( document ).ready(function() { init();});
function init() {

  var mouse_button = false;
  jQuery('.ui-draggable').live({
      mousedown: function () {
          mouse_button = true;
      },
      mouseup: function () {

          if (jQuery(this).attr('data-pos') == 'out' && jQuery(this).attr('data-id')) {
              var p = jQuery('#' + jQuery(this).attr('data-id'));
              var offset = p.offset();
              jQuery(this).hide();
              jQuery(this).animate({ left: offset.left, top: offset.top, width: jQuery(this).width, height: jQuery(this).height }, 100, function () {
                  jQuery(this).remove();
                  $( ".ui-droppable" ).each(function() {
                    if($(this).children().length == 0) {
                      $( this ).removeClass("dontDrop");
                    }
                  });
                  //if(p[0].hasAttribute("draggable"))
                  p.draggable("enable");

             //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
             //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));

              });
          }
          mouse_button = false;
      },
      mouseout: function () {
          if (mouse_button) {
              mouse_button = false;
          }
      }

  });

    jQuery( '.ui-draggable' ).draggable( {
      cursor: 'move',
      helper: 'clone',
      connectToSortable: ".ui-droppable",
      revert: function (event, ui) {
        }
    } );

    jQuery(".ui-droppable").sortable({
        cursor: "move",
        connectWith: ".ui-droppable",
        receive: function (event, ui) {

        if($(this).children().length >= 1) {

            $(this).children().addClass('filled');
            $(this).addClass('dontDrop');

            $( ".ui-droppable" ).each(function() {
              if($(this).children().length == 0) {
                $( this ).removeClass("dontDrop");
              }
            });
       //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
       //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));
        }else {
            $(this).children().removeClass('filled');
        }
        if (jQuery(this).data().sortable.currentItem) {
                jQuery(this).data().sortable.currentItem.attr('data-id', jQuery(ui.item).attr("id"));
               // if(jQuery(ui.item)[0].hasAttribute("draggable"))
                jQuery(ui.item).draggable("disable");
            }

        },
        out: function (event, ui) {  if (ui.helper) { ui.helper.attr('data-pos', 'out'); } },
        over: function (event, ui) { ui.helper.attr('data-pos', 'in'); }
    });

  }

Body:
Determining when to revert may be best done in .draggable() using revert: function(){}.

Function: A function to determine whether the element should revert to its start position. The function must return true to revert the element.

You can do this:

  jQuery('.ui-draggable').draggable({
    cursor: 'move',
    helper: 'clone',
    connectToSortable: ".ui-droppable",
    revert: function(item) {
      if (!item) {
        return true;
      } else {
        if (item.hasClass("dontDrop")) {
          return true;
        }
      }
      return false;
    }
  });

the revert function is passed false if the draggable item is not accepted. For example, if it is dropped on something that is not a target. If the draggable item is accepted, a jQuery Object is passed back.

See more: jQueryUI sortable,draggable revert event

The logic is a little confusing. If what is passed back is false, we return true to revert letting draggable revert the item to it's position. If what is passed back is not false, then it's an object we can test. If the target is "full", we revert. Otherwise we do not revert.

Sortable still wants add the item for some reason. May need to adjust to update and clear out any items that are not class "filled".

Fiddle: https://jsfiddle.net/Twisty/7mmburcx/32/


问:
session variable not available in global before(:each, :type => :controller)
I'm refactoring some specs, in controller specs I have a before(:each) which sets up things required in the session, wanted to avoid duplication and put the initial setup global for each controller spec

my before filter is...

```<code>config.before(:each, :type => :controller) do

  #...

  session[:current_user] = @user
  session[:instance] = @instance

  #...

end
</code>```

@user and @instance are also set in the before(:each)
i've just hidden them for readability here

I get the following error when running the controller tests

```<code>undefined method `session' for nil:NilClass
</code>```

I would expect the global before callbacks to have the same things as the ones in the individual tests but I guess maybe they are loaded before the rails environment has been initialised?

Thanks

答: Use controller.stub!(:session, { :current_user => @user, :instance => @instance })

Body:
I'm refactoring some specs, in controller specs I have a before(:each) which sets up things required in the session, wanted to avoid duplication and put the initial setup global for each controller spec

my before filter is...

config.before(:each, :type => :controller) do

  #...

  session[:current_user] = @user
  session[:instance] = @instance

  #...

end

@user and @instance are also set in the before(:each)
i've just hidden them for readability here

I get the following error when running the controller tests

undefined method `session' for nil:NilClass

I would expect the global before callbacks to have the same things as the ones in the individual tests but I guess maybe they are loaded before the rails environment has been initialised?

Thanks


问:
Rust/Rocket can't compile `state` and `pear_codegen`
I'm getting started with Rust and Rocket.

I'm following the instructions with the Rocket Getting Started and I'm getting "error: Could not compile state." The full log is here:`

~/.cargo/bin/cargo run
      Updating registry https://github.com/rust-lang/crates.io-index  Downloading rocket_codegen v0.3.3  Downloading rocket v0.3.3

  Compiling gcc v0.3.54    Compiling smallvec v0.4.4    Compiling libc
  v0.2.34    Compiling version_check v0.1.3    Compiling language-tags
  v0.2.2    Compiling serde v1.0.23    Compiling state v0.3.2
  error[E0554]: #![feature] may not be used on the stable release
  channel  -->
  /Users/ktenjin/.cargo/registry/src/github.com-1ecc6299db9ec823/state-0.3.2/src/lib.rs:1:1
  | 1 | #![feature(const_fn)]   | ^^^^^^^^^^^^^^^^^^^^^

error[E0554]: #![feature] may not be used on the stable release
  channel  -->
  /Users/ktenjin/.cargo/registry/src/github.com-1ecc6299db9ec823/state-0.3.2/src/lib.rs:2:1
  | 2 | #![feature(const_unsafe_cell_new)]   |
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error[E0554]: #![feature] may not be used on the stable release
  channel  -->
  /Users/ktenjin/.cargo/registry/src/github.com-1ecc6299db9ec823/state-0.3.2/src/lib.rs:3:1
  | 3 | #![feature(const_atomic_usize_new)]   |
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error[E0554]: #![feature] may not be used on the stable release
  channel  -->
  /Users/ktenjin/.cargo/registry/src/github.com-1ecc6299db9ec823/state-0.3.2/src/lib.rs:4:1
  | 4 | #![feature(const_atomic_bool_new)]   |
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 4 previous errors

error: Could not compile state. warning: build failed, waiting for
  other jobs to finish... error: build failed

I run it again and I got

error: Could not compile pear_codegen.

How do I resolve this. Please help! Thanks!

答:
The rocket tutorial states that you need rust nightly in order to compile it. In order to install nightly, you do as they say in this page they link in the tutorial:

install rustup

do rustup default nightly

This is all in the docs, so it should be obvious. But from my own experience I often miss those obvious things because starting with a new language is hard and you have jumped over many hurdles already and these might just have been the one hurdle which made you stumble.


问:
WP-admin does not redirect to login page
If I browse to my wordpress wp-admin directory,  I recall that I used to get redirected to the login page if I was not already logged in.  Now I get the standard wordpress page not found error.  I'm not aware of changing any configuration that would alter this behavior.   Are there things that could have been done to stop the auto redirection from occurring?  Or something I need to re-enable or reverse to get that behaviour back?</p>

答:
Yes, generally it is a practice used for security reasons, because you see if I know that you are using Wordpress then I can easily guess all your URLs, login URL, Admin URL, Register URL, etc...

There are some plugins that would do that for you, IThemes is an example.

Themes Security hides common WordPress security vulnerabilities,
  preventing attackers from learning too much about your site and away
  from sensitive areas like your site’s login, admin, etc.

Changes the URLs for WordPress dashboard areas including login, admin
  and more

So the short answer is, yes you can configure it one way or another.

To Undo it, configure it again


问:
Passing a multidimensional array through hidden input via POST
So I researched online to see how I can pass an array which I POST through form.

Here's what I did.

```<code>    $itemsArr = array();
    while ($row = $result->fetch_assoc()) {
    $totalPrice += $row['item_price'];
    $totalItemsOnCart += $row['quantity'];
    $itemId = $row['item_idPK'];
    $itemName = $row['item_name'];
    $itemPrice = $row['item_price'];
    $itemQty = $row['quantity'];
    $itemsArr[] = array($userId, $itemId, $itemQty);

    echo "<tr>";
    echo "<td>".$itemId."</td>";
    echo "<td>".$itemName."</td>";
    echo "<td>".$itemPrice."</td>";
    echo "<td>".$itemQty."</td>";
    echo "</tr>";
    }
</code>```

Then, I used the foreach loop to iterate through the multidimensional array.

```<code>echo "<form class = 'BreadCode' action='Function_Cart.php' method='POST'>";
foreach($itemsArr as $value){
    print_r($value);
    echo '<input type="hidden" name="itemsArr[]" value="'. $value. '">';
}
    echo "<input type='hidden' name='userId' value='$userId'>";
    echo "<input type='hidden' name='itemId' value='$itemId'>";
    echo "<input type='hidden' name='quantity' value='$itemQty'>";
    echo "<input class='PayButton' type='submit' name='Btn-pay' value='Pay'>";
    echo "</form>";
</code>```

I keep getting an  "Array to string conversion" error with or without the echo for the hidden input within the foreach() loop

I haven't really tried sending an array via form through POST method in the past. I just don't know how to go about this.

Below is the result of print_r()

```<code>Array ( [0] => 5112 [1] => 105 [2] => 2 )
Array ( [0] => 5112 [1] => 104 [2] => 1 )
</code>```

Please help.

Thank you.

答:
You just need to encode array to json and decode it on action page

```<code>echo '<input type="hidden" name="itemsArr" value="'.json_encode($itemsArr). '">';
</code>```

And at your action Page just decode it

```<code>$itemsArr = json_decode($_POST['itemsArr'],true)
</code>```

Body:
So I researched online to see how I can pass an array which I POST through form.

Here's what I did.

    $itemsArr = array();
    while ($row = $result->fetch_assoc()) {
    $totalPrice += $row['item_price'];
    $totalItemsOnCart += $row['quantity'];
    $itemId = $row['item_idPK'];
    $itemName = $row['item_name'];
    $itemPrice = $row['item_price'];
    $itemQty = $row['quantity'];
    $itemsArr[] = array($userId, $itemId, $itemQty);

    echo "
";
    echo "".$itemId."	";
    echo "".$itemName."	";
    echo "".$itemPrice."	";
    echo "".$itemQty."	";
    echo "
";
    }

Then, I used the foreach loop to iterate through the multidimensional array.

echo "<form class = 'BreadCode' action='Function_Cart.php' method='POST'>";
foreach($itemsArr as $value){
    print_r($value);
    echo '<input type="hidden" name="itemsArr[]" value="'. $value. '">';
}
    echo "<input type='hidden' name='userId' value='$userId'>";
    echo "<input type='hidden' name='itemId' value='$itemId'>";
    echo "<input type='hidden' name='quantity' value='$itemQty'>";
    echo "<input class='PayButton' type='submit' name='Btn-pay' value='Pay'>";
    echo "</form>";

I keep getting an  "Array to string conversion" error with or without the echo for the hidden input within the foreach() loop

I haven't really tried sending an array via form through POST method in the past. I just don't know how to go about this.

Below is the result of print_r()

Array ( [0] => 5112 [1] => 105 [2] => 2 )
Array ( [0] => 5112 [1] => 104 [2] => 1 )

Please help.

Thank you.

Body:
You just need to encode array to json and decode it on action page

echo '<input type="hidden" name="itemsArr" value="'.json_encode($itemsArr). '">';

And at your action Page just decode it

$itemsArr = json_decode($_POST['itemsArr'],true)


问:
How to echo <img src with PHP variables as values of the src attribute
I am getting error when I try to echo image in PHP.  Here is my code:

```<code>$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '
    <img src = "'$pathx'.'$row["filename"]'">
    ';
    //filenames in database end with appropriate image extensions like .png

}
</code>```

And I am getting this error:
    Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ','
    or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

```<code>echo'<img src = "directory/images/girl-g2109_5_720.jpg">';
</code>```

答:
Try this

There are multiple ways to display the image. You can also use like this.

```<code>if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $image=$row["filename"];
?>
<img src="directory/images/<?php echo $image;?>">
<?php
}
 ?>
</code>```

Output

```<code><img src="directory/images/image_name.png">
</code>```

Body:
I am getting error when I try to echo image in PHP.  Here is my code:

$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '

    ';
    //filenames in database end with appropriate image extensions like .png

}

And I am getting this error:
    Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ','
    or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

echo'';

Body:
Try this

There are multiple ways to display the image. You can also use like this.

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $image=$row["filename"];
?>
<img src="directory/images/<?php echo $image;?>">
<?php
}
 ?>

Output

<img src="directory/images/image_name.png">


问:
tensorflow installation error in Window + anaconda
i tried to install tensorflow in my anaconda by creating a virtual env

```<code> conda create -n tensorflow python=3.5
</code>```

but after i type y, nothing happened. How can i fix this?

答:
So what you did is creating an environment called tensorflow, you need to install it as well

you can do either

conda install tensorflow

or

pip install tensorflow

Body:
i tried to install tensorflow in my anaconda by creating a virtual env

 conda create -n tensorflow python=3.5

but after i type y, nothing happened. How can i fix this?


问:
UPDATE two rows - MySQL
I'm trying to update two rows in my database using a query (which is going to be run from a PHP script) and there is just one Condition (WHERE). What I've tried is:

```<code>$sql = 'UPDATE ' . CANNED_MESSAGES . "
                SET canned_message_content = '" . $db->sql_escape($content) . "',
                    canned_message_title = '" . $db->sql_escape($title) . "'
                WHERE id = '" . intval($id) . "'" ;
$db->sql_query($sql);
</code>```

Can you tell me whats wrong with my query? :)

答:
This may be due to Quotes mismatch. Please use this </p>

```<code>$sql = "UPDATE '" . CANNED_MESSAGES ."'
                SET canned_message_content = '" . $db->sql_escape($content) . "',
                    canned_message_title = '" . $db->sql_escape($title) . "'
                WHERE id = '" . intval($id) . "' " ;
</code>```

Title: UPDATE two rows - MySQL

Body:
I'm trying to update two rows in my database using a query (which is going to be run from a PHP script) and there is just one Condition (WHERE). What I've tried is:

$sql = 'UPDATE ' . CANNED_MESSAGES . "
                SET canned_message_content = '" . $db->sql_escape($content) . "',
                    canned_message_title = '" . $db->sql_escape($title) . "'
                WHERE id = '" . intval($id) . "'" ;
$db->sql_query($sql);

Can you tell me whats wrong with my query? :)

Body:
This may be due to Quotes mismatch. Please use this

$sql = "UPDATE '" . CANNED_MESSAGES ."'
                SET canned_message_content = '" . $db->sql_escape($content) . "',
                    canned_message_title = '" . $db->sql_escape($title) . "'
                WHERE id = '" . intval($id) . "' " ;


问:
loop through rows to copy range meeting criteria
I have a workbook with a sheet (sheet2) containing 1600+ rows and 700+ columns.

Col A is name and Col B is counta of all columns from C to last col. It is always > 0.

The cell values of each column are like "29.11.17_124". Not all cells in these columns are filled. There are empty cells too. Each filled cell per col begins with the same date string.

I have a macro which asks for a date string. Then finds the col number where that string is. Suppose it is col 65. Then all rows from col A to col 65 are copied  to sheet4. But in this sheet (sheet4), since the col B calculates new counta, I have to delete all rows where counta is < 1 as well.

Basically, I am copying 1600+ rows and then deleting 1000 rows (where counta is 0) in sheet4.

I want to modify my code so that only those rows whose counta is 1 and more are copied. The code to iterate through each row of sheet2 but also evaluate the new counta as derived from the col range.

```<code>Sub dcopyrange()
Dim rng1 As Range
Dim sh1 As Worksheet, sh2 As Worksheet
Dim fc As Integer
Dim lc As Integer
Dim valuee1 As Variant
Dim lRow As Long
Dim lRow2 As Long
Dim iCntr As Long
Sheet4.Cells.Clear
sheet2.Select
lRow2 = sheet2.Cells(Rows.Count, "A").End(xlUp).Row

Set sh1 = Sheets("Sheet2")
 Set sh2 = Sheets("Sheet4")

valuee1 = InputBox("enter date dd-m-yy", "Report by department")
Set rng1 = sh1.UsedRange.Find(valuee1, , xlValues, xlPart)
If Not rng1 Is Nothing Then

MsgBox "Found in column " & rng1.Column

fc = 1
lc = (fc + rng1.Column) - 1

 Range(Columns(fc), Columns(lc)).copy sh2.Range("A1")

Else
MsgBox "Not found", vbCritical
End If
ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Add Key:=Range("b1:b2500" _
        ), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet4").Sort
        .SetRange Range("A1:ZZ2500")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    Sheet4.Activate

    lRow = Sheet4.Cells(Rows.Count, "A").End(xlUp).Row

    For iCntr = lRow To 1 Step -1

    If Cells(iCntr, 2).Value = 0 Then Cells(iCntr, 2).EntireRow.Clear

    Next iCntr
End Sub
</code>```

答:
```<code>Sub filtercopyrange()

Dim rng1 As Range
Dim sh1 As Worksheet, sh2 As Worksheet
Dim fcol As Integer
Dim lcol As Integer
Dim valuee1 As Variant
Dim lRow2 As Long
Dim lRow1 As Long
Dim iCntr As Long
Dim i As Integer
Dim ct As Variant

Sheet7.Cells.Clear
Sheet2.Select

Set sh1 = Sheets("Sheet2")
 Set sh2 = Sheets("Sheet7")

valuee1 = InputBox("enter date dd-mm-yyyy", "Column Range")
Set rng1 = sh1.UsedRange.Find(valuee1, , xlValues, xlPart)
If Not rng1 Is Nothing Then
MsgBox "Found in column " & rng1.Column
fcol = 1
lcol = (fcol + rng1.Column) - 1
Else
MsgBox "Not found", vbCritical
End If

lRow2 = Sheet2.Cells(Rows.Count, "A").End(xlUp).Row

For i = 1 To lRow2
With sh1

        ct = Application.WorksheetFunction.CountA(Range(Cells(i, 3), Cells(i, lcol)))
        If ct > 0 Then
         Sheet2.Range(Cells(i, 1), Cells(i, lcol)).Copy

        Sheet7.Range("a" & Rows.Count).End(xlUp).Offset(1,0).PasteSpecial

        Else
        End If

End With
        Next
Sheet7.Activate
lRow1 = Sheet7.Cells(Rows.Count, "A").End(xlUp).Row

Range("A1:bz" & lRow1).Sort key1:=Range("B1:B" & lRow1), _
   order1:=xlDescending, Header:=xlNo
End Sub
</code>```

Body:
I have a workbook with a sheet (sheet2) containing 1600+ rows and 700+ columns.

Col A is name and Col B is counta of all columns from C to last col. It is always > 0.

The cell values of each column are like "29.11.17_124". Not all cells in these columns are filled. There are empty cells too. Each filled cell per col begins with the same date string.

I have a macro which asks for a date string. Then finds the col number where that string is. Suppose it is col 65. Then all rows from col A to col 65 are copied  to sheet4. But in this sheet (sheet4), since the col B calculates new counta, I have to delete all rows where counta is < 1 as well.

Basically, I am copying 1600+ rows and then deleting 1000 rows (where counta is 0) in sheet4.

I want to modify my code so that only those rows whose counta is 1 and more are copied. The code to iterate through each row of sheet2 but also evaluate the new counta as derived from the col range.

Sub dcopyrange()
Dim rng1 As Range
Dim sh1 As Worksheet, sh2 As Worksheet
Dim fc As Integer
Dim lc As Integer
Dim valuee1 As Variant
Dim lRow As Long
Dim lRow2 As Long
Dim iCntr As Long
Sheet4.Cells.Clear
sheet2.Select
lRow2 = sheet2.Cells(Rows.Count, "A").End(xlUp).Row

Set sh1 = Sheets("Sheet2")
 Set sh2 = Sheets("Sheet4")

valuee1 = InputBox("enter date dd-m-yy", "Report by department")
Set rng1 = sh1.UsedRange.Find(valuee1, , xlValues, xlPart)
If Not rng1 Is Nothing Then

MsgBox "Found in column " & rng1.Column

fc = 1
lc = (fc + rng1.Column) - 1

 Range(Columns(fc), Columns(lc)).copy sh2.Range("A1")

Else
MsgBox "Not found", vbCritical
End If
ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Add Key:=Range("b1:b2500" _
        ), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet4").Sort
        .SetRange Range("A1:ZZ2500")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    Sheet4.Activate

    lRow = Sheet4.Cells(Rows.Count, "A").End(xlUp).Row

    For iCntr = lRow To 1 Step -1

    If Cells(iCntr, 2).Value = 0 Then Cells(iCntr, 2).EntireRow.Clear

    Next iCntr
End Sub


问:
How to equal two different ids from another table?
```<code>select student.student_fname,
student.student_mname,
student.student_lname, logs.time, logs.transaction,logs.entity_type,prof.professor_fname,prof.professor_mname,prof.professor_lname
from student_tbl as student,
logs_tbl as logs,
professor_tbl as prof
where student.student_id=logs.entity_id
and prof.professor_id=logs.entity_id
and logs.date ='$date_today'
and logs.course_id='$course'
and logs.sections_id='$sections'
and logs.rooms_id='$room'
group by logs.date,
logs.term,
logs.course_id,
logs.entity_id
order by logs.logs_id asc
</code>```

In student_tbl and professor_tbl I have student_id and professor_id that is equal to the entity_id of logs_tbl. How do i compare those two id from different tables to entity_id in logs_tbl? it is the only line that is giving me error. or maybe you have a suggestion? aside from sql injection stuff

UPDATE

i have student_tbl the columns there are: student_id, student_fname, student_mname, student_lname. i also have professor_tbl and the columns there are: professor_id, professor_fname, professor_mname, professor_lname, and my third table which has all the basis is the logs_tbl the columns there are: entity_id(this is where student_id and professor_id will equate), course_id,rooms_id,sections_id,time,date,transaction,entity_type.
This is what i want to display:

student_fname/professor_fname (depending on the entity_id)

student_mname/professor_mname (depending on the entity_id)

student_lname/professor_lname (depending on the entity_id)

time

transaction

entity_type

Sample data display:

Kris | Consta | Roca | 11:30 | in | student

Bob | Jones | Marley | 11:32 | in | student

Ronald | James | Leon | 11:35 | in | professor

Kris | Consta | Roca | 1:00 | out | student

Bob | Jones | Marley | 1:05 | out | student

Ronald | James | Leon | 1:06 | out | professor

答:
```<code>  select student.student_fname,  student.student_mname, student.student_lname, logs.time, logs.transaction,logs.entity_type
          from student_tbl as student inner join logs_tbl as logs on student.student_id=logs.entity_id
     where   logs.date ='$date_today'
                and logs.course_id='$course'
                and logs.sections_id='$sections'
                and logs.rooms_id='$room'
                group by logs.date,  logs.term,
                logs.course_id,
                logs.entity_id

    UNION

      select prof.professor_fname,prof.professor_mname,prof.professor_lname , logs.time, logs.transaction,logs.entity_type
          from   professor_tbl as prof inner join logs_tbl as logs   on prof.professor_id=logs.entity_id
             where   logs.date ='$date_today'
                and logs.course_id='$course'
                and logs.sections_id='$sections'
                and logs.rooms_id='$room'
                group by logs.date,  logs.term,
                logs.course_id,
                logs.entity_id
</code>```

Body:
select student.student_fname,
student.student_mname,
student.student_lname, logs.time, logs.transaction,logs.entity_type,prof.professor_fname,prof.professor_mname,prof.professor_lname
from student_tbl as student,
logs_tbl as logs,
professor_tbl as prof
where student.student_id=logs.entity_id
and prof.professor_id=logs.entity_id
and logs.date ='$date_today'
and logs.course_id='$course'
and logs.sections_id='$sections'
and logs.rooms_id='$room'
group by logs.date,
logs.term,
logs.course_id,
logs.entity_id
order by logs.logs_id asc

In student_tbl and professor_tbl I have student_id and professor_id that is equal to the entity_id of logs_tbl. How do i compare those two id from different tables to entity_id in logs_tbl? it is the only line that is giving me error. or maybe you have a suggestion? aside from sql injection stuff

UPDATE

i have student_tbl the columns there are: student_id, student_fname, student_mname, student_lname. i also have professor_tbl and the columns there are: professor_id, professor_fname, professor_mname, professor_lname, and my third table which has all the basis is the logs_tbl the columns there are: entity_id(this is where student_id and professor_id will equate), course_id,rooms_id,sections_id,time,date,transaction,entity_type.
This is what i want to display:

student_fname/professor_fname (depending on the entity_id)

student_mname/professor_mname (depending on the entity_id)

student_lname/professor_lname (depending on the entity_id)

time

transaction

entity_type

Sample data display:

Kris | Consta | Roca | 11:30 | in | student

Bob | Jones | Marley | 11:32 | in | student

Ronald | James | Leon | 11:35 | in | professor

Kris | Consta | Roca | 1:00 | out | student

Bob | Jones | Marley | 1:05 | out | student

Ronald | James | Leon | 1:06 | out | professor


问:
Set corner radius of `UISegmentedControl` equal to that of `UISearchController`
I have several boxes on a page and I would like them all the have the corner radius of the UISearchController also on that page.

I tried to set the corner radius of my segmented control equal to that of the search controller. However, _searchController.searchBar.layer.cornerRadius returns 0 instead of its actual value in both viewDidLoad and viewDidAppear.

I tried the textfield inside of the search bar, but it also returns 0 for its corner radius.

答:
```<code>#define CornerRadius    6

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController setNavigationBarHidden:YES];

    [self.userNameTextfield.layer setCornerRadius:CornerRadius];
    [self.userNameTextfield.layer setBorderColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_login"]].CGColor];
    [self.userNameTextfield.layer setBorderWidth:1.0];
    [self.userNameTextfield.layer setMasksToBounds:YES];

    [self.passwordTextfield.layer setCornerRadius:CornerRadius];
    [self.passwordTextfield.layer setBorderColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_login"]].CGColor];
    [self.passwordTextfield.layer setBorderWidth:1.0];
    [self.passwordTextfield.layer setMasksToBounds:YES];

    // Do any additional setup after loading the view, typically from a nib.
}
</code>```

<p>set both corner radius like this </p>

Body:
#define CornerRadius    6

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController setNavigationBarHidden:YES];

    [self.userNameTextfield.layer setCornerRadius:CornerRadius];
    [self.userNameTextfield.layer setBorderColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_login"]].CGColor];
    [self.userNameTextfield.layer setBorderWidth:1.0];
    [self.userNameTextfield.layer setMasksToBounds:YES];

    [self.passwordTextfield.layer setCornerRadius:CornerRadius];
    [self.passwordTextfield.layer setBorderColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_login"]].CGColor];
    [self.passwordTextfield.layer setBorderWidth:1.0];
    [self.passwordTextfield.layer setMasksToBounds:YES];

    // Do any additional setup after loading the view, typically from a nib.
}

set both corner radius like this


问:
Error while requesting a transaction
When I requesting a CXTansaction in CXStratCallAction it showing the error message as  "Error Domain=com.apple.CallKit.error.requesttransaction Code=1 "(null)" ". Can anyone explain this Error message.

答:
The app isn’t entitled to perform the actions in the requested transaction.

Refer the link for error codes

Title: Error while requesting a transaction