问:
How to set top bottom and right side content using flexbox css
I am new in flexbox. I have try to set top , bottom and right side content. See Demo

But I need to set in mobile size like image.

Left side and right side is not same height.

Can we set like image mention above or any other type to set in mobile and tablet screen size

.main {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.left {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}

.center {
  background: #ddd;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 50%;
  flex: 0 0 50%;
  max-width: 50%;
}

.right {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="left">
    <ul>
      <li>1 height not fix</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
      Large content
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
  <div class="right">
    <ul>
      <li>1 height not fix</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
</div></code>```

答:
```<code>.main{
      display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
    }
    .left{

      -webkit-box-flex: 0;
        -ms-flex: 0 0 30%;
        flex: 0 0 30%;
        max-width: 30%;
    }
    .center{
      background:#ddd;
        -webkit-box-flex: 0;
        -ms-flex: 0 0 70%;
        flex: 0 0 70%;
        max-width: 70%;
    }

     ul {
       background:#f00;
       margin-top: 0;
       margin-bottom: 20px;
       padding-top: 15px;
       padding-bottom: 15px;
     }
</code>```

```<code><div class="main">
  <div class="left">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>

     <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
    Large content
    </p>
    <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>

</div>
</code>```

Body:
I am new in flexbox. I have try to set top , bottom and right side content. See Demo

But I need to set in mobile size like image.

Left side and right side is not same height.

Can we set like image mention above or any other type to set in mobile and tablet screen size

.main {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.left {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}

.center {
  background: #ddd;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 50%;
  flex: 0 0 50%;
  max-width: 50%;
}

.right {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}

1 height not fix

2

3

      Large content

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.

1 height not fix

2

3

Body:
.main{
      display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
    }
    .left{

      -webkit-box-flex: 0;
        -ms-flex: 0 0 30%;
        flex: 0 0 30%;
        max-width: 30%;
    }
    .center{
      background:#ddd;
        -webkit-box-flex: 0;
        -ms-flex: 0 0 70%;
        flex: 0 0 70%;
        max-width: 70%;
    }

     ul {
       background:#f00;
       margin-top: 0;
       margin-bottom: 20px;
       padding-top: 15px;
       padding-bottom: 15px;
     }

<div class="main">
  <div class="left">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>

     <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
    Large content
    </p>
    <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>

</div>


来源: stackexchange

问:
Rounded Background text like Instagram, ReplacementSpan not working as required
I was trying to do something similar to Instagram below -

But i want this curves like Instagram -

Now i am stuck in one more problem -
When i types,. text does not goes automatically to next line, I have to press return , like normally editText works in fixed width. (In short multiline is not working fine with ReplacementSpan)

Below is sample code for what i have done -

```<code>public class EditextActivity extends AppCompatActivity {

    EditText edittext;
    RoundedBackgroundSpan roundedBackgroundSpan;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editext_screen);
        edittext=(EditText)findViewById(R.id.edittext);
       // edittext.setText("Hello My name is Karandeep Atwal.\n\n Hii this is test");
        roundedBackgroundSpan= new RoundedBackgroundSpan(Color.RED,Color.WHITE);
        edittext.getText().setSpan(roundedBackgroundSpan, 0, edittext.getText().length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }

    public class RoundedBackgroundSpan extends ReplacementSpan implements LineHeightSpan {

        private static final int CORNER_RADIUS = 15;
        private static final int PADDING_X = 10;

        private int   mBackgroundColor;
        private int   mTextColor;

        /**
         * @param backgroundColor background color
         * @param textColor text color
         */
        public RoundedBackgroundSpan(int backgroundColor, int textColor) {
            mBackgroundColor = backgroundColor;
            mTextColor = textColor;
        }

        @Override
        public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
            return (int) (PADDING_X + paint.measureText(text,start, end) + PADDING_X);
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            float width = paint.measureText(text,start, end);
            RectF rect = new RectF(x, top, x + width + 2 * PADDING_X, bottom);
            paint.setColor(mBackgroundColor);
            canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, paint);
            paint.setColor(mTextColor);
            canvas.drawText(text, start, end, x + PADDING_X, y, paint);
        }

        @Override
        public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fontMetricsInt) {

        }
    }

}
</code>```

Below is my xml -

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

    <EditText
        android:padding="5dp"
        android:background="@drawable/border"
        android:id="@+id/edittext"
        android:layout_centerInParent="true"
        android:textColor="@android:color/black"
        android:gravity="center"
        android:hint="hi"
        android:singleLine="false"
        android:inputType="textMultiLine"
        android:textSize="30sp"
        android:maxWidth="100dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
</code>```

Below is what i am getting when i type using setSpan -

This is normal behaviour for fixed width, that i want -

答:
Enhancing BackgroundColorSpan by @tttzof351 to support alignment:

```<code>import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.text.style.LineBackgroundSpan
import kotlin.math.abs
import kotlin.math.sign

class BackgroundColorSpan(backgroundColor: Int,
                          private val padding: Int,
                          private val radius: Int) : LineBackgroundSpan {
    private val rect = RectF()
    private val paint = Paint()
    private val paintStroke = Paint()
    private val path = Path()
    private var prevWidth = -1f
    private var prevLeft = -1f
    private var prevRight = -1f
    private var prevBottom = -1f
    private var prevTop = -1f

    private val ALIGN_CENTER = 0
    private val ALIGN_START = 1
    private val ALIGN_END = 2

    init {
        paint.color = backgroundColor
        paintStroke.color = backgroundColor
    }

    private var align = ALIGN_CENTER

    fun setAlignment(alignment: Int) {
        align = alignment
    }

    override fun drawBackground(
            c: Canvas,
            p: Paint,
            left: Int,
            right: Int,
            top: Int,
            baseline: Int,
            bottom: Int,
            text: CharSequence,
            start: Int,
            end: Int,
            lnum: Int) {

        val width = p.measureText(text, start, end) + 2f * padding
        val shiftLeft: Float
        val shiftRight: Float

        when (align) {
            ALIGN_START -> {
                shiftLeft = 0f - padding
                shiftRight = width + shiftLeft
            }

            ALIGN_END -> {
                shiftLeft = right - width + padding
                shiftRight = (right + padding).toFloat()
            }
            else -> {
                shiftLeft = (right - width) / 2
                shiftRight = right - shiftLeft
            }
        }

        rect.set(shiftLeft, top.toFloat(), shiftRight, bottom.toFloat())

        if (lnum == 0) {
            c.drawRoundRect(rect, radius.toFloat(), radius.toFloat(), paint)
        } else {
            path.reset()
            val difference = width - prevWidth
            val diff = -sign(difference) * (2f * radius).coerceAtMost(abs(difference / 2f)) / 2f
            path.moveTo(
                    prevLeft, prevBottom - radius
            )

            if (align != ALIGN_START) {
                path.cubicTo(//1
                        prevLeft, prevBottom - radius,
                        prevLeft, rect.top,
                        prevLeft + diff, rect.top
                )
            } else {
                path.lineTo(prevLeft, prevBottom + radius)
            }
            path.lineTo(
                    rect.left - diff, rect.top
            )
            path.cubicTo(//2
                    rect.left - diff, rect.top,
                    rect.left, rect.top,
                    rect.left, rect.top + radius
            )
            path.lineTo(
                    rect.left, rect.bottom - radius
            )
            path.cubicTo(//3
                    rect.left, rect.bottom - radius,
                    rect.left, rect.bottom,
                    rect.left + radius, rect.bottom
            )
            path.lineTo(
                    rect.right - radius, rect.bottom
            )
            path.cubicTo(//4
                    rect.right - radius, rect.bottom,
                    rect.right, rect.bottom,
                    rect.right, rect.bottom - radius
            )
            path.lineTo(
                    rect.right, rect.top + radius
            )

            if (align != ALIGN_END) {
                path.cubicTo(//5
                        rect.right, rect.top + radius,
                        rect.right, rect.top,
                        rect.right + diff, rect.top
                )
                path.lineTo(
                        prevRight - diff, rect.top
                )
                path.cubicTo(//6
                        prevRight - diff, rect.top,
                        prevRight, rect.top,
                        prevRight, prevBottom - radius
                )

            } else {
                path.lineTo(prevRight, prevBottom - radius)
            }
            path.cubicTo(//7
                    prevRight, prevBottom - radius,
                    prevRight, prevBottom,
                    prevRight - radius, prevBottom
            )

            path.lineTo(
                    prevLeft + radius, prevBottom
            )

            path.cubicTo(//8
                    prevLeft + radius, prevBottom,
                    prevLeft, prevBottom,
                    prevLeft, rect.top - radius
            )
            c.drawPath(path, paintStroke)

        }
        prevWidth = width
        prevLeft = rect.left
        prevRight = rect.right
        prevBottom = rect.bottom
        prevTop = rect.top
    }
}
</code>```

Results:

ContentLicense: CC BY-SA 3.0

Body:
I was trying to do something similar to Instagram below -

But i want this curves like Instagram -

Now i am stuck in one more problem -
When i types,. text does not goes automatically to next line, I have to press return , like normally editText works in fixed width. (In short multiline is not working fine with ReplacementSpan)

Below is sample code for what i have done -

public class EditextActivity extends AppCompatActivity {

    EditText edittext;
    RoundedBackgroundSpan roundedBackgroundSpan;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editext_screen);
        edittext=(EditText)findViewById(R.id.edittext);
       // edittext.setText("Hello My name is Karandeep Atwal.\n\n Hii this is test");
        roundedBackgroundSpan= new RoundedBackgroundSpan(Color.RED,Color.WHITE);
        edittext.getText().setSpan(roundedBackgroundSpan, 0, edittext.getText().length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }

    public class RoundedBackgroundSpan extends ReplacementSpan implements LineHeightSpan {

        private static final int CORNER_RADIUS = 15;
        private static final int PADDING_X = 10;

        private int   mBackgroundColor;
        private int   mTextColor;

        /**
         * @param backgroundColor background color
         * @param textColor text color
         */
        public RoundedBackgroundSpan(int backgroundColor, int textColor) {
            mBackgroundColor = backgroundColor;
            mTextColor = textColor;
        }

        @Override
        public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
            return (int) (PADDING_X + paint.measureText(text,start, end) + PADDING_X);
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            float width = paint.measureText(text,start, end);
            RectF rect = new RectF(x, top, x + width + 2 * PADDING_X, bottom);
            paint.setColor(mBackgroundColor);
            canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, paint);
            paint.setColor(mTextColor);
            canvas.drawText(text, start, end, x + PADDING_X, y, paint);
        }

        @Override
        public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fontMetricsInt) {

        }
    }

}

Below is my xml -

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

    <EditText
        android:padding="5dp"
        android:background="@drawable/border"
        android:id="@+id/edittext"
        android:layout_centerInParent="true"
        android:textColor="@android:color/black"
        android:gravity="center"
        android:hint="hi"
        android:singleLine="false"
        android:inputType="textMultiLine"
        android:textSize="30sp"
        android:maxWidth="100dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

Below is what i am getting when i type using setSpan -

This is normal behaviour for fixed width, that i want -

Body:
Enhancing BackgroundColorSpan by @tttzof351 to support alignment:

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.text.style.LineBackgroundSpan
import kotlin.math.abs
import kotlin.math.sign

class BackgroundColorSpan(backgroundColor: Int,
                          private val padding: Int,
                          private val radius: Int) : LineBackgroundSpan {
    private val rect = RectF()
    private val paint = Paint()
    private val paintStroke = Paint()
    private val path = Path()
    private var prevWidth = -1f
    private var prevLeft = -1f
    private var prevRight = -1f
    private var prevBottom = -1f
    private var prevTop = -1f

    private val ALIGN_CENTER = 0
    private val ALIGN_START = 1
    private val ALIGN_END = 2

    init {
        paint.color = backgroundColor
        paintStroke.color = backgroundColor
    }

    private var align = ALIGN_CENTER

    fun setAlignment(alignment: Int) {
        align = alignment
    }

    override fun drawBackground(
            c: Canvas,
            p: Paint,
            left: Int,
            right: Int,
            top: Int,
            baseline: Int,
            bottom: Int,
            text: CharSequence,
            start: Int,
            end: Int,
            lnum: Int) {

        val width = p.measureText(text, start, end) + 2f * padding
        val shiftLeft: Float
        val shiftRight: Float

        when (align) {
            ALIGN_START -> {
                shiftLeft = 0f - padding
                shiftRight = width + shiftLeft
            }

            ALIGN_END -> {
                shiftLeft = right - width + padding
                shiftRight = (right + padding).toFloat()
            }
            else -> {
                shiftLeft = (right - width) / 2
                shiftRight = right - shiftLeft
            }
        }

        rect.set(shiftLeft, top.toFloat(), shiftRight, bottom.toFloat())

        if (lnum == 0) {
            c.drawRoundRect(rect, radius.toFloat(), radius.toFloat(), paint)
        } else {
            path.reset()
            val difference = width - prevWidth
            val diff = -sign(difference) * (2f * radius).coerceAtMost(abs(difference / 2f)) / 2f
            path.moveTo(
                    prevLeft, prevBottom - radius
            )

            if (align != ALIGN_START) {
                path.cubicTo(//1
                        prevLeft, prevBottom - radius,
                        prevLeft, rect.top,
                        prevLeft + diff, rect.top
                )
            } else {
                path.lineTo(prevLeft, prevBottom + radius)
            }
            path.lineTo(
                    rect.left - diff, rect.top
            )
            path.cubicTo(//2
                    rect.left - diff, rect.top,
                    rect.left, rect.top,
                    rect.left, rect.top + radius
            )
            path.lineTo(
                    rect.left, rect.bottom - radius
            )
            path.cubicTo(//3
                    rect.left, rect.bottom - radius,
                    rect.left, rect.bottom,
                    rect.left + radius, rect.bottom
            )
            path.lineTo(
                    rect.right - radius, rect.bottom
            )
            path.cubicTo(//4
                    rect.right - radius, rect.bottom,
                    rect.right, rect.bottom,
                    rect.right, rect.bottom - radius
            )
            path.lineTo(
                    rect.right, rect.top + radius
            )

            if (align != ALIGN_END) {
                path.cubicTo(//5
                        rect.right, rect.top + radius,
                        rect.right, rect.top,
                        rect.right + diff, rect.top
                )
                path.lineTo(
                        prevRight - diff, rect.top
                )
                path.cubicTo(//6
                        prevRight - diff, rect.top,
                        prevRight, rect.top,
                        prevRight, prevBottom - radius
                )

            } else {
                path.lineTo(prevRight, prevBottom - radius)
            }
            path.cubicTo(//7
                    prevRight, prevBottom - radius,
                    prevRight, prevBottom,
                    prevRight - radius, prevBottom
            )

            path.lineTo(
                    prevLeft + radius, prevBottom
            )

            path.cubicTo(//8
                    prevLeft + radius, prevBottom,
                    prevLeft, prevBottom,
                    prevLeft, rect.top - radius
            )
            c.drawPath(path, paintStroke)

        }
        prevWidth = width
        prevLeft = rect.left
        prevRight = rect.right
        prevBottom = rect.bottom
        prevTop = rect.top
    }
}

Results:

ContentLicense: CC BY-SA 4.0


问:
How to display circle avatar on AppBar?
I am trying to display Circle Avatar on AppBar.

Here is my code

```<code>AppBar(
    ...
    actions: <Widget>[
        CircleAvatar(
            radius: 14,
            backgroundImage: userProfilePictureValue != null
                ? NetworkImage(
                    userProfilePictureValue,
                )
                : Icon(Icons.add),
        )
)
</code>```

Here is the second way which I tried

```<code>AppBar(
    ...
    actions: <Widget>[
        Container(
            width: 20,
            height: 20,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color:Colors.blueGrey
            ),
            child: StreamBuilder<String>(
                stream: userProfilePicture,
                builder: (context, snapshot) {
                    return ClipOval(
                        child: userProfilePictureValue != null
                            ? CachedNetworkImage(
                                imageUrl:
                                    "${userProfilePictureValue}",
                                fit: BoxFit.fill,
                             )
                            : Icon(
                                Icons.person,
                                size: 40,
                                color: Colors.white,
                            ),
                    );
            }),
    )]
)
</code>```

In first case the image is not displayed as circular and in second case it is displayed as egg shaped instead of circular.

答:
You can wrap it in a FlatButton like

FlatButton(
  child: CircleAvatar(
    backgroundImage: AssetImage("your_image"),
  ),
)
```

Title: How to display circle avatar on AppBar?

Body:
I am trying to display Circle Avatar on AppBar.

Here is my code

AppBar(
    ...
    actions: <Widget>[
        CircleAvatar(
            radius: 14,
            backgroundImage: userProfilePictureValue != null
                ? NetworkImage(
                    userProfilePictureValue,
                )
                : Icon(Icons.add),
        )
)

Here is the second way which I tried

AppBar(
    ...
    actions: <Widget>[
        Container(
            width: 20,
            height: 20,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color:Colors.blueGrey
            ),
            child: StreamBuilder<String>(
                stream: userProfilePicture,
                builder: (context, snapshot) {
                    return ClipOval(
                        child: userProfilePictureValue != null
                            ? CachedNetworkImage(
                                imageUrl:
                                    "${userProfilePictureValue}",
                                fit: BoxFit.fill,
                             )
                            : Icon(
                                Icons.person,
                                size: 40,
                                color: Colors.white,
                            ),
                    );
            }),
    )]
)

In first case the image is not displayed as circular and in second case it is displayed as egg shaped instead of circular.


问:
How to find rows in SQL DB with a definite word length?
Good day, I've got a column with text in my table, but i need to export words 17 letters long only in it.

I tried to use

```<code>where description like '%_%_%_%_%_%_%_%_%_%_%_%_%_%_%'
</code>```

but my query newer  completes.

This is an example of text cell

REIGHT CAR DUMP T.M. "HOWO", COMMERCIAL NAME A7, MODEL TOTAL 4 PIECES,
  WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3) VIN: LZZ5DYSD5KA545780;
  CHASSIS NUMBER LZZ5DYSD5KA545780; ENGINE NUMBER 191007018247;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4) VIN: LZZ5DYSD2KA545784;
  CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137;
  TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE
  –

I am using Microsoft SQL management studio

答: Can you write a function that returns the entire string, then splits the string using the space character? Then you could search the split array for strings where the previous string is VIN: and the next string is numeric and 17 long (don't forget to remove the possible ; from the right side of the string before you call your length function).</p>

Body:
Good day, I've got a column with text in my table, but i need to export words 17 letters long only in it.

I tried to use

where description like '%_%_%_%_%_%_%_%_%_%_%_%_%_%_%'

but my query newer  completes.

This is an example of text cell

REIGHT CAR DUMP T.M. "HOWO", COMMERCIAL NAME A7, MODEL TOTAL 4 PIECES,
  WITHOUT PACKING IDENTIFICATION NUMBER ENGINE NUMBER 191007018177;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 3) VIN: LZZ5DYSD5KA545780;
  CHASSIS NUMBER LZZ5DYSD5KA545780; ENGINE NUMBER 191007018247;
  TRANSMISSION NUMBER NO; NO BRIDGE NUMBERS 4) VIN: LZZ5DYSD2KA545784;
  CHASSIS NUMBER LZZ5DYSD2KA545784; ENGINE NUMBER 191007018137;
  TRANSMISSION NUMBER NO; BRIDGE ROOMS ARE NOT AVAILABLE FREIGHT VEHICLE
  –

I am using Microsoft SQL management studio


问:
Loop through all the resources in a .resx file
Is there a way to loop through all the resources in a .resx file in C#?

答:
Simple read loop use this code</p>

```<code>var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);

foreach (DictionaryEntry dictionaryEntry in resx)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key);
    Console.WriteLine("Val: " + dictionaryEntry.Value);
}
</code>```

Body:
Simple read loop use this code

var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);

foreach (DictionaryEntry dictionaryEntry in resx)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key);
    Console.WriteLine("Val: " + dictionaryEntry.Value);
}


问:
SpannableString#setSpan set wrong text range
I use following code, it wrap wrong text range to bold

```<code>    final StyleSpan span = new StyleSpan(BOLD);
    SpannableString ss = new SpannableString("line 1\nline 2");
    Log.d(getPackageName(), String.valueOf(ss.charAt(12)));
    ss.setSpan(span, 7, 12, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    ((TextView) findViewById(R.id.text)).setText(ss);
</code>```

the result is like following:

I'm confused ss.charAt(12) return '2', but setSpan, when i setSpan with end "12", span doesn't include "2"

答:
I find setSpan(span, start, end, flag), "start" is first char index, and "end" is "last char index + 1", I don't know it's bug or expected

```<code>    final ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
    SpannableString ss = new SpannableString("line 1\nline 2");
    Log.d(getPackageName(), String.valueOf(ss.charAt(12)));
    ss.setSpan(span, 0, 13, 0);
    ((TextView) findViewById(R.id.text)).setText(ss);
</code>```

I guess setSpan use String#substring:

```<code> * @param      beginIndex   the beginning index, inclusive.
 * @param      endIndex     the ending index, exclusive.
 * @return     the specified substring.
 * @exception  IndexOutOfBoundsException  if the
 *             {@code beginIndex} is negative, or
 *             {@code endIndex} is larger than the length of
 *             this {@code String} object, or
 *             {@code beginIndex} is larger than
 *             {@code endIndex}.
 */
public String substring(int beginIndex, int endIndex) {
</code>```

Body:
I use following code, it wrap wrong text range to bold

    final StyleSpan span = new StyleSpan(BOLD);
    SpannableString ss = new SpannableString("line 1\nline 2");
    Log.d(getPackageName(), String.valueOf(ss.charAt(12)));
    ss.setSpan(span, 7, 12, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    ((TextView) findViewById(R.id.text)).setText(ss);

the result is like following:

I'm confused ss.charAt(12) return '2', but setSpan, when i setSpan with end "12", span doesn't include "2"

Body:
I find setSpan(span, start, end, flag), "start" is first char index, and "end" is "last char index + 1", I don't know it's bug or expected

    final ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
    SpannableString ss = new SpannableString("line 1\nline 2");
    Log.d(getPackageName(), String.valueOf(ss.charAt(12)));
    ss.setSpan(span, 0, 13, 0);
    ((TextView) findViewById(R.id.text)).setText(ss);

I guess setSpan use String#substring:

 * @param      beginIndex   the beginning index, inclusive.
 * @param      endIndex     the ending index, exclusive.
 * @return     the specified substring.
 * @exception  IndexOutOfBoundsException  if the
 *             {@code beginIndex} is negative, or
 *             {@code endIndex} is larger than the length of
 *             this {@code String} object, or
 *             {@code beginIndex} is larger than
 *             {@code endIndex}.
 */
public String substring(int beginIndex, int endIndex) {


问:
Change the value of a field in one table based off the value of field in a different table in Access using VBA
I am creating a side along inventory system using Access.

I created a transaction table that adds and removes Kits at the point of a deployment. I have another table that has detail information of those kit.

I am trying to update a status field in the details tables when the status of a kit changes in the transaction table.

This is what I have

```<code>Option Compare Database

Private Sub Command48_Click()
    If Me.KIT_ITEM_Card_Number.Value = [TEST2]![Kit Item Card Number] Then
        [TEST2]![Status] = "Removed"
    End If
End Sub
</code>```

答:
Run an update query:

Private Sub Command48_Click()

    Dim Sql As String

    ' Use one of these:
    ' If value is a number.
    Sql = "Update [TEST2] Set [Status] = 'Removed' Where [Kit Item Card Number] = " & Me!KIT_ITEM_Card_Number.Value & ""
    ' If value is a text.
    Sql = "Update [TEST2] Set [Status] = 'Removed' Where [Kit Item Card Number] = '" & Me!KIT_ITEM_Card_Number.Value & "'"

    CurrentDb.Execute Sql

End Sub
```

And do rename your buttons to something meaningful.

Body:
I am creating a side along inventory system using Access.

I created a transaction table that adds and removes Kits at the point of a deployment. I have another table that has detail information of those kit.

I am trying to update a status field in the details tables when the status of a kit changes in the transaction table.

This is what I have

Option Compare Database

Private Sub Command48_Click()
    If Me.KIT_ITEM_Card_Number.Value = [TEST2]![Kit Item Card Number] Then
        [TEST2]![Status] = "Removed"
    End If
End Sub

Body:
Run an update query:

Private Sub Command48_Click()

    Dim Sql As String

    ' Use one of these:
    ' If value is a number.
    Sql = "Update [TEST2] Set [Status] = 'Removed' Where [Kit Item Card Number] = " & Me!KIT_ITEM_Card_Number.Value & ""
    ' If value is a text.
    Sql = "Update [TEST2] Set [Status] = 'Removed' Where [Kit Item Card Number] = '" & Me!KIT_ITEM_Card_Number.Value & "'"

    CurrentDb.Execute Sql

End Sub

And do rename your buttons to something meaningful.


问:
INSERT INTO .. ON DUPLICATE KEY UPDATE for multiple items
I want to do something like this

```<code>INSERT INTO t (t.a, t.b, t.c)
VALUES ('key1','key2','value')
ON DUPLICATE KEY UPDATE
t.c = 'value';
INSERT INTO t (t.a, t.b, t.c)
VALUES ('key1','key3','value2')
ON DUPLICATE KEY UPDATE
t.c = 'value2';
</code>```

t.a and t.b are keys. This all works fine but i get an error on the second insert. With phpMyAdmin a query like this works fine but i'm guessing it's running the queries independently as it prints out the results from that query as comments?

Something like this would be good too but i will need to have different values for each item. I prefer this but i'm not sure how i can change the value on the update for each value.

```<code>INSERT INTO t (t.a, t.b, t.c)
VALUES ('key1','key2','value'), ('key1','key3','value2')
ON DUPLICATE KEY UPDATE
t.c = ???
</code>```

The problem is in the question marks, what should i put there so that each insert/update will have the correct value? Obviously if i put a value there all the fields will get that value.

If there is another way of doing an "update if exists, otherwise insert" query on multiple fields with two keys, i'm up for other ideas too. I guess i could run each query separately (like phpMyAdmin?) but it's going to be a lot of queries so i really want to avoid that.

答:
After MySQL 8.0.19, you can use as keyword, for example:

INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new
  ON DUPLICATE KEY UPDATE c = new.a+new.b;
```

<p>or</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new(m,n,p)
  ON DUPLICATE KEY UPDATE c = m+n;
</code>```

ref: https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

OwnerDisplayName: Antti

ContentLicense: CC BY-SA 2.5

Body:
I want to do something like this

INSERT INTO t (t.a, t.b, t.c)
VALUES ('key1','key2','value')
ON DUPLICATE KEY UPDATE
t.c = 'value';
INSERT INTO t (t.a, t.b, t.c)
VALUES ('key1','key3','value2')
ON DUPLICATE KEY UPDATE
t.c = 'value2';

t.a and t.b are keys. This all works fine but i get an error on the second insert. With phpMyAdmin a query like this works fine but i'm guessing it's running the queries independently as it prints out the results from that query as comments?

Something like this would be good too but i will need to have different values for each item. I prefer this but i'm not sure how i can change the value on the update for each value.

INSERT INTO t (t.a, t.b, t.c)
VALUES ('key1','key2','value'), ('key1','key3','value2')
ON DUPLICATE KEY UPDATE
t.c = ???

The problem is in the question marks, what should i put there so that each insert/update will have the correct value? Obviously if i put a value there all the fields will get that value.

If there is another way of doing an "update if exists, otherwise insert" query on multiple fields with two keys, i'm up for other ideas too. I guess i could run each query separately (like phpMyAdmin?) but it's going to be a lot of queries so i really want to avoid that.

Body:
After MySQL 8.0.19, you can use as keyword, for example:

INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new
  ON DUPLICATE KEY UPDATE c = new.a+new.b;

or

INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new(m,n,p)
  ON DUPLICATE KEY UPDATE c = m+n;

ref: https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html


问:
Extend angular service worker (ngsw-worker.js)
I want to extend native service worker for angular pwa.
Task:
change all base fetched urls (called origin in sw)
It needs for mirrors - on url for all mirrors in sw.
I have tried to register custom sw via copy ngsw-worker.js and extend it,
but it broke config and updating mechanism for sw (because i have to disable default serviceworker flag in angular.json for exclude default ngsw-worker.js file usage).</p>

答:
ServiceWorkerModule.register('custom-ngsw.js', {enabled: true, registrationStrategy: 'registerImmediately'})

just pass another file and copy whole code from sw.
also files can be merged via importScripts('some.js');


问:
in react native want to get Home Page data according with respect to logged in email
In my project i logged in with email password, after that want to get Home Page data according with respect to logged in email, The API will return the response data for that specific user, in useState() i have passed static email, which i need to change dynamic
Home Page code :

```<code>```import React,{useState} from 'react';
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
 const [email]= useState('test@xyz.com')
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen;```
</code>```

答:
Just do small changes.

Pass email from the login screen to the home screen like below example;

```<code> this.props.navigation.navigate('Home',{email: "You Email Id using"});
</code>```

And no need to show any default email. Just do something like this

```<code>import React,{useState} from 'react';
import _ from 'lodash'; // use can you any other if you like instead of lodash
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
// Retrive email from props. `_.get` method only check if data not available the // set `undefined`.
 const [email]= useState(_.get(props.navigation, 'state.params.email'));
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen
</code>```

Body:
In my project i logged in with email password, after that want to get Home Page data according with respect to logged in email, The API will return the response data for that specific user, in useState() i have passed static email, which i need to change dynamic
Home Page code :

```import React,{useState} from 'react';
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
 const [email]= useState('test@xyz.com')
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen;```

Body:
Just do small changes.

Pass email from the login screen to the home screen like below example;

 this.props.navigation.navigate('Home',{email: "You Email Id using"});

And no need to show any default email. Just do something like this

import React,{useState} from 'react';
import _ from 'lodash'; // use can you any other if you like instead of lodash
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
// Retrive email from props. `_.get` method only check if data not available the // set `undefined`.
 const [email]= useState(_.get(props.navigation, 'state.params.email'));
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen


问:
Why doesn't PHP auto html decode my POST?
I'm using Zend Framework for a project. Why when I make POST request and get the params in my controller by $this->_request->getParams() it shows undecoded values? For example a string like Speakers & keyboards in my HTML form is retrieved as Speakers & keyboards from getParams() within PHP.

Doesn't PHP autodecode every posted value?

答: PHP autodecodes the escaped content, not content which is in HTML entities.</p>


问:
Django app on Heroku: Issues with continuous development AFTER deployment
So, I just updated my Django app for Heroku and GIT pushed my master branch to production for the first time. Works well. However, when I try to run my app locally on the same master branch, I get all these errors. Understandably, since I've updated the settings file specifically for production on Heroku.

My question is the following:

If I want to continue my development locally and periodically push stable versions to production, do I need to maintain 2 settings.py files? (ie, one for dev and one for prod)

I'm a beginner, so sorry if this question sounds ridiculous, but I can't seem to find any clear information about this, after reading Heroku's documentation about deployment: https://devcenter.heroku.com/articles/git

I just want to be able to continue running my development locally.

Any suggestions would be greatly appreciated.

答:
I guess the biggest issue between the development and production environments is difference in databases they use. So use environment variables for both development and production modes.

Create an .env file at project root

```<code>SECRET_KEY='somesupersecretivesecretkey'
DEBUG=True #set to false while pushing to Heroku, leave at True while working in development
DB_NAME='dbname'
DB_USER='dbuser'
DB_PASSWORD='dbpassword'
DB_HOST='127.0.0.1'
MODE='dev' #set to 'prod' in production
ALLOWED_HOSTS='.localhost', '.herokuapp.com', '.127.0.0.1'
DISABLE_COLLECTSTATIC=1
</code>```

In your project settings (you only need one), check which mode you are in (production or development) and choose which database to use (the one installed in Heroku or the one on your machine). Assuming you are using Postgres, something like this:

import os
import django_heroku
import dj_database_url
from decouple import config,Csv

MODE=config("MODE", default="dev")
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
# development
if config('MODE')=="dev":
   DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.postgresql_psycopg2',
           'NAME': config('DB_NAME'),
           'USER': config('DB_USER'),
           'PASSWORD': config('DB_PASSWORD'),
           'HOST': config('DB_HOST'),
           'PORT': '',
       }

   }
# production
else:
   DATABASES = {
       'default': dj_database_url.config(
           default=config('DATABASE_URL')
       )
   }

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
```

Before pushing your code to Heroku, after changing the .env variable appropriately, run heroku config:set $(cat .env | sed '/^$/d; /#[[:print:]]*$/d') to enforce the database changes in heroku's dashboard... Hope it helps

Body:
I guess the biggest issue between the development and production environments is difference in databases they use. So use environment variables for both development and production modes.

Create an .env file at project root

SECRET_KEY='somesupersecretivesecretkey'
DEBUG=True #set to false while pushing to Heroku, leave at True while working in development
DB_NAME='dbname'
DB_USER='dbuser'
DB_PASSWORD='dbpassword'
DB_HOST='127.0.0.1'
MODE='dev' #set to 'prod' in production
ALLOWED_HOSTS='.localhost', '.herokuapp.com', '.127.0.0.1'
DISABLE_COLLECTSTATIC=1

In your project settings (you only need one), check which mode you are in (production or development) and choose which database to use (the one installed in Heroku or the one on your machine). Assuming you are using Postgres, something like this:

import os
import django_heroku
import dj_database_url
from decouple import config,Csv

MODE=config("MODE", default="dev")
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
# development
if config('MODE')=="dev":
   DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.postgresql_psycopg2',
           'NAME': config('DB_NAME'),
           'USER': config('DB_USER'),
           'PASSWORD': config('DB_PASSWORD'),
           'HOST': config('DB_HOST'),
           'PORT': '',
       }

   }
# production
else:
   DATABASES = {
       'default': dj_database_url.config(
           default=config('DATABASE_URL')
       )
   }

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())

Before pushing your code to Heroku, after changing the .env variable appropriately, run heroku config:set $(cat .env | sed '/^$/d; /#[[:print:]]*$/d') to enforce the database changes in heroku's dashboard... Hope it helps


问:
Access constructor's properties inside constructor
I have the following constructor function.

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: function(r, c, r2, c2) {
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}
```

I need to access and modify the property tablo_nesne within the afterSelectionEnd function. However, the this keyword points to the wrong context. How do I fix this issue?

答:
you can bind this to tablo_getir to access this at Tablo by calling bind(this) on tablo_getir

or declare a self = this
at your Tablo
and use it at your tablo_getir

or you can make your tablo_getir as an arrow function it should bind this automatically

Body:
I have the following constructor function.

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: function(r, c, r2, c2) {
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}

I need to access and modify the property tablo_nesne within the afterSelectionEnd function. However, the this keyword points to the wrong context. How do I fix this issue?


问:
Visual Basic Compiler (vbc.exe) Using-up All System Memory (RAM & Virtual)
I have an asp.net web application using VB in Visual Studio 2019. The project builds compiles and runs fine. We publish the files and drop them in the www root folder, works great.

We have one aspx file that started to get really big. It's over 5,000 lines now, 423kb.
This would work when hitting the aspx compiled, but would choke the roselyn compiler when accessing the published aspx.

BC31498: Length of String constant exceeds current memory limit. Try splitting the string into multiple constants.

We removed the rosyln compiler from the bin, and the reference in the web.config. This caused .NET to use C:\Windows\Microsoft.NET\Framework64\v4.0.30319\vbc.exe to compile it, we would get a slow down and it would then work, and the server would come back up. It had to build and cache the files I assume.

ANYWAY, the page is bigger now, and the published page will not load. We get the following error.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\vbc.exe failed with the following error.

Server Error in '/' Application.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: The compiler failed with error code -2147023441.

Show Detailed Compiler Output:

c:\windows\system32\inetsrv> "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\vbc.exe" /t:library /utf8output......

Can you not have large aspx files? Too many div tags?
I cleared the temp folder in the .net framework folder. There is no .NET version mismatch. Published code also works fine on a non production machine with MUCH more RAM(48GB).

Please help, thank you.

答: You are running into this issue in roslyn. The native compiler (the one coming from C:\Windows\Microsoft.NET\Framework64\v4.0.30319) can handle slightly larger strings, but the issue is the same. The string literal that you are using is too big for the compiler to compile. My recommendation to you is to use resource files (.resx) instead of string literals. This should allow your page to be any size.</p>


问:
Extract only numbers and only string from pandas dataframe
I am trying to extract only numbers and only strings in two different dataframes. I am using regular expression to extract numbers and string.

```<code>import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)
</code>```

I have also tried using '([\d+][\d+\.\d+])' and '([\d+\.\d+])'

Here I am getting output but not what I am expecting. Though I am expecting float numbers I am not getting 1.5 or 2.5.

I am getting something like below image:

```<code>df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)
</code>```

In this case when the number is at the end or in the beginning then I am getting the string but if the number placed in the middle or any other place then the result which I expect I am not getting.
Current output is like below image:

I think my regular expression is not correct. Which will be the right regular expression to solve these problems? Or is there any other way to extract only numbers and only strings in pandas dataframe?

答:
You may take advantage of built-in str methods isnumeric() or isalpha() instead of regular expressions. See below:

```<code># get rid of letters and handle floating points
>>> "".join([c for c in "word234with23numbers" if c.isnumeric() or c == "."])
"23423"

>>> "".join([c for c in "gelb3.5" if c.isnumeric() or c == "."])
"3.5"

# get rid of numbers
>>> "".join([c for c in "word234with23numbers" if c.isalpha()])
"wordwithnumbers"
</code>```

Body:
I am trying to extract only numbers and only strings in two different dataframes. I am using regular expression to extract numbers and string.

import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)

I have also tried using '([\d+][\d+\.\d+])' and '([\d+\.\d+])'

Here I am getting output but not what I am expecting. Though I am expecting float numbers I am not getting 1.5 or 2.5.

I am getting something like below image:

df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)

In this case when the number is at the end or in the beginning then I am getting the string but if the number placed in the middle or any other place then the result which I expect I am not getting.
Current output is like below image:

I think my regular expression is not correct. Which will be the right regular expression to solve these problems? Or is there any other way to extract only numbers and only strings in pandas dataframe?

Body:
You may take advantage of built-in str methods isnumeric() or isalpha() instead of regular expressions. See below:

# get rid of letters and handle floating points
>>> "".join([c for c in "word234with23numbers" if c.isnumeric() or c == "."])
"23423"

>>> "".join([c for c in "gelb3.5" if c.isnumeric() or c == "."])
"3.5"

# get rid of numbers
>>> "".join([c for c in "word234with23numbers" if c.isalpha()])
"wordwithnumbers"


问:
Database connection failed for local MSSQL server with pymssql
I had been working with pyodbcfor database connection in windows envirnment and it is working fine but now I want to switch to pymssql so that it is easier to be deployed to Linux machine as well. But I am getting this error:

(20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (localhost:1433)\nNet-Lib error during Unknown error (10060)\n')

My connection code for using both pyodbc and pymssql is:

```
    import pyodbc
    import pymssql

    def connectODSDB_1():
        conn_str = (
            r"Driver={SQL Server};"
            r"Server=(local);"
            r"Database=populatedSandbox;"
            r"Trusted_Connection=yes;"
        )
        return pyodbc.connect(conn_str)

    def connectODSDB_2():
        server = '(local)'
        database = 'populatedSandbox'
        conn = pymssql.connect(server=server, database=database)
        return conn

```

What could be the problem? And solution?

答:
I have faced the same issue while using RDS(AWS database instance). We should configured the inbound outbound rules.
  Do following steps to configure.

```<code>Services->RDS->DB Instances -> Select DB-> Connectivity&Security
</code>```

Under Security Section

```<code>VPC security groups -> click on security group
</code>```

Change the inbound rules.

```<code>Check the source IP and change into anywhere or specific IP
</code>```

Body:
I had been working with pyodbcfor database connection in windows envirnment and it is working fine but now I want to switch to pymssql so that it is easier to be deployed to Linux machine as well. But I am getting this error:

(20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (localhost:1433)\nNet-Lib error during Unknown error (10060)\n')

My connection code for using both pyodbc and pymssql is:

    import pyodbc
    import pymssql

    def connectODSDB_1():
        conn_str = (
            r"Driver={SQL Server};"
            r"Server=(local);"
            r"Database=populatedSandbox;"
            r"Trusted_Connection=yes;"
        )
        return pyodbc.connect(conn_str)

    def connectODSDB_2():
        server = '(local)'
        database = 'populatedSandbox'
        conn = pymssql.connect(server=server, database=database)
        return conn

What could be the problem? And solution?

Body:
I have faced the same issue while using RDS(AWS database instance). We should configured the inbound outbound rules.
  Do following steps to configure.

Services->RDS->DB Instances -> Select DB-> Connectivity&Security

Under Security Section

VPC security groups -> click on security group

Change the inbound rules.

Check the source IP and change into anywhere or specific IP


问:
android - kotlin - mvvm - posting data to webservice
I want to post some data to webservice and get the result . this is my code :

```<code>fab.setOnClickListener {
 viewModel.newBimeGozar(name)
                    .observe(this@BimeGozarAct, Observer {
                        dialogbimegozarNew?.hidePg()
                    })
}
</code>```

this is my viewmodel :

```<code>class BimeNewViewModel:ViewModel() {
private val repository=BimeNewRepository()

fun newBimeGozar(name: String): MutableLiveData<StatModel> {
    return repository.newBimeGozar(name)
}
</code>```

this is my repository :

```<code>fun newBimeShode(
    name: String
): MutableLiveData<StatModel> {
    scope.launch {
        val request = api.newBimeShode(name)
        withContext(Dispatchers.Main) {
            try {
                val response = request.await()
                regBimeshodeLiveData.value = response
            } catch (e: HttpException) {
                Log.v("this", e.message);
            } catch (e: Throwable) {
                Log.v("this", e.message);
            }
        }
    }
    return regBimeshodeLiveData;
}
</code>```

it works fine but there is a problem . I think the observer keeps running and if the result's answer is an error and user press fab button again , it creates a new observer and after this , it returns two value , the first value is the first run and the second value is the second run

how can I fix this ? what is the correct way for  submitting forms ?

答:
If your problem is because of LiveData, you should use SingleLiveEvent like as follow

```<code>// For first article
val _liveData = MutableLiveData<Event<StatModel>>()

// For second article
val _liveData = SingleLiveEvent<StatModel>()
</code>```

If you do not know SingleLiveEvent, you can find it here and here.

If your problem is because of your ui element, I think the best solution is to disable the submit button after submitting for the first time.

Body:
I want to post some data to webservice and get the result . this is my code :

fab.setOnClickListener {
 viewModel.newBimeGozar(name)
                    .observe(this@BimeGozarAct, Observer {
                        dialogbimegozarNew?.hidePg()
                    })
}

this is my viewmodel :

class BimeNewViewModel:ViewModel() {
private val repository=BimeNewRepository()

fun newBimeGozar(name: String): MutableLiveData<StatModel> {
    return repository.newBimeGozar(name)
}

this is my repository :

fun newBimeShode(
    name: String
): MutableLiveData<StatModel> {
    scope.launch {
        val request = api.newBimeShode(name)
        withContext(Dispatchers.Main) {
            try {
                val response = request.await()
                regBimeshodeLiveData.value = response
            } catch (e: HttpException) {
                Log.v("this", e.message);
            } catch (e: Throwable) {
                Log.v("this", e.message);
            }
        }
    }
    return regBimeshodeLiveData;
}

it works fine but there is a problem . I think the observer keeps running and if the result's answer is an error and user press fab button again , it creates a new observer and after this , it returns two value , the first value is the first run and the second value is the second run

how can I fix this ? what is the correct way for  submitting forms ?

Body:
If your problem is because of LiveData, you should use SingleLiveEvent like as follow

// For first article
val _liveData = MutableLiveData<Event<StatModel>>()

// For second article
val _liveData = SingleLiveEvent<StatModel>()

If you do not know SingleLiveEvent, you can find it here and here.

If your problem is because of your ui element, I think the best solution is to disable the submit button after submitting for the first time.


问:
NLTK MLE model clarification trigrams and greater
I am learning NLTK and have a question about data preprocessing and the MLE model. Currently I am trying to generate words with the MLE model. The problem is that   when I pick an n>=3. My model will produce words completely fine until it gets to a period ('.'). Afterwards, it will only output end-of-sentence paddings.

This is essentially what I am doing.

tokenized_text = [list(map(str.lower, word_tokenize(sent)))
                  for sent in sent_tokenize(MYTEXTINPUT)]

n = 3
train_data, padded_sents = padded_everygram_pipeline(n, tokenized_text)
model = MLE(n)
model.fit(train_data, padded_sents)
model.generate(20)

# OUTPUT:
eg:
blah beep bloop . </s> </s> </s> </s> </s> </s> </s> </s> (continues till 20 words reached)

```

I suspect that the answer to my problem lies in the way my n-grams are prepared for the model. So is there a way to format/prepare the data so that, for example, trigrams, are generated like   this --> ( . , </s>, <s> ) so that the model will try to start another sentence again and output more words ?

Or is there another way to avoid my problem written above ?

答:
The question is when generating from a language model, when to stop generating.

A simple idiom for generating would have been:

From this tutorial snippet, in code that can be achieved with:

```<code>detokenize = TreebankWordDetokenizer().detokenize

def generate_sent(model, num_words, random_seed=42):
    """
    :param model: An ngram language model from `nltk.lm.model`.
    :param num_words: Max no. of words to generate.
    :param random_seed: Seed value for random.
    """
    content = []
    for token in model.generate(num_words, random_seed=random_seed):
        if token == '<s>':
            continue
        if token == '</s>':
            break
        content.append(token)
    return detokenize(content)
</code>```

But there's actually a similar generate() function already in NLTK, from https://github.com/nltk/nltk/blob/develop/nltk/lm/api.py#L182

```<code>def generate(self, num_words=1, text_seed=None, random_seed=None):
    """Generate words from the model.
    :param int num_words: How many words to generate. By default 1.
    :param text_seed: Generation can be conditioned on preceding context.
    :param random_seed: A random seed or an instance of `random.Random`. If provided,
    makes the random sampling part of generation reproducible.
    :return: One (str) word or a list of words generated from model.
    Examples:
    >>> from nltk.lm import MLE
    >>> lm = MLE(2)
    >>> lm.fit([[("a", "b"), ("b", "c")]], vocabulary_text=['a', 'b', 'c'])
    >>> lm.fit([[("a",), ("b",), ("c",)]])
    >>> lm.generate(random_seed=3)
    'a'
    >>> lm.generate(text_seed=['a'])
    'b'
    """
    text_seed = [] if text_seed is None else list(text_seed)
    random_generator = _random_generator(random_seed)
    # This is the base recursion case.
    if num_words == 1:
        context = (
            text_seed[-self.order + 1 :]
            if len(text_seed) >= self.order
            else text_seed
        )
        samples = self.context_counts(self.vocab.lookup(context))
        while context and not samples:
            context = context[1:] if len(context) > 1 else []
            samples = self.context_counts(self.vocab.lookup(context))
        # Sorting samples achieves two things:
        # - reproducible randomness when sampling
        # - turns Mapping into Sequence which `_weighted_choice` expects
        samples = sorted(samples)
        return _weighted_choice(
            samples,
            tuple(self.score(w, context) for w in samples),
            random_generator,
        )
    # We build up text one word at a time using the preceding context.
    generated = []
    for _ in range(num_words):
        generated.append(
            self.generate(
                num_words=1,
                text_seed=text_seed + generated,
                random_seed=random_generator,
            )
        )
    return generated
</code>```

More details from the implementation on https://github.com/nltk/nltk/pull/2300 (note, see the hidden comments in the code review)

Body:
I am learning NLTK and have a question about data preprocessing and the MLE model. Currently I am trying to generate words with the MLE model. The problem is that   when I pick an n>=3. My model will produce words completely fine until it gets to a period ('.'). Afterwards, it will only output end-of-sentence paddings.

This is essentially what I am doing.

tokenized_text = [list(map(str.lower, word_tokenize(sent)))
                  for sent in sent_tokenize(MYTEXTINPUT)]

n = 3
train_data, padded_sents = padded_everygram_pipeline(n, tokenized_text)
model = MLE(n)
model.fit(train_data, padded_sents)
model.generate(20)

# OUTPUT:
eg:
blah beep bloop . </s> </s> </s> </s> </s> </s> </s> </s> (continues till 20 words reached)

I suspect that the answer to my problem lies in the way my n-grams are prepared for the model. So is there a way to format/prepare the data so that, for example, trigrams, are generated like   this --> ( . , </s>, <s> ) so that the model will try to start another sentence again and output more words ?

Or is there another way to avoid my problem written above ?

Body:
The question is when generating from a language model, when to stop generating.

A simple idiom for generating would have been:

From this tutorial snippet, in code that can be achieved with:

detokenize = TreebankWordDetokenizer().detokenize

def generate_sent(model, num_words, random_seed=42):
    """
    :param model: An ngram language model from `nltk.lm.model`.
    :param num_words: Max no. of words to generate.
    :param random_seed: Seed value for random.
    """
    content = []
    for token in model.generate(num_words, random_seed=random_seed):
        if token == '<s>':
            continue
        if token == '</s>':
            break
        content.append(token)
    return detokenize(content)

But there's actually a similar generate() function already in NLTK, from https://github.com/nltk/nltk/blob/develop/nltk/lm/api.py#L182

def generate(self, num_words=1, text_seed=None, random_seed=None):
    """Generate words from the model.
    :param int num_words: How many words to generate. By default 1.
    :param text_seed: Generation can be conditioned on preceding context.
    :param random_seed: A random seed or an instance of `random.Random`. If provided,
    makes the random sampling part of generation reproducible.
    :return: One (str) word or a list of words generated from model.
    Examples:
    >>> from nltk.lm import MLE
    >>> lm = MLE(2)
    >>> lm.fit([[("a", "b"), ("b", "c")]], vocabulary_text=['a', 'b', 'c'])
    >>> lm.fit([[("a",), ("b",), ("c",)]])
    >>> lm.generate(random_seed=3)
    'a'
    >>> lm.generate(text_seed=['a'])
    'b'
    """
    text_seed = [] if text_seed is None else list(text_seed)
    random_generator = _random_generator(random_seed)
    # This is the base recursion case.
    if num_words == 1:
        context = (
            text_seed[-self.order + 1 :]
            if len(text_seed) >= self.order
            else text_seed
        )
        samples = self.context_counts(self.vocab.lookup(context))
        while context and not samples:
            context = context[1:] if len(context) > 1 else []
            samples = self.context_counts(self.vocab.lookup(context))
        # Sorting samples achieves two things:
        # - reproducible randomness when sampling
        # - turns Mapping into Sequence which `_weighted_choice` expects
        samples = sorted(samples)
        return _weighted_choice(
            samples,
            tuple(self.score(w, context) for w in samples),
            random_generator,
        )
    # We build up text one word at a time using the preceding context.
    generated = []
    for _ in range(num_words):
        generated.append(
            self.generate(
                num_words=1,
                text_seed=text_seed + generated,
                random_seed=random_generator,
            )
        )
    return generated

More details from the implementation on https://github.com/nltk/nltk/pull/2300 (note, see the hidden comments in the code review)


问:
Different type of user registration in flask
I am new in Flask and I just wanted to create a simple market place with it. There are three type of users [sellers, buyers, admins] in my website. I think each type of users should have it's own registration and login because due to their role different type of information should be provided. On the other hand each user may have multiple role in the website therefore I don't think that it could be possible to create just one table for all users and assign role to them. As a result I think there should be three table for each type of users.

since there is only on user loader for users, how can I achieve my goal.

I am not sure whether it is correct or not, I think I could create a complete user with all required columns and based on the address that the user use to register, add the proper information to the database. and based on the address that user uses to login find the proper role and show a proper view.

答:
You can use one model for all types of User:

```<code>class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    usertype = db.Column(db.String(120))
    password_hash = db.Column(db.String(128))
</code>```

User Loader will just have the ID :

```<code>@login.user_loader
def load_user(id):
    return User.query.get(int(id))
</code>```

Make sure during register you should ask user type :

```<code>class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    usertype = SelectField('User Type', choices = [('sellers', 'sellers'),('buyers', 'buyers')], validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')
</code>```

And No need to provide User type during Login:

```<code>class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')
</code>```

And in HTMl files you can code accordingly. Take the example of this piece of code taken from base.html.

```<code>    {% if current_user.usertype == 'buyers' %}
      <ul class="nav navbar-nav">
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">List
          <span class="caret"></span></a>
          <ul class="dropdown-menu">
             <li><a href="{{ url_for('buyerslist')}}">List of buyers</a></li>
          </ul>
        </li>
      </ul>
    {% endif %}
</code>```

Body:
You can use one model for all types of User:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    usertype = db.Column(db.String(120))
    password_hash = db.Column(db.String(128))

User Loader will just have the ID :

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

Make sure during register you should ask user type :

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    usertype = SelectField('User Type', choices = [('sellers', 'sellers'),('buyers', 'buyers')], validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

And No need to provide User type during Login:

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')

And in HTMl files you can code accordingly. Take the example of this piece of code taken from base.html.

    {% if current_user.usertype == 'buyers' %}
      <ul class="nav navbar-nav">
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">List
          <span class="caret"></span></a>
          <ul class="dropdown-menu">
             <li><a href="{{ url_for('buyerslist')}}">List of buyers</a></li>
          </ul>
        </li>
      </ul>
    {% endif %}


问:
How to monitor method execution at third party library?
I have task to somehow monitor method calling at logback library. I started doing it with spring aop. So, for instance, i should catch all methods execution at ch.qos.logback.classic.Logger class. And there is my Aspect for it:

```<code>@Aspect
@Configuration
public class LogbackAspect {

    @Before(value = "execution(* ch.qos.logback.classic.Logger.*(..))")
    public void getInfo(JoinPoint joinPoint) {
         System.out.println("+++++AOP " + joinPoint.getSignature().getName());
}
}
</code>```

But it's not working for now, so, is there any possibility to intercept method execution with spring aop? Or there are some better ways to do it?

答:
Unfortunately, you can only weave your own code.

Brendon's answer is incorrect because it is focused on Android. On platforms with normal Java like Windows, MacOS, Linux you can intercept third-party code, given the following conditions:

You use full AspectJ, not Spring AOP. AspectJ can be used without Spring or also in Spring projects.

You use LTW (load-time weaving), usually via JVM parameter -javaagent:/path/to/aspectjweaver.jar, and configure aop.xml correctly.

As an alternative you can use the AspectJ compiler ajc directly via command line or via AspectJ Maven Plugin in order to do binary weaving, i.e. weaving aspect code into your 3rd party library, creating new woven class files and re-packaging them into a new JAR. Then you would use that JAR in place of the original. (BTW, this would also work for Android if the library is something you can deliver and install with your app and not some system class/library which cannot be replaced or overridden.)

I recommend LTW over binary weaving if you have no restrictions using Java command line parameters. There is even a chapter in the Spring manual describing how to use it directly in Spring.

Update: Here is an MCVE showing you how to do that in plain Java + AspectJ LTW.

Let's create an AspectJ project in Eclipse with installed AJDT (AspectJ Development Tools). Of course you can also create a Maven project with AspectJ Maven Plugin or even without because actually you do not need the AspectJ compiler if you use LTW via -javaagent:/path/to/aspectjweaver.jar. My sample project has this structure (Eclipse layout, not Maven, I just did it quickly):

The file contents are as follows.

src/de/scrum_master/app/Application.java

package de.scrum_master.app;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

public class Application {
  private static final Logger logger = (Logger) LoggerFactory.getLogger(Application.class);

  public static void main(String[] args) {
    logger.info("Example log from {}", Application.class.getSimpleName());
  }
}
```

<p><strong><em>src/logback.xml</em></strong></p>

<pre class="lang-xml prettyprint-override"><code><configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
</code>```

src/de/scrum_master/aspect/LogbackAspect.aj (or simply LogbackAspect.java)

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LogbackAspect {
  @Before(value = "execution(* ch.qos.logback.classic.Logger.*(..))")
  public void getInfo(JoinPoint joinPoint) {
    System.out.println(joinPoint);
  }
}
```

<p><strong><em>src/META-INF/aop.xml</em></strong></p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<aspectj>
  <aspects>
    <aspect name="de.scrum_master.aspect.LogbackAspect" />
  </aspects>
  <weaver options="-verbose -showWeaveInfo" />
</aspectj>
</code>```

Now create a simple Java run configuration for Application and add the Java agent to the command line:

Now run the program and the console log will be like this:

[AppClassLoader@18b4aac2] info AspectJ Weaver Version 1.9.5 built on Thursday Nov 28, 2019 at 11:28:53 PST
[AppClassLoader@18b4aac2] info register classloader sun.misc.Launcher$AppClassLoader@18b4aac2
[AppClassLoader@18b4aac2] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_LTW_Logback_60295366/bin/META-INF/aop.xml
[AppClassLoader@18b4aac2] info register aspect de.scrum_master.aspect.LogbackAspect
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(ch.qos.logback.classic.Level ch.qos.logback.classic.Logger.getEffectiveLevel())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:109) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(int ch.qos.logback.classic.Logger.getEffectiveLevelInt())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:113) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(ch.qos.logback.classic.Level ch.qos.logback.classic.Logger.getLevel())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:117) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
(...)
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(java.lang.Object ch.qos.logback.classic.Logger.readResolve())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:787) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
[AppClassLoader@18b4aac2] info processing reweavable type de.scrum_master.aspect.LogbackAspect: de\scrum_master\aspect\LogbackAspect.aj
[AppClassLoader@18b4aac2] info successfully verified type de.scrum_master.aspect.LogbackAspect exists.  Originates from de\scrum_master\aspect\LogbackAspect.aj
execution(void ch.qos.logback.classic.Logger.setLevel(Level))
execution(void ch.qos.logback.classic.Logger.setLevel(Level))
execution(String ch.qos.logback.classic.Logger.toString())
execution(void ch.qos.logback.classic.Logger.addAppender(Appender))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(void ch.qos.logback.classic.Logger.info(String, Object))
execution(void ch.qos.logback.classic.Logger.filterAndLog_1(String, Marker, Level, String, Object, Throwable))
execution(void ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(String, Marker, Level, String, Object[], Throwable))
execution(String ch.qos.logback.classic.Logger.getName())
execution(LoggerContext ch.qos.logback.classic.Logger.getLoggerContext())
execution(void ch.qos.logback.classic.Logger.callAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
16:04:52.791 [main] INFO  de.scrum_master.app.Application - Example log from Application
```

I think this is exactly what you want. Please refer to the Spring manual in order to find out how to configure AspectJ LTW there.

Body:
I have task to somehow monitor method calling at logback library. I started doing it with spring aop. So, for instance, i should catch all methods execution at ch.qos.logback.classic.Logger class. And there is my Aspect for it:

@Aspect
@Configuration
public class LogbackAspect {

    @Before(value = "execution(* ch.qos.logback.classic.Logger.*(..))")
    public void getInfo(JoinPoint joinPoint) {
         System.out.println("+++++AOP " + joinPoint.getSignature().getName());
}
}

But it's not working for now, so, is there any possibility to intercept method execution with spring aop? Or there are some better ways to do it?

Body:
Unfortunately, you can only weave your own code.

Brendon's answer is incorrect because it is focused on Android. On platforms with normal Java like Windows, MacOS, Linux you can intercept third-party code, given the following conditions:

You use full AspectJ, not Spring AOP. AspectJ can be used without Spring or also in Spring projects.

You use LTW (load-time weaving), usually via JVM parameter -javaagent:/path/to/aspectjweaver.jar, and configure aop.xml correctly.

As an alternative you can use the AspectJ compiler ajc directly via command line or via AspectJ Maven Plugin in order to do binary weaving, i.e. weaving aspect code into your 3rd party library, creating new woven class files and re-packaging them into a new JAR. Then you would use that JAR in place of the original. (BTW, this would also work for Android if the library is something you can deliver and install with your app and not some system class/library which cannot be replaced or overridden.)

I recommend LTW over binary weaving if you have no restrictions using Java command line parameters. There is even a chapter in the Spring manual describing how to use it directly in Spring.

Update: Here is an MCVE showing you how to do that in plain Java + AspectJ LTW.

Let's create an AspectJ project in Eclipse with installed AJDT (AspectJ Development Tools). Of course you can also create a Maven project with AspectJ Maven Plugin or even without because actually you do not need the AspectJ compiler if you use LTW via -javaagent:/path/to/aspectjweaver.jar. My sample project has this structure (Eclipse layout, not Maven, I just did it quickly):

The file contents are as follows.

src/de/scrum_master/app/Application.java

package de.scrum_master.app;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

public class Application {
  private static final Logger logger = (Logger) LoggerFactory.getLogger(Application.class);

  public static void main(String[] args) {
    logger.info("Example log from {}", Application.class.getSimpleName());
  }
}

src/logback.xml

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

src/de/scrum_master/aspect/LogbackAspect.aj (or simply LogbackAspect.java)

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LogbackAspect {
  @Before(value = "execution(* ch.qos.logback.classic.Logger.*(..))")
  public void getInfo(JoinPoint joinPoint) {
    System.out.println(joinPoint);
  }
}

src/META-INF/aop.xml

<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
  <aspects>
    <aspect name="de.scrum_master.aspect.LogbackAspect" />
  </aspects>
  <weaver options="-verbose -showWeaveInfo" />
</aspectj>

Now create a simple Java run configuration for Application and add the Java agent to the command line:

Now run the program and the console log will be like this:

[AppClassLoader@18b4aac2] info AspectJ Weaver Version 1.9.5 built on Thursday Nov 28, 2019 at 11:28:53 PST
[AppClassLoader@18b4aac2] info register classloader sun.misc.Launcher$AppClassLoader@18b4aac2
[AppClassLoader@18b4aac2] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_LTW_Logback_60295366/bin/META-INF/aop.xml
[AppClassLoader@18b4aac2] info register aspect de.scrum_master.aspect.LogbackAspect
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(ch.qos.logback.classic.Level ch.qos.logback.classic.Logger.getEffectiveLevel())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:109) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(int ch.qos.logback.classic.Logger.getEffectiveLevelInt())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:113) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(ch.qos.logback.classic.Level ch.qos.logback.classic.Logger.getLevel())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:117) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
(...)
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(java.lang.Object ch.qos.logback.classic.Logger.readResolve())' in Type 'ch.qos.logback.classic.Logger' (Logger.java:787) advised by before advice from 'de.scrum_master.aspect.LogbackAspect' (LogbackAspect.aj)
[AppClassLoader@18b4aac2] info processing reweavable type de.scrum_master.aspect.LogbackAspect: de\scrum_master\aspect\LogbackAspect.aj
[AppClassLoader@18b4aac2] info successfully verified type de.scrum_master.aspect.LogbackAspect exists.  Originates from de\scrum_master\aspect\LogbackAspect.aj
execution(void ch.qos.logback.classic.Logger.setLevel(Level))
execution(void ch.qos.logback.classic.Logger.setLevel(Level))
execution(String ch.qos.logback.classic.Logger.toString())
execution(void ch.qos.logback.classic.Logger.addAppender(Appender))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.getChildByName(String))
execution(Logger ch.qos.logback.classic.Logger.createChildByName(String))
execution(void ch.qos.logback.classic.Logger.info(String, Object))
execution(void ch.qos.logback.classic.Logger.filterAndLog_1(String, Marker, Level, String, Object, Throwable))
execution(void ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(String, Marker, Level, String, Object[], Throwable))
execution(String ch.qos.logback.classic.Logger.getName())
execution(LoggerContext ch.qos.logback.classic.Logger.getLoggerContext())
execution(void ch.qos.logback.classic.Logger.callAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
execution(int ch.qos.logback.classic.Logger.appendLoopOnAppenders(ILoggingEvent))
16:04:52.791 [main] INFO  de.scrum_master.app.Application - Example log from Application

I think this is exactly what you want. Please refer to the Spring manual in order to find out how to configure AspectJ LTW there.


问:
Print Date and Time In Visual Studio C++ build?
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:

```<code>Binary Build date: 03/03/2009 @ 10:00AM
</code>```

I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.

Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.

答: You can use the macros __TIME__ and __DATE__. Note the double underscores. These are unrolled at compile time and hence you will get the last compile time saved in your file(s).

OwnerDisplayName: Brock Woolf

Body:
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:

Binary Build date: 03/03/2009 @ 10:00AM

I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.

Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.

LastEditorDisplayName: Iraimbilanja

OwnerDisplayName: dirkgently

LastEditorDisplayName: TheTXI