text:
Q: When is the suffix -tor and -ter used? Can someone help me in understanding the suffix -tor and -ter?
I am not able to understand it properly and I always mix the spelling like:

*

*"computor" when it should be computer

*"administrater" when it should be administrator

A: As reflected in comments, there's no real "rule" here (though there's a tendency for -or to occur more often in words with Latin roots). So basically, you just have to learn them.
But things aren't as bad as they appear. Not only is the -er form more common in established words - it's far more "productive" for new terms. Also, as RegDwight points out in this ELU answer on the subject, there are many words where either spelling is acceptable (adviser/advisor, convener/convenor, etc.).
So instead of having to learn every word separately, all you have to do is remember those where only -or is acceptable (which as of today, includes administrator).
In short, slow as it might be, the general trend is towards -er. Adopt that as your default, and with any luck by the time you need one of today's more obscure "-or - only" words, the -er form will be acceptable!

EDIT: As @Anixx correctly points out, strictly speaking there is no currently productive suffix -ter in Modern English (the only instances where it's recognized as a meaningful "morphemic element" are laughter::laugh and slaughter::slay). This question and answer address the -or / -er distinction.

A: There is no suffix -ter- in English.
If the 't' is part of the root, then English uses the suffix -er. If 't' is not a part of the root, then English uses Latin suffix -tor-.
Note that the suffixes have different origin. The suffix -er also was borrowed from Latin but from Latin suffix -ari- (-arius with the ending).
There are also English words with suffix -ster as in hipster, youngster. It was initially a feminine suffix. They should not be confused with the first two.
There are also some words inherited from PIE which had the -ter- suffix in PIE but in English it became a part of the root ("daughter" for instance).

A: There is also a usage trend to use -tor when the intent is to emphasize that the agent is a person, while -ter is used when the agent is not necessarily a person.
For example,
'computor' the original term meaning a person performing computation
later becoming 'computer' when calculations were performed by either people or machines. Following a transition period where either word was used for either meaning; computer is now commonly understood to mean a machine.


text:
Q: Exoplayer 2 change media source to clip video I am trying to implement exoplayer 2 for one of our applications.
Seems like the documentation and examples for something more complicated than automatic playback is very poor.
My problem is I create a mediasource and set it to the player, after that I have a custom icon that plays the video and on finish I seek back to 0.
Also I have a custom dual seekbar that when moved it will seek to a position and clip the video between the selected start and end time.
I am not sure if changing source of the player without recreating the whole thing is even possible.
I init my player as:
@AfterViews
protected void init() {
        TrackSelector trackSelector = new DefaultTrackSelector();
        mPlayer = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector);
        mVideoView.setPlayer(mPlayer);
        mPlayer.addListener(this);
}

After that I prepare the player like this:
public void setVideoPath(final String videoPath) {
        mVideoPath = videoPath;
        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "yourApplicationName"));
        // This is the MediaSource representing the media to be played.
        videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(videoPath));
        mPlayer.prepare(videoSource);
}

When my play icon is clicked it runs:
@Click(R.id.view_video_preview_container_play)
    void onPlayClicked() {
        mPlayButton.setVisibility(GONE);
        mPlayer.setPlayWhenReady(true);
}

When the playback is finished I do:
@Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {

        if (playbackState == STATE_ENDED) {
            mPlayButton.setVisibility(VISIBLE);
            mPlayer.seekTo(0);
            mPlayer.setPlayWhenReady(false);
        }
}

No when I seek I do:
disposable = source
                .debounce(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(range -> {
                            mPlayer.stop();
                            mPlayButton.setVisibility(VISIBLE);
                            clippingSource = new ClippingMediaSource(videoSource, 2000000, 5000000);
                            mPlayer.prepare(clippingSource);
                        }
                );

Now when the source emits to my observable I get back:
2018-11-16 12:48:16.463 28090-28209/nl.dtt.vormats E/ExoPlayerImplInternal: Source error.
    com.google.android.exoplayer2.source.ClippingMediaSource$IllegalClippingException: Illegal clipping: not seekable to start
        at com.google.android.exoplayer2.source.ClippingMediaSource$ClippingTimeline.<init>(ClippingMediaSource.java:350)
        at com.google.android.exoplayer2.source.ClippingMediaSource.refreshClippedTimeline(ClippingMediaSource.java:296)
        at com.google.android.exoplayer2.source.ClippingMediaSource.onChildSourceInfoRefreshed(ClippingMediaSource.java:262)
        at com.google.android.exoplayer2.source.ClippingMediaSource.onChildSourceInfoRefreshed(ClippingMediaSource.java:34)
        at com.google.android.exoplayer2.source.CompositeMediaSource$1.onSourceInfoRefreshed(CompositeMediaSource.java:103)
        at com.google.android.exoplayer2.source.BaseMediaSource.refreshSourceInfo(BaseMediaSource.java:73)
        at com.google.android.exoplayer2.source.ExtractorMediaSource.notifySourceInfoRefreshed(ExtractorMediaSource.java:400)
        at com.google.android.exoplayer2.source.ExtractorMediaSource.prepareSourceInternal(ExtractorMediaSource.java:348)
        at com.google.android.exoplayer2.source.BaseMediaSource.prepareSource(BaseMediaSource.java:137)
        at com.google.android.exoplayer2.source.CompositeMediaSource.prepareChildSource(CompositeMediaSource.java:109)
        at com.google.android.exoplayer2.source.ClippingMediaSource.prepareSourceInternal(ClippingMediaSource.java:216)
        at com.google.android.exoplayer2.source.BaseMediaSource.prepareSource(BaseMediaSource.java:137)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.prepareInternal(ExoPlayerImplInternal.java:396)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:286)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:166)
        at android.os.HandlerThread.run(HandlerThread.java:65)

Unfortunately as I stated before the documentation if very poor and I managed only to find out that the exceptions is thrown at:
if (startUs != 0 && !window.isSeekable) {
          throw new IllegalClippingException(IllegalClippingException.REASON_NOT_SEEKABLE_TO_START);
}

Specifically window.isSeekable is false.

A: The solution was to recreate the the MediaSource as it seems like the same MediaSource can not be reused.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I disable a UIButton? I am working on a project in which I have to show all photos of Photo Library in a plist and show them horizontally on UIButtons.
My app will also have an edit button: when the user clicks this button, a delete mark (such as usually appears in other iPhone/iPad apps) should show on each button.
But here's the crucial bit: as soon as this delete mark appears, the functionality of the button should be disabled. I've tried accomplishing this with the following:
{
  editbutton.enabled=NO;
}

...but it neither produces an error nor works. What should I do?

A: setter for property enabled is overridden in class UIButton. try to send a message.
 [editbutton setEnabled:NO];

A: Use the enabled property of UIControl which the super class of UIButton and set it with NO.
myButton.enabled = NO;
You could also try as @Marvin suggested,
In that case your button will not respond to any touch event from user,

A: Swift 3 and above
editButton.isEnabled = false
setEnabled is now part of the setter method for isEnabled.

A: Please set this...
 editButton.userInteractionEnabled = NO;

or You can use
 editButton.enabled = NO;

A: In addition to the above:
Set
editButton.userInteractionEnabled = NO;
or you can use
editButton.enabled = NO;
You might want to gray out the button so the user knows it was disabled:
editButton.alpha = 0.66

A: yourBtn.userInteractionEnabled = NO;


text:
Q: How to concat int resource id R.string.id_name + _1 like we do with string? Example:
if (i = 1) getString("R.string.name_user" + "_1");

I want to add a suffix to string resource id.
How can I do the above but the value that will pass to getString() will be int, not a string?

A: int id = getResources().getIdentifier("name_user" + "_1", "string", getPackageName());
String result = getString(id);

A: You can use Resources.getIdentifier().

*

*int id = resources.getIdentifier("name_user{your-suffix}", "string", "your-package-name")

*then getString(id)
Note: You should avoid doing this, it is not efficient.


text:
Q: Add checkboxes and multi-select-dropdown in angular-datatables v8.0.0 Facing issues with implementing checkboxes and multi-select dropdown in angular datatables.
npm package angular-datatables: 8.0.0
Trying to create checkbox and ng-multiselect-dropdown column in angular datatables. but after the implementation of following code getting [Object, Object] in the browser display.
in .ts file this is the following code
this.dtOptions = {
pagingType: 'full_numbers',
responsive: true,
serverSide: true,
processing: true,
autoWidth: true,
searchHighlight: true,
visible: true,
api: true,
"ordering": true,
searchDelay: 2000,
"scrollCollapse": true,
'columnDefs': [ {
'orderable': false,
targets: 0,
width: 20,
className: 'select-checkbox'
},
{
targets: 1,
}],
ajax: (dataTablesParameters: any, callback) => {
this.checkClass = "overlay";
this.newService.getNewList("test", dataTablesParameters)
.subscribe(resp => {
this.checkClass = "hiddenOverlay";
this.totRecs = 15;
if (this.totRecs === 10000 && this.showPop) {
this.delayedPopover();
}
callback({
recordsTotal: 15,// assign total records
recordsFiltered: 15,// assign total records
data: resp.body['data'],
});
});
},
columns: [
{ data: null  },//checkbox1
{ data: null  },//checkbox2
{ data: 'FIELD1', "defaultContent": "N/A" },
{ data: null }, //multiselect
],
};
in .html file

Submit
Skip
Claim No
Drivers

<input type="checkbox" name="websitecheck">
<input type="checkbox"  name="websitecheck1" >
{{c.FIELD1}}

<ng-multiselect-dropdown
[style.pointer-events]="c.SKIPPED==1 ? 'none' : 'auto'"
[disabled]="c.SKIPPED==1?1:0"
class="custom-font-size"
[placeholder]="'Select Drivers'"
[settings]="dropdownSettings"
[data]="dropdownList"
[(ngModel)]="c.DRIVERS"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
>
</ng-multiselect-dropdown>

`


text:
Q: regular expression: the outcome is not as expected import re
pattern = "[0-9]+[st|nd|rd|th]?"
str2 = "1st 1 2 3 4 5th "
a = re.findall(pattern, str2)
print(a)

Expected Output
['1st', '1', '2', '3', '4', '5th']

Actual Output
['1s', '1', '2', '3', '4', '5t']

A: import re
pattern = r'[0-9]+(?:st|nd|rd|th)?'
str2 = "1st 1 2 3 4 5th "
a = re.findall(pattern, str2)
print(a)

Output:
['1st', '1', '2', '3', '4', '5th']
Your mistake was to use square brackets instead of parentheses. Square brackets usually used to indicate a range (like 0-9) rather then "OR" which is what you wanted in the suffix. For further reading:
What is the difference between square brackets and parentheses in a regex?
If you change only the parentheses, output will be as follow:
[('1', 'st'), ('1', ''), ('2', ''), ('3', ''), ('4', ''), ('5', 'th')]
This is still not what you wanted, so we made a second change to pattern: adding ?: is the syntax that creates a non-capturing group (means "treat it as one group").


text:
Q: Response cookies available in browser I asked a very similar question yesterday, but I've made some further research and the title for yesterday's question isn't quite accurate.
I have an ASP.NET/C# app. In my server-side code, I'm setting a couple cookies: MyLogin and MySession. In my C# code I'm adding add these code to the Response.Cookies.  I see them come back in the response in fiddler.
My server-side code is being called via JavaScript like so:
document.location.href = myURL;
debugger;

In fiddler I see the MyLogin cookie has an expiration set to a month from today.  MySession doesn't have an expiration.
I'm using the IE developer tools to step through my JavaScript code above.  While I'm stopped at the debugger line above I run the following test page that I created in the same directory as my .aspx page:

I see the cookies that I sent up with document.location.href = myURL, but not the cookies sent back in the response.  I'd expect the cookies that were set on each http request/reponse would keep getting sent up to the browser with every request, until they expired.
I'm definitely not seeing the MySession and MyLogin cookies getting passed up with a web service call that's being called from JavaScript in the load for myURL.
Yesterday it was suggested that the cookies might be httponly, but the http property on both the MyLogin and MySession cookies is false in my C# code.  Is there a way to view this property in Fiddler?
-Eric

A: I turned out that the problem had to do with case-sensitivity in cookie urls.  I was setting the cookies against
http://myserver/mydir

but was trying to read them in
http://myserver/MyDir.

See Why are cookie paths case sensitive?
-Eric


text:
Q: Quadratic optimization problem with quadratic constraint Given  $A = A^T \in \mathbb{R}^{n \times n}, X = \begin{bmatrix}x & \eta\end{bmatrix} \text{with} \ x, \eta \in \mathbb{R}^n$ and $||x|| = ||\eta|| = 1$ (vectors in $\mathbb{R}^n$ are treated as columns) solve
$$ \min_{v \in \mathbb{R}^2} f(v):= v^TX^TAXv$$ such that $$ h(v):=v^TX^TXv-1 = 0 $$
First attempt:
Construct the Lagrangian,
$L := f(v) + \lambda h(v)$
$$\frac{\partial L}{\partial v} = 2(X^TAX)v + 2\lambda(X^TX)v = 0$$
Premultiply by $v^T$ to get
$$\lambda = -v^TX^TAXv $$
Substituting this back yields a very complicated equation in $v$ which I'm unable to solve.
Second attempt:
Since $X^TAX$ is symmetric, $v^TX^TAXv \ge ||v_m||^2 \lambda_{\min}(X^TAX)$ where $v_m$ is the eigenvector corresponding to the least eigenvalue $\lambda_{\min}(X^TAX)$ of $X^TAX$. Therefore the minimizer of the original problem is $v = \alpha v_m$ with $\alpha \in \mathbb{R}$ such that $h(v) = 0$.
My second attempt is still a hunch, and I'm not being able to prove the correctness of my hunch.
Question : I'm looking for a complete solution or hints to any of my approaches in order to get an analytical solution to the minimization problem.
The solution to this has been given in the book, but without proof, and I am unsuccessful at getting the same solution. The given minimizer for $v$ is the eigenvector of the smaller eigenvalue of $X^TAX$ scaled appropriately such that the norm is 1.

A: This is the definition of generalized eigenvalues, i.e. you are looking for the minimum generalized eigenvalue of the pair $(X^TAX, X^TX)$.

A: I am not sure if I understand the problem correctly.
Let:

*

*2 by 2 matrix $B = X^{T}AX$,

*2 by 2 matrix $C = X^{T}X$
Then:

*

*Objective: $f(x) = \vec{v} B \vec{v} $

*Constraint: $g(x) = \vec{v} C \vec{v} - 1 = 0$
$f(x) = (b_{11}v_{1} + b_{21}v_{2})v_{1} + (b_{12}v_{1} + b_{22}v_{2})v_{2}$
$f(x) = b_{11}v_{1}^{2} + b_{21}v_{2}v_{1} + b_{12}v_{1}v_{2} + b_{22}v_{2}^{2}$
$g(x) = c_{11}v_{1}^{2} + c_{21}v_{2}v_{1} + c_{12}v_{1}v_{2} + c_{22}v_{2}^{2} - 1$
Lagrange:
$L = f(x) + \lambda g(x)$
$0 = \frac{\partial L}{\partial v_{1}} = 2b_{11}v_{1} + b_{21}v_{2} + b_{12}v_{2} + \lambda (2c_{11}v_{1} + c_{21}v_{2} + c_{12}v_{2})$
$0 = \frac{\partial L}{\partial v_{2}} = 2b_{22}v_{2} + b_{12}v_{1} + b_{21}v_{1} + \lambda (2c_{22}v_{2} + c_{12}v_{1} + c_{21}v_{1})$
$0 = c_{11}v_{1}^{2} + c_{21}v_{2}v_{1} + c_{12}v_{1}v_{2} + c_{22}v_{2}^{2} - 1 $


text:
Q: Cannot open https sites with Webkit browsers I have tested this using:

*

*Mac OS X 10.7.2

*Google Chrome 14.0.835.202 Stable w/o any extensions installed

*Google Chrome 16.0.906.0 Canary w/o any extensions installed

*Mail.app 5.1

The error message in Chrome is
Google Chrome could not load the webpage because <server> took too long to respond. The website may be down, or you may be experiencing issues with your Internet connection.
I would also have tested Safari, but it crashes on start-up.
I basically can't connect to secure URLs on Webkit browsers. It works in both Opera and Firefox.
Another computer on the same network can connect using Chrome, so it is not a network related issue.

A: I fixed this by rebooting my computer.


text:
Q: Cross-validation: error estimation and bias When obtaining the error estimation of a model over a dataset using k-fold cross-validation, lower values of the error estimation necessarily imply a lower bias? Are both concepts, error estimation and bias, equivalent?

A: Higher test errors can also indicate lower bias, e.g. if the training error is low. So, lower error is not equivalent to lower bias.


text:
Q: Where to find the error messages of Postfix I cannot sent mail by using Postfix (SMTP) on Ubuntu Server 11.04.
So, there must be some errors,
But where to see the error message?

A: log files for postfix
can be
/var/log/mail.log
/var/log/mail.err
/var/log/mail.info
and also you can grep logs for /var/log/syslog file.

A: Have you already stumbled upon this comprehensive Postfix Debugging Howto?  There's the following notice concerning logging:

Postfix logs all failed and successful deliveries to a logfile. The file is usually called /var/log/maillog or /var/log/mail; the exact pathname is defined in the /etc/syslog.conf file.

(syslog.conf specifies where the mail-facility logs get written to, it's rather self-explaining when you look at it.)

A: I was not able to locate logs anywhere and I was running Ubuntu 20.04 LTS, turns out this was a permission issue for some strange reason. the problem was with the syslog permission. The following helped me to resolve it:
sudo chown syslog:adm /var/log
sudo chmod 0775 /var/log

sudo service rsyslog restart
sudo service postfix restart


text:
Q: Webi 4.1 BO variable not aggregating I have created a measure variable:
= If IsNull([OBJECT 1]) And IsNull([OBJECT 2]) Then 0  ElseIf

Not(IsNull([OBJECT 2])) Then

DaysBetween([DATE 1];[DATE 2])

Else

DaysBetween([DATE 1];[DATE 3])

This works fine when the Unique Object is present but when I remove the unique ID I expect it aggregate but I get Multivalue. Please advise how best to correct this?
Thank you for your time in advance.
I have tried ForEach () to the Unique ID but still not getting what I need. I want a separate table with my Sum Count etc. as a dynamic Summary but getting Multivalue. This should be simple but it's creating a big headache !!!

A: If you wrap your formula in a Sum() function...

That should do it...


text:
Q: Merging SVG together I have a SVG which renders some content as below (svg-1),
----------------
| (Image)  Text|
|              |
|              |
|              |
|              |
|              |
|         Text |
----------------

I have a Seperate set of Svg documents which have some content in it as below (svg-2)
----------------
|              |
|              |
| Some Content |
| here         |
|              |
|              |
|              |
|              |
----------------

What I am trying to achieve is to get a combined svg similar to below
----------------
| (Image)  Text|
|              |
| Some Content |
| here         |
|              |
|              |
|         Text |
----------------

I belive the href tag could be something that can be used here but wasnt very sure on if that was the best approach or how exaclt to implement it.
Here is the code for the svg-01 also named as svg01.svg
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg width="200mm" height="300mm"
    xmlns="http://www.w3.org/2000/svg" dominant-baseline="hanging">
    <image x="1.74mm" y="1.59mm" height="19.97mm" width="23.41mm" href=".."/>
    <text x="139.85mm" y="1.85mm" font-size="12pt">Text</text>
    <text x="142.05mm" y="289.72mm" font-size="12pt">Text</text>
</svg>

Here is my code for the attempted combined svg
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg width="300mm" height="200mm"
    xmlns:xlink="http://www.w3.org/1999/xlink>
    xmlns="http://www.w3.org/2000/svg" dominant-baseline="hanging">
    <image xlink:href="svg01.svg" />
    <text x="43.12mm" y="50.54mm" width="73.98mm" height="8.41mm" font-size="12pt">Some Content here</text>
</svg>

Is this behaviour possible in svg
What is the best approach of achieving my requirement ? Does svg provide any sort of templating functionality ?
Would really appreciate some help here

A: If your SVGs are the same size, you can just take the content of each and combine it like so. You may have to adjust things if your SVGs are different sizes or have different view boxes.
First SVG
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg width="200mm" height="300mm"
    xmlns="http://www.w3.org/2000/svg" dominant-baseline="hanging">
    <image x="1.74mm" y="1.59mm" height="19.97mm" width="23.41mm" href=".."/>
    <text x="139.85mm" y="1.85mm" font-size="12pt">Text</text>
    <text x="142.05mm" y="289.72mm" font-size="12pt">Text</text>
</svg>

Second SVG
<svg width="200mm" height="300mm"
    xmlns:xlink="http://www.w3.org/1999/xlink>
    <text x="43.12mm" y="50.54mm" width="73.98mm" height="8.41mm" font-size="12pt">Some Content here</text>
</svg>

Combined SVG
<svg width="200mm" height="300mm"
    xmlns="http://www.w3.org/2000/svg" dominant-baseline="hanging">

    <!-- Content from first SVG -->
    <image x="1.74mm" y="1.59mm" height="19.97mm" width="23.41mm" href=".."/>
    <text x="139.85mm" y="1.85mm" font-size="12pt">Text</text>
    <text x="142.05mm" y="289.72mm" font-size="12pt">Text</text>

    <!-- Content from second SVG -->
    <text x="43.12mm" y="50.54mm" width="73.98mm" height="8.41mm" font-size="12pt">Some Content here</text>
</svg>


text:
Q: Is better to detect for exceptions and throw them or just let runtime throw them? Lets say there is setup like this:
public class MyClass
{
    public void DoSomething(string Data)
    {
      //if (String.IsNullOrWhiteSpace(Data))
        //throw new NullReferenceException();

      //Do something with Data and let it throw??
    }
}

public class EntryPointClass
{
  public void DoIt(string Data)
  {
     var logicClass = new MyClass();

     try
     {
        logicClass.DoSomething(Data);
     }
     catch(Exception ex)
     {

     }
  }
}

In DoSomething I can detect a problem and throw an exception. In testing EntryPointClass I can test the expected outcome or test that something in happened in the catch.
Why is it better to throw an exception rather than just wait for one to happen? Either way we've caught it!

A: You do both:
public void DoSomething(string Data)
{
  if (String.IsNullOrWhiteSpace(Data))
    //throw new NullReferenceException();
    throw new ArgumentException("Data");

  //Do something with Data and let it throw??
}

The aim is to throw early and provide specific information.
The direct reason to throw here is that the contract with DoSomething() is broken. Signal it, don't wait for `DoSomething() to carry on and break other contracts.
Fail fast, fail early.

A: Throw your own exceptions to prevent from the outside seeing the actual source of the exception and therefore having information about you implementation.
You can throw argument exception with a custom message or a custom exception to provide more details to why the argument was invalid.

A: The point of using Exception handling, is to handle exceptions that may be out of your control.  If you're planning on wrapping your code in a try-catch block, with an exception of NullReferenceException, then you should have something in place to handle this type of exception and perform any necessary operations related to this error.
That being said, in situations where you know you may have the possibility of having an error which would throw an exception, it is better to check for this situation -- and not throw an error at all, but gracefully handle it.  Otherwise you're just coding by exception, which is an anti-pattern.
Remember, exceptions are exactly that, exceptions to your rules, and not a catch-all for anything that may go wrong in the execution of your code.

A: Think of exception as of a man who jumps out of a burning house and crying for help: You do not want them to scare general populace, but you do want them to notify right people to do something about the fire.
With that in mind:
1) If you have something wrong in DoSomething AND you know how to fix it - you do not need an exception : just fix it inside DoSomething.
2) If DoSomething is in trouble handling the issue (wrong attribute, resources unavailable, etc..) - use exception to ESCALATE the issue and handle it on a level where such handling is possible.
3) If DoSomething is screwed in a way you cannot influence in any way (like filesystem crash and IO exceptions everywhere) - just catch an exception, log it and shutdown gracefully - at least such situation will not look like an implosion.

A: One set of circumstances where you shouldn't attempt to detect an error condition ahead of time, rather than just letting the code fail, is where there is a dependency on an external resource, outside of your code's control. E.g. anything dealing with the network, file system, etc.
The issue with any of these is that the checking code can succeed and then the actual operation can still fail. All you've done by adding checking code is increased the amount of code you've written - you still have to write code to deal with actual failures anyway.

A: Eric Lippert has a great article on Exception.
Please follow the link. It is very good resource on how exceptions should be handled.
As a rule of thumb, try to avoid the exceptions rather than trying to handle the exception. And dont catch all the exceptions. I see Catch(Exception ex) in your code. Catch the exception which you can handle. There is nothing much you can do when you get OutofMemoryException, ThreadAbortException
I agree with Henk Holterman.


text:
Q: Wait for database result in GWT Async call Is there any way I can wait for the database to return the result before the comparison is made?
private boolean checkAuthantication(String email, String password) {
    String encryptedPassword = encryptPassword(password);
    String dbPassword = Comav200.GetInstance().getPasswordFromDatabase(email);

    if (encryptedPassword.equals(dbPassword)) {
        return true;
    }
    else {
        return false;
    }
}

Any ideas?

A: You could use a while loop or a timer of 2-3 seconds. But I think your code automatically waits untill the dbPassword is filled.

A: Why dont you use AsyncCallback?
http://www.tutorialspoint.com/gwt/gwt_rpc_communication.htm


text:
Q: How do I use QGIS to merge maximum values of multiple TIF files into one "maximum value' raster? I have 14 rasters that represent water storage for the same area over a range of years, 2002 to 2015. I am looking for a way to find the maximum value at each pixel location.
I am not looking for the maximum value for each raster; I am looking for the  maximum value for each pixel of 14 rasters at each location.


text:
Q: 100% CPU usage when reading named pipe in Go I have a short Go program which reads from a named pipe and processes each line as an external process writes to the pipe. The named pipe is created before the program runs using mkfifo.
The process is taking up 100% of the CPU when waiting for a new line from the named pipe, even when it's not doing any processing. It's running on Ubuntu 14.04. Any ideas?
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)

awaitingExit := false

var wg sync.WaitGroup

go func() {
    for sig := range c {
        awaitingExit = true

        // wait for goroutines to finish processing new lines
        wg.Wait()
        os.Exit(1)
    }
}()

file, err := os.OpenFile("file.fifo", os.O_RDONLY, os.ModeNamedPipe)

defer file.Close()

if err != nil {
    log.Fatal(err)
}

reader := bufio.NewReader(file)

// infinite loop
for {
    line, _, _ := reader.ReadLine()

    // stop handling new lines if we're waiting to exit
    if !awaitingExit && len(line) > 0 {
        wg.Add(1)

        go func(uploadLog string) {
            defer wg.Done()
            handleNewLine(uploadLog)
        }(string(line))
    }
}

func handleNewLine(line string) {
    ....
}

A: Your "infinite loop" is really infinite: you never exit it or jump out of it.
It contains an if:
// stop handling new lines if we're waiting to exit
if !awaitingExit && len(line) > 0 {
    // code omitted
}

But if the condition is false, you're still not getting out of the for loop, just continue with another iteration. Once you reach the end of reader, this loop will consume 100% of a core because after that it will not wait for anything just trying to read (which will immediately return EOF) and checking the awaitExit variable and doing these 2 steps again.
You either need to add condition to the for loop to exit sometime, or use a break statement to break out of it.
Altered for loop with a condition:
for !awaitingExit {
}

Altered for with a break statement:
for {
    if awaitingExit {
        break
    }
    // code omitted
}

Note: if awaitingExit variable is changed by another goroutine, you need proper synchronization, or better, use channels for exit signalling.


text:
Q: UTF8 Text Encoding - Windows Phone 8.1 C++ I have an api which returns a UTF8 string but on my app the TextBlock that shows this string is using other encoding than UTF8. How can I deal with such a problem ?
Thanks,

A: From our discussion I'm guessing that the HttpClient object is performing an incorrect conversion due to either the server failing to specify an encoding, or specifying the wrong encoding. Check the content encoding and content type response headers.


text:
Q: bitmaps not looking smooth I am loading raster files (png) in my viewer application. When I view these files in an application such as IrfanView everything looks very smooth. Somehow the antialiasing settings in my viewer application do not work: lines have very jagged edges.
I do set the SmoothingMode = Drawing2D.SmoothingMode.AntiAlias. I've tried different combinations of the various settings but to no avail.
Is GDI+ not capable of this like IrfanView is?

A: bitmaps aren't antialiased, text and vector images are - perhaps your problem is that the images are being stretched and resized


text:
Q: How the Text readjusts when an image appears? In some news applications when it loads it shows a list of articles. When we click on an article, it goes to its detailed page. In the detailed page 1st there will be only the text related to the article. But suddenly an image comes(related to the article) on the top left corner and the text re-aligns itself to contain the image.
Wht are they doing here? Are they still using UILabel? If i am just adding a UIImageView inside a UILabel, the text will be be adjusted even before the image appears.How can I replicate this myself?

A: I might be wrong, but i think what they are doing probably similar to the following steps:

*

*User clicks on Article

*Article description is being loaded, async download of image is being initiated

*once the article description is downloaded the detailsview gets added on top of the navigationstack and appears.

*user reads the text....

*at some point the download of the image finishes, the viewcontroller gets notified in some way and does a re-layout of the detailsview.

the re-layouting (or however you want to call it) will do two things (probably in an animated fashion)
As I'm not aware how to wrap text around images within a UILabel (keen to get ahold of that knowlegde tough) I would suggest, that what they do is simply creating a second label with the Imageview in place and then fading the first one (text only) out while fading the second one (containing text and image) at the same time..
not sure if this helps you, but I hope so.

cheers
TGiF sam

A: Use UIWebView, the readjustment you are talking about is html basic property, download your content in html format or make a html file programmatic once you download text and image and show them in UIWebView.


text:
Q: Entity Framework Core Find and Composite Key The Find() method takes an array of objects describing the primary key you're attempting to find. The documentation is unclear as to how to handle composite primary keys. I tried searching the GitHub repository, but was unable to find the source code for the Finder.Find() method.
For example, I've used the fluent API to define the following composite primary key:
modelBuilder.Entity<Article>()
    .HasKey( x => new { x.CommunityID, x.ArticleID } );

Do I call Find() like this:
Find( new object[] {1, 2} );

or like this:
Find( new object[] { new {CommunityID = 1, ArticleID = 2} } );

If it's the first approach, is the order of the parameters the same as the order of properties defined on the fluent API anonymous object?

A: Find has a signature of: params object[] keyValues
No need to pass in an array, just each key separately:
.Find(1, 2);

If it's the first approach, is the order of the parameters the same as
  the order of properties defined on the fluent API anonymous object?

Yes, you'll need to pass in the PKs in the same order as defined within your fluent API map.


text:
Q: Defining second font-lock-comment-face in Emacs Is it possible to define a second comment face and comment-start indicator in Emacs such that the second comment highlight appears even if called from within the first comment-face?
I currently have a custom Emacs mode with the following:
.emacs file::
(set-face-attribute 'font-lock-comment-face nil :foreground "gray70")
custom_mode.el::
(set (make-local-variable 'comment-start) "//")
Is it possible to add:
.emacs file::
(set-face-attribute 'font-lock-comment-face nil :foreground "gray70")
(set-face-attribute 'font-lock-comment2-face nil :foreground "forestgreen")
custom_mode.el::
(set (make-local-variable 'comment-start) "//")
(set (make-local-variable 'comment2-start) "||")
such that the line
//Test comment: ||Second test comment
is rendered in two colors?
Would I need to define 'comment2' elsewhere?
Thanks!

A: Coloring comments is generally handled by font-lock referring to the mode's syntax table, this only supports one face for comments.
You can however, specify a regexp for font-lock to force highlight in any color you want, this way we can specify a regexp that matches "//" followed by text, followed by "||" followed by more text, and have font-lock highlight the "||" and the following text only.
Here is a basic implementation of this in a major mode.
;; your custom face to color secondary comments blue
(defface my-second-comment-face '((t (:foreground "blue"))) "its a face")

(define-derived-mode testy-mode fundamental-mode
  "test"
  (modify-syntax-entry ?/ "<1")
  (modify-syntax-entry ?/ "<2")
  (modify-syntax-entry 10 ">")
  (font-lock-add-keywords
   'testy-mode
   ;; this highlights || followed by anything to the end of the line as long as there is
   ;; a // before it on the same line.
   ;; the 2 means only highlight the second regexp group, and the t means highlight it
   ;; even if it has been highlighted already, which is should have been.
   '(("\\(//.*\\)\\(||.*$\\)" 2 'my-second-comment-face t))))

You should note that this is a basic solution that doesn't handle all cases. A normal case like
foobar // comment || more comments

will be handled correctly, but something like
foobar "string//string" || text

will not work correctly, the || text will be highlighted even though // occurs in a string

If you want fontification of these secondary comments to be "smarter" you will need to look into more advanced techniques for fontification. You use a hook in jit-lock-functions to do this. In your jit lock function, you would need to scan for the ||text pattern and highlight it based on whether or not it is already in a comment which you can find out with syntax-ppss assuming your syntax table is set up correctly.


text:
Q: Add dictionary to a file python Let's say I have a dictionary and write it to a file, how could I extend another dictionary or a key-value pair to the existing dictionary in the file?
For example: {'a':1, 'b':2} is already in my file, but, I want to add another dictionary {'d':4, 'e':5} to the existing dictionary and make it like {'a':1,'b':2,'c':3,'d':4} instead of {'a':1, 'b':2}{'d':4, 'e':5} in the file. Thank you so much!

A: Hi this is your solution :
x = {"a": 1, "b": 2}
y = {"c": 3, "d": 4}
z = {**x, **y}


text:
Q: Why can't I convert this string into an integer? No mater how I try this I keep getting the same error I need to get a user input using the JOptionPane and then convert it to an integer.
This is my code
import javax.swing.JOptionPane; // Imports JOptionPane class.

public class MailOrderEMH {
    public static void main(String[] args) {
        // Declare string variables
        String title;
        String firstName;
        String lastName;
        String streetAddress;
        String city;
        String state;
        String zip;
        int numBoxes;
        int count = 1;
        String enterAnother = "Y"; //INITILIZE the loop control variable

        //Conver srring to integer
        numBoxes = Integer.parseInt(JOptionPane.showInputDialog("Enter Number of Boxes: "));

        //get input values from user
        title = JOptionPane.showInputDialog("What is your title ex. (Ms. Mr. Dr.) ");

        //get input values from user
        firstName = JOptionPane.showInputDialog("Enter First Name: ");

        //get input values from user
        lastName = JOptionPane.showInputDialog("Enter Last Name: ");

        //get input values from user
        streetAddress = JOptionPane.showInputDialog("Enter Street Address: ");

        //get input values from user
        city = JOptionPane.showInputDialog("Enter City: ");

        //get input values from user
        state = JOptionPane.showInputDialog("Enter State: ");

        //get input values from user
        zip = JOptionPane.showInputDialog("Enter Zip Code: ");

        while (count <= numBoxes) {
            System.out.println(title + firstName + lastName);
            System.out.println(streetAddress);
            System.out.println(city + state + zip);
            System.out.println("Box" + count + "of" + numBoxes);
            count = count + 1;
        }
        //get input values from user
        enterAnother = JOptionPane.showInputDialog(" Do you want to produce more labels? Y or N ");

        while (enterAnother.equal("Y" || "y")) {
            //get input values from user
            title = JOptionPane.showInputDialog("What is your title ex. (Ms. Mr. Dr.) ");

            //get input values from user
            firstName = JOptionPane.showInputDialog("Enter First Name: ");

            //get input values from user
            lastName = JOptionPane.showInputDialog("Enter Last Name: ");

            //get input values from user
            streetAddress = JOptionPane.showInputDialog("Enter Street Address: ");

            //get input values from user
            city = JOptionPane.showInputDialog("Enter City: ");

            //get input values from user
            state = JOptionPane.showInputDialog("Enter State: ");

            //get input values from user
            zip = JOptionPane.showInputDialog("Enter Zip Code: ");

            //get input values from user
            numBoxes = JOptionPane.showInputDialog("Enter Number of Boxes: ");
        }
        // End program.
        System.exit(0);
    }
}

And this is the error
error: incompatible types: String cannot be converted to int
            ( "Enter Number of Boxes: " );

A: What is this in while statement enterAnother.equal("Y" || "y") ?
It must be
while (enterAnother.equals("Y") || enterAnother.equals("y"))

And in this line
numBoxes = JOptionPane.showInputDialog
                    ( "Enter Number of Boxes: " );

You are trying to convert String to int. You need to use parseInt this way
numBoxes = Integer.parseInt(JOptionPane.showInputDialog
                ( "Enter Number of Boxes: " ));


text:
Q: Warping Image having Lat Lon Geolocation array I'm trying to implement a script to project an image having the two matrices of Lat and Lon points. I've followed the steps proposed in:
Unable to warp HDF5 files
and everything is fine. I create the three .vrt files and than by using:
gdalwarp -geoloc -t_srs EPSG:4326 img.vrt output.tif

the final image is correctly projected.
Also, just for visualization purposes the following code does is job:
plt.pcolormesh(lon,lat,img, cmap='rainbow')
plt.show()

Now, I want to create a script without having to create the .vrt files every time. So I started following Writing numpy array to raster file
but I'm not able to obtain the desired projection (Actually, the output image is similar to the input one, just horizontally translate of some pixels). Here is the key part of code:
ny = img.shape[0]
nx = img.shape[1]

xmin, ymin, xmax, ymax = [lon.min(), lat.min(), lon.max(), lat.max()]
xres = (xmax - xmin) / float(nx)
yres = (ymax - ymin) / float(ny)
geotransform = (xmin, xres, 0, ymin, 0, -yres)

# create the 1-band raster file
dst_ds = gdal.GetDriverByName('GTiff').Create('myGeoTIFF.tif', ny, nx, 1, gdal.GDT_Byte)

dst_ds.SetGeoTransform(geotransform)    # specify coords
srs = osr.SpatialReference()            # establish encoding
srs.ImportFromEPSG(4326)                # WGS84 lat/long
dst_ds.SetProjection(srs.ExportToWkt()) # export coords to file

dst_ds.GetRasterBand(1).WriteArray(img)   # write r-band to the raster
dst_ds.FlushCache()                     # write to disk

dst_ds = None

I think I'm missing something when I create the geotransform matrix because in this way I introduce only one corner of the image without giving any info about the transformation.
How do I solve the problem?


text:
Q: Python multithreading pyshark Im new to python and I'm testing the library pyshark.
I want to sniff the traffic all the time and do other things. But when I start the sniffer, all other code stop working. I've tried asyincio thread and multithreading, but it always give me different errors.
This the code that I want to run without blocking the application.
import pyshark
import asyncio

class Sniffer:

    @staticmethod
    @asyncio.coroutine
    def sniff():
        cap = pyshark.LiveCapture(interface='en0')
        cap.sniff_continuously(packet_count=0)
        for pkt in cap:
            print(pkt)

Thanks in advice.

A: You can try multi-threading class.
https://docs.python.org/3/library/threading.html
For example :
import thread
obj = Sniffer()
thread.start_new_thread( obj.sniff,)

Another way if you tired to multi threading or someone else, create new python file and import your sniffer.
For example :
# new python file
import sniffer
obj = sniffer.Sniffer()
while True:
    obj.sniff()

Thi way use your processor cores. This is as multi thread with little difference, your operating system make this work automatically.


text:
Q: Как можно объединить git - репозиторий r2 и r3 внутри r1 с коммитами и т.д.? Структура папок:
r1 /
  .git
      r2/
         .git
          main.cpp
      r3/
         .git
          main1.cpp

Мне нужно объединить репозиторий r2 и r3 внутри r1 чтобы все коммити и истории перемешались
Я хочу, чтобы папки оставались на своих местах, а все истории и коммиты были объединены
точнее, здесь я клонировал репозиторий r2 и r3 внутри r1
, а затем опубликовал
Но потом не смог открыт репозиторию r2 и r3 внутри github
Там папка отображается, но открывается

A: Есть такая утилита git filter-repo, официально рекомендованная авторами git.
Позволяет переписать историю в репозитории по указанным правилам. В частности, можно перенести во всех коммитах все файлы из корня репозитория в подпапку.
Выполняете такое действие с репозиториями r2 и r3.
Далее у r1 подключаете и r2 и r3 как remote, делаете из обоих fetch, и межите их master'а в master r1.
Готово.
PS конкретные команды не привожу, так как в разных ОС (Win, Linux) они будут сильно отличаться мелкими деталями типа кавычек, слэшей и т.д.


text:
Q: Sync through openIDM without using an Active Directory plugin? I am setting up an OpenIDM server that syncs data between an OpenDJ store which is managed by my company and an Active Directory store that is going to be managed by a client-company.
The goal is to not require anything to be installed to the Client's AD instance. This works fine for the most part, but I cannot get the passwords to synch between the two.
I found the guide for password syncing, but that requires an Active Directory plugin (and an OpenDJ one, but that's not such a problem).
Is it possible to set up a system where we can store a user account's password in the OpenDJ store through OpenIDM without needing such a plugin?
It would be acceptable if we can't change the password, only read it, but we need the password in order to set up logging in via OpenAM.

A: Passwords which are changed directly in AD are hashed, and therefore unrecoverable as cleartext. The only way you would be able to get the cleartext password from AD (in order to provision it elsewhere) is by involving some other system before it is hashed. For example, installing the AD Password Plugin on the AD server will intercept the change event and send the cleartext password to OpenIDM (via REST). Similarly you could ask the users to change their password via the OpenIDM UI instead of directly against AD.
Short of either of those options, you would likely have to come up with an alternate architecture that does not rely upon having the password copied to different systems; essentially, you could delegate authentication to AD when needed, leaving the password in that one location. OpenAM should be able to support such a scheme.


text:
Q: Pipelines -> Runs -> Run pipeline howto provide pipeline resource in request body I have a parent pipeline which publish pipeline artifacts.
And the child pipeline which has a parent pipeline added as a resource pipeline and consumes the parent's artifacts.
I would like to programatically (by REST API) create a run of  multistage child pipeline and provide the parent pipeline resource.
How to craft a request body for pipelines' run endpoint?
According to ms docs PipelineResourceParameters contains only version? Are there any examples how to use it?
Is it a resource name and buildnumber?
https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run%20pipeline?view=azure-devops-rest-6.1#pipelineresourceparameters
Where can I find any examples of requests bodies?

A: The pipeline resource is set in advance in the pipelines. By default, the pipeline will select last successful run as the resource. We can choose the pipeline resource version when we run the pipeline.

Here is my request body sample:
{
  "resources":{
        "pipelines":{
            "Parent":{
                "version":"20201225.1"
            }
        }
    }
}

If you want to find the sample of Rest API, in addition to referring to the examples in the official documentation, you can also check the developer tool (F12) in the browser. For example, run a pipeline manually and check the rest api:


text:
Q: Jest - mocking zlib function which is wrapped in promisify does not work I'm trying to test a file which uses zlib which is wrapped in promisify but when the test reaches the line in the code which uses zlib I get a jest timeout error.
: Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Error:
Module file:
import zlib from 'zlib';
import util from 'util';
const zlibGunzip = util.promisify(zlib.gunzip);

async function unzipObjectContent(objectBody): Promise<string> {
    const buff = objectBody as Buffer;

    try {
      const data = await zlibGunzip(buff);
      const utf8String = data.toString('utf8');
      const parsedJson = JSON.parse(utf8String);

      return JSON.stringify(parsedJson);
    } catch (error) {
      logger.error(`unzipObjectContent -> failed to unzip file ${error}`);
      throw error;
    }
  }

Test File
jest.mock('zlib');
import zlib from 'zlib';

let gunzipMock: jest.SpyInstance;
gunzipMock = jest.spyOn(zlib, 'gunzip');
gunzipMock.mockResolvedValue(JSON.stringify(problemZipContent));

When I debug the test, I see that it reaches the call to await zlibGunzip(buff); but then an error is thrown. It does not reaches the catch block either.
Please advise on how can I test this.
Thank you

A: Mock the zlib.gunzip() method and its implementation, since the second argument of this method is a Node.js error-first callback, you need to call the callback function manually in your test. So that the promise returned from util.promisify(zlib.gunzip) will be resolved.
E.g.
index.ts:
import zlib from 'zlib';
import util from 'util';

const zlibGunzip = util.promisify(zlib.gunzip);

export async function unzipObjectContent(objectBody): Promise<string> {
  const buff = objectBody as Buffer;

  try {
    const data = await zlibGunzip(buff);
    const utf8String = data.toString('utf8');
    const parsedJson = JSON.parse(utf8String);

    return JSON.stringify(parsedJson);
  } catch (error) {
    console.error(`unzipObjectContent -> failed to unzip file ${error}`);
    throw error;
  }
}

index.test.ts:
import zlib from 'zlib';
import { unzipObjectContent } from './';
import { mocked } from 'ts-jest/utils';

jest.mock('zlib');

const mzlib = mocked(zlib);

describe('67475685', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    const problemZipContent = Buffer.from(JSON.stringify({ name: 'teresa teng' }));
    mzlib.gunzip.mockImplementationOnce((buffer, callback: any) => {
      callback(null, problemZipContent);
    });
    const actual = await unzipObjectContent(problemZipContent);
    expect(actual).toEqual('{"name":"teresa teng"}');
    expect(mzlib.gunzip).toBeCalledTimes(1);
  });
});

test result:
 PASS  examples/67475685/index.test.ts (7.156 s)
  67475685
    ✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |   83.33 |      100 |     100 |   83.33 |
 index.ts |   83.33 |      100 |     100 |   83.33 | 16-17
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.656 s, estimated 8 s


text:
Q: I have a table with 2 columns where the second one contains 2 cells in an excel file and i want to convert it to a dictionary using Python the table
I want to obtain the following dictioanary :
{S1: 1,2 , S[2]: 1,3 , S[3]:2,3 , S[4]: 1,2 , S[5] : 1,3}


text:
Q: How to Create Separate Folder in iOS swift 3 I am implementing an native iOS app. I am capturing images and videos by using the custom camera and stored into Photos in iPhone but I need to save in seperate single  folder for images and videos. And also I need to set a password for that folder through my App.Can anyone guide me for do this task?

A: var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let docDirectory: String = paths[0] as? String ?? ""
    // Get documents folder
let dataPath: String = URL(fileURLWithPath: docDirectory).appendingPathComponent("/yourFolder").absoluteString
if !FileManager.default.fileExists(atPath: dataPath) {
       try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
  }


text:
Q: How to print dict string I'm trying to print my string from a raw input with brackets.
Here is my code.
words = (raw_input('Please enter a string:  '))

names = list(words)
print names

I'm getting this:
['H', 'e', 'l', 'l', 'o']

I only need like this:
[Hello]

A: You dont need list , just use format or %s :
words = raw_input('Please enter a string: ')

names = '[{}]'.format(words) # or '[%s]'%words
print names

and if the user write more than one word you can first split the input and print it (Note that you need to be sure that there are space between them ):
print words.split()

A: words is a string and can be considered as a list of characters.
list(words) changes the string into a list of it's characters.
If what you want is a list with only one element (the string), make a list with that element:
>>> words = "This is a Test."
>>> names = [words]
>>> print names
['This is a Test.']

If what you want is a list of every words in the string, split the string:
>>> words = "This is a Test."
>>> names = words.split()
>>> print names
['This', 'is', 'a', 'Test.']

.split() splits the string at every space to make a list of strings.
EDIT: I just understood you wanted the string printed between brackets and without the quotes, Kasra's format string is good then.

A: Try using:

words = (raw_input('Please enter a string:  '))
names = []
names.append(words)

A: >>> words = []
>>> words.append(raw_input('enter the code: '))
enter the code: vis
>>> words
['vis']


text:
Q: Why OnChange event is not getting fired upon changing a cell value in database table? I have been working on this code for the last 24 hours but it ain't working.
I want the OnChange event to get hit If I modify a cell in Services table but it doesn't, no matter what I do.
I have enabled the services broker on the database but still, it doesn't work.
Code:
class Program
    {
        static void Main(string[] args)
        {
            var cs = Utility.getConnectionString();
            using (SqlConnection connection = new SqlConnection(cs))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(@"Select [Services].[ServiceName], [Services].[ServicePrice] from dbo.Services", connection);
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(OnChange);
                SqlDependency.Start(cs);
                command.ExecuteReader().Dispose();
            }
            Console.ReadKey();
        }

        private static void OnChange(object sender, SqlNotificationEventArgs e)
        {
            Console.WriteLine(e.Info);
        }
    }

Making changes to the db using edit more or update query.
enter image description here

A: Below is a worked example based on your code that displays SqlNotificationEventArgs values when the event is fired and re-subscribes only when valid.
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{

    static void Main(string[] args)
    {

        SqlDependency.Start(Utility.getConnectionString());

        GetDataWithSqlDependency();
        Console.WriteLine("Waiting for data changes");
        Console.WriteLine("Press any key to quit");
        Console.ReadKey();

        SqlDependency.Stop(Utility.getConnectionString());

    }

    static void GetDataWithSqlDependency()
    {

        using (var connection = new SqlConnection(Utility.getConnectionString()))
        using (var cmd = new SqlCommand(@"SELECT [Services].[ServiceName], [Services].[ServicePrice] from dbo.Services;", connection))
        {
            var dependency = new SqlDependency(cmd);
            dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
            connection.Open();
            cmd.ExecuteReader().Dispose();
        }

    }
    static void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {

        Console.WriteLine($"OnDependencyChange Event fired. SqlNotificationEventArgs: Info={e.Info}, Source={e.Source}, Type={e.Type}");

        if ((e.Info != SqlNotificationInfo.Invalid)
            && (e.Type != SqlNotificationType.Subscribe))
        {
            SqlDependency.Start(Utility.getConnectionString());
            GetDataWithSqlDependency();
            Console.WriteLine($"Data changed.");
        }
        else
        {
            Console.WriteLine("SqlDependency not restarted");
        }

    }

}

static class Utility
{
    public static string getConnectionString()
    {
        return @"Data Source=.;Initial Catalog=YourDatabase;Application Name=SqlDependencyExample;Integrated Security=SSPI";
    }

}

This is DDL for the test database:
CREATE DATABASE YourDatabase;
GO
ALTER DATABASE YourDatabase SET ENABLE_BROKER;
GO
USE YourDatabase;
GO
CREATE TABLE dbo.Services(
      ServiceName varchar(100) NOT NULL
        CONSTRAINT PK_Services PRIMARY KEY
    , ServicePrice decimal(10,2) NOT NULL
);
GO

These queries fire the OnChanged event:
INSERT INTO dbo.Services VALUES('SomeService', 1.00);
GO
UPDATE dbo.Services SET ServicePrice = 2.00 WHERE ServiceName = 'SomeService';
GO
DELETE FROM dbo.Services WHERE ServiceName = 'SomeService';
GO

EDIT:
If you run your application using a minimally privileged account (a best practice), below is an example script to grant the minimum permissions needed for SqlDependency.
--create user for schema ownership
CREATE USER SqlDependencySchemaOwner WITHOUT LOGIN;
GO
--create schema for SqlDependency objects
CREATE SCHEMA SqlDependency AUTHORIZATION SqlDependencySchemaOwner;
GO

--add existing login as a minimally privileged database user with default schema SqlDependency
CREATE USER YourLogin WITH DEFAULT_SCHEMA = SqlDependency;

--grant user control permissions on SqlDependency schema
GRANT CONTROL ON SCHEMA::SqlDependency TO YourLogin;

--grant user impersonate permissions on SqlDependency schema owner
GRANT IMPERSONATE ON USER::SqlDependencySchemaOwner TO YourLogin;
GO

--grant database permissions needed to create and use SqlDependency objects
GRANT CREATE PROCEDURE TO YourLogin;
GRANT CREATE QUEUE TO YourLogin;
GRANT CREATE SERVICE TO YourLogin;
GRANT REFERENCES ON
    CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO YourLogin;
GRANT VIEW DEFINITION TO YourLogin;
GRANT SELECT to YourLogin;
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO YourLogin;
GRANT RECEIVE ON QueryNotificationErrorsQueue TO YourLogin;
GO

--grant permissions on user objects used by application
GRANT SELECT ON dbo.Services TO YourLogin;
GO

A: Done.
It was only because I haven't been using sa as a login. Only I changed my database to sa and used that in the connection string. It worked.
Discussion:
Question
it could be from the dbo being mapped to a Windows account that sometimes is invalid. 'dbo' really is the user that created the database. This problem happen for instance if I create the sample on the SQL instance on my laptop at work, then I go home and continue from home. At home I don't have access to the domain ActiveDirectory and the samples sudenly stop working because 'dbo' is realy my Windows account and is no longer available. Messages (like notifications) sent by 'dbo' sit in sys.transmissions_queue with a status complaining 'Could not retrieve info about user '...' from the domain controller'. Running EXECUTE AS USER='dbo' in the database also shows the same error happening. The fix in this case is to change 'dbo' to a login that is valid, e.g.  by running ALTER AUTHORIZATION ON DATABASE::[dbname] TO [sa];

A:   using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();

            SqlDependency.Start(connectionString);

            string commandText = "select ID, status from dbo.VendorSetup";

            SqlCommand cmd = new SqlCommand(commandText, conn);

            SqlDependency dependency = new SqlDependency(cmd);

            dependency.OnChange += new OnChangeEventHandler(dbChangeNotification);

            var reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                var employee = new VendorSetup
                {
                    ID = Convert.ToInt32(reader["ID"]),
                    status = reader["status"].ToString(),
                    //Age = Convert.ToInt32(reader["Age"])
                };

                employees.Add(employee);
            }
        }

        return employees;
    }

    private void dbChangeNotification(object sender, SqlNotificationEventArgs e)
    {
        _hubcontext.Clients.All.SendAsync("displayNotification");
    }


text:
Q: Calling the same function within the function #include<stdio.h>
int slogan();
int main()
{
    slogan(slogan());
    return 0;
}
int slogan()
{
    printf("onlyme\n");
}

My doubt is, the slogan function has no argument list in its prototype, then how come it        accepts the function call as its argument?

A: In c the empty parameter list does not mean function that takes no arguments. It means function with unspecified number of arguments
To declare a function that takes no arguments write :
int func(void);

A: Because in C,
int slogan();

declares a function without saying anything about its arguments. This is not a prototype declaration at all, it's an old-style K&R declaration. The prototype declaration for a function taking to arguments is
int slogan(void);

The former form exists for backward compability with pre-1989 C, when you couldn't provide argument information in the prototype at all.

A: Look at First answer here(and second)
The first answer will give you an Accurate explanation of a functions declaration
Section 6.11.6 Function declarators(K&R C)

The use of function declarators with empty parentheses (not
  prototype-format parameter type declarators) is an obsolescent
  feature.


text:
Q: Как найти все теги по вхождению в название класса с помощью BeautifulSoup Python? Дана структура:

Как можно с помощью BeautifulSoup найти все теги td у которых в названии класса есть '1234_', далее внутри них найти тег  у него уже достать имя атрибута eu
soup.find_all('td', class_='?')find('span').get('eu')

A: from bs4 import BeautifulSoup
import re

html_doc = """

	"""

soup = BeautifulSoup(html_doc, 'html.parser')

links = [item['eu'] for item in soup.findAll('td', attrs={'class':re.compile("1234_")})]

for i in links:
    print(i)


text:
Q: Can I create single instance of Get.find<>()? Currently to display value from controller I am using next construction:
Get.find<XMLFilesStatController>().foo.value,
Get.find<XMLFilesStatController>().bar.value,
Get.find<XMLFilesStatController>().baz.value,

Can I create in class single instance that point to Get.find<XMLFilesStatController>() ?
Something like:
var xmlCtrl = Get.find<XMLFilesStatController>();
and then use it as: xmlCtrl.foo?
I tried to do it like:
class XMLProcessingStatisticView extends StatelessWidget {
  var formKey = GlobalKey<FormState>();

  var xmlCtrl = Get.find<XMLFilesStatController>();

On main.dart I am creating:
main() {
  //....
  Get.lazyPut<XMLFilesStatController>(() => XMLFilesStatController());

  runApp(MyApp());
}

So instance XMLFilesStatController is initialized. But I need way to shortcut Get.find
But got an error:
errors.dart:202 Uncaught (in promise) Error: "XMLFilesStatController" not found. You need to call "Get.put(XMLFilesStatController())" or "Get.lazyPut(()=>XMLFilesStatController())"

A: You need to use Get.put(XMLFilesStatController()) or Get.lazyPut(()=>XMLFilesStatController()) at first. Then you can create your object by calling var xmlCtrl = Get.find<XMLFilesStatController>(); .
If you want your XMLFilesStatController object to be permanent i.e. you want to create the object for only one time and use it for whole app lifecycle, then you need to do this Get.put(XMLFilesStatController(),permanent=true)

A: You can do exactly what you described, but your problem is that you haven't instantiated XMLFilesStatController yet. You first have to use Get.put(XMLFilesStatController()); or Get.lazyPut(()=>XMLFilesStatController());.
After that you can just use var xmlCtrl = Get.find<XMLFilesStatController>(); like you said.
Take a look at dependency management.


text:
Q: text in table cell wrap 1st picture is the expected way in a table cell, 2nd picture is the failed outcome using the following table rules. 1st picture's table cell items can be written in two lines, but in the 2nd picture it cannot make two or three lines, please help me to modify the rules to make the 2nd one as 1st one, Thank you very much
    \sisetup{table-format=4.2(3),
             separate-uncertainty}
    \small
    \setlength\tabcolsep{0pt}
\begin{threeparttable}
    \caption{}
    \label{tbl:Filt res polymer}
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}>{$}l<{$} *{6}{S} }
    \toprule
\textbf{Year}
    &{\textbf{{Permissioned
lottery-based}}}
            & \mcc[3]{\textbf{CMC}}          \\
    \cmidrule{2-3}
    \cmidrule(l){4-5}
    \cmidrule(l){6-7}
% \textbf{[ppb]}
    & \mcc{\textbf{1.05}}
        & \mcc{\textbf{2.10}}
            & \mcc{\textbf{0.525}}
                & \mcc{\textbf{1.05}}
                    & \mcc{\textbf{2.10}} \\
    \midrule

    \bottomrule

\end{tabular*}
\begin{tablenotes}[]\small
\item[*]
\end{tablenotes}
\end{threeparttable}
\end{table*}

A: I guessing that you like to obtain the following table design:

With  tabularray package you can simply split text in cel into two lines by
{first line\\ second line}

In MWE below is used recent version (2022B) of package which enable with option guard simple writing of `S column headers.
\documentclass{article}
\usepackage{tabularray}
\UseTblrLibrary{booktabs, siunitx}

\begin{document}
\begin{table}
    \sisetup{table-format=4.2(2),
             minimum-decimal-digits = 2,
             separate-uncertainty,
             tight-spacing}
    \small
    \setlength\tabcolsep{0pt}
\begin{talltblr}[
caption = {caption},
  label = {tbl:Filt res polymer},
remark{Sorce} = {Annual report \dots}
                ]{colsep=3pt,
                  colspec = {@{} l *{6}{Q[c, m, si]} @{}},
                 row{1,2} = {font=\bfseries, guard},
                 }
    \toprule
 \SetCell[r=2]{c} Year
    & \SetCell[c=2]{c} {Permissioned\\ lottery-based}
            &       & \SetCell[c=2]{c}  CMC
                            &       & \SetCell[c=2]{c}  ???
                                            &   \\
    \cmidrule[lr]{2-3}
    \cmidrule[lr]{4-5}
    \cmidrule[l]{6-7}
    & 1.05  & 2.1   & 0.525 & 1.05  & 2.10  & ? \\
    \midrule
2021
    & 1234.56(7)
            & 234.56(1)
                    & 34.56(2)
                            & 4.56(3)
                                    & 5432.1(6)
                                            & 432.1(8)        \\
2022
     & 432.1(8)
            & 5432.1(6)
                    & 4.56(3)
                            & 34.56(2)
                                    & 234.56(1)
                                           & 1234.56(7)     \\
   \bottomrule
\end{talltblr}
\end{table}
\end{document}


text:
Q: Countdown timer for different time zones I need to develop a countdown timer hour for the company offices:
One office is in Brazil and the other is in Japan
Brazil = UTC-03:00
JAPAN = UTC+09:00
Both offices open at 8 AM and closes 8 PM, when Brazilian office is opening, the Japanese office is closing.
How can i configure to a japanese see the brazilian office closed and japanese office open and vice versa
Follow the link: http://lickslegal.webflow.io/teste/relogio
My javascript code:
function getTimeRemaining(endtime){

  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(endtime, clock_location, status, add_class, remove_class){

  clock_location.find('.relogio_status').removeClass(remove_class);
  clock_location.find('.relogio_status').addClass(add_class);

  var timeinterval = setInterval(function(){
    var t = getTimeRemaining(endtime);

    var show_message = ' '+status+' in ';

    if (t.days > 0) {
        show_message += t.days+" d ";
    }

    show_message += (t.hours < 10 ? '0':'')+t.hours+":"+(t.minutes < 10 ? '0':'')+t.minutes+":"+(t.seconds < 10 ? '0':'')+t.seconds;

    clock_location.find('.status_clock_text').html(show_message);

    if(t.total==0){
      // clearInterval(timeinterval);
      // location.reload();
      clock_city('rio_de_janeiro');
    }
  },1000);
}

function when_monday(){
    var will_monday = new Date();
    will_monday.setDate(will_monday.getDate() + (1 + 7 - will_monday.getDay()) % 7);

    return {
        'year': will_monday.getFullYear(),
        'month': (will_monday.getMonth() +1),
        'date': will_monday.getDate(),
        'full': will_monday,
        'open_or_close': will_monday.getFullYear()+"-"+(will_monday.getMonth() +1)+"-"+will_monday.getDate()
    };
}

function go_tomorrow(){
    var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

    return {
        'year': tomorrow.getFullYear(),
        'month': (tomorrow.getMonth() +1),
        'date': tomorrow.getDate(),
        'full': tomorrow,
        'open_or_close': tomorrow.getFullYear()+"-"+(tomorrow.getMonth() +1)+"-"+tomorrow.getDate()
    };
}

function clock_city(city_id){
    var today = new Date();

    var y = today.getFullYear();
    var m = (today.getMonth() +1);
    var d = today.getDate();

    var location_city = $("#"+city_id);

    var city_open_time = location_city.find('.open_time').text();
    var city_close_time = location_city.find('.close_time').text();
    var city_close_date = location_city.find('.close_date').text();

    // var city_open_deadline = y+"-"+m+"-"+d+" "+city_open_time;
    var city_close_deadline = y+"-"+m+"-"+d+" "+city_close_time;

    var hora_atual = (today.getHours() < 10 ? '0':'')+today.getHours()+':'+today.getMinutes();

    if (hora_atual >= city_open_time && hora_atual < city_close_time){
        //ABERTO
        console.log('aberto');
        initializeClock(city_close_deadline, location_city, 'closing', 'office_open', 'office_closed');
    }else{
        //FECHADO
        console.log('fechado');

        //Verifica se for SEXTA ou FDS
        if ( (today.getDay() +1) == 6 || today.getDay() == 6 || today.getDay() == 0) {
            var city_open_deadline = when_monday().open_or_close+" "+city_open_time;
        }else{
            var city_open_deadline = go_tomorrow().open_or_close+" "+city_open_time;
        }
        initializeClock(city_open_deadline, location_city, 'opening', 'office_closed', 'office_open');
    }
}

$(document).ready(function() {
    clock_city('rio_de_janeiro');
    clock_city('tokyo');
});

A: Part of the problem is your site says the Brazil office hours are from 08:00 to 20:00 and the Japan office hours are from 08:00 to 20:00. Neither of these ranges is correct. Brazil office hours are 11:00 to 23:00 and Japan office hours are 23:00 to 11:00. As a general rule, use UTC everywhere except the final display.
new Date() generates a Date object holding the current date, in UTC. With your reference times also in UTC, no conversion is needed to find the time remaining. Since you don't actually care about dates, only durations, you don't need to make any timezone adjustments for the output.

A: The UTC offset can be added to the current UTC date and time:

console.log( 'Z+0:',           new Date            )  // current UTC time
console.log( 'Z-3:', new Date( new Date -3 * 36e5) )  // current UTC time minus 3 hours
console.log( 'Z+8:', new Date(+new Date +8 * 36e5) )  // + used to convert to number

console.log( 'Tests:' )
console.log( 'Z+0:',           new Date(0)            )  // "1970-01-01T00:00:00.000Z"
console.log( 'Z-3:', new Date( new Date(0) -3 * 36e5) )  // "1969-12-31T21:00:00.000Z"
console.log( 'Z+8:', new Date(+new Date(0) +8 * 36e5) )  // "1970-01-01T08:00:00.000Z"


text:
Q: ionic2 can not build due to cross walk plugin After 3 days of struggling , I am not able to install ionic2. Actually it works for androids with version 4.4.2  and above (in versions less than this, shows a blank screen, a common problem in forum or github issue part). For working in android ex. 4.2.1 , I found out that I should install cross walk plugin. But after that, my app didn't build anymore.
I found different solutions, like this or this one. But again, the same errors.
My error while running: ionic build android :
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_armv7DebugCompile'.
   > Could not resolve org.xwalk:xwalk_core_library:16+.
     Required by:
         :android:unspecified
      > Could not resolve org.xwalk:xwalk_core_library:16+.
         > Failed to list versions for org.xwalk:xwalk_core_library.
            > Unable to load Maven meta-data from https://jcenter.bintray.com/or
g/xwalk/xwalk_core_library/maven-metadata.xml.
               > Could not GET 'https://jcenter.bintray.com/org/xwalk/xwalk_core
_library/maven-metadata.xml'.
                  > Connect to jcenter.bintray.com:443 [jcenter.bintray.com/5.15
3.35.248] failed: Connection timed out: connect

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug

BUILD FAILED

Total time: 27.432 secs

 option to get more log output.

Error: cmd: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_armv7DebugCompile'.
   > Could not resolve org.xwalk:xwalk_core_library:16+.
     Required by:
         :android:unspecified
      > Could not resolve org.xwalk:xwalk_core_library:16+.
         > Failed to list versions for org.xwalk:xwalk_core_library.
            > Unable to load Maven meta-data from https://jcenter.bintray.com/or
g/xwalk/xwalk_core_library/maven-metadata.xml.
               > Could not GET 'https://jcenter.bintray.com/org/xwalk/xwalk_core
_library/maven-metadata.xml'.
                  > Connect to jcenter.bintray.com:443 [jcenter.bintray.com/5.15
3.35.248] failed: Connection timed out: connect

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.

Any idea?
And  one more question. Why ionic2 doesn't support android less than version 4.4.2 ?


text:
Q: application.yml number property is changed My application.yml looks like this:
test:
  icode: 0002

But when I get this value:
@Value("${baidu.icode}")
private String icode;

The icode field is 2.0, but I want it to be 0002, what should I do?

A: To make sure that your YAML properties will stay exactly the same, just wrap them in quotation marks:
test:
  icode: "0002"


text:
Q: Need help with stacking my website design I'm having one of those pull-my-hair-out moments that has become an all consuming obsession at work and I can't figure it out for the life of me.
I'm working on a site where I have a repeating background image (gradient of blue) and I need to put another image on top of that which goes beneath my "container" div. The large image that I'm having to put the "container" on top of has designs that appear to pop out of the sides.
The trouble that I'm having is this: when the user shrinks the window size, my buttons (that are within the container div) get all jumbled up and go one on top of another when I do this in IE and Firefox. I would like it to stay in the same spot on top of the large image in its spot despite the size of the window.
I think it has to do with absolute position, something that I'm not too familiar with, but I'm wondering if this is possible. I have also never used tables and have just used div tags to create sites. Fairly new at this - just have been designing websites for about a year now.
Help!

A: I am answering this without seeing an example, so bear with me.
It sounds as though the container div does not have a width assigned to it.
Since the container div doesn't have a width, it is shrinking and expanding causing the buttons to jumble up. Also, make sure that your buttons and such are positioned absolutely inside of your container div. Your container div must have position:relative; set in its style in order to absolutely position items inside of it. However, it sounds as though you have your positioning already set accordingly, it is just worth re-mentioning.


text:
Q: implement splitView programmatically in Android I am trying to create a splitView in Android programmatically. This feature is completely new to me. After some research, I realized the Fragment has to be used.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

I am wondering, is the LinearLayout the best option for a layout? Secondly is it possible to add UI parts like buttons, pickers onto the fragment programmatically as well?

A: If you dont want to use fragment layout or building application in lower android version which does not have fragment support, in this case you can get the split view by calling two separate XML files in one activity. Just but build two xml as per requirement on left and right. Small example
LinearLayout layoutMain = new LinearLayout(this);
    layoutMain.setOrientation(LinearLayout.HORIZONTAL);
    setContentView(layoutMain);
    LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    RelativeLayout layoutLeft = (RelativeLayout) inflate.inflate(
        R.layout.firstxml, null);
    RelativeLayout layoutRight = (RelativeLayout) inflate.inflate(
        R.layout.secondxml, null);

RelativeLayout.LayoutParams relParam = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT,
    RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutMain.addView(layoutLeft, 100, 100);
layoutMain.addView(layoutRight, relParam);

}
`

A: You can use any layout with Fragments, totally depends on your requirement.
Yes you can add views like Buttons etc to Fragment programmatically. Declare the layout of the  Fragment to be a Layout.
One example of adding views programmatically --- R.layout.main could be a LinearLayout with no child views
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
    ViewGroup mViewGroup = inflater.inflate(R.layout.main, container, false);
    Button mButton = new Button(getActivity());
    mButton.setLayoutParameters(new LinearLayout.LayoutParams(
                                 LinearLayout.LayoutParams.FILL_PARENT,
                                 LinearLayout.LayoutParams.FILL_PARENT));
    mViewGroup.add(mButton);
}


text:
Q: Writer in a txt file using Spring Batch How to organize writer in a txt file using Spring Batch?
Spring Batch has:

*

*FlatFIleItemWriter

*StaxEventItemWriter

*StoredProcedureItemWriter

*JDBCPagingItemWriter

*MongoItemWriter

but which can I use to write data to txt?

A: A text file is a flat file, so you can use the FlatFileItemWriter. You can implement the LineAggregator interface to write any type of structured or unstructured text. You can find an example in this section: https://docs.spring.io/spring-batch/4.0.x/reference/html/readersAndWriters.html#SimplifiedFileWritingExample


text:
Q: How to save Multiline TextInput value separately in mysql 5 db This is my TextInput:
InputArea
I want to save textInput values separately
const [textInput, setTextInput] = useState('')

      <TextInput
        multiline={true}
        style={allStyles.textInput}
        placeholder="Type Here"
        onChangeText={setTextInput}
        value={textInput}
      />

console.log(textInput);

the input text will be like this:
360-654-3438
309-395-3513
248-277-2718
951-288-7491
770-886-9060
203-332-2145

i want the console log result be like this:
{
    number: 360-654-3438,
    number: 309-395-3513,
    number: 248-277-2718,
    number: 951-288-7491,
    number: 770-886-9060,
    number: 203-332-2145
}

and save them to my database separately by a for loop or something like that.
the rest of the code will be like this:
for (let number of textInput) => {
  axios.post(`[address]/save_numbers?number=${number.number}&account={account.id}`)
}

A: textInput.split("\n").forEach((e) => {
axios.post(`[address]/save_numbers?number=${e}&account={account.id}`)
})


text:
Q: Can I enable "Hey Siri" only when using AirPods? I have "Hey Siri" turned on so I can use my phone hands-free when my AirPods are in (if I'm running, washing dishes, etc.). But I'd prefer not to have it listening all the time.
Is there a way to configure "Hey Siri" so it only listens through AirPods, but is otherwise disabled?

A: It doesn't appear that is a feature that can be enabled only on the AirPods. According to the support page it must be enabled on whatever device (iPhone, Mac, etc) they are connected to to work.
According to Apple all dictation is processed locally on device though they do have a transcript log sent to Apple with a random identifier assigned. This is different than the audio recordings you can opt in allowing in the Analytics & Improvement setting's page. You can delete request history associated by going to Settings > Siri & Search > Siri & Dictation History and tapping Delete Siri & Dictation History.


text:
Q: Stuck adding list selection listener to program I asked a similar question yesterday and while I got some direction I am now stuck. I have a program that contains a GUI with two lists which are side-by-side. The first list (which I will refer to as left) contains a number of items which are parsed from an uploaded file.
The other list (I'll call the right list) is empty by default. The user can use some buttons to transfer items between the two lists. At runtime the items in the right list will be kept and the left list will be discarded. Now I have successfully added a counter that shows dynamically the total count of items for each list.
I had an idea yesterday that I want to add another dynamic counter that will show the user how many items are selected in the left list (but haven't been moved yet). The reason for this is that users may have very large lists (300+ items) and need to move a certain amount (like 50).. Having a counter to show how many items they have currently selected will save them a little time.
I understand to do this I need to use a list selection listener that will have a method to set the text of my JLabel. The problem is I can't figure out the method to get the size of the list.
Here is where my list is created.
input = new DefaultListModel();

Here it is populated with an array of items that was filled during a buffered writer based on the upload file.
String[] inputItems = new String[MainWriter.entryDetails.size()];
inputItems = MainWriter.entryDetails.toArray(inputItems);

for(int i = 0; i < inputItems.length; i++){
            input.addElement(inputItems[i]);
        }

Creating the list:
inputDetails = new JList(output);
        inputDetails.setVisibleRowCount(10);
        inputDetails.setFixedCellHeight(20);
        inputDetails.setFixedCellWidth(400);
        inputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        //Creates a new scroll pane for the inputDetails.
        JScrollPane list2 = new JScrollPane(inputDetails);

Here is my attempt at creating the list selection listener..
inputDetails.addListSelectionListener(new ListSelectionListener(){

            @Override
            public void valueChanged(ListSelectionEvent arg0) {

                selectedCount.setText(inputDetails.);

            }

        });

As you see I'm not sure what the best method would be to set the text to the currently selected items.
I believe that is enough information to illustrate my problem. I want to have the line Selected Items and then dynamically say how many items in the left list the user has highlighted.
Any help would be greatly appreciated.
EDIT:
As suggested I added the following:
inputDetails.addListSelectionListener(new ListSelectionListener(){

            @Override
            public void valueChanged(ListSelectionEvent arg0) {

                String counter = Integer.toString(inputDetails.getSelectedIndices().length);
                selectedCount.setText("Currently Selected Transactions: "+counter);

            }

        });

however the JLabel does not appear to be updating, can someone advise me on the problem?

A: In the listener, selectedCount.getSelectedIndices().length will tell you how many items are currently selected.


text:
Q: How to disable implicit type conversion for Constants? I have the following code snippent:
type ErrorCode string

const (
    INVALID_REQUEST ErrorCode = "INVALID_REQUEST"
)

type Response struct {
    ErrorCode string `json:"errorCode"`
}

func BuildResponseError(errorCode ErrorCode) string {
    user := &Response{ErrorCode: string(errorCode)}
    response, err := json.Marshal(user)
    if err != nil {
        log.Println(err)
        return `{"errorCode":"bad_request"}`
    }

    return string(response)
}

I can call function BuildResponseError like that:
BuildResponseError("wrong_request")

Is there a way to disable this implicit type conversion? I want to call this function only like this, using a enum value:
BuildResponseError(INVALID_REQUEST)

A: You can't disable the possibility to assign a string to a variable of your ErrorCode type since ErrorCode's underlying type is string and according to Go's assignability  rules:

A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:
...

*

*x's type V and T have identical underlying types and at least one of V or T is not a defined type

Source: https://golang.org/ref/spec#Assignability
So that functionality is built-in into the language.
One way to achieve similar functionality (not exactly the same but the closest you can get) would be to define the type like:
type ErrorCode struct {
    Code string
}

And then a variable (you can't define a constant of that type):
var (
    INVALID_REQUEST ErrorCode = ErrorCode{"INVALID_REQUEST"}
)

You should then modify your code, of course, to take the Code from inside that type to build the response:
user := &Response{ErrorCode: errorCode.Code}

That way the function can't be called using a string, only ErrorCode values will be accepted.
Playground: https://play.golang.org/p/qoKrGiJQtxv


text:
Q: How to use AddMenu in Lauterbach while a PRACTICE script loop is running(and blocking) execution? I have created a PRACTICE Lauterbach script in order retrieve certain strings from buffers, from different situations.
I place 4 breakpoints in the different places where I retrieve the buffers from.
I wanted to retrieve the info in a non-blocking way, as if the it was an interrupt service routine. To this end, I made use of the GLOBALON command, as follows:
            GLOBALON PBREAK GOSUB BB_HIT_CALLBACK

And inside the BB_HIT_CALLBACK, I inserted the service routines for each of the 4 breakpoints.
            BB_HIT_CALLBACK:
                IF (sYmbol.EXIST(BREAK_LABEL1))
                 (
                     IF (REGISTER(pc)==ADDRESS.offset(BREAK_LABEL1))
                     (
                         GOSUB ISR1

                     )
                 )
                IF (sYmbol.EXIST(BREAK_LABEL2))
                 (
                     IF (REGISTER(pc)==ADDRESS.offset(BREAK_LABEL2))
                     (
                         GOSUB ISR1

                     )
                 )
                IF (sYmbol.EXIST(BREAK_LABEL3))
                 (
                     IF (REGISTER(pc)==ADDRESS.offset(BREAK_LABEL3))
                     (
                         GOSUB ISR1

                     )
                 )
                IF (sYmbol.EXIST(BREAK_LABEL4))
                 (
                     IF (REGISTER(pc)==ADDRESS.offset(BREAK_LABEL4))
                     (
                         GOSUB ISR1

                     )
                 )
            RETURN

On the other hand, in the normal execution, I placed a simple infinite loop.
                WHILE TRUE()
                (
                    If (!STATE.RUN())
                    (
                      Go
                    )
                )

                ENDDO

This mantains the program in a loop, only broken by the GLOBALON PBREAK command. I wish to be able to have a toolbar button to end the execution of this loop, but while running, the script only responds to the breakpoints, and UI elements are being ignored.
How can I stop the execution of the loop, from a UI element?
I have been able to set read the seconds, and timeout at 60 seconds, but that is not good enough for what I want.

A: It sounds like GLOBALON PBREAK is not the best solution for your problem.
You could use command breakpoints to directly execute any PRACTICE command or script when each breakpoint is hit:
Break.Set BREAK_LABEL1 /CMD "DO your_script.cmm ISR1"
Break.Set BREAK_LABEL2 /CMD "DO your_script.cmm ISR2"
Break.Set BREAK_LABEL3 /CMD "DO your_script.cmm ISR3"
Break.Set BREAK_LABEL4 /CMD "DO your_script.cmm ISR4"

This is also possible with the Break.Set dialog if you click the "advanced" button.
With this setup, your_script.cmm could look like this:
PRIVATE &arg
ENTRY &arg

IF "&arg"!=""
(
    GOSUB &arg
)
ELSE
(
    // script called without arguments -- maybe set the breakpoints here
)

ENDDO

ISR1:
    PRINT "ISR1 reached!"

    // resume execution of core
    Go.direct
    RETURN

// and so on for ISR2 to ISR4

This way, your script would not need to be running at all. You could set up a toolbar button, menu item or even a dialog that starts another script, which in turn stops the core and removes the breakpoints.