问:
Page_Load called in Firefox, but not IE
I've been thrown into an ASP.NET project and I've got a page which contains a control that is fetched via AJAX.

The Page_Load function of the control does a little bit of logic necessary to get the correct values from the Query string.

The problem is that the Page_Load function isn't called in IE.

If I put a breakpoint in, I can load the page in FF and watch it stop, but in IE: no deal.

I'm pretty (read: COMPLETELY) new to ASP.NET, but I'm a pretty experienced PHP developer.
So I'm thinking it's probably some funk with the way that IE does the AJAX callback to get the control.

Has anyone got any ideas?

Cheers

答:
i'd try to use the IE Developer Toolbar to help debug the IE problem but I think you are on the right track.

You can also enable script debugging in the Advanced Options of IE and debug the script.

Title: Page_Load called in Firefox, but not IE

OwnerDisplayName: Jeff Martin

LastEditorDisplayName: Jeff Martin


来源: stackexchange

问:
Unable to change Spinnaker Time zone using configue file
I am trying to change spinnaker timezone that is hosted on my Aws Ec2 instance . I changed the value in spinnaker-local.yml and restart spinnaker service .
but its not showing the impact on my spinnaker management ui timezone.

Thanks in advance.

答:
You also need to change the timezone in the UI's settings.js file.

This is the field that controls the timezone in the UI. Changing it really depends on how you manage Spinnaker's configuration, but that's what you'll want to change.

ContentLicense: CC BY-SA 3.0


问:
In Batch, using FIND or FINDSTR and saving its output to a variable with SET
I have a file that contains a lot of lines, e.g.

```<code>foo=1
foobar=2
bar=3
</code>```

I want to use FIND (or FINDSTR) to read this file and use SET to set a variable foobar to 2, etc.

I would much prefer to only use Batch and tools that come with Windows - no third-party tools. But if it's impossible without any, then I'm open to using them.

答:
If the file holding your "var=value" lines is set.txt, the following will do it:

```<code>for /f "delims=^= tokens=1-2" %%v in (set.txt) do set %%v=%%w
</code>```

I've made assumptions -- if there are more requirements/restrictions than how I've addressed the problem you must clarify the question.

Body:
I have a file that contains a lot of lines, e.g.

foo=1
foobar=2
bar=3

I want to use FIND (or FINDSTR) to read this file and use SET to set a variable foobar to 2, etc.

I would much prefer to only use Batch and tools that come with Windows - no third-party tools. But if it's impossible without any, then I'm open to using them.

Body:
If the file holding your "var=value" lines is set.txt, the following will do it:

for /f "delims=^= tokens=1-2" %%v in (set.txt) do set %%v=%%w

I've made assumptions -- if there are more requirements/restrictions than how I've addressed the problem you must clarify the question.


问:
Difference between PostbackURL and response.redirect on buttonclick
Whats the exact difference between PostbackURL property of a button and redirecting to the same page using Response.Redirect() to the same URL on Button Click event in Code behind and which one to use?

答:
Post back url is basically same as server. Transfer. It will maintain view state of your page and from post back page you will get your page object and all value but it will work for only url of same server.

Repose. Redirect means transfer your browser execution to point this page. Means you can write response. Redirect (“www.google.com”)   so when it will firer browser go to  Google website. url not required on same server

More detail check


问:
Animate window width right to left
I am making a sidebar-style app which is located on the left of right side of the screen.
I am trying to make it look like it's sliding in and out of the screen, but when it's on the right, it slides in from the left still.

I can't find any right to left options regarding window width, so I was hoping to find the answer here.

Here is my current working animation code for left to right:

```<code>    public static void AnimateSize(this Window target, double newWidth, EventHandler completed)
    {
        var length = new TimeSpan(0, 0, 0, 0, Settings.Default.AnimationTime);
        var sb = new Storyboard {Duration = new Duration(length)};

        var aniWidth = new DoubleAnimationUsingKeyFrames();

        aniWidth.Duration = new Duration(length);

        aniWidth.KeyFrames.Add(new EasingDoubleKeyFrame(target.ActualWidth,
            KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 00))));
        aniWidth.KeyFrames.Add(new EasingDoubleKeyFrame(newWidth, KeyTime.FromTimeSpan(length)));

        Storyboard.SetTarget(aniWidth, target);
        Storyboard.SetTargetProperty(aniWidth, new PropertyPath(FrameworkElement.WidthProperty));

        sb.Children.Add(aniWidth);

        sb.Completed += completed;
        sb.Begin();
    }
</code>```

called like this:

```<code>_window.AnimateSize(0, delegate { _window.Hide(); });
</code>```

and this:

```<code>_window.Width = 0;
_window.Show();
_window.AnimateSize(Settings.Default.Width, delegate { });
</code>```

Thanks.

答:
I had similar task to accomplish. I used to animate the left property of my window and make it appear as though it slides from the outside and disappears in the same fashion. but when a colleague who uses two screens used it , the window would slide onto the other screen.

The work around used was to simultaneously animate the width and left properties. this gives the effect of the window appearing at the desired location and unfurling towards the left.

```<code>DoubleAnimation daLeftAppear = new DoubleAnimation(popupWidthDetails.workAreaWidth, (<workAreaWidth> - <windowWidth> - 5), new Duration(TimeSpan.FromSeconds(1)));
        daLeftAppear.EasingFunction = new QuarticEase();
        Storyboard.SetTargetName(daLeftAppear, this.Name);
        Storyboard.SetTargetProperty(daLeftAppear, new PropertyPath(LeftProperty));

        DoubleAnimation daWidthAppear = new DoubleAnimation(0, 100, new Duration(TimeSpan.FromSeconds(1)));
        daWidthAppear.EasingFunction = new QuarticEase();
        Storyboard.SetTargetName(daWidthAppear, this.Name);
        Storyboard.SetTargetProperty(daWidthAppear, new PropertyPath(WidthProperty));

        sbAppear = new Storyboard();
        sbAppear.Children.Add(daLeftAppear);
        sbAppear.Children.Add(daWidthAppear);
</code>```

Title: Animate window width right to left

Body:
I am making a sidebar-style app which is located on the left of right side of the screen.
I am trying to make it look like it's sliding in and out of the screen, but when it's on the right, it slides in from the left still.

I can't find any right to left options regarding window width, so I was hoping to find the answer here.

Here is my current working animation code for left to right:

    public static void AnimateSize(this Window target, double newWidth, EventHandler completed)
    {
        var length = new TimeSpan(0, 0, 0, 0, Settings.Default.AnimationTime);
        var sb = new Storyboard {Duration = new Duration(length)};

        var aniWidth = new DoubleAnimationUsingKeyFrames();

        aniWidth.Duration = new Duration(length);

        aniWidth.KeyFrames.Add(new EasingDoubleKeyFrame(target.ActualWidth,
            KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 00))));
        aniWidth.KeyFrames.Add(new EasingDoubleKeyFrame(newWidth, KeyTime.FromTimeSpan(length)));

        Storyboard.SetTarget(aniWidth, target);
        Storyboard.SetTargetProperty(aniWidth, new PropertyPath(FrameworkElement.WidthProperty));

        sb.Children.Add(aniWidth);

        sb.Completed += completed;
        sb.Begin();
    }

called like this:

_window.AnimateSize(0, delegate { _window.Hide(); });

and this:

_window.Width = 0;
_window.Show();
_window.AnimateSize(Settings.Default.Width, delegate { });

Thanks.

Body:
I had similar task to accomplish. I used to animate the left property of my window and make it appear as though it slides from the outside and disappears in the same fashion. but when a colleague who uses two screens used it , the window would slide onto the other screen.

The work around used was to simultaneously animate the width and left properties. this gives the effect of the window appearing at the desired location and unfurling towards the left.

DoubleAnimation daLeftAppear = new DoubleAnimation(popupWidthDetails.workAreaWidth, (<workAreaWidth> - <windowWidth> - 5), new Duration(TimeSpan.FromSeconds(1)));
        daLeftAppear.EasingFunction = new QuarticEase();
        Storyboard.SetTargetName(daLeftAppear, this.Name);
        Storyboard.SetTargetProperty(daLeftAppear, new PropertyPath(LeftProperty));

        DoubleAnimation daWidthAppear = new DoubleAnimation(0, 100, new Duration(TimeSpan.FromSeconds(1)));
        daWidthAppear.EasingFunction = new QuarticEase();
        Storyboard.SetTargetName(daWidthAppear, this.Name);
        Storyboard.SetTargetProperty(daWidthAppear, new PropertyPath(WidthProperty));

        sbAppear = new Storyboard();
        sbAppear.Children.Add(daLeftAppear);
        sbAppear.Children.Add(daWidthAppear);


问:
My code gets the error expected ')'
I have tried to look for any curly brackets or parenthesis that don't have a pair but I can't find anything. Please let me know if you find the error or any other errors. The code is supposed to take the amount of minutes you take in the shower and turn it into the amount of bottles or water you used.

```<code>#include <stdio.h>
#include <cs50.h>

int main(void)

{
printf("Minutes: ");
int minutes = get_int();

if (minutes >0)
{
    int bottles = (128*(1.5*minutes)/16);
    printf("Bottles:%i \n "bottles);
}
else
{
    printf("Please type in a positive integer\n");
}

}
</code>```

Thanks for your help! :)

答:
You should use , (comma) while passing values in printf.

printf("Bottles:%i \n ", bottles);

So the final code is

```<code>#include <stdio.h>
#include <cs50.h>

int main(void)

{
    printf("Minutes: ");
    int minutes = get_int();

    if (minutes >0)
    {
        int bottles = (128*(1.5*minutes)/16);
        printf("Bottles:%i \n ", bottles);
    }
    else
    {
        printf("Please type in a positive integer\n");
    }

}
</code>```

Title: My code gets the error expected ')'

Body:
I have tried to look for any curly brackets or parenthesis that don't have a pair but I can't find anything. Please let me know if you find the error or any other errors. The code is supposed to take the amount of minutes you take in the shower and turn it into the amount of bottles or water you used.

#include <stdio.h>
#include <cs50.h>

int main(void)

{
printf("Minutes: ");
int minutes = get_int();

if (minutes >0)
{
    int bottles = (128*(1.5*minutes)/16);
    printf("Bottles:%i \n "bottles);
}
else
{
    printf("Please type in a positive integer\n");
}

}

Thanks for your help! :)

Body:
You should use , (comma) while passing values in printf.

printf("Bottles:%i \n ", bottles);

So the final code is

#include <stdio.h>
#include <cs50.h>

int main(void)

{
    printf("Minutes: ");
    int minutes = get_int();

    if (minutes >0)
    {
        int bottles = (128*(1.5*minutes)/16);
        printf("Bottles:%i \n ", bottles);
    }
    else
    {
        printf("Please type in a positive integer\n");
    }

}


问:
Is there an open source library to serve files over the net? (with complete ui)
im currently working on a closed network (security reasons) and i wish to have a website which will serve many usefull downloads.

Is there an open-source library which i can use to upload such thing? with complete ui and functionality?

[priority for javascript libs]

thanks!

答:
If you are running windows and looking for a full UI solution, you should check out Filezilla Server https://filezilla-project.org/download.php?type=server

If you don't mind using the command line:

If you are looking for a webserver, I suggest apache2/httpd webserver https://httpd.apache.org/

For FTP I recommend ProFTPd http://www.proftpd.org/

And for Network share I suggest using NFS https://en.wikipedia.org/wiki/Network_File_System

If you are looking to serve things locally on a small network, a network share may be best


问:
Intent.ACTION_HEADSET_PLUG is received when activity starts
I am trying to pause music that is playing when the headset is unplugged.

I have created a BroadcastReceiver that listens for ACTION_HEADSET_PLUG intents and acts upon them when the state extra is 0 (for unplugged). My problem is that an ACTION_HEADSET_PLUG intent is received by my BroadcastReceiver whenever the activity is started. This is not the behavior that I would expect. I would expect the Intent to be fired only when the headset is plugged in or unplugged.

Is there a reason that the ACTION_HEADSET_PLUG Intent is caught immediately after registering a receiver with that IntentFilter? Is there a clear way that I can work with this issue?

I would assume that since the default music player implements similar functionality when the headset is unplugged that it would be possible.

What am I missing?

This is the registration code

```<code>registerReceiver(new HeadsetConnectionReceiver(),
                 new IntentFilter(Intent.ACTION_HEADSET_PLUG));
</code>```

This is the definition of HeadsetConnectionReceiver

```<code>public class HeadsetConnectionReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Log.w(TAG, "ACTION_HEADSET_PLUG Intent received");
    }

}
</code>```

答:
I ran into the same issue. I'm not sure what causes it, but at least in my testing it seems to be consistent, which means you can work around it. I did just that by adding a boolean member variable that starts as true, and is set to false on the first onReceive(Context, Intent) call. This flag then controls whether I actually process the unplug event or not.

For your reference, here is the code I use to do just that, which is available in context here.

```<code>private boolean isFirst;

public void onReceive(Context context, Intent intent)
{
    if(!isFirst)
    {
        // Do stuff...
    }
    else
    {
        Log.d("Hearing Saver", "First run receieved.");
        isFirst = false;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to pause music that is playing when the headset is unplugged.

I have created a BroadcastReceiver that listens for ACTION_HEADSET_PLUG intents and acts upon them when the state extra is 0 (for unplugged). My problem is that an ACTION_HEADSET_PLUG intent is received by my BroadcastReceiver whenever the activity is started. This is not the behavior that I would expect. I would expect the Intent to be fired only when the headset is plugged in or unplugged.

Is there a reason that the ACTION_HEADSET_PLUG Intent is caught immediately after registering a receiver with that IntentFilter? Is there a clear way that I can work with this issue?

I would assume that since the default music player implements similar functionality when the headset is unplugged that it would be possible.

What am I missing?

This is the registration code

registerReceiver(new HeadsetConnectionReceiver(),
                 new IntentFilter(Intent.ACTION_HEADSET_PLUG));

This is the definition of HeadsetConnectionReceiver

public class HeadsetConnectionReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Log.w(TAG, "ACTION_HEADSET_PLUG Intent received");
    }

}

Body:
I ran into the same issue. I'm not sure what causes it, but at least in my testing it seems to be consistent, which means you can work around it. I did just that by adding a boolean member variable that starts as true, and is set to false on the first onReceive(Context, Intent) call. This flag then controls whether I actually process the unplug event or not.

For your reference, here is the code I use to do just that, which is available in context here.

private boolean isFirst;

public void onReceive(Context context, Intent intent)
{
    if(!isFirst)
    {
        // Do stuff...
    }
    else
    {
        Log.d("Hearing Saver", "First run receieved.");
        isFirst = false;
    }
}


问:
Firebase android, how find data
How do I find user data from Firebase database?
This is how my database looks like:

I'm saving my data under tokens:

```<code>String token = FirebaseInstanceId.getInstance().getToken();
if (token == null) return;
databaseReference = FirebaseDatabase.getInstance().getReference(token);
</code>```

I need to find all location coordinates from all users and set up marker, but everything that I made, it's accessing to current user:

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseInstanceId.getInstance().getToken());
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot child : dataSnapshot.getChildren()){
            double allLat = (double) dataSnapshot.child("lat").getValue();
            double allLng = (double) dataSnapshot.child("lng").getValue();
        mMap.addMarker(new MarkerOptions().position(new LatLng(allLat, allLng)).title("Пользователь"));}
    }
</code>```

答:
```<code>DatabaseReference userRef = FirebaseDatabase.getInstance().getReference();
userRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                HashMap<String,Object> hm = (HashMap<String, Object>) dataSnapshot.getValue();
                String allLat = String.valueOf(hm.get("lat"));
                String allLng = String.valueOf(hm.get("lng"));
                Log.e("!_@_@------> ", allLat + " " + allLng);

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

Title: Firebase android, how find data

Body:
How do I find user data from Firebase database?
This is how my database looks like:

I'm saving my data under tokens:

String token = FirebaseInstanceId.getInstance().getToken();
if (token == null) return;
databaseReference = FirebaseDatabase.getInstance().getReference(token);

I need to find all location coordinates from all users and set up marker, but everything that I made, it's accessing to current user:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseInstanceId.getInstance().getToken());
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot child : dataSnapshot.getChildren()){
            double allLat = (double) dataSnapshot.child("lat").getValue();
            double allLng = (double) dataSnapshot.child("lng").getValue();
        mMap.addMarker(new MarkerOptions().position(new LatLng(allLat, allLng)).title("Пользователь"));}
    }


问:
Trying to install Bright Game Panel (PHP/Apache)
I am getting this error "MySQL extension could not be found or is not installed. Please recompile your Apache with the MySQL extension included." for my Bright Game Panel.

You can see from the picture that everything except this is working. My sql server is running.

答:
Find another piece of software.

This software requires the old PHP mysql extension, which was deprecated in PHP 5.5 and removed entirely in PHP 7.0.


问:
AsyncTask, LinearLayout Android Update visibility
I am trying to change visibility of a Linear Layout through findViewById() and then SetVisiblity(). But When I debug, I am seeing null values only.

Please find the snippet in the BackgroundMainActivity.java below in the onPostExecute() method.

I commented it. Please help.

MainActivity.java

```<code>button_getUsername.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, v);
            backgroundMainActivity.execute("random", editText_username.getText().toString());
        }
    });
</code>```

BackgroundMainActivity.java

```<code>public class BackgroundMainActivity extends AsyncTask<String, Void , String> {

    public BackgroundMainActivity(Context ct, View view) {
        context = ct;
        rootView = view;
    }

    @Override
    protected String doInBackground(String... params) {
        String login_URL = "some url";
        try {
            String username = params[1];

            URL url = new URL(login_URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String postData = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8");
            bufferedWriter.write(postData);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));

            result = bufferedReader.readLine();

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPreExecute(){

    }

    @Override
    protected void onPostExecute (String result){
        if(result.equals("success")){

//need to make this change
//LinearLayout someLayout = (LinearLayout)rootview.findViewById(R.id.layout_content);
//someLayout.setVisibility(View.VISIBLE);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(result)
                    .setPositiveButton("Ok",null)
                    .show();
        }

    }

    @Override
    protected void onProgressUpdate(Void... values){
        super.onProgressUpdate(values);
    }
}
</code>```

EDIT:

activity_main.xml

ss_layout_questions is gone by default. I want to make it visible once "result.equals( "success") " in BackgroundMainActivity.java.

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.xtremustechnologies.chotu.useractivity.MainActivity">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:background="@color/lightGreen"
        android:layout_gravity="top">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignEnd="@+id/textviewr2"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="30dp"
                    android:text="CHOTU"
                    android:textColor="@color/white"
                    android:textSize="40dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="40dp"
                    android:text="Your Personal Assistant"
                    android:textColor="@color/white"
                    android:textSize="12dp" />
            </LinearLayout>

            <TextView
                android:id="@+id/ss_textview_questions"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="40dp"
                android:text="Security Questions "
                android:textColor="@color/black"
                android:textSize="20dp"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/ss_et_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_gravity="center_horizontal"
                android:hint="Enter Username" />

            <Button
                android:id="@+id/ss_button_getusername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/ss_et_username"
                android:layout_centerHorizontal="true"
                android:onClick="clickGetUsername"
                android:layout_gravity="center_horizontal"
                android:text="Submit" />

            <LinearLayout
                android:id="@+id/ss_layout_questions"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/textviewr3"
                    android:layout_centerHorizontal="false"
                    android:layout_marginLeft="40dp"
                    android:layout_marginRight="40dp"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/ss_button_dob"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginRight="50dp"
                        android:text="Date of Birth" />

                    <TextView
                        android:id="@+id/ss_textView_dob"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right|center_vertical|center_horizontal"
                        android:layout_weight="1"
                        android:text="TextView"
                        android:textSize="20dp" />
                </LinearLayout>

                <TextView
                    android:id="@+id/ss_textView_question1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <Button
                    android:id="@+id/ss_button_submit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:background="@color/black"
                    android:text="Submit"
                    android:textColor="@color/white" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
</android.support.constraint.ConstraintLayout>
</code>```

答:
Its working finally. Here is what I did

I added a new class inside BackgroundMainActivity.java and then called it in the onPostExecute() method.

```<code>class a{

public Button button_reset, button_dob;
public LinearLayout layout_questions;
public TextView textView_title;
public EditText editText_username;

public void makeVisible(ForgotPasswordActivity context){

    LinearLayout layout_questions = (LinearLayout) context.findViewById(R.id.ss_layout_questions);
    layout_questions.setVisibility(View.VISIBLE);
}
</code>```

onPostExecute() in BackgroundMainActivity.java

```<code>a obj = new a();
        obj.makeVisible((ForgotPasswordActivity) context);
</code>```

Body:
I am trying to change visibility of a Linear Layout through findViewById() and then SetVisiblity(). But When I debug, I am seeing null values only.

Please find the snippet in the BackgroundMainActivity.java below in the onPostExecute() method.

I commented it. Please help.

MainActivity.java

button_getUsername.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, v);
            backgroundMainActivity.execute("random", editText_username.getText().toString());
        }
    });

BackgroundMainActivity.java

public class BackgroundMainActivity extends AsyncTask<String, Void , String> {

    public BackgroundMainActivity(Context ct, View view) {
        context = ct;
        rootView = view;
    }

    @Override
    protected String doInBackground(String... params) {
        String login_URL = "some url";
        try {
            String username = params[1];

            URL url = new URL(login_URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String postData = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8");
            bufferedWriter.write(postData);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));

            result = bufferedReader.readLine();

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPreExecute(){

    }

    @Override
    protected void onPostExecute (String result){
        if(result.equals("success")){

//need to make this change
//LinearLayout someLayout = (LinearLayout)rootview.findViewById(R.id.layout_content);
//someLayout.setVisibility(View.VISIBLE);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(result)
                    .setPositiveButton("Ok",null)
                    .show();
        }

    }

    @Override
    protected void onProgressUpdate(Void... values){
        super.onProgressUpdate(values);
    }
}

EDIT:

activity_main.xml

ss_layout_questions is gone by default. I want to make it visible once "result.equals( "success") " in BackgroundMainActivity.java.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.xtremustechnologies.chotu.useractivity.MainActivity">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:background="@color/lightGreen"
        android:layout_gravity="top">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignEnd="@+id/textviewr2"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="30dp"
                    android:text="CHOTU"
                    android:textColor="@color/white"
                    android:textSize="40dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="40dp"
                    android:text="Your Personal Assistant"
                    android:textColor="@color/white"
                    android:textSize="12dp" />
            </LinearLayout>

            <TextView
                android:id="@+id/ss_textview_questions"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="40dp"
                android:text="Security Questions "
                android:textColor="@color/black"
                android:textSize="20dp"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/ss_et_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_gravity="center_horizontal"
                android:hint="Enter Username" />

            <Button
                android:id="@+id/ss_button_getusername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/ss_et_username"
                android:layout_centerHorizontal="true"
                android:onClick="clickGetUsername"
                android:layout_gravity="center_horizontal"
                android:text="Submit" />

            <LinearLayout
                android:id="@+id/ss_layout_questions"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/textviewr3"
                    android:layout_centerHorizontal="false"
                    android:layout_marginLeft="40dp"
                    android:layout_marginRight="40dp"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/ss_button_dob"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginRight="50dp"
                        android:text="Date of Birth" />

                    <TextView
                        android:id="@+id/ss_textView_dob"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right|center_vertical|center_horizontal"
                        android:layout_weight="1"
                        android:text="TextView"
                        android:textSize="20dp" />
                </LinearLayout>

                <TextView
                    android:id="@+id/ss_textView_question1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <Button
                    android:id="@+id/ss_button_submit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:background="@color/black"
                    android:text="Submit"
                    android:textColor="@color/white" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
</android.support.constraint.ConstraintLayout>

Body:
Its working finally. Here is what I did

I added a new class inside BackgroundMainActivity.java and then called it in the onPostExecute() method.

class a{

public Button button_reset, button_dob;
public LinearLayout layout_questions;
public TextView textView_title;
public EditText editText_username;

public void makeVisible(ForgotPasswordActivity context){

    LinearLayout layout_questions = (LinearLayout) context.findViewById(R.id.ss_layout_questions);
    layout_questions.setVisibility(View.VISIBLE);
}

onPostExecute() in BackgroundMainActivity.java

a obj = new a();
        obj.makeVisible((ForgotPasswordActivity) context);


问:
Chatterbot: installation
I have tried to install the module "Chatterbot 0.4.6",  but it fails with the following error:

```<code>Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 742, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip/wheel.py", line 346, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip/wheel.py", line 317, in clobber
    ensure_dir(destdir)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/nltk'
</code>```

What could be causing this to happen?

答:
As correctly recommended by @Adryr83, the sudo command is often needed for linux platforms when installing Python packages with pip.

For example:

sudo pip install chatterbot

Title: Chatterbot: installation

Body:
I have tried to install the module "Chatterbot 0.4.6",  but it fails with the following error:

Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 742, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip/wheel.py", line 346, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip/wheel.py", line 317, in clobber
    ensure_dir(destdir)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/nltk'

What could be causing this to happen?


问:
doinbackground() method is not called in aync task
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

```<code>private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Any help is appreciated.
Thank you

答:
In doInBackground() method you have shown a toast. If you want to show a toast then it must run on the UI Thread. But doInBackground() method runs on different thread.

Please remove that toast from there. Maybe one thing you can do that, you can use runOnUiThread to show Toast.

Body:
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}

Any help is appreciated.
Thank you


问:
Convert AdaptiveIconDrawable to Bitmap in Android O preview
With the new preview release yesterday I started to update my app to this version. Part of my app is to list installed applications with the associated icons.

```<code>Drawable drawable = mPackageManager.getApplicationIcon(packageName);
</code>```

This part of the app still works. Apps like the clock, calculator or messages already support the new version of icons, so they return a AdaptiveIconDrawable.

```<code>Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
</code>```

This part doesn't work anymore. Is there any other way to convert AdaptiveIconDrawable to a Bitmap? Thanks in advance.

答:
We can achieve by following way,

AppIconHelper.java

```<code>public class AppIconHelper {

    public static Bitmap getAppIcon(PackageManager mPackageManager, String packageName) {

        if (Build.VERSION.SDK_INT >= 26) {
            return AppIconHelperV26.getAppIcon(mPackageManager, packageName);
        }

        try {
            Drawable drawable = mPackageManager.getApplicationIcon(packageName);

            return ((BitmapDrawable) drawable).getBitmap();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
</code>```

For device supporting Android O( >=26) we can call AppIconHelperV26 class to get the AppIcon, In this, if its drawable is AdaptiveIconDrawable, we are doing the following steps
1. Get the Foreground and Background drawable and create as Layer Drawable
2. Using Canvas we can convert the Layer drawable to Bitmap

AppIconHelperV26.java

```<code>public class AppIconHelperV26 {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static Bitmap getAppIcon(PackageManager mPackageManager, String packageName) {

        try {
            Drawable drawable = mPackageManager.getApplicationIcon(packageName);

            if (drawable instanceof BitmapDrawable) {
                return ((BitmapDrawable) drawable).getBitmap();
            } else if (drawable instanceof AdaptiveIconDrawable) {
                Drawable backgroundDr = ((AdaptiveIconDrawable) drawable).getBackground();
                Drawable foregroundDr = ((AdaptiveIconDrawable) drawable).getForeground();

                Drawable[] drr = new Drawable[2];
                drr[0] = backgroundDr;
                drr[1] = foregroundDr;

                LayerDrawable layerDrawable = new LayerDrawable(drr);

                int width = layerDrawable.getIntrinsicWidth();
                int height = layerDrawable.getIntrinsicHeight();

                Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

                Canvas canvas = new Canvas(bitmap);

                layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                layerDrawable.draw(canvas);

                return bitmap;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}
</code>```

Now you can call AppIconHelper.getAppIcon to get the Bitmap,

AppListAdapter.java

```<code>@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    //... your code here
    Bitmap appIcon = AppIconHelper.getAppIcon(packageManager, packageName);
    imageView.setImageBitmap(appIcon);

}
</code>```

Body:
With the new preview release yesterday I started to update my app to this version. Part of my app is to list installed applications with the associated icons.

Drawable drawable = mPackageManager.getApplicationIcon(packageName);

This part of the app still works. Apps like the clock, calculator or messages already support the new version of icons, so they return a AdaptiveIconDrawable.

Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();

This part doesn't work anymore. Is there any other way to convert AdaptiveIconDrawable to a Bitmap? Thanks in advance.

Body:
We can achieve by following way,

AppIconHelper.java

public class AppIconHelper {

    public static Bitmap getAppIcon(PackageManager mPackageManager, String packageName) {

        if (Build.VERSION.SDK_INT >= 26) {
            return AppIconHelperV26.getAppIcon(mPackageManager, packageName);
        }

        try {
            Drawable drawable = mPackageManager.getApplicationIcon(packageName);

            return ((BitmapDrawable) drawable).getBitmap();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

For device supporting Android O( >=26) we can call AppIconHelperV26 class to get the AppIcon, In this, if its drawable is AdaptiveIconDrawable, we are doing the following steps
1. Get the Foreground and Background drawable and create as Layer Drawable
2. Using Canvas we can convert the Layer drawable to Bitmap

AppIconHelperV26.java

public class AppIconHelperV26 {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static Bitmap getAppIcon(PackageManager mPackageManager, String packageName) {

        try {
            Drawable drawable = mPackageManager.getApplicationIcon(packageName);

            if (drawable instanceof BitmapDrawable) {
                return ((BitmapDrawable) drawable).getBitmap();
            } else if (drawable instanceof AdaptiveIconDrawable) {
                Drawable backgroundDr = ((AdaptiveIconDrawable) drawable).getBackground();
                Drawable foregroundDr = ((AdaptiveIconDrawable) drawable).getForeground();

                Drawable[] drr = new Drawable[2];
                drr[0] = backgroundDr;
                drr[1] = foregroundDr;

                LayerDrawable layerDrawable = new LayerDrawable(drr);

                int width = layerDrawable.getIntrinsicWidth();
                int height = layerDrawable.getIntrinsicHeight();

                Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

                Canvas canvas = new Canvas(bitmap);

                layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                layerDrawable.draw(canvas);

                return bitmap;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Now you can call AppIconHelper.getAppIcon to get the Bitmap,

AppListAdapter.java

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    //... your code here
    Bitmap appIcon = AppIconHelper.getAppIcon(packageManager, packageName);
    imageView.setImageBitmap(appIcon);

}


问:
Can I make IntelliJ IDEA look more like Eclipse?
I've been developing in Eclipse for a long while, but am taking a hard look at IntelliJ IDEA 9.0.3 because of its good Flex development tools and Maven flexmojos integration.

But I just CAN'T STAND the look of the thing on Ubuntu 10.04.  Coming from Eclipse, the fonts and colors make everything very hard to read....very straining on the eyes.  I've played around with fonts and colors and now its a little bit better.

But has some kind soul already created some sort of profile I can load into IDEA and poof -- make it visually look more like Eclipse?

答:
Install Eclipse Color Theme Plugin: https://marketplace.eclipse.org/content/eclipse-color-theme

Download "IntelliJ Dracula" theme: http://www.eclipsecolorthemes.org/?view=theme&id=14105 (select the Eclipse Color Theme (XML) file download).

In Eclipse, go to Windows > Preferences > General > Appearances > Color Theme > Import a theme. And select the xml file just downloaded.


问:
C# Cannot implicity convert int[] to int
```<code>public int[] kdPegawai;
if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
{
    kdPegawai[1] = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
}
</code>```

I need to put value from combobox to kdPegawai array, but keep getting error like this:

cannot implicitly convert int[] to int

答:
Array value assignment is wrong</p>

```<code> public int[] kdPegawai = new int[1];
 if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
        {
            kdPegawai[0] =  Convert.ToInt16(comboBoxKdPegawai.Text) ;
        }
</code>```

Body:
public int[] kdPegawai;
if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
{
    kdPegawai[1] = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
}

I need to put value from combobox to kdPegawai array, but keep getting error like this:

cannot implicitly convert int[] to int

Body:
Array value assignment is wrong

 public int[] kdPegawai = new int[1];
 if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
        {
            kdPegawai[0] =  Convert.ToInt16(comboBoxKdPegawai.Text) ;
        }


问:
FileOutputStream writing out 0 bytes
I'm trying to send a file through Java sockets from one program to the other. My code is based off of this question. The issue is that on the Ubuntu machine hosting the server, the file sent over is 0 bytes in size. The code has worked on a local connection on my Windows laptop, so perhaps the issue has to do with the remote connection?

Server code:

```<code>int g = Integer.parseInt(in.readLine());
if(g > -1) {
    InputStream fIn = client.getInputStream();
    for(int i = 0; i < g; i++) {
        String name = in.readLine();
        byte[] bytes = new byte[16*1024];
        File f = new File("plugins/" + name + ".jar");
        if(!f.exists()) f.createNewFile();
        FileOutputStream fOut = new FileOutputStream(f);
        int count;
        while ((count = fIn.read(bytes)) >= 0) {
            fOut.write(bytes, 0, count);
        }
        fOut.flush();
        fOut.close();
    }
    System.out.println("[" + client.getRemoteSocketAddress().toString() + "] added " + g + " new plugins.");
    client.close();
}else{
    client.close();
}
</code>```

Client code:

```<code>JFileChooser fd = new JFileChooser("C:\\");
fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
fd.setMultiSelectionEnabled(true);
fd.setFileFilter(new FileNameExtensionFilter(null,"jar"));
int r = fd.showOpenDialog(null);
if(r == JFileChooser.APPROVE_OPTION) {
    File[] files = fd.getSelectedFiles();
    OutputStream fOut = sock.getOutputStream();
    out.println(files.length);
    for(File f : files) {
        out.println(f.getName().split("\\.")[0]);
        byte[] bytes = new byte[16 * 1024];
        FileInputStream fIn = new FileInputStream(f);
        int count;
        while ((count = fIn.read(bytes)) >= 0) {
            fOut.write(bytes, 0, count);
        }
        fIn.close();
    }
}else{
    out.println(-1);
}
sock.close();
</code>```

答:
As said in the comments there are different issues in you code.

To recognise the end of single file you can simply add the file size after the filename separated by a Semicolon;

```<code>out.println(f.getName().split("\\.")[0] + "; size" + f.length());
</code>```

On the Server side you accumulate the file size read / written stop read ing the content of the file close it  and read the next line (filename / file size).

As said in the comments there are different issues.
You use fIn and fOut which is not clear how they are defined.
On the client side you use fOut while the Socket OutputStream is named 'out'.
Similar thing on the server side. You read the number of files from in but afterwards you get the InputStream (again?) from the Socket and use that as fIn. Depending on your in that may or may not work.

Also reading a line from via readLine from an InputStream and also binary content is not that trivial. In my example code I'm using the DataInputStream for that even the readLine method is deprecated.

The Example also uses the "try with resources" Syntax to ensure that all resources (Streams, Sockets) get closed in the case of an Exception.

The Example does not show how to deal with the file size on the server side  That's up to you.

The example is completely runnable on a single machine and shows how to copy a single file via socket based on your code.

```<code>import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientServerSocketExample {

    private static class Server {

        public void run() throws IOException {

            try (ServerSocket serverSocket = new ServerSocket(41000, 10, InetAddress.getLocalHost())) {
                try (Socket client = serverSocket.accept()) {

                    try (DataInputStream in = new DataInputStream(client.getInputStream())) {

                        int g = Integer.parseInt(in.readLine());

                        if(g > -1) {
                            for(int i = 0; i < g; i++) {
                                String[] filenameAndSize = in.readLine().split(";");
                                String name = filenameAndSize[0];
                                byte[] bytes = new byte[16*1024];
                                File f = new File("/tmp/" + name + ".jar");
                                if(!f.exists()) f.createNewFile();
                                try (FileOutputStream fOut = new FileOutputStream(f)) {
                                    int count;
                                    while ((count = in.read(bytes)) >= 0) {
                                        fOut.write(bytes, 0, count);
                                    }
                                    fOut.flush();
                                }
                            }
                            System.out.println("[" + client.getRemoteSocketAddress().toString() + "] added " + g + " new plugins.");

                        }
                    }
                }
            }
        }

    }

    private static class Client {

        public void run() throws IOException {
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 41000) );

                sendFiles(socket);
            }
        }

        private static void sendFiles(Socket sock) throws IOException {
            File[] files = new File[]{new File("some.jar")};
            OutputStream fOut = sock.getOutputStream();
            PrintStream out = new PrintStream(fOut);

            out.println(files.length);
            for(File f : files) {
                out.println(f.getName().split("\\.")[0] + "; size" + f.length());

                byte[] bytes = new byte[16 * 1024];
                try (FileInputStream fIn = new FileInputStream(f)) {
                    int count;
                    while ((count = fIn.read(bytes)) >= 0) {
                        out.write(bytes, 0, count);
                    }
                    out.flush();
                }
            }
        }

    }

    public static void main(String ... args) throws IOException, InterruptedException {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    new Server().run();
                } catch (IOException ioe) {
                    System.out.println(ioe);
                }

            }

        }).start();

        System.out.println("Waiting for the Server to come up");
        Thread.sleep(500);

        new Client().run();
    }

}
</code>```

There may be an issue in this solution when the client sends a \r as new line separator and the file starts with \n. The server may count the \n as part of the line separator and the file will be corrupt (one byte will be missing).

Title: FileOutputStream writing out 0 bytes

Body:
I'm trying to send a file through Java sockets from one program to the other. My code is based off of this question. The issue is that on the Ubuntu machine hosting the server, the file sent over is 0 bytes in size. The code has worked on a local connection on my Windows laptop, so perhaps the issue has to do with the remote connection?

Server code:

int g = Integer.parseInt(in.readLine());
if(g > -1) {
    InputStream fIn = client.getInputStream();
    for(int i = 0; i < g; i++) {
        String name = in.readLine();
        byte[] bytes = new byte[16*1024];
        File f = new File("plugins/" + name + ".jar");
        if(!f.exists()) f.createNewFile();
        FileOutputStream fOut = new FileOutputStream(f);
        int count;
        while ((count = fIn.read(bytes)) >= 0) {
            fOut.write(bytes, 0, count);
        }
        fOut.flush();
        fOut.close();
    }
    System.out.println("[" + client.getRemoteSocketAddress().toString() + "] added " + g + " new plugins.");
    client.close();
}else{
    client.close();
}

Client code:

JFileChooser fd = new JFileChooser("C:\\");
fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
fd.setMultiSelectionEnabled(true);
fd.setFileFilter(new FileNameExtensionFilter(null,"jar"));
int r = fd.showOpenDialog(null);
if(r == JFileChooser.APPROVE_OPTION) {
    File[] files = fd.getSelectedFiles();
    OutputStream fOut = sock.getOutputStream();
    out.println(files.length);
    for(File f : files) {
        out.println(f.getName().split("\\.")[0]);
        byte[] bytes = new byte[16 * 1024];
        FileInputStream fIn = new FileInputStream(f);
        int count;
        while ((count = fIn.read(bytes)) >= 0) {
            fOut.write(bytes, 0, count);
        }
        fIn.close();
    }
}else{
    out.println(-1);
}
sock.close();

Body:
As said in the comments there are different issues in you code.

To recognise the end of single file you can simply add the file size after the filename separated by a Semicolon;

out.println(f.getName().split("\\.")[0] + "; size" + f.length());

On the Server side you accumulate the file size read / written stop read ing the content of the file close it  and read the next line (filename / file size).

As said in the comments there are different issues.
You use fIn and fOut which is not clear how they are defined.
On the client side you use fOut while the Socket OutputStream is named 'out'.
Similar thing on the server side. You read the number of files from in but afterwards you get the InputStream (again?) from the Socket and use that as fIn. Depending on your in that may or may not work.

Also reading a line from via readLine from an InputStream and also binary content is not that trivial. In my example code I'm using the DataInputStream for that even the readLine method is deprecated.

The Example also uses the "try with resources" Syntax to ensure that all resources (Streams, Sockets) get closed in the case of an Exception.

The Example does not show how to deal with the file size on the server side  That's up to you.

The example is completely runnable on a single machine and shows how to copy a single file via socket based on your code.

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientServerSocketExample {

    private static class Server {

        public void run() throws IOException {

            try (ServerSocket serverSocket = new ServerSocket(41000, 10, InetAddress.getLocalHost())) {
                try (Socket client = serverSocket.accept()) {

                    try (DataInputStream in = new DataInputStream(client.getInputStream())) {

                        int g = Integer.parseInt(in.readLine());

                        if(g > -1) {
                            for(int i = 0; i < g; i++) {
                                String[] filenameAndSize = in.readLine().split(";");
                                String name = filenameAndSize[0];
                                byte[] bytes = new byte[16*1024];
                                File f = new File("/tmp/" + name + ".jar");
                                if(!f.exists()) f.createNewFile();
                                try (FileOutputStream fOut = new FileOutputStream(f)) {
                                    int count;
                                    while ((count = in.read(bytes)) >= 0) {
                                        fOut.write(bytes, 0, count);
                                    }
                                    fOut.flush();
                                }
                            }
                            System.out.println("[" + client.getRemoteSocketAddress().toString() + "] added " + g + " new plugins.");

                        }
                    }
                }
            }
        }

    }

    private static class Client {

        public void run() throws IOException {
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 41000) );

                sendFiles(socket);
            }
        }

        private static void sendFiles(Socket sock) throws IOException {
            File[] files = new File[]{new File("some.jar")};
            OutputStream fOut = sock.getOutputStream();
            PrintStream out = new PrintStream(fOut);

            out.println(files.length);
            for(File f : files) {
                out.println(f.getName().split("\\.")[0] + "; size" + f.length());

                byte[] bytes = new byte[16 * 1024];
                try (FileInputStream fIn = new FileInputStream(f)) {
                    int count;
                    while ((count = fIn.read(bytes)) >= 0) {
                        out.write(bytes, 0, count);
                    }
                    out.flush();
                }
            }
        }

    }

    public static void main(String ... args) throws IOException, InterruptedException {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    new Server().run();
                } catch (IOException ioe) {
                    System.out.println(ioe);
                }

            }

        }).start();

        System.out.println("Waiting for the Server to come up");
        Thread.sleep(500);

        new Client().run();
    }

}

There may be an issue in this solution when the client sends a \r as new line separator and the file starts with \n. The server may count the \n as part of the line separator and the file will be corrupt (one byte will be missing).


问:
Direct IP call android
Im creating an Android App in which the clients can call each other without using a SIP proxy (server).

I downloaded the CSipSimple, it has a "local" option in which the clients in a local network can call each other directly.

What if I am connected to the mobile network. If i know the public IP of the destination, can I call him direclty?

If you can suggest another applications that fulfill the mentioned requirements please do mention them.

thanks

答:
Yes, you should be able to make direct call with almost all SIP clients. I am using mizudroid and works with that.

In this case, you just need to enter the full URI for the destination and not just the extension name.

So instead of calling to "john" you will have to enter

```<code>john@ipaddress:port
</code>```

Example:

```<code>john@192.168.1.33:14321
</code>```

Some sip clients might require to prefix all these with "sip:":

```<code>sip:john@192.168.1.33:14321
</code>```

As you can see, the tricky part is to find out the correct port. SIP clients are using random local ports by default, but some of them allows you to set the port explicitly. (Don't be confused with the server sip signaling ports which is usually 5060 after the SIP standards.)

Also please note that the role of a sip registrar is exactly this: so you don't have to play finding out the peer's exact address as the server can handle this for you automatically.

Some sip clients might require to enter a sip server address in settings/login, however most of them allows you to use the softphone without any address entered or they have an option to specify serverless/local/registerless or you might just enter a fake address (then the softphone might display "register failed" but you should be able to make direct calls as i have described above)

Title: Direct IP call android

Body:
Yes, you should be able to make direct call with almost all SIP clients. I am using mizudroid and works with that.

In this case, you just need to enter the full URI for the destination and not just the extension name.

So instead of calling to "john" you will have to enter

john@ipaddress:port

Example:

john@192.168.1.33:14321

Some sip clients might require to prefix all these with "sip:":

sip:john@192.168.1.33:14321

As you can see, the tricky part is to find out the correct port. SIP clients are using random local ports by default, but some of them allows you to set the port explicitly. (Don't be confused with the server sip signaling ports which is usually 5060 after the SIP standards.)

Also please note that the role of a sip registrar is exactly this: so you don't have to play finding out the peer's exact address as the server can handle this for you automatically.

Some sip clients might require to enter a sip server address in settings/login, however most of them allows you to use the softphone without any address entered or they have an option to specify serverless/local/registerless or you might just enter a fake address (then the softphone might display "register failed" but you should be able to make direct calls as i have described above)


答:
If you want to create an array with a single item, try this instead:

```<code>public int[] kdPegawai;
if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
{
    kdPegawai = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
}
</code>```

Recall that kdPegawai[1] = ... means that you're trying to assign something to the second item of the array, which (I assume) isn't what you're trying to do here. Also recall that the second item of the array is an integer, not an array of integers (hence the error).

A single-item array is pointless in most cases, though (unless you're doing a library call that requires you to pass an array or something like that). If it's only ever going to be a single item, consider just using an int.

Alternatively, you can initialize the array ahead of time and do something like:

```<code>kdPegawai[0] = Convert.ToInt16(comboBoxKdPegawai.Text);
</code>```

Important note: array[1] is the second item in an array, not the first item. The first item in the array is array[0].

Title: C# Cannot implicity convert int[] to int

Body:
If you want to create an array with a single item, try this instead:

public int[] kdPegawai;
if (Convert.ToInt16(comboBoxJumlahPegawai.Text) == 4)
{
    kdPegawai = new int[] { Convert.ToInt16(comboBoxKdPegawai.Text) };
}

Recall that kdPegawai[1] = ... means that you're trying to assign something to the second item of the array, which (I assume) isn't what you're trying to do here. Also recall that the second item of the array is an integer, not an array of integers (hence the error).

A single-item array is pointless in most cases, though (unless you're doing a library call that requires you to pass an array or something like that). If it's only ever going to be a single item, consider just using an int.

Alternatively, you can initialize the array ahead of time and do something like:

kdPegawai[0] = Convert.ToInt16(comboBoxKdPegawai.Text);

Important note: array[1] is the second item in an array, not the first item. The first item in the array is array[0].


问:
Should WebClient instances be reused in Silverlight
I'm writing a Silverlight application for Windows Phone 7 which has a class that needs to make multiple requests to WebClient.DownloadStringAsync()

Am I better off creating a new instance of WebClient for each request, or is it more efficient to initialise a single instance in a field and use that for each request (making sure to only have one request active at any one time)?

```<code>public class MainViewModel : INotifyPropertyChanged
{
    private readonly WebClient _wc;

    public MainViewModel()
    {
        _wc = new WebClient
        {
            Credentials = new NetworkCredential( "yyyyyyy", @"xxxxxx" )
        };

    }

    readonly Uri _baseUrl = new Uri( @"https://some.web.url" );

    public void GetServices()
    {
        _wc.DownloadStringCompleted += GetServicesCompleted;
        var uri = new Uri( _baseUrl, "/path" );
        _wc.DownloadStringAsync( uri );
    }

    private void GetServicesCompleted( object sender, DownloadStringCompletedEventArgs e )
    {
        _wc.DownloadStringCompleted -= GetServicesCompleted;

        string result = e.Result;

        // other logic...

        GetServiceResources();
    }

    private void GetServiceResources()
    {
        _wc.DownloadStringCompleted += GetServicesResourcesDownloaded;
        var url = new Uri( _baseUrl, "/path2" );
        _wc.DownloadStringAsync( url );
    }

    // etc
}
</code>```

答:
You should also be aware, that if anything like WCF client proxies the web client will probably not remain in a happy state if something goes wrong during a connection. That is, it's probably not fault tolerant.

Therefore, I would think that you should probably just re-instantiate it each time. Plus if used correctly in using blocks you'll more effectively manage your resources (though as BFree points out, WebClient isn't a particularly heavy resource).

Not that this will specifically help, but for a WCF web service specific solution we used an implementation based on http://www.acorns.com.au/blog/?p=113 to provide a fault tolerant web client for our WCF web services proxies. We required this since we were only dependency injecting the WCF endpoints (or mock in some instances) at startup.

Body:
I'm writing a Silverlight application for Windows Phone 7 which has a class that needs to make multiple requests to WebClient.DownloadStringAsync()

Am I better off creating a new instance of WebClient for each request, or is it more efficient to initialise a single instance in a field and use that for each request (making sure to only have one request active at any one time)?

public class MainViewModel : INotifyPropertyChanged
{
    private readonly WebClient _wc;

    public MainViewModel()
    {
        _wc = new WebClient
        {
            Credentials = new NetworkCredential( "yyyyyyy", @"xxxxxx" )
        };

    }

    readonly Uri _baseUrl = new Uri( @"https://some.web.url" );

    public void GetServices()
    {
        _wc.DownloadStringCompleted += GetServicesCompleted;
        var uri = new Uri( _baseUrl, "/path" );
        _wc.DownloadStringAsync( uri );
    }

    private void GetServicesCompleted( object sender, DownloadStringCompletedEventArgs e )
    {
        _wc.DownloadStringCompleted -= GetServicesCompleted;

        string result = e.Result;

        // other logic...

        GetServiceResources();
    }

    private void GetServiceResources()
    {
        _wc.DownloadStringCompleted += GetServicesResourcesDownloaded;
        var url = new Uri( _baseUrl, "/path2" );
        _wc.DownloadStringAsync( url );
    }

    // etc
}


问:
Printing the patterns using only one loop
I have printed this pattern using one loop:

```<code>*
**
***
****
*****

String s = "";
for (i = 1; i <= n; ++i) {
    s += "*";
    System.out.println(s);
}
</code>```

Now i want how to print following patterns using only one loop.

```<code>1)
    *
   * *
  * * *
 * * * *
* * * * *

2)
  * * * * *
   * * * *
    * * *
     * *
      *

3)
   1 2 3 4 5
   1 2 3 4
   1 2 3
   1 2
   1
</code>```

and other similar patterns using only one loop, I have done all of them using more than one loop.

答:
Print pattern using single loop:

the code is written in objective-c any one can use this logic and write program in their respective language.

int k = 5;

```<code>for (int i = 1; i<= k; i++)
{
    NSLog(@"%d",i);
    if (i==k) {
        i=0;
        k--;
        NSLog(@"\n");
    }
}
</code>```

Output:

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Body:
I have printed this pattern using one loop:

*
**
***
****
*****

String s = "";
for (i = 1; i <= n; ++i) {
    s += "*";
    System.out.println(s);
}

Now i want how to print following patterns using only one loop.

1)
    *
   * *
  * * *
 * * * *
* * * * *

2)
  * * * * *
   * * * *
    * * *
     * *
      *

3)
   1 2 3 4 5
   1 2 3 4
   1 2 3
   1 2
   1

and other similar patterns using only one loop, I have done all of them using more than one loop.

Body:
Print pattern using single loop:

the code is written in objective-c any one can use this logic and write program in their respective language.

int k = 5;

for (int i = 1; i<= k; i++)
{
    NSLog(@"%d",i);
    if (i==k) {
        i=0;
        k--;
        NSLog(@"\n");
    }
}

Output:

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1


问:
How to read the body of a POST request with GCDWebServer in Swift
I'm trying to use GCDWebServer to read/write to a file in the documents directory. Reading the file seems fairly straight-forward and I've pretty much got that how I need.

I want to write to the file using a POST request. So I tried adding a handler for method "POST", but in the process block I can't seem to read the body of the request at all.

If I do something like:

```<code>webServer?.addHandler(forMethod: "POST", path: "/post", request: GCDWebServerDataRequest.self, processBlock: {request in

        dump(request)

        return GCDWebServerDataResponse(html: "An error occurred.")
    })
</code>```

That prints all the headers to the console (in an NSObject). But how do I read in the body to a variable?

(iOS 10.3, Swift 3, XCode 8.3.2)

答:
```<code>    self.webServer?.addHandler(forMethod: "POST", path: "/uploadfile", request: GCDWebServerMultiPartFormRequest.classForCoder(), processBlock: { (request) -> GCDWebServerResponse? in

        print("ádasdnaskdnaskjd=====<")
        let get = request as! GCDWebServerMultiPartFormRequest

        do {

            if let files = get.files {

               try files.forEach({ (file) in

                    if let multipartFile = file as? GCDWebServerMultiPartFile {

                        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
                        let urlOfFile = documentsPath.appending("/\(multipartFile.fileName!)");
                        let url = URL(fileURLWithPath: urlOfFile)

                        let fileManager = FileManager.default
                        try fileManager.moveItem(at: URL(fileURLWithPath: multipartFile.temporaryPath), to: url);

                        print("URL of file: \(url)")
                    }

                })

            }

            return GCDWebServerDataResponse.init(html: "")

        } catch {
            print(error.localizedDescription)
        }

        return GCDWebServerDataResponse.init(html: "")

    })
</code>```

You can use postman to test it with body (form-data)

Body:
I'm trying to use GCDWebServer to read/write to a file in the documents directory. Reading the file seems fairly straight-forward and I've pretty much got that how I need.

I want to write to the file using a POST request. So I tried adding a handler for method "POST", but in the process block I can't seem to read the body of the request at all.

If I do something like:

webServer?.addHandler(forMethod: "POST", path: "/post", request: GCDWebServerDataRequest.self, processBlock: {request in

        dump(request)

        return GCDWebServerDataResponse(html: "An error occurred.")
    })

That prints all the headers to the console (in an NSObject). But how do I read in the body to a variable?

(iOS 10.3, Swift 3, XCode 8.3.2)

Body:
    self.webServer?.addHandler(forMethod: "POST", path: "/uploadfile", request: GCDWebServerMultiPartFormRequest.classForCoder(), processBlock: { (request) -> GCDWebServerResponse? in

        print("ádasdnaskdnaskjd=====<")
        let get = request as! GCDWebServerMultiPartFormRequest

        do {

            if let files = get.files {

               try files.forEach({ (file) in

                    if let multipartFile = file as? GCDWebServerMultiPartFile {

                        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
                        let urlOfFile = documentsPath.appending("/\(multipartFile.fileName!)");
                        let url = URL(fileURLWithPath: urlOfFile)

                        let fileManager = FileManager.default
                        try fileManager.moveItem(at: URL(fileURLWithPath: multipartFile.temporaryPath), to: url);

                        print("URL of file: \(url)")
                    }

                })

            }

            return GCDWebServerDataResponse.init(html: "")

        } catch {
            print(error.localizedDescription)
        }

        return GCDWebServerDataResponse.init(html: "")

    })

You can use postman to test it with body (form-data)


问:
Missing token, in client side mode please provide a secret error, how do I solve this?
I am working on a client and I get the following error 'Missing token, in client side mode please provide a secret error'. Please view the below code:</p>

```<code>var stream = require('getstream');
client = stream.connect('q3nwu4pbz222', null, '25553');
readonlyToken = client.feed('user', '1').getReadOnlyToken();
user1 = browserClient.feed('user', '1', readonlyToken);
user1.get({limit:1}, callbackWhenFinished);
</code>```

答:
The problem is with your third line of code:

```<code>readonlyToken = client.feed('user', '1').getReadOnlyToken();
</code>```

This can only be generated by the back-end code, not the JavaScript running in the browser. This is why my previous example for you was using 'client' variables called backendClient and frontendClient to help you differentiate where you needed to execute the different parts of your code.

Body:
I am working on a client and I get the following error 'Missing token, in client side mode please provide a secret error'. Please view the below code:

var stream = require('getstream');
client = stream.connect('q3nwu4pbz222', null, '25553');
readonlyToken = client.feed('user', '1').getReadOnlyToken();
user1 = browserClient.feed('user', '1', readonlyToken);
user1.get({limit:1}, callbackWhenFinished);

Body:
The problem is with your third line of code:

readonlyToken = client.feed('user', '1').getReadOnlyToken();

This can only be generated by the back-end code, not the JavaScript running in the browser. This is why my previous example for you was using 'client' variables called backendClient and frontendClient to help you differentiate where you needed to execute the different parts of your code.