问:
Linking button to another page
I currently have a button

```<code>class Button extends Component{
    render(){
        return(
            <View>
                onPress= #I need this to return the second page of my app
                <Text style={styles.buttonText}>Next Page</Text>
            </View>
        )
    }
}
</code>```

What should I do to link this button to the second page of my app? Assuming I have already imported the page.

```<code>import SecondPage from './SecondPage'
</code>```

答:
There are 2 ways you can achieve this. Details below

Option 1: If you are using react router, you could use Link to redirect users to the second page.

Declare a route in your router config to go to the second page and use . More details here
http://knowbody.github.io/react-router-docs/api/Link.html

Option 2: If you are not using react router and just redirecting, use the onClick on the button to redirect to a new URL. E.g. React: How to navigate via clickHandlers?

Note- Option 2 is a dirty way of navigating from one page to other. A sophisticated way will be to use react-router. You will need it when your app grows big and there are many redirects happening on the page.

Hope that helps!

Title: Linking button to another page

Body:
I currently have a button

class Button extends Component{
    render(){
        return(
            <View>
                onPress= #I need this to return the second page of my app
                <Text style={styles.buttonText}>Next Page</Text>
            </View>
        )
    }
}

What should I do to link this button to the second page of my app? Assuming I have already imported the page.

import SecondPage from './SecondPage'


来源: stackexchange

问:
div Img background doesn't work in my CSS
So this is my CSS code:

```<code>#plaatje {
background-image: url('Plaatjes\slider_two_temp.jpg');
width: 100%;
height: 600px;
position: absolute;
top: 0px;
left: 0px;
</code>```

}

And it won't work at all. I placed the picture in the same map as my HTML file.

答:
your code looks fine do a couple of things!

First check whether the id #plaatje is referenced correctly? also check for the path of css and html file

second check the path for your image the path you give in css is relative to your css file you should enter the correct path! if you're not sure about that use absolute path e.g  background-image: url('http://localhost/Plaatjes/images/slider_two_temp.jpg'); but beware if you have a large application you might then need to change all the paths for live server!

the last thing you could do is to hit ctrl+f12 for inspect element there you can what actually is wrong with your code!

also check your console by hitting ctrl+f12 many times the issues is that we are not using the correct path for our files which results in File not found error

if none of above works share your html code , css code so we can have a look at it
hope that helps!!!

ContentLicense: CC BY-SA 3.0

Body:
So this is my CSS code:

#plaatje {
background-image: url('Plaatjes\slider_two_temp.jpg');
width: 100%;
height: 600px;
position: absolute;
top: 0px;
left: 0px;

}

And it won't work at all. I placed the picture in the same map as my HTML file.


问:
Exception thrown: 'System.Exception' in Alea.dll "i32 is not struct type
I am trying to use Gpu.Default.For from the Alea GPU library, but I keep getting an exception:

```<code>i32 is not a struct type error.
</code>```

What does this error mean, and why am I getting it with this simple Gpu.Default.For loop?

```<code>for (Int32 j = 0; j <= TimePeriodArray.Length - 1; j++)
//Gpu.Default.For(0, TimePeriodArray.Length - 1, j =>
{
    Int32 days = TimePeriodArray[j];
    Double[] CalcResult = new Double[CloseArray.Length];

    for (Int32 Index = days; Index <= CloseArray.Length - 1; Index++)
    {
        Gpu.Default.For(Index - 1, Index - days, i =>
        {
            CalcResult[Index] = CalcResult[Index] + CloseArray[i];
        });

        CalcResult[Index] = CalcResult[Index] / days;
    }

    CalcResultsList.Add(CalcResult);
//});
}
</code>```

答: Two things: first, you new an array inside GPU code, which is not supported. Second, I guess CalcResultsList is of type List, which is also not supported. The reason is, it is not efficient to allocate new memory within GPU code. GPU code will be executed with many threads, allocation inside GPU code is not recommended.

Body:
I am trying to use Gpu.Default.For from the Alea GPU library, but I keep getting an exception:

i32 is not a struct type error.

What does this error mean, and why am I getting it with this simple Gpu.Default.For loop?

for (Int32 j = 0; j <= TimePeriodArray.Length - 1; j++)
//Gpu.Default.For(0, TimePeriodArray.Length - 1, j =>
{
    Int32 days = TimePeriodArray[j];
    Double[] CalcResult = new Double[CloseArray.Length];

    for (Int32 Index = days; Index <= CloseArray.Length - 1; Index++)
    {
        Gpu.Default.For(Index - 1, Index - days, i =>
        {
            CalcResult[Index] = CalcResult[Index] + CloseArray[i];
        });

        CalcResult[Index] = CalcResult[Index] / days;
    }

    CalcResultsList.Add(CalcResult);
//});
}


问:
Is it faster to read from fixed-width columns in SQLite?
Would it generally be faster to read from a table where there are no varchar or other variable length data stored? In MySQL, this is faster because it can calculate exactly where a row will be stored on the disk. </p>

答:
This question is not meaningful in the context of SQLite as it supports only a single TEXT field type.  The distinction of "fixed-width" vs. "variable-length" doesn't exist here.

While SQLite will let you define a field as having a certain type, all this does is (at most) set that field's preference for the type to use when storing ambiguous data (e.g., whether "3" will be stored as INTEGER, REAL, or TEXT).  You can still store any kind of data in any SQLite field regardless of its type.

Specifically relating to CHAR vs. VARCHAR, http://www.sqlite.org/datatype3.html tells us:

If the declared type of the column
  contains any of the strings "CHAR",
  "CLOB", or "TEXT" then that column has
  TEXT affinity. Notice that the type
  VARCHAR contains the string "CHAR" and
  is thus assigned TEXT affinity.

ContentLicense: CC BY-SA 2.5


问:
Replacemet of a variable in shell script from another file - preferably python
My shell script:

```<code>#!/bin/sh
.....
a='30'
b='2'
c='0.9'
.....
</code>```

Is there a way to replace the values of my variables using python script/any other language? I should be able to replace the values with multiple values also. For example, I should be able to set b = '2 1 3' and a = '0.9 0.8' ..

答:
It's simple: add a line to the top of your Bash script:

```<code>source thevars.sh
</code>```

Then you can write all the variable assignments you require using a trivial Python script to create thevars.sh.

The Bash script can be modified slightly to have default arguments in case thevars.sh does not exist:

```<code>test -f thevars.sh && source thevars.sh

a=${a-30}
b=${b-2
c=${c-0.9}
</code>```

Then if thevars.sh has any variables assigned, they will be used instead of the defaults--for example:

```<code>a="foo bar"
b=9001
</code>```

Body:
My shell script:

#!/bin/sh
.....
a='30'
b='2'
c='0.9'
.....

Is there a way to replace the values of my variables using python script/any other language? I should be able to replace the values with multiple values also. For example, I should be able to set b = '2 1 3' and a = '0.9 0.8' ..

Body:
It's simple: add a line to the top of your Bash script:

source thevars.sh

Then you can write all the variable assignments you require using a trivial Python script to create thevars.sh.

The Bash script can be modified slightly to have default arguments in case thevars.sh does not exist:

test -f thevars.sh && source thevars.sh

a=${a-30}
b=${b-2
c=${c-0.9}

Then if thevars.sh has any variables assigned, they will be used instead of the defaults--for example:

a="foo bar"
b=9001


问:
Weird behavior on UILabel with \n on StoryBoard
I want to add a line feed on an UILabel. On storyboard using \ndoes not work at all.
Here is an example.

Adding Labels

On StoryBoard I've created 2 UILabel and set their content in dedicated field:

Label 1\nhello with \n created by ALT+RETURN

Label 2\nhello with explicit \n

Then I added a third label and configure it on controller, not on Story Board:

label3.numberOfLines = 0
label3.text = "Label3\nhello"

Context

This is a brand new project, on Xcode 8. Language is Swift 3.1 and AutoLayout is off. So there must not have any interferences from any external libraries, nor AutoLayout.

Result

Here is the rendering.

Conclusion

UILabel behavior is not the same if used on StoryBoard or code source and this is really disturbing. Of course while you faced and solved this problem everything seems to be cristal clear, as the answer is known.

This problem is easily solved by using a UITextView instead of UILabel. So as for now and until I rather prefer using UITextView for displaying simple text on multilines despite the fact UILabel must work for this purpose.

答:
There is a difference between the carriage return character (\n) and the characters \n.  The singular character \n is a carriage return and as you have seen splits the line.  However the two characters \ & n just represent the two different characters themselves.

When doing a Storyboard in Interface Builder and characters you enter into a UILabel are all counted as individual characters so if you type \n you are actually entering the character '\' and the character 'n'.  To enter the special single carriage return character (\n) you therefore have to use ALT+RETURN.

Now in code you can be more flexible.  When entering some text like this "Line1\nLine2" the \n is treated as the single carriage return character so to enter the characters '\' & 'n' next to each other you have to use "Line1\nLine2" (the double \ indicates a single '\' character).

So when it works you are getting the single carriage return character (\n) in the string and when it doesn't you are getting the two separate characters.

You don't mention how the \n is added when it doesn't work (outside of a Storyboard) but it must be being added to the string as two separate characters.

As an example:

```<code>let str1 = "12345\n67890
let str2 = "12345\\n67890
print (str1.characters.count) // prints 11
print (str2.characters.count) // prints 12
</code>```

Body:
There is a difference between the carriage return character (\n) and the characters \n.  The singular character \n is a carriage return and as you have seen splits the line.  However the two characters \ & n just represent the two different characters themselves.

When doing a Storyboard in Interface Builder and characters you enter into a UILabel are all counted as individual characters so if you type \n you are actually entering the character '\' and the character 'n'.  To enter the special single carriage return character (\n) you therefore have to use ALT+RETURN.

Now in code you can be more flexible.  When entering some text like this "Line1\nLine2" the \n is treated as the single carriage return character so to enter the characters '\' & 'n' next to each other you have to use "Line1\nLine2" (the double \ indicates a single '\' character).

So when it works you are getting the single carriage return character (\n) in the string and when it doesn't you are getting the two separate characters.

You don't mention how the \n is added when it doesn't work (outside of a Storyboard) but it must be being added to the string as two separate characters.

As an example:

let str1 = "12345\n67890
let str2 = "12345\\n67890
print (str1.characters.count) // prints 11
print (str2.characters.count) // prints 12


问:
How to read File using PDFReader
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

```<code>public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}
</code>```

答:
You're reading the whole file to a string and passing to PdfReader which is completely wrong. You need to pass path of the file or File inputFile itself.

You can try

```<code>PdfReader reader = new PdfReader(inputFile.getCanonicalPath());//or inputFile.getName()
</code>```

Or,

```<code>PdfReader reader = new PdfReader(inputFile);
</code>```

Title: How to read File using PDFReader

Body:
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}

Body:
You're reading the whole file to a string and passing to PdfReader which is completely wrong. You need to pass path of the file or File inputFile itself.

You can try

PdfReader reader = new PdfReader(inputFile.getCanonicalPath());//or inputFile.getName()

Or,

PdfReader reader = new PdfReader(inputFile);

ContentLicense: CC BY-SA 4.0


问:
Javascript timer to use multiple times in a page
I have this Javascript count down timer that works perfectly. Only problem is i can use it for only one time in one page. I want to use it multiple times.

I think script use id ="timer" that is why i am not able to use it multiple times.

Below  is the JS code:

```<code><script>
var startTime = 60; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
var space = '       ';

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = "00" + space + minutes + space + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

window.onload = function() {
  var now = new Date();
  var hrs = now.getHours();
  var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
    display = document.querySelector("#timer");

  startTimer(setMinutes, display);
};
</script>
</code>```

答:
Just declare intervalLoop outside of the startTimer function, it'll be available globally.

```<code>var intervalLoop = null

function startTimer(duration, display) {
  intervalLoop = setInterval(function() { .... }
})

function stopTimer() {
  clearInterval(intervalLoop) // Also available here!
})
</code>```

Body:
Just declare intervalLoop outside of the startTimer function, it'll be available globally.

var intervalLoop = null

function startTimer(duration, display) {
  intervalLoop = setInterval(function() { .... }
})

function stopTimer() {
  clearInterval(intervalLoop) // Also available here!
})


问:
Ember rootURL in templates
I am trying to migrate my app away from baseURL to rootURL router configuration. I am stuck determining which url to use for images stored in public/assets in my templates.

Before I was using assets/images/myimage.png, now I want to do something like {{rootURL}}assets/images/myimage.png, but injecting it from the route seems rather hacky.

setupController(controller, model) {
    this._super(controller, model);
    this.controllerFor('application').set('rootURL', this.get('router.rootURL'));
}
```

Is there an established way to do this?

Thanks in advance.

答: You can import it like import config from 'app-name/config/environment' and use it like config.rootURL

Title: Ember rootURL in templates

Body:
I am trying to migrate my app away from baseURL to rootURL router configuration. I am stuck determining which url to use for images stored in public/assets in my templates.

Before I was using assets/images/myimage.png, now I want to do something like {{rootURL}}assets/images/myimage.png, but injecting it from the route seems rather hacky.

setupController(controller, model) {
    this._super(controller, model);
    this.controllerFor('application').set('rootURL', this.get('router.rootURL'));
}

Is there an established way to do this?

Thanks in advance.


问:
Easiest way to use Picasso in notification (icon)
I'm looking for an easy way to use Picasso to load a noticiation icon (which is a URL on a remote webpage). In a previous version of the app I'm working on this code seemed to work:

```<code>        Bitmap speakerPic = null;
        try {
            speakerPic = new AsyncTask<Void, Void, Bitmap>() {
                @Override
                protected Bitmap doInBackground(Void... params) {
                    try {
                        return Picasso.with(c).load(session.getSpeaker().getPhotoUrl()).get();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }.execute().get(1500, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        if (speakerPic != null) {
            builder.setLargeIcon(speakerPic);
        } else {
            builder.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.ic_launcher));
        }
</code>```

But now I get an TimeOutException every time (and I fallback to a default icon in my res folder). I have to use this AsyncTask because Picasso (/network) may not happen on the UI thread. (although I'm blocking the UI thread for 1.5sec here..).

I know Picasso can handle remoteviews, but I don't want to use a custom view for my notificiation. Also I couldn't find a way to get the RemoteView for the NoticifationIcon.

Is there a way to set the icon of my notification simply using Picasso?

答:
Image loading code using Picaso 2.5.2 starts in middle of this method,besides that all stuff is simple notification code, just copy and paste ,replace "image_url" with actual image url.</p>

```<code>            private Notification notification;
               public  void genrateNewsNotification(String title, final int id) {
                    try {
                        final Context context=GcmService.this;
                        final NotificationCompat.Builder mBuilder;
                        final NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.cancel(id);
                        Intent notificationIntent = new Intent(context, YourActivity.class);

                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                        stackBuilder.addParentStack(MainActivity.class);
                        stackBuilder.addNextIntent(notificationIntent);
                        final PendingIntent contentIntent =
                                stackBuilder.getPendingIntent(
                                        id,
                                        PendingIntent.FLAG_UPDATE_CURRENT
                                );
                        mBuilder = new NotificationCompat.Builder(context);
                        mBuilder.setContentTitle("Custom Notification");
                        mBuilder.setAutoCancel(true);
                        mBuilder.setPriority(Notification.PRIORITY_MAX);
                        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                        if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) {
                            mBuilder.setSmallIcon(R.drawable.launch_lolipop);
                        } else {
                            mBuilder.setSmallIcon(R.drawable.launcher_icon);
                        }
                        mBuilder.setContentText(title);
                        mBuilder.setContentIntent(contentIntent);
                        notification= mBuilder.build();

        // image code starts from here

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            try{
                                Picasso.with(context).load("image_url")
                                        .into(target);
                                notificationManager.notify(id, notification);
                            }
                            catch (Exception e){
            // notification without image in case of Exception
                                notificationManager.notify(id, notification);
                            }

                        }else{
                            notificationManager.notify(id, notification);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            **// main stuff goes here ,it is an inner class**

               private Target target = new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        if (bitmap != null) {
                            RemoteViews views;
                            views = new RemoteViews(getPackageName(), R.layout.custom_notification);
                            views.setTextViewText(R.id.title,  "Daily Notification");
                            views.setTextColor(R.id.title,getResources().getColor(R.color.black));
                            views.setImageViewBitmap(R.id.big_picture,  bitmap);
                            views.setImageViewBitmap(R.id.big_icon, BitmapFactory.decodeResource(getResources(), R.drawable.launcher_icon));

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                notification.bigContentView = views;
                            }
                        }
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                        Log.i("errorDrawable","errorDrawable");
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }

                };
</code>```

Body:
I'm looking for an easy way to use Picasso to load a noticiation icon (which is a URL on a remote webpage). In a previous version of the app I'm working on this code seemed to work:

        Bitmap speakerPic = null;
        try {
            speakerPic = new AsyncTask<Void, Void, Bitmap>() {
                @Override
                protected Bitmap doInBackground(Void... params) {
                    try {
                        return Picasso.with(c).load(session.getSpeaker().getPhotoUrl()).get();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }.execute().get(1500, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        if (speakerPic != null) {
            builder.setLargeIcon(speakerPic);
        } else {
            builder.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.ic_launcher));
        }

But now I get an TimeOutException every time (and I fallback to a default icon in my res folder). I have to use this AsyncTask because Picasso (/network) may not happen on the UI thread. (although I'm blocking the UI thread for 1.5sec here..).

I know Picasso can handle remoteviews, but I don't want to use a custom view for my notificiation. Also I couldn't find a way to get the RemoteView for the NoticifationIcon.

Is there a way to set the icon of my notification simply using Picasso?

Body:
Image loading code using Picaso 2.5.2 starts in middle of this method,besides that all stuff is simple notification code, just copy and paste ,replace "image_url" with actual image url.

            private Notification notification;
               public  void genrateNewsNotification(String title, final int id) {
                    try {
                        final Context context=GcmService.this;
                        final NotificationCompat.Builder mBuilder;
                        final NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.cancel(id);
                        Intent notificationIntent = new Intent(context, YourActivity.class);

                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                        stackBuilder.addParentStack(MainActivity.class);
                        stackBuilder.addNextIntent(notificationIntent);
                        final PendingIntent contentIntent =
                                stackBuilder.getPendingIntent(
                                        id,
                                        PendingIntent.FLAG_UPDATE_CURRENT
                                );
                        mBuilder = new NotificationCompat.Builder(context);
                        mBuilder.setContentTitle("Custom Notification");
                        mBuilder.setAutoCancel(true);
                        mBuilder.setPriority(Notification.PRIORITY_MAX);
                        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                        if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) {
                            mBuilder.setSmallIcon(R.drawable.launch_lolipop);
                        } else {
                            mBuilder.setSmallIcon(R.drawable.launcher_icon);
                        }
                        mBuilder.setContentText(title);
                        mBuilder.setContentIntent(contentIntent);
                        notification= mBuilder.build();

        // image code starts from here

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            try{
                                Picasso.with(context).load("image_url")
                                        .into(target);
                                notificationManager.notify(id, notification);
                            }
                            catch (Exception e){
            // notification without image in case of Exception
                                notificationManager.notify(id, notification);
                            }

                        }else{
                            notificationManager.notify(id, notification);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            **// main stuff goes here ,it is an inner class**

               private Target target = new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        if (bitmap != null) {
                            RemoteViews views;
                            views = new RemoteViews(getPackageName(), R.layout.custom_notification);
                            views.setTextViewText(R.id.title,  "Daily Notification");
                            views.setTextColor(R.id.title,getResources().getColor(R.color.black));
                            views.setImageViewBitmap(R.id.big_picture,  bitmap);
                            views.setImageViewBitmap(R.id.big_icon, BitmapFactory.decodeResource(getResources(), R.drawable.launcher_icon));

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                notification.bigContentView = views;
                            }
                        }
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                        Log.i("errorDrawable","errorDrawable");
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }

                };


问:
Wordpress Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 72 bytes) in /wp-includes/meta.php on line 837
I am new in wordpress. i am getting below error.

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried
  to allocate 72 bytes) in
  /wp-includes/meta.php on line 837

while accessing new post page. and also i have added below code in htaccess file.

```<code><IfModule mod_php5.c>
php_value memory_limit 512M
</IfModule>
</code>```

Please help me to sort out this issue.

答:
In my case deleting old wordpress post revisions helped. Also you can restrict the amount of revision per article or disable it altogether.

Here's how I did it: Limit or Disable and clean up old wordPress revisions

Body:
I am new in wordpress. i am getting below error.

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried
  to allocate 72 bytes) in
  /wp-includes/meta.php on line 837

while accessing new post page. and also i have added below code in htaccess file.

<IfModule mod_php5.c>
php_value memory_limit 512M
</IfModule>

Please help me to sort out this issue.


问:
How to replace sendStickyBroadcast in Android?
As you know,
sendStickyBroadcast method is now deprecated. How to replace it?

Of course I can use sendBroadcast but then it will be not sticky.

答:
This is Google's explanation to why Sticky Broadcasts was deprecated.

Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

Hope this helps.


问:
make width of  equal to its text contents
I have below snippet where td takes up space unnecessarily. For e.g. if the text contents inside td take 20 pixels width, td should also be 20 pixels wide. Can you help me fix it?

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
}

span {
   background-color: #7e7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table></code>```

答:
Please replace this code with your old code.

I hop here you find your solution.

tr {
  width: 100%;
  display:table-row;
}
tr td
{
  display:inline-block;
}
.td2{
   width:auto;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;

   max-width: 180px;
}
.text{
  max-width: 180px;
  font-size: 14px;
}
span {
   background-color: #7e7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span class="text">Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table></code>```

Title: make width of <td> equal to its text contents

Body:
I have below snippet where td takes up space unnecessarily. For e.g. if the text contents inside td take 20 pixels width, td should also be 20 pixels wide. Can you help me fix it?

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
}

span {
   background-color: #7e7;
}

The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily

    <input type="checkbox" name="checkbox" value="value">
    Excessive exhaust materialssss

    <input type="checkbox" name="checkbox" value="value">
    Excessive

Body:
Please replace this code with your old code.

I hop here you find your solution.

tr {
  width: 100%;
  display:table-row;
}
tr td
{
  display:inline-block;
}
.td2{
   width:auto;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;

   max-width: 180px;
}
.text{
  max-width: 180px;
  font-size: 14px;
}
span {
   background-color: #7e7;
}

<h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span class="text">Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table>


问:
Most updated and deleted table?
How can we see most deleted and most updated table in sql server 2012 and upper levels.

And how can we see table that makes the most io?

Does these statistics withheld in Sql Server?

答:
Index fragmentation should help - looking at number of rows and fragmentation:

```<code>SELECT
     B.name AS TableName
    ,C.name AS IndexName
    ,C.fill_factor AS IndexFillFactor
    ,D.rows AS RowsCount
    ,A.avg_fragmentation_in_percent
    ,A.page_count
FROM
    sys.dm_db_index_physical_stats(DB_ID(),NULL,NULL,NULL,NULL) A
INNER JOIN
    sys.objects B
ON
    A.object_id = B.object_id
INNER JOIN
    sys.indexes C
ON
    B.object_id = C.object_id AND A.index_id = C.index_id
INNER JOIN
    sys.partitions D
ON
    B.object_id = D.object_id AND A.index_id = D.index_id
WHERE
    C.index_id > 0
order by
    avg_fragmentation_in_percent desc
</code>```

PFE: Thanks to Neeraj Dwivedi at SQL Central

Title: Most updated and deleted table?

Body:
Index fragmentation should help - looking at number of rows and fragmentation:

SELECT
     B.name AS TableName
    ,C.name AS IndexName
    ,C.fill_factor AS IndexFillFactor
    ,D.rows AS RowsCount
    ,A.avg_fragmentation_in_percent
    ,A.page_count
FROM
    sys.dm_db_index_physical_stats(DB_ID(),NULL,NULL,NULL,NULL) A
INNER JOIN
    sys.objects B
ON
    A.object_id = B.object_id
INNER JOIN
    sys.indexes C
ON
    B.object_id = C.object_id AND A.index_id = C.index_id
INNER JOIN
    sys.partitions D
ON
    B.object_id = D.object_id AND A.index_id = D.index_id
WHERE
    C.index_id > 0
order by
    avg_fragmentation_in_percent desc

PFE: Thanks to Neeraj Dwivedi at SQL Central


问:
Calculate time difference with time zone
I have a PHP page and a database in which I know the following:

server time (server running PHP & DB)

user time zone

date/time of an event stored in DB

My system allows users to cancel an event (stamped with a certain time), and I need to figure out whether the event is within 12 hours of the user's time based on their current time zone. For example, suppose I have the following:

server time (GMT): 7/1/2017 @ 3:30 PM

user time zone: (GMT -7:00) Mountain Time (US & Canada)

date/time of event: 7/1/2017 @ 8:30 PM (Mountain Time)

What would be the PHP formula to calculate the hours between user's current time and event time based on their known time zone? Note: We have many users in different time zones BUT we know their time zones because we store it in each user's database record. In order to solve the problem, we first need to calculate the user's current time by doing the math with server time and their time zone. Then we need to do a subtraction between their current time and the event time.

The time zone values I am storing are decimals in this format: -7.0 (That is Mountain time, 7 hours later than GMT.) Whatever time zone calculation occurs needs to be able to take a decimal like that.

What is the PHP code to do this?

答:
Use the diff() method of PHP's DateTime class like this:-

```<code>$user_time= new DateTime('.....',new DateTimeZone('Pacific/Nauru'));
$event_time= new DateTime('....',new DateTimeZone('Pacific/Nauru'));
var_dump($event_time->diff($user_time));
</code>```

This will give you a DateInterval object:-

```<code>object(DateInterval)[48]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 2
  public 'h' => int 11
  public 'i' => int 34
  public 's' => int 41
  public 'invert' => int 0
  public 'days' => int 2
</code>```

Retrieving the values you want from that is trivial.

Body:
Use the diff() method of PHP's DateTime class like this:-

$user_time= new DateTime('.....',new DateTimeZone('Pacific/Nauru'));
$event_time= new DateTime('....',new DateTimeZone('Pacific/Nauru'));
var_dump($event_time->diff($user_time));

This will give you a DateInterval object:-

object(DateInterval)[48]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 2
  public 'h' => int 11
  public 'i' => int 34
  public 's' => int 41
  public 'invert' => int 0
  public 'days' => int 2

Retrieving the values you want from that is trivial.


问:
C++ How linkage happens between a static variable in two different projects
I am new to C++ linux and i have question how this is working,

header.h

```<code>static int arr [2] [2] = {some values}
</code>```

lib.cpp - includes the header.h file and creates an .so

source.cpp - includes the same header.h file(and dynamicaly links lib.so) and while linking, throws an .gnu.linkonce_t error

So, to avoid that, I went with this approach,

header.h

```<code>class x {

static int arr [2] [2];
}
</code>```

lib.cpp - includes the header.h file and creates an .so

source.cpp -

```<code>int x::arr = {define some values}
</code>```

includes the same header.h file and does NOT throw an link error

答:
Seams like you don't know what happens when you declare a static variable in a header.

Read more about it here.

Your solution with placing the static array in the class is fine, but under some circumstances could cause static order initialization fiasco, so you have to be careful when you use static class member variables.

If you prefer the 1st way, you could declare the array like extern variable, and define it in the source file.

Body:
I am new to C++ linux and i have question how this is working,

header.h

static int arr [2] [2] = {some values}

lib.cpp - includes the header.h file and creates an .so

source.cpp - includes the same header.h file(and dynamicaly links lib.so) and while linking, throws an .gnu.linkonce_t error

So, to avoid that, I went with this approach,

header.h

class x {

static int arr [2] [2];
}

lib.cpp - includes the header.h file and creates an .so

source.cpp -

int x::arr = {define some values}

includes the same header.h file and does NOT throw an link error


问:
Filter the results of a query using conditions in asp.net with entity framework
I want to know how many people are in a especify local, using entry and exit validation of this person. If he has entered in the local, then he will generate a transaction with a TrCode = "C0". when he comes out of the place, he will generate a TrCode = "CI". There are other types of TrCode, but it is useless for this kind o validation. i have a query that returns to me this result down bellow:

```<code>        var query = from a in context.CardDB
                    join c in context.tblTransaction on a.CardNo equals c.CardNo
                    where c.TrCode == "C0" || c.TrCode == "CI"
                    where c.TrSiteCode == sitecode
                    select c;
</code>```

Now I have all the rows that have the TrCode == "C0" or TrCode == "CI". But the result gives me all the transactions that the employers(CardDB) did. So the result gives a lot of transactions made of different employers. Sometimes some employer make 2 or even 3 transcations like, when he arrives and when he goes out for lunch, then he cames back etc.

I have to show in a grid just the employers that have in general count more transactions TrCode == "C0" than TrCode == "CI". So, what i have to do to count the transcations of only the employers with the same ID, and, when showing it in the grid, show just a row of this employers and not all the rows.

Since already, Thank you!

答:
```<code>var queryNumberC0 = query.Where(c => c.TrCode == "C0").Select(c => c.ID).GroupBy(c => c.Value).ToList();
var queryNumberC1 = query.Where(c => c.TrCode == "C1").Select(c => c.ID).GroupBy(c => c.Value).ToList();
</code>```

And to get the number of the ID y (Key is the ID of the customer):

```<code>int y = [Customer's ID];
int temp = queryNumberC0.Find(c => c.Key == y);
</code>```

You don't have to specifie the ToList() at the end of the query, do what you want with the result. I just find it easier to browse

Body:
I want to know how many people are in a especify local, using entry and exit validation of this person. If he has entered in the local, then he will generate a transaction with a TrCode = "C0". when he comes out of the place, he will generate a TrCode = "CI". There are other types of TrCode, but it is useless for this kind o validation. i have a query that returns to me this result down bellow:

        var query = from a in context.CardDB
                    join c in context.tblTransaction on a.CardNo equals c.CardNo
                    where c.TrCode == "C0" || c.TrCode == "CI"
                    where c.TrSiteCode == sitecode
                    select c;

Now I have all the rows that have the TrCode == "C0" or TrCode == "CI". But the result gives me all the transactions that the employers(CardDB) did. So the result gives a lot of transactions made of different employers. Sometimes some employer make 2 or even 3 transcations like, when he arrives and when he goes out for lunch, then he cames back etc.

I have to show in a grid just the employers that have in general count more transactions TrCode == "C0" than TrCode == "CI". So, what i have to do to count the transcations of only the employers with the same ID, and, when showing it in the grid, show just a row of this employers and not all the rows.

Since already, Thank you!

Body:
var queryNumberC0 = query.Where(c => c.TrCode == "C0").Select(c => c.ID).GroupBy(c => c.Value).ToList();
var queryNumberC1 = query.Where(c => c.TrCode == "C1").Select(c => c.ID).GroupBy(c => c.Value).ToList();

And to get the number of the ID y (Key is the ID of the customer):

int y = [Customer's ID];
int temp = queryNumberC0.Find(c => c.Key == y);

You don't have to specifie the ToList() at the end of the query, do what you want with the result. I just find it easier to browse


问:
Changer spinner style - Android Studio
I'm working on the "design" of an application we created for a school project. How can I change the design (text size, text color, color of the spinner etc.)of a spinner on Android Studio?

This is my code :

public class MainActivity extends AppCompatActivity {

    private String flowerSpinnerValue, modeSpinnerValue;
    private Flower flower;

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

        final Spinner flowerSpinner = (Spinner) findViewById(R.id.flowerSpinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.flowers_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        flowerSpinner.setAdapter(adapter);
        flowerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (flowerSpinner.getSelectedItem().equals("Basil")) {
                    flower = new Basil();
                }

                if(flowerSpinner.getSelectedItem().equals("Mint")) {
                    flower = new Mint();
                    System.out.println("jusia");
                }
                if (flowerSpinner.getSelectedItem().equals("Thyme")) {
                    flower = new Thyme();
                }
            }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><Spinner
        android:id="@+id/flowerSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/ChooseFlower"
        android:layout_toEndOf="@+id/ChooseFlower"
        android:layout_toRightOf="@+id/ChooseFlower"
        android:backgroundTint="?android:attr/actionMenuTextColor"
        android:keepScreenOn="false"
        android:splitMotionEvents="false"
        android:textAlignment="center"
        android:visibility="visible" /></code>```

I think I should change something in my XML code but I don't know what.
Thanks for your help !

答:
this is working for me

```<code>    String[] columns = new String[] {DatabaseAdapter.ACTIVITYTYPE};
    int[] to = new int[] {R.id.tvSpin};
    final SimpleCursorAdapter mAdapter1 = new SimpleCursorAdapter(this, R.layout.spin_text, location_cursor, columns1, to1);
    mAdapter1.setDropDownViewResource(R.layout.drop_down_view);
    spinner.setAdapter(mAdapter1);
</code>```

drop_down_view.xml

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

     <TextView
        android:id="@+id/tvSpin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:layout_gravity="center|left"
        android:paddingLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/BGo"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        />

</LinearLayout>
</code>```

spin_text.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
     >

        <TextView
            android:id="@+id/tvSpin"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Doctors Name"
            android:textColor="@color/Black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/tv_Product1"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product1"
            android:textColor="@color/Black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/tv_Product2"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product2"
            android:textColor="@color/Black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/tv_Product3"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product3"
            android:textColor="@color/Black"
            android:textSize="12sp" />

         <TextView
            android:id="@+id/tv_Product4"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product4"
            android:textColor="@color/Black"
            android:textSize="12sp" />

          <TextView
            android:id="@+id/tv_Product5"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product5"
            android:textColor="@color/Black"
            android:textSize="12sp" />

    </LinearLayout>
</LinearLayout>
</code>```

Title: Changer spinner style - Android Studio

Body:
I'm working on the "design" of an application we created for a school project. How can I change the design (text size, text color, color of the spinner etc.)of a spinner on Android Studio?

This is my code :

public class MainActivity extends AppCompatActivity {

    private String flowerSpinnerValue, modeSpinnerValue;
    private Flower flower;

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

        final Spinner flowerSpinner = (Spinner) findViewById(R.id.flowerSpinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.flowers_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        flowerSpinner.setAdapter(adapter);
        flowerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (flowerSpinner.getSelectedItem().equals("Basil")) {
                    flower = new Basil();
                }

                if(flowerSpinner.getSelectedItem().equals("Mint")) {
                    flower = new Mint();
                    System.out.println("jusia");
                }
                if (flowerSpinner.getSelectedItem().equals("Thyme")) {
                    flower = new Thyme();
                }
            }

<Spinner
        android:id="@+id/flowerSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/ChooseFlower"
        android:layout_toEndOf="@+id/ChooseFlower"
        android:layout_toRightOf="@+id/ChooseFlower"
        android:backgroundTint="?android:attr/actionMenuTextColor"
        android:keepScreenOn="false"
        android:splitMotionEvents="false"
        android:textAlignment="center"
        android:visibility="visible" />

I think I should change something in my XML code but I don't know what.
Thanks for your help !

Body:
this is working for me

    String[] columns = new String[] {DatabaseAdapter.ACTIVITYTYPE};
    int[] to = new int[] {R.id.tvSpin};
    final SimpleCursorAdapter mAdapter1 = new SimpleCursorAdapter(this, R.layout.spin_text, location_cursor, columns1, to1);
    mAdapter1.setDropDownViewResource(R.layout.drop_down_view);
    spinner.setAdapter(mAdapter1);

drop_down_view.xml

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

     <TextView
        android:id="@+id/tvSpin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:layout_gravity="center|left"
        android:paddingLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/BGo"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        />

</LinearLayout>

spin_text.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
     >

        <TextView
            android:id="@+id/tvSpin"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Doctors Name"
            android:textColor="@color/Black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/tv_Product1"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product1"
            android:textColor="@color/Black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/tv_Product2"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product2"
            android:textColor="@color/Black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/tv_Product3"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product3"
            android:textColor="@color/Black"
            android:textSize="12sp" />

         <TextView
            android:id="@+id/tv_Product4"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product4"
            android:textColor="@color/Black"
            android:textSize="12sp" />

          <TextView
            android:id="@+id/tv_Product5"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="Product5"
            android:textColor="@color/Black"
            android:textSize="12sp" />

    </LinearLayout>
</LinearLayout>


问:
How to bind a combo box to a collection asynchronously where the objects gets updated WPF
I have created a WPF binding it was working fine but then I realised I needed a refresh button show when I call the SetUpData function I am getting this error:

Additional information: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

C#:

```<code>public async void GetShows(string serviceDocUri)
{

    await Task.Run(() => _Shows = new ObservableCollection<Show>());

    await Task.Run(() => GetAllShowsWithPath("", directoryShowDoc)); //Error shows on this line
}
</code>```

More C#:

```<code>public MainWindow()
{
    InitializeComponent();
    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}
</code>```

More C#:

```<code>private async void SetUpData()
{
    await Task.Run(() => _VizManager.GetShows(_TrioLocalHost));

    //This is binded to my WPF combobox
    Workspace.This.TrioShow = _VManager._Shows;

}
</code>```

More C#:

```<code>private async Task GetAllShowsWithPath(string directoryPath, XmlDocument xmlDoc)
{
    string siteRoot = "http://";
    foreach (XmlNode showNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='show']/atom:title", nameSpaceManager_))
    {
        _Shows.Add(new Show { Title = "showTitle", ShowLink = "showLink", FullPath = "fullPath" });
    }

    foreach (XmlNode dirNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='directory' and not(atom:category/@term='show')]/atom:title", nameSpaceManager_))
    {
        string dir = dirNode.InnerText;
        XmlDocument xmlDoc1 = new XmlDocument();
        string directoryPath1 = directoryPath + "/" + dir;
        string xml = "";
        string page = siteRoot + "/directory/shows" + directoryPath1 + "/";
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(page))
        {
            response.Headers.Add("Accepts", "application/atomsvc+xml");
            using (HttpContent content = response.Content)
            {
                string data = await content.ReadAsStringAsync();
                if (data != null)
                {
                    xml = data;
                }
            }
        }
        xmlDoc1.LoadXml(xml);
        await this.GetAllShowsWithPath(directoryPath1, xmlDoc1);
    }
}
</code>```

答:
Your code is a mess, to be honest. You don't call a method Get* if it doesn't return something, to begin with. And why are you creating and awaiting several tasks inside other tasks?

Anyway, the ObservableCollection<Show> should (must) be created on the UI thread. Create it the first thing you do in the constructor of the window or view model or wherever it's defined:

```<code>public MainWindow()
{
    InitializeComponent();
    _Shows = new ObservableCollection<Show>();
    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}
</code>```

Your GetAllShowsWithPath method should then return an IEnumerable<Show> that you populate the data-bound ObservableCollection with back on the UI thread. You could change the return type of the method to Task<List<Show>> and return a list of objects instead of trying to access the ObservableCollection from within the method.

The other option would be to use the BindingOperations.EnableCollectionSynchronization method to enable the collection to be accessed across multiple threads:

```<code>private readonly object _lock = new object();
public MainWindow()
{
    InitializeComponent();
    _Shows = new ObservableCollection<Show>();
    BindingOperations.EnableCollectionSynchronization(_Shows, _lock);

    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}
</code>```

You must still create the collection and call this method on the UI thread though.

Body:
I have created a WPF binding it was working fine but then I realised I needed a refresh button show when I call the SetUpData function I am getting this error:

Additional information: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

C#:

public async void GetShows(string serviceDocUri)
{

    await Task.Run(() => _Shows = new ObservableCollection<Show>());

    await Task.Run(() => GetAllShowsWithPath("", directoryShowDoc)); //Error shows on this line
}

More C#:

public MainWindow()
{
    InitializeComponent();
    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}

More C#:

private async void SetUpData()
{
    await Task.Run(() => _VizManager.GetShows(_TrioLocalHost));

    //This is binded to my WPF combobox
    Workspace.This.TrioShow = _VManager._Shows;

}

More C#:

private async Task GetAllShowsWithPath(string directoryPath, XmlDocument xmlDoc)
{
    string siteRoot = "http://";
    foreach (XmlNode showNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='show']/atom:title", nameSpaceManager_))
    {
        _Shows.Add(new Show { Title = "showTitle", ShowLink = "showLink", FullPath = "fullPath" });
    }

    foreach (XmlNode dirNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='directory' and not(atom:category/@term='show')]/atom:title", nameSpaceManager_))
    {
        string dir = dirNode.InnerText;
        XmlDocument xmlDoc1 = new XmlDocument();
        string directoryPath1 = directoryPath + "/" + dir;
        string xml = "";
        string page = siteRoot + "/directory/shows" + directoryPath1 + "/";
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(page))
        {
            response.Headers.Add("Accepts", "application/atomsvc+xml");
            using (HttpContent content = response.Content)
            {
                string data = await content.ReadAsStringAsync();
                if (data != null)
                {
                    xml = data;
                }
            }
        }
        xmlDoc1.LoadXml(xml);
        await this.GetAllShowsWithPath(directoryPath1, xmlDoc1);
    }
}

Body:
Your code is a mess, to be honest. You don't call a method Get* if it doesn't return something, to begin with. And why are you creating and awaiting several tasks inside other tasks?

Anyway, the ObservableCollection<Show> should (must) be created on the UI thread. Create it the first thing you do in the constructor of the window or view model or wherever it's defined:

public MainWindow()
{
    InitializeComponent();
    _Shows = new ObservableCollection<Show>();
    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}

Your GetAllShowsWithPath method should then return an IEnumerable<Show> that you populate the data-bound ObservableCollection with back on the UI thread. You could change the return type of the method to Task<List<Show>> and return a list of objects instead of trying to access the ObservableCollection from within the method.

The other option would be to use the BindingOperations.EnableCollectionSynchronization method to enable the collection to be accessed across multiple threads:

private readonly object _lock = new object();
public MainWindow()
{
    InitializeComponent();
    _Shows = new ObservableCollection<Show>();
    BindingOperations.EnableCollectionSynchronization(_Shows, _lock);

    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}

You must still create the collection and call this method on the UI thread though.


问:
how can I give customise your product functionality in my nodejs shopping site
I want to design a website for Cards in nodejs. How can I give customer the feature of designing  their own product i.e, card, cups or t-shirts by giving their own text and image like in printvenue. Is there any js or third party tool which I can use for this??</p>

答:
It sounds like you want to build a CMS product. Most probably you will have to build from scratch.

My two cents... Checkout html contenteditable, for a WYSIWYG CMS experience,


问:
Connect php to mysql safely using encrypted password
I am a php beginner and was wondering what it the best way to connect to mysql database safely.

To start, I know that I need to save the password in a config file, but should I save it encrypted or plain?

Should the password passed to mysql_connect be plain?

If so, should I encrypt the password in config file and then decrypt it? Is the decryption possible?

答:
This is why DB encryption is really not secure. At a minimum it must be in RAM memory to access the encrypted data.

If the DB encryption is stored on the server in any manner an attacker who gains admin access will get the key.

Secure all servers with 2-factor authentication.

The next step up is to move the DB to a server that is not connected to the Internet on a very secure and limited server with rate limiting/exception logging the the Internet facing server connects to.

Additionally the key can be secured at rest in an HSM.

It all depends on the security requirements. First you need to define the threat model and then the security requirements, nothing is fully secure so there is a design tradeoff.


问:
How to write superscript in android?
I am trying to write a subscript in android textview and this is the code that I am using. </p>

```<code>txt.setText(String.valueOf((int)num) + (Html.fromHtml("<sup><small>2<small></sup>")));
</code>```

<p>When I am running this program, the 2 looks as the same as the other text from integer num.  </p>

答: From what i see in your code, you didn't close the small tag. Just do this: 2. Notice the "/" character in the second  tag.

Title: How to write superscript in android?

Body:
I am trying to write a subscript in android textview and this is the code that I am using.

txt.setText(String.valueOf((int)num) + (Html.fromHtml("2")));

When I am running this program, the 2 looks as the same as the other text from integer num.

Body: From what i see in your code, you didn't close the small tag. Just do this: <small>2</small>. Notice the "/" character in the second </small> tag.


问:
Multiple Multi-Select dropdown
This is a situation I have never encountered previously. I am doing a survey where i have the same multi-select drop down in the same form. Basically it is a survey about cars, how many cars, the drivers of each car.....and so on. Each car is a new div with a unique id. Each div is a new page in the survey and has the same questions on it. Im good with all the other questions but there is a question called activities where a user can select multiple items,   multi-select or it could be checkboxes. Not sure what to use. I just need to be able to store multiples, multiple times.
I hope I explained this well enough. If not I can answer any questions you may have.

Example

```<code><form>
<div id="page_1">
   <select id="activities_1" name="activities" type="multiple">
   </select>
</div>
<div id="page_2">
   <select id="activities_2" name="activities" type="multiple">
   </select>
</div>
.......
</form>
</code>```

答:
Give each input an unique name.

```<code><select name="activities1" multiple>
</select>

<select name="activities2" multiple>
</select>
</code>```

To obtain the multiple submitted values on the same name in the servlet, use request.getParameterValues() instead of request.getParameter().

```<code>String[] activities1 = request.getParameterValues("activities1");
String[] activities2 = request.getParameterValues("activities2");
</code>```

Title: Multiple Multi-Select dropdown

Body:
This is a situation I have never encountered previously. I am doing a survey where i have the same multi-select drop down in the same form. Basically it is a survey about cars, how many cars, the drivers of each car.....and so on. Each car is a new div with a unique id. Each div is a new page in the survey and has the same questions on it. Im good with all the other questions but there is a question called activities where a user can select multiple items,   multi-select or it could be checkboxes. Not sure what to use. I just need to be able to store multiples, multiple times.
I hope I explained this well enough. If not I can answer any questions you may have.

Example

<form>

   <select id="activities_1" name="activities" type="multiple">
   </select>

   <select id="activities_2" name="activities" type="multiple">
   </select>

.......
</form>

Body:
Give each input an unique name.

<select name="activities1" multiple>
</select>

<select name="activities2" multiple>
</select>

To obtain the multiple submitted values on the same name in the servlet, use request.getParameterValues() instead of request.getParameter().

String[] activities1 = request.getParameterValues("activities1");
String[] activities2 = request.getParameterValues("activities2");


问:
Access TextBlock Text inside a DataTemplate UWP
I searched all over the internet on this question, but I can't made progress in my UWP application.

I have a ListView with a DataTemplate:

```<code><ListView x:Name="lvEszTmplt" Margin="50,61,0,0" ItemClick="lvEszTmplt_ItemClick_1" SelectionChanged="lvEszTmplt_SelectionChanged_1"   >
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,8" x:Name="spItem" >
                    <TextBlock x:Name="tbAzonosito" >
                                <Run Text="Azonosító: " Foreground="DarkGray"/>
                                <Run Text="{Binding Azonosito}"
                                     Foreground="DarkGray"
                                     />

                    </TextBlock>
                    <TextBlock x:Name="tbMegnevezes" >
                                <Run Text="Megnevezés: " Foreground="DarkGray"/>
                                <Run Text="{Binding Megnevezes}"
                                     Foreground="DarkGray"/>

                    </TextBlock>
                    <TextBlock x:Name="tbSerial" >
                                <Run Text="Serial: " Foreground="DarkGray"/>
                                <Run Text="{Binding Serial}"
                                     Foreground="DarkGray"/>
                    </TextBlock>
                    <TextBlock x:Name="tbSorszam"   >
                                <Run Text="Sorszám: " Foreground="DarkGray"/>
                                <Run Text="{Binding Sorszam}"
                                     Foreground="DarkGray"/>
                    </TextBlock>

                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

In the ListView, the "Azonosito" is an ID column.
When I click on a Item, it should go to another Frame and take the ID from the ListView, and load the Deatails View with the data from the ID.

How can I do this?

Thank you for helping me out!

答:
@Krzysztof Bracha have a good answer.But I see you forget add the IsItemClickEnabled property.

You can use IsItemClickEnabled=true to enabled ItemClick.

And you should bind the sources to ListView.

You also can use x:bind to binding the data.

If your sources' type is ObservableCollection that you can use the code as @Krzysztof Bracha.

If you need get the control in ListView that you can use VisualTreeHelper.GetChild(DependencyObject reference, int childIndex); to get it.

See:https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth

Body:
I searched all over the internet on this question, but I can't made progress in my UWP application.

I have a ListView with a DataTemplate:

<ListView x:Name="lvEszTmplt" Margin="50,61,0,0" ItemClick="lvEszTmplt_ItemClick_1" SelectionChanged="lvEszTmplt_SelectionChanged_1"   >
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,8" x:Name="spItem" >
                    <TextBlock x:Name="tbAzonosito" >
                                <Run Text="Azonosító: " Foreground="DarkGray"/>
                                <Run Text="{Binding Azonosito}"
                                     Foreground="DarkGray"
                                     />

                    </TextBlock>
                    <TextBlock x:Name="tbMegnevezes" >
                                <Run Text="Megnevezés: " Foreground="DarkGray"/>
                                <Run Text="{Binding Megnevezes}"
                                     Foreground="DarkGray"/>

                    </TextBlock>
                    <TextBlock x:Name="tbSerial" >
                                <Run Text="Serial: " Foreground="DarkGray"/>
                                <Run Text="{Binding Serial}"
                                     Foreground="DarkGray"/>
                    </TextBlock>
                    <TextBlock x:Name="tbSorszam"   >
                                <Run Text="Sorszám: " Foreground="DarkGray"/>
                                <Run Text="{Binding Sorszam}"
                                     Foreground="DarkGray"/>
                    </TextBlock>

                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

In the ListView, the "Azonosito" is an ID column.
When I click on a Item, it should go to another Frame and take the ID from the ListView, and load the Deatails View with the data from the ID.

How can I do this?

Thank you for helping me out!


问:
Django import-export of excel data
I'm using django import export (DIE) to import some data. I have a problem importing the data.

my admin.py:

```<code>class TestResource(resources.ModelResource):

    class Meta:
            model = Test
            exclude = ('id',)
            import_id_fields = ['VS',]
            skip_unchanged = True

 class TestAdmin(ImportExportMixin,admin.ModelAdmin):

      fieldsets = [
        ('VS',      {'fields':['VS']}),
        ('pool',    {'fields':['pool']}),
        ('pool_port', {'fields':['pool_port']}),
        ('idc',        {'fields':['idc']})
       ]

    list_display = ('VS','pool','pool_port','idc')
    list_filter = ['pool_port']
    search_fields = ['VS','pool','pool_port','idc']
    resource_class = TestResource
admin.site.register(Test,TestAdmin)
</code>```

I want to import an excel file like:

But:

I want to import all the rows . Please tell me how to ignore the duplicates. Thanks in advance!

答:
OK I find one way to import. Import the file with save(). If you guys have a better way please tell me~

The code as follow:

```<code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings")

import django
django.setup()

import xlrd
from Test.models import Test

def input(VS,pool_text,port,idc_text):
    i = Test(
        VS = vs,
        pool = pool_text,
        pool_port = port,
        idc = idc_text
        )
    i.save()

files = xlrd.open_workbook('test.xls')
sh = files.sheet_by_index(0)
n = 0
for i in range(1,sh.nrows):

    vs = sh.cell(i,0).value
    pool_text = sh.cell(i,1).value
    port = sh.cell(i,2).value
    idc = sh.cell(i,3).value
    input(vs,pool_text,port,idc)
    n += 1
print n
</code>```

Title: Django import-export of excel data

Body:
I'm using django import export (DIE) to import some data. I have a problem importing the data.

my admin.py:

class TestResource(resources.ModelResource):

    class Meta:
            model = Test
            exclude = ('id',)
            import_id_fields = ['VS',]
            skip_unchanged = True

 class TestAdmin(ImportExportMixin,admin.ModelAdmin):

      fieldsets = [
        ('VS',      {'fields':['VS']}),
        ('pool',    {'fields':['pool']}),
        ('pool_port', {'fields':['pool_port']}),
        ('idc',        {'fields':['idc']})
       ]

    list_display = ('VS','pool','pool_port','idc')
    list_filter = ['pool_port']
    search_fields = ['VS','pool','pool_port','idc']
    resource_class = TestResource
admin.site.register(Test,TestAdmin)

I want to import an excel file like:

But:

I want to import all the rows . Please tell me how to ignore the duplicates. Thanks in advance!

Body:
OK I find one way to import. Import the file with save(). If you guys have a better way please tell me~

The code as follow:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings")

import django
django.setup()

import xlrd
from Test.models import Test

def input(VS,pool_text,port,idc_text):
    i = Test(
        VS = vs,
        pool = pool_text,
        pool_port = port,
        idc = idc_text
        )
    i.save()

files = xlrd.open_workbook('test.xls')
sh = files.sheet_by_index(0)
n = 0
for i in range(1,sh.nrows):

    vs = sh.cell(i,0).value
    pool_text = sh.cell(i,1).value
    port = sh.cell(i,2).value
    idc = sh.cell(i,3).value
    input(vs,pool_text,port,idc)
    n += 1
print n


问:
List of list with variable size of element with no brackets and apostrophes
I want to make list of list, like in 1 element of new list should be variable size of elements of another list.

For exmaple:

```<code>Input buffor[]:

> "0,70"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,70"
>
> ...
>
> ,"n"
</code>```

variable size, for example = 14 => list[0] = 14 elements of another list

```<code>(list[0] - list[13]) with no [] or ' between elements

Output list[]:

> list[0] = "0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0"
>
> ...
>
> list[n] = ...
</code>```

I got this line:

```<code>values = [values[i:i + size] for i in range(0, len(values), size)]
</code>```

, but it is producing something like this:

```<code>> ['"val1"', ',"val2"', ... ,',"val13"']
</code>```

答:
Task is parsing html file, and proccesing to csv format printed in stdout.

Code:

```<code>> #!/usr/bin/python3
> # -*- coding: utf-8 -*-
> #regex import re
> #argv from sys import argv
> #stdin from sys import stdin
> #csv import csv
> #variable length of argv argvLen = len(argv)
> #args
> #1 file if ( (argvLen > 1 ) and (argvLen < 3 ) ):
>     filename = argv[1]
>     with open(filename, 'r') as myfile:
>         html = myfile.read().replace('\n', '')
> #2 files dodać try catch elif (argvLen == 3):
>     filename = argv[1]
>     filename2 = argv[2]
>     with open(filename, 'r') as myfile:
>         html = myfile.read().replace('\n', '')
>     with open(filename2, 'r') as myfile:
>         users_list = [val.strip() for val in myfile]
> #no files elif ( (argvLen == 1) or (argvLen > 4) ):
>     print("Required 1 or 2 parameters![FILE NAME1 - FILE NAME2].\n")
>     exit(0) #or quit()
> #separating <table></table> from html file regex = r'<table width="100%" class="problems">([\S\s]*?)<\/table>' table =
> re.search(regex, html) if table:
>     print("Done. Seperate <table>\n")
>     table = table.group(1) else:
>     print("Error. No match <table>!\n")
> #getting names regex = r'<th>(\S*?)<\/th>' names = re.findall(regex, table) if names:
>     print("Done. Names.\n") else:
>     print("Error. No match names!\n")
> #getting kinds regex = r'\/problems\/[^>]*>([\S\s]*?)<\/a>' comp = re.findall(regex, table) if comp:
>     print("Done. Kinds.\n") else:
>     print("Error. No match kinds!\n")
> #size of comp size = len(comp)
> #competitions + final score size += 1   print("Size: " + str(size) + "\n")
> #getting users regex = r'\/users\/[^>]*>([\S\s]*?)<\/a>' users = re.findall(regex, table) if users:
>     print("Done. Users.\n") else:
>     print("Error. No match users!\n")
> #getting nicknames regex = r"\/users\/([\S]*?)'" nicks = re.findall(regex, table) if nicks:
>     print("Done. Nicks.\n") else:
>     print("Error. No match nicks!\n")
> #getting values regex = r'<(?:font|td)[^>]*>(\d+(?:\.\d+)|-)' values = re.findall(regex, table) if values:
>     print("Done. Values.\n") else:
>     print("Error. No match values!\n")
> #replace "-" to "0.0" values = [val.replace('-', '0.0') for val in values]
> #replace "." to "," values = [val.replace('.', ',') for val in values]
>
> #Editing Data for i in range(len(names)):
>     names[i] = '"' + names[i] + '"'
>     for i in range(len(values)):
>     values[i] = '"' + values[i] + '"'   for i in range(len(comp)):
>     comp[i] = '"' + comp[i] + '"'   if 'users_list' in globals():
>     for i in range(len(users_list)):
>         users_list[i] = '"' + users_list[i] + '"'   t1 = [] for i in range(len(comp)):
>     if i == 0:
>         t1 = comp[0]
>         continue
>     t1 += "," + comp[i]
>     for i in range(len(values)):
>     if ( (i % size) == 0 ):
>         continue
>     values[i] = "," + values[i]
> #print for en in values:
>     print(str(en))
> #TODO
> #here łaczenie values = [values[i:i + size] for i in range(0, len(values), size)]
> #editing nick for i in range(len(users)):
>     #if name == null then name = nickname
>     if not users[i]:
>             users[i] = nicks[i]
>     #add " " - csv format
>     users[i] = '"' + users[i] + '"'
>     nicks[i] = '"' + nicks[i] + '"'
>
> #First Row of CSV csvtable = [] csvtable.append(names[1] + ',' + '"NICK"' + ',' + t1 + ',' + names[3])
> #Rest Data of CSV for i in range(len(users)):
>     #checking if name is on list
>     if 'users_list' in globals():
>         for check in users_list:
>             if(users[i-1] == check ):
>                 csvtable.append(users[i-1] + ',' + nicks[i-1] + ',' + str(values[i-1])[1:-1])
>
>     else:
>         csvtable.append(users[i-1] + ',' + nicks[i-1] + ',' + str(values[i-1])[1:-1])
>
> #printing csv file
> #for csv in csvtable:
> #   print(csv)
</code>```

This is html file to parsing:

https://pastebin.com/waE7yrr0

And here is output what i looking for:

"NAME","NICK","WIPING40","WIPING41","WIPING42","WIPING43","WIPING44","WIPING45","WIPING46","WIPING47","WIPING48","WIPING49","WIPING4A","WIPING4B1","WIPING4C","SCORE"

"Marcel
Rzepka","other019","1,00","2,00","2,00","2,00","3,00","4,00","4,00","2,00","2,00","4,00","3,00","4,00","7,00","40,00"

"vaaadus","dtoton","1,00","2,00","2,00","2,00","3,00","4,00","4,00","2,00","2,00","4,00","3,00","4,00","7,00","40,00"

"Zuzanna Zelek","zuza98","1,00","2,00","2,00","2,00","2,70","4,00","4,00","2,00","2,00","4,00","3,00","4,00","7,00","39,70"

"Paweł Redman","theinvsblman","1,00","2,00","2,00","2,00","3,00","4,00","3,20","1,80","2,00","4,00","3,00","4,00","7,00","39,00"

. . . .

I dont know python good, maybe there is a better solution of this problem.
All regexes are fine.

Body:
I want to make list of list, like in 1 element of new list should be variable size of elements of another list.

For exmaple:

Input buffor[]:

> "0,70"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,70"
>
> ...
>
> ,"n"

variable size, for example = 14 => list[0] = 14 elements of another list

(list[0] - list[13]) with no [] or ' between elements

Output list[]:

> list[0] = "0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0"
>
> ...
>
> list[n] = ...

I got this line:

values = [values[i:i + size] for i in range(0, len(values), size)]

, but it is producing something like this:

> ['"val1"', ',"val2"', ... ,',"val13"']

Body:
Task is parsing html file, and proccesing to csv format printed in stdout.

Code:

> #!/usr/bin/python3
> # -*- coding: utf-8 -*-
> #regex import re
> #argv from sys import argv
> #stdin from sys import stdin
> #csv import csv
> #variable length of argv argvLen = len(argv)
> #args
> #1 file if ( (argvLen > 1 ) and (argvLen < 3 ) ):
>     filename = argv[1]
>     with open(filename, 'r') as myfile:
>         html = myfile.read().replace('\n', '')
> #2 files dodać try catch elif (argvLen == 3):
>     filename = argv[1]
>     filename2 = argv[2]
>     with open(filename, 'r') as myfile:
>         html = myfile.read().replace('\n', '')
>     with open(filename2, 'r') as myfile:
>         users_list = [val.strip() for val in myfile]
> #no files elif ( (argvLen == 1) or (argvLen > 4) ):
>     print("Required 1 or 2 parameters![FILE NAME1 - FILE NAME2].\n")
>     exit(0) #or quit()
> #separating <table></table> from html file regex = r'<table width="100%" class="problems">([\S\s]*?)<\/table>' table =
> re.search(regex, html) if table:
>     print("Done. Seperate <table>\n")
>     table = table.group(1) else:
>     print("Error. No match <table>!\n")
> #getting names regex = r'<th>(\S*?)<\/th>' names = re.findall(regex, table) if names:
>     print("Done. Names.\n") else:
>     print("Error. No match names!\n")
> #getting kinds regex = r'\/problems\/[^>]*>([\S\s]*?)<\/a>' comp = re.findall(regex, table) if comp:
>     print("Done. Kinds.\n") else:
>     print("Error. No match kinds!\n")
> #size of comp size = len(comp)
> #competitions + final score size += 1   print("Size: " + str(size) + "\n")
> #getting users regex = r'\/users\/[^>]*>([\S\s]*?)<\/a>' users = re.findall(regex, table) if users:
>     print("Done. Users.\n") else:
>     print("Error. No match users!\n")
> #getting nicknames regex = r"\/users\/([\S]*?)'" nicks = re.findall(regex, table) if nicks:
>     print("Done. Nicks.\n") else:
>     print("Error. No match nicks!\n")
> #getting values regex = r'<(?:font|td)[^>]*>(\d+(?:\.\d+)|-)' values = re.findall(regex, table) if values:
>     print("Done. Values.\n") else:
>     print("Error. No match values!\n")
> #replace "-" to "0.0" values = [val.replace('-', '0.0') for val in values]
> #replace "." to "," values = [val.replace('.', ',') for val in values]
>
> #Editing Data for i in range(len(names)):
>     names[i] = '"' + names[i] + '"'
>     for i in range(len(values)):
>     values[i] = '"' + values[i] + '"'   for i in range(len(comp)):
>     comp[i] = '"' + comp[i] + '"'   if 'users_list' in globals():
>     for i in range(len(users_list)):
>         users_list[i] = '"' + users_list[i] + '"'   t1 = [] for i in range(len(comp)):
>     if i == 0:
>         t1 = comp[0]
>         continue
>     t1 += "," + comp[i]
>     for i in range(len(values)):
>     if ( (i % size) == 0 ):
>         continue
>     values[i] = "," + values[i]
> #print for en in values:
>     print(str(en))
> #TODO
> #here łaczenie values = [values[i:i + size] for i in range(0, len(values), size)]
> #editing nick for i in range(len(users)):
>     #if name == null then name = nickname
>     if not users[i]:
>             users[i] = nicks[i]
>     #add " " - csv format
>     users[i] = '"' + users[i] + '"'
>     nicks[i] = '"' + nicks[i] + '"'
>
> #First Row of CSV csvtable = [] csvtable.append(names[1] + ',' + '"NICK"' + ',' + t1 + ',' + names[3])
> #Rest Data of CSV for i in range(len(users)):
>     #checking if name is on list
>     if 'users_list' in globals():
>         for check in users_list:
>             if(users[i-1] == check ):
>                 csvtable.append(users[i-1] + ',' + nicks[i-1] + ',' + str(values[i-1])[1:-1])
>
>     else:
>         csvtable.append(users[i-1] + ',' + nicks[i-1] + ',' + str(values[i-1])[1:-1])
>
> #printing csv file
> #for csv in csvtable:
> #   print(csv)

This is html file to parsing:

https://pastebin.com/waE7yrr0

And here is output what i looking for:

"NAME","NICK","WIPING40","WIPING41","WIPING42","WIPING43","WIPING44","WIPING45","WIPING46","WIPING47","WIPING48","WIPING49","WIPING4A","WIPING4B1","WIPING4C","SCORE"

"Marcel
Rzepka","other019","1,00","2,00","2,00","2,00","3,00","4,00","4,00","2,00","2,00","4,00","3,00","4,00","7,00","40,00"

"vaaadus","dtoton","1,00","2,00","2,00","2,00","3,00","4,00","4,00","2,00","2,00","4,00","3,00","4,00","7,00","40,00"

"Zuzanna Zelek","zuza98","1,00","2,00","2,00","2,00","2,70","4,00","4,00","2,00","2,00","4,00","3,00","4,00","7,00","39,70"

"Paweł Redman","theinvsblman","1,00","2,00","2,00","2,00","3,00","4,00","3,20","1,80","2,00","4,00","3,00","4,00","7,00","39,00"

. . . .

I dont know python good, maybe there is a better solution of this problem.
All regexes are fine.


问:
Javascript timer to use multiple times in a page
I have this Javascript count down timer that works perfectly. Only problem is i can use it for only one time in one page. I want to use it multiple times.

I think script use id ="timer" that is why i am not able to use it multiple times.

Below  is the JS code:

```<code><script>
var startTime = 60; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
var space = '       ';

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = "00" + space + minutes + space + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

window.onload = function() {
  var now = new Date();
  var hrs = now.getHours();
  var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
    display = document.querySelector("#timer");

  startTimer(setMinutes, display);
};
</script>
</code>```

答:
```<code>window.setInterval(function(){ Your function }, 1000);
</code>```

Here 1000 means timer 1 sec

Body:
window.setInterval(function(){ Your function }, 1000);

Here 1000 means timer 1 sec


问:
show all options using prompt.choice
I'm using PromptDialog.Choice to show options to user. The problem is :

I've 4 options but only 3 of them are showed. If user wants to see the last option, must use scroll. My bot is configured for messenger channel.

I've this :

```<code>           var dialog = new PromptDialog.PromptChoice<string>(options, "I can assist you with : ", "Sorry, that wans't a valid option", 2);
           context.Call(dialog, UserChose);
</code>```

How to override PromptStyler to get this done ?

I want to show all the options to user when prompt is created without scroll.
Is that possible ?

答:
EDIT after Ezequiel's comment:
If you use PromptStyle.Keyboard, you will automatically get a correct display as the QuickReply style is now supported by the framework:

Initial answer:

If you are only using Facebook Messenger channel, you may use Ezequiel Jadib's Quick Replies implementation: https://github.com/ejadib/QuickReplies

It uses Facebook's ChannelData to set up real quick replies that Facebook Messenger displays in a good look-and-feel: https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies

Samples:

You can read more info on this blog post: http://southworks.com/blog/2016/09/15/sending-facebooks-quick-replies-using-microsoft-bot-framework/

Title: show all options using prompt.choice

Body:
I'm using PromptDialog.Choice to show options to user. The problem is :

I've 4 options but only 3 of them are showed. If user wants to see the last option, must use scroll. My bot is configured for messenger channel.

I've this :

           var dialog = new PromptDialog.PromptChoice<string>(options, "I can assist you with : ", "Sorry, that wans't a valid option", 2);
           context.Call(dialog, UserChose);

How to override PromptStyler to get this done ?

I want to show all the options to user when prompt is created without scroll.
Is that possible ?


问:
How to initialize Spring Data JPA Page to null?
This is a code snippet of my project. Here I'm trying to get paginated data using Spring Data JPA. The pagination part works fine. However when searchParameter is NULL then I just want to return empty create a blank page in my UI

```<code>public Page<AccessLog> getDataInRange(long fromTime, long toTime, String searchParameter, Integer start,
                                          Integer length) {
        Page<AccessLog> accessPage;
        if (searchParameter != null) {
            accessPage = accessRepository.findBySystemTimestampBetween(fromTime, toTime,
                    new PageRequest(start, length));
        } else
            accessPage = null;
        return accessPage;
    }
</code>```

However, this give an error when search parameter is null

Exception during execution of SpringSecurity application
  java.lang.NullPointerException: null

which caused because of that "null" value set as accessLogPage.

Any ideas?

答:
The searchParameter should be handled in the controller itself.

Try something like this in your controller

```<code>@Controller
public class BaseController {

    @RequestMapping("/")
    public ModelAndView welcome(...) {

        //get your searchParameter here

        if(searchParameter == null) {
            return new ModelAndView("blank-page");
        }

        //call your service layer to fetch the data and then return the actual page

        ModelAndView modelAndView = new ModelAndView("actual-page");
        modelAndView.addObject("data", FETCHED_DATA_FROM_SERVICE_LAYER);
        return new ModelAndView("actual-page");

    }

}
</code>```

Body:
This is a code snippet of my project. Here I'm trying to get paginated data using Spring Data JPA. The pagination part works fine. However when searchParameter is NULL then I just want to return empty create a blank page in my UI

public Page<AccessLog> getDataInRange(long fromTime, long toTime, String searchParameter, Integer start,
                                          Integer length) {
        Page<AccessLog> accessPage;
        if (searchParameter != null) {
            accessPage = accessRepository.findBySystemTimestampBetween(fromTime, toTime,
                    new PageRequest(start, length));
        } else
            accessPage = null;
        return accessPage;
    }

However, this give an error when search parameter is null

Exception during execution of SpringSecurity application
  java.lang.NullPointerException: null

which caused because of that "null" value set as accessLogPage.

Any ideas?

Body:
The searchParameter should be handled in the controller itself.

Try something like this in your controller

@Controller
public class BaseController {

    @RequestMapping("/")
    public ModelAndView welcome(...) {

        //get your searchParameter here

        if(searchParameter == null) {
            return new ModelAndView("blank-page");
        }

        //call your service layer to fetch the data and then return the actual page

        ModelAndView modelAndView = new ModelAndView("actual-page");
        modelAndView.addObject("data", FETCHED_DATA_FROM_SERVICE_LAYER);
        return new ModelAndView("actual-page");

    }

}


问:
div Img background doesn't work in my CSS
So this is my CSS code:

```<code>#plaatje {
background-image: url('Plaatjes\slider_two_temp.jpg');
width: 100%;
height: 600px;
position: absolute;
top: 0px;
left: 0px;
</code>```

}

And it won't work at all. I placed the picture in the same map as my HTML file.

答:
try this i think

#plaatje {
  background-image:url('http://investorplace.com/wp-content/uploads/2016/02/google-amazon-goog-amzn-stock-300x200.jpg');
}```

https://jsfiddle.net/karanmehta786/rd1yezc2/

Body:
So this is my CSS code:

#plaatje {
background-image: url('Plaatjes\slider_two_temp.jpg');
width: 100%;
height: 600px;
position: absolute;
top: 0px;
left: 0px;

}

And it won't work at all. I placed the picture in the same map as my HTML file.

Body:
try this i think

#plaatje {
  background-image:url('http://investorplace.com/wp-content/uploads/2016/02/google-amazon-goog-amzn-stock-300x200.jpg');
}

https://jsfiddle.net/karanmehta786/rd1yezc2/


问:
What is the alternative for String.format() in GWT?
While GWT is not emulate all java's core, what can be used as alternative for:

```<code>String.format("The answer is - %d", 42)?
</code>```

What is the ellegant and efficient pattern to inject arguments to message in GWT?

答:
why not writing a method like:

```<code>String appendAnswer(int result) {
    return "The answer is - "  + Integer.toString(result);
}
</code>```

is resolving your problem because you do nothing like formatting in your code.

if you ever face the problem like converting integer/byte to Hex String you should use:

```<code>Integer.toString(int, 16);
</code>```

Body:
While GWT is not emulate all java's core, what can be used as alternative for:

String.format("The answer is - %d", 42)?

What is the ellegant and efficient pattern to inject arguments to message in GWT?

Body:
why not writing a method like:

String appendAnswer(int result) {
    return "The answer is - "  + Integer.toString(result);
}

is resolving your problem because you do nothing like formatting in your code.

if you ever face the problem like converting integer/byte to Hex String you should use:

Integer.toString(int, 16);