text:
Q: Python equivalent for #ifdef DEBUG In C we write code like
#ifdef DEBUG
printf("Some debug log... This could probably be achieved by python logging.Logger");
/* Do some sanity check code */
assert someCondition
/* More complex sanitycheck */
while(list->next){
assert fooCheck(list)
}

#endif

Is there a way to do this in python?
Edit: I got my answer, and more :)
Paolo, Steven Rumbalski and J Sebastian gave me the information I was looking for. Thanks das for the detailed answer, although I'll probably not use a preprocessor right now.
J Sebastian, whose comment got deleted because the answer in which he posted his comment, deleted his answer I think.
He said I could use the isEnabledFor() method in Logger to feed a conditional.
Thanks everyone for your inputs. This is my first question. I wish I could accept paolo, or j sebastian's answers. But since those were offered as comments, I'll accept das' answer.
I will probably use either http://nestedinfiniteloops.wordpress.com/2012/01/15/if-debug-python-flavoured/ or Logger.isEnabledFor()

A: Mohammad's answer is the right approach: use if __debug__.
In fact, Python completely removes the if statement if the expression is a static constant (such as True, False, None, __debug__, 0, and 0.0), making if __debug__ a compile-time directive rather than a runtime check:
>>> def test():
...     if __debug__:
...         return 'debug'
...     return 'not debug'
...
>>> import dis
>>> dis.dis(test)
  3           0 LOAD_CONST               1 ('debug')
              2 RETURN_VALUE

The -O option is explained in detail in the python documentation for command line options, and there is similar optimization for assert statements.
So don't use an external preprocessor—for this purpose, you have one built in!

A: If you are looking for assertions in Python, assert is an actual valid python statement.
http://docs.python.org/2/reference/simple_stmts.html#assert

A: check the result of sys.gettrace() is None. That will mean that there is no debugger
import sys
if sys.gettrace():
    print("debug mode!")
else:
   print("debug mode is off!")

A: Use __debug__ in your code:
if __debug__:
    print 'Debug ON'
else:
    print 'Debug OFF'

Create a script abc.py with the above code and then

*

*Run with python -O abc.py

*Run with python abc.py
Observe the difference.

A: What you are looking for is a preprocessor for python. Generally you have three options:

*

*Write a selfmade script/program which replaces parts of your sourcecode based on certain templates before passing the result on to the interpreter (May be difficult)

*Use a special purpose python preprocessor like pppp - Poor's Python Pre-Processor

*Use a general purpose preprocessor like GPP
I recommend trying pppp first ;)
The main advantage of a preprocessor compared to setting a DEBUG flag and running code if (DEBUG == True) is that conditional checks also cost CPU cycles, so it is better to remove code that does not need to be run (if the python interpreter doesn't do that anyway), instead of skipping it.

A: I use another approach - to test module as standalone/direct running:
import ...

DEBUG = False

....

def main():
    pass

if __name__ == '__main__':
    DEBUG = True
    main()

It gives - flexibility to run as module inside project DEBUG will False, when standalone DEBUG will True.
This suitable for example to load data from local file or from request:
def load_csv():
    fn = get_csv_filename()  # will return path depending DEBUG
    if DEBUG:
        if not exists(fn):
            store_df(request_bond_list(), fn)
        return pd.read_csv(fn)
    return request_bond_list()

It also help me to control a path depending DEBUG mode. As you know when module placed in different directory from a main code the path will be 'module' directory in case we run module as standalone (for tests), but when we implements methods from this module inside 'main' then path will set to root of your project.
So you can use DEBUG to tune the path for different situations
(or you can directly change 'path' in "if __name__ == '__main__':")


text:
Q: Firebase deploy hosting. Others can see the changes but I can't After I build my Angular 5 app and then run
firebase deploy --only hosting

... other people (not within network) can see the proper changes and I am the only one who can't see them.
I am the only developer. I cleared cache on Chrome, opened in private mode, used another browser (Firefox), and nothing.
I can see the changes when I use a VPN. Is this problem related to my IP address? Why does it happen?

A: Most likely you are hitting a node on the CDN that accidentally wasn't clear when you deployed the latest update. This should be really rare.
The simplest fix is to deploy the update again, which will force another purge of all CDN edges. If that doesn't fix it, reach out to Firebase support for personalized help in troubleshooting

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is this a secure method of escaping a SQL query parameter? At my work it used to be tradition to form SQL queries by unsafely concatenating parameters into the query strings. This leads, of course, to SQL injection vulnaribilities. This wasn't considered a huge issue because all of the Java software in which this happens runs on closed networks of which all users are assumed to be trusted. Also, the queries are executed from client-side applications with database access, so a user could technically execute malicious queries anyway.
Nonetheless, it's planned to support prepared statements in the new version of the database layer. In the meantime, I've written a small library on top of the existing database layer (which only supports executing a query from a SQL String, without the option for prepared statements or parameter escaping) that allows writing safe parameterized queries by escaping string parameters.
As part of this library, I've wrote the following method that escapes a String literal. I escape the same characters as PHP's addslashes function, but I try to avoid its multibyte character vulnerability by detecting supplementary (32-bit) characters:
private String escapeString(String str)
{
    List<Character> toEscape = Arrays.asList('\'', '"', '\\', '\0');

    StringBuilder result = new StringBuilder();
    for(int i = 0; i < str.length(); ++i)
    {
        char c = str.charAt(i);

        if(i < str.length() - 1 && c >= '\uD800' && c <= '\uDBFF')
        {
            char next = str.charAt(i + 1);

            if(next >= '\uDC00' && next <= '\uDFFF')
            {
                // Two-char supplementary character. Escape neither.
                result.append(c);
                result.append(next);
                ++i;
                continue;
            }
        }

        if(toEscape.contains(c))
        {
            // Special character. Add escaping \.
            result.append('\\');
        }

        // Copy character itself.
        result.append(c);
    }

    return result.toString();
}

My question is whether this method of escaping queries is secure enough (and I didn't oversee anything or made an implementation mistake). It can be assumed the input String is valid UTF-16. The DBMS's this will be used with are MySQL and Oracle.

A: Without an ORM, prepared statements or stored procedures I'd be cautious of any string SQL sanitization routine.

A: No.
Let's say you have an integer field which they input a PIN into:
"SELECT columns FROM table WHERE PIN = " + sanitizedstring
and then for input you type in:
1234 OR 1 = 1
And now your "pin" always is accepted, without any funny characters being used.
This could work for fields besides ints too (since yes, you could validate that an int input is actually an int before handing it over to the SQL.)


text:
Q: How to use Tweepy set_access_token? So I am a complete beginner to Tweepy, and I was trying to get started from their tutorial with the following code:
import tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

public_tweets = api.home_timeline()
for tweet in public_tweets:
    print tweet.text

Before the OAuthHandler, I added the consumer_key, consumer_secret, etc as something like:
consumer_key = 'aslkjfdalskdjflsjlfsakdjflasjdkf'
consumer_secret = 'ldsjlfksajldjflasjdljflasjdf'

access_token = 'asldkfjasjdfalsjdflksajkfdlasd'
acess_token_secret = 'alskjdflksajdlfjsalfd'

Of course, with the proper values. however, when I run the whole example, I get nothing printed out. What am I doing wrong? I understand I am supposed to get a list of tweets back. Am I not supposed to pass the values in as a string? I tried looking for tweepy documentation regarding OAuthHandler but didn't really come up with anything.
Any help would be greatly appreciated, thanks!!

A: For anyone else that might have this problem, it was a very simple issue– I created a new account and didn't have anything in my timeline. Naturally, nothing was printing.


text:
Q: Unable to set value dynamically for Lightning:InputField I have created a lightning component with lightning record edit form and a couple of fields. Wrote a Javascript method such that When I change the first field to a particular value then second field is updated. Below is my code.
<aura:component implements="force:appHostable">
   <aura:attribute name='test' type='String'/>
   <lightning:recordEditForm
                          aura:id="editForm"
                          objectApiName="Case"
                          recordTypeId="{XXXXXXXXXXXXX}">

        <lightning:inputField aura:id="subject" fieldName="Subject" onchange="{!c.subjectChanged}"/>

        <lightning:inputField aura:id="description" value="{!v.test}" fieldName="Description"/>

</lightning:recordEditForm>
</aura:component>

Below is the Controller code
({
    subjectChanged : function(component, event, helper) {
        var subjectValue = component.find("subject").get("v.value");
        if(subjectValue === "U") {
            //var descriptionValue = component.find("description");
            //descriptionValue.set("v.value","User");
            component.set('v.test','User');
        }

    }
})

*

*Updated Subject field to U, then Description got updated to 'User'

*Update the Description field value to XYZ or clear the value.

*Change the subject field to X and then update back to U.

*Notice that JS method got executed, but description is not updated to 'User'.

Whenever, user updates subject field to U, I want the description to be set to User. Any thoughts on this?

A: From documentation: https://developer.salesforce.com/docs/component-library/bundle/lightning:inputField/documentation
.....The assumption is that there are unsaved changes that should not be overwritten. If you want to be able to overwrite user changes, you can use lightning:input instead....

A: I found a way around that.
You can bind your inputField value to an aura:attribute, and then set the value of the aura:attribute. This is particularly useful for Lookup fields on the object, where using lightning:input loses functionality.
Example:
<aura:attribute name="myFieldValue" type="string"/>
<lightning:recordEditForm objectApiName="MyObject__c"
        onload="{!c.handleLoad}"
        onsubmit="{!c.handleSubmit}"
        onsuccess="{!c.handleSuccess}"
        onerror="{!c.handleError}">
    <lightning:inputField fieldName="MyLookupField__c" value="{!v.myFieldValue}"/>
</lightning:recordEditForm>

Javascript controller:
somethingHappened: function(newDataValue){
    component.set("v.myFieldValue", newDataValue);
}


text:
Q: Index reset needed when adding Crawl Component + CrawlDB? I've added a second crawl component and a second CrawlDB to my Search Service Application in SP 2010. The topology is online where the second crawl component is attached to the new CrawlDB.
Do I need to make an index reset or any other configuration to make the new crawl active and working in parallel with first one?

A: You dont to reset the index if you just want new content coming to this component. But if you want to divide the content equally then Reset the Index and perform a Full Crawl.
Or if you see any issue after adding new crawl DB i.e crawling on content source not completed etc.then you need a index reset followed by full crawl.


text:
Q: Looking for the Mach-O loader source code in the Darwin sources As I understand it, Mach-O should be part of the Darwin open source packages. Could someone please help me locate the loader? I've no idea where it is and where to download that code from.
Any help would be greatly appreciated!

A: Mach-O is loaded by many components, e.g. the dyld for loading a dynamic library, the XNU kernel for loading into memory and run it, etc. Which part do you want?
But no matter which, you can find the latest source code in http://opensource.apple.com/release/mac-os-x-1063/.


text:
Q: android custom dialog imageButton onclicklistener this is my custom dialog class:
package com.WhosAround.Dialogs;

import com.WhosAround.AppVariables;
import com.WhosAround.R;
import com.WhosAround.AsyncTasks.LoadUserStatus;
import com.WhosAround.Facebook.FacebookUser;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class MenuFriend extends Dialog{

    private FacebookUser friend;
    private AppVariables app;

    public MenuFriend(Context context, FacebookUser friend) {
        super(context, android.R.style.Theme_Translucent_NoTitleBar);
        this.app = (AppVariables) context.getApplicationContext();
        this.friend = friend;
    }

    public void setDialog(String userName, Drawable userProfilePicture)
    {
        setContentView(R.layout.menu_friend);
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        TextView name = (TextView) findViewById(R.id.menu_user_name);
        TextView status = (TextView) findViewById(R.id.menu_user_status);
        ImageView profilePicture = (ImageView) findViewById(R.id.menu_profile_picture);
        ImageButton closeButton = (ImageButton) findViewById(R.id.menu_close);
        name.setText(userName);
        profilePicture.setImageDrawable(userProfilePicture);

        if (friend.getStatus() != null)
            status.setText(friend.getStatus());
        else
            new LoadUserStatus(app, friend, status).execute(0);
        closeButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dismiss();

            }
        })

    }

}

for some reason eclipse tells me the following errors on closeButton imageButton:
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){})

The type new DialogInterface.OnClickListener(){} must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int)

The method onClick(View) of type new DialogInterface.OnClickListener(){} must override or implement a supertype method

why is that ?

A: The OnClickListener interface comes in subclasses. You are probably importing DialogInterface.OnClickListener, instead of View.OnClickListener.
The different subclasses of the interface have different implementations of onClick().
public interface View.OnClickListener() {
    // This implementation gives you a reference to the View that was clicked.
    onClick(View v);
}
public interface DialogInterface.OnClickListener() {
    // This implementation gives you references to the dialog in which the click happend
    onClick(DialogInterface dialog, int which);
}

Change your setOnClickListener to this:
closeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            dismiss();

        }
    })


text:
Q: Avoid installing optional deps with Yarn In my yarn.lock file I have only one reference to momentjs:
pikaday@^1.6.0:
  version "1.6.1"
  resolved "https://registry.yarnpkg.com/pikaday/-/pikaday-1.6.1.tgz#b91bcb9b8539cedd8d6d08e4e7465e12095671b0"
  optionalDependencies:
    moment "2.x"

I delete all the node_modulesfolder and the yarn.lock file, and run yarn --ignore-optional but the new yarn.lock generated contains the same lines, and it installs moment in my node_modules so it gets included in my bundle.
I am running on the yarn version 0.27.5.
How can avoid to install this dep marked as optional?

A: Turns out Yarn indeed lists all optional dependencies at yarn.lock. However, when --ignore-optional flag is specified those modules aren't installed into node_modules/.


text:
Q: Error on simple html dom removing elements I am using simple html dom. I hav this code:

this is inner text

this is inner anchor
This is outer test

I want to fetch This is outer test only.
Here is my code :
$html = file_get_html(SITE_URL.'/forumlist.php');
$html->find('.two',0)->outertext = "";
$html->find('.three',0)->outertext = "";
$html->save();
echo $html->find('.one',0)->plaintext;

and I got disappointed..

A: As far as I read the documentation, I don't think you can get that out as easy as you imagine ( I might be wrong of course ), but you can just remove the unneeded strings manually with str_replace:
$string = '

this is inner text

this is inner anchor
This is outer test

';

$html = str_get_html( $string );
echo str_replace(
        array(
            $html->find('.two',0)->plaintext,
            $html->find('.three',0)->plaintext
        ),
        null,
        $html->find('.one',0)->plaintext
    );

This should actually do the trick, if you know the structure of the html.


text:
Q: Set corner radius of `UISegmentedControl` equal to that of `UISearchController` I have several boxes on a page and I would like them all the have the corner radius of the UISearchController also on that page.
I tried to set the corner radius of my segmented control equal to that of the search controller. However, _searchController.searchBar.layer.cornerRadius returns 0 instead of its actual value in both viewDidLoad and viewDidAppear.
I tried the textfield inside of the search bar, but it also returns 0 for its corner radius.

A: #define CornerRadius    6

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController setNavigationBarHidden:YES];

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

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

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

set both corner radius like this


text:
Q: ionrangeslider: How to not show anything when from value is less than min value I have set up a ionrangeslider. I am mainly using it for displaying my temperature values
I keep updating the from value using ajax dynamically
                        <input type="text" class="js-range-slider" id="test" name="my_range" value=""
                            data-min="40"
                            data-max="210"
                            data-from="{{row2.7}}"
                            data-grid="true",
                            data-hide-min-max="true",
                            data-postfix="'F"
                        />

                        $('.js-range-slider').ionRangeSlider()

                        //later i am changing the from value using

                         let intst = $(#test).data("ionRangeSlider");

                         intst.update({
                           from: 0 //your new value
                         });

I have min: 40 and max: 210, and when my from: 0, then i want the slider not show anything
where what i see

A: add data-type:
<input type="text" class="js-range-slider" id="test" name="my_range" value=""
                            data-min="40"
                            data-max="210"
                            data-from="{{row2.7}}"
                            data-grid="true"
                            data-hide-min-max="true"
                            data-postfix="'F"
                            data-type="double"
                        />

$('.js-range-slider').ionRangeSlider();

//later i am changing the from value using

var inst = $("#test").data("ionRangeSlider");

inst.update({
  from: 0,
});
<link href="https://cdn.jsdelivr.net/npm/ion-rangeslider@2.3.0/css/ion.rangeSlider.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ion-rangeslider@2.3.0/js/ion.rangeSlider.min.js"></script>

<input type="text" class="js-range-slider" id="test" name="my_range" value=""
                            data-min="40"
                            data-max="210"
                            data-from="{{row2.7}}"
                            data-grid="true"
                            data-hide-min-max="true"
                            data-postfix="'F"
                            data-type="double"
                        />


text:
Q: flatMapFirst, but delaying the latest item Im looking for an operator (or a chain of operators) that, like flatMapFirst, discards items while waiting for the current observable to complete, which when it does, immediately spans another stream for the latest item seen.
I hope this diagram explains it better:
x -> [X1,X2,X3]

Input:  -a-----------b---c--d-------------------------
Output: ---A1-A2-A3----B1--B2--B3--D1-D2-D3-----------

As you can see, c got skipped, since d arrived after it. But notice as well that d arrived while b was still being processed and as soon as b was done, d started being processed.
This operator allows me to finish computations, as opposed to flatMapLatest which might switch from observable to observable, without ever giving a complete result for a computation. It behaves like flatMapFirst but the last element is still processed, allowing a consistent state in idle periods when the input elements stream does not have any elements.
concatMap could be the answer here, but if too many items get between b and d, the output stream would delay the latest item's computation far too long.
flatMapFirst (d is discarded)

Input:  -a-----------b---c--d----------------
Output: ---A1-A2-A3----B1--B2--B3------------

flatMapLatest (periods of starvation can happen)

Input:  -abcdefghijklmnop-----
Output: -------------------P1-

concatMap (too much work can get scheduled)

Input:  -a-----------b-c-d-e-f------------------------------------------
Output: ---A1-A2-A3----B1--B2--B3-C1-C2-C3--D1-D2-D3-E1-E2-E3--F1-F2-F3-

A: When in doubt, you can always write your own operator. (Note that in the below, I have only tested the happy path and didn't put in any threading guards.):
extension ObservableType {
    public func specialOp<O>(_ selector: @escaping (Self.E) throws -> O) -> RxSwift.Observable<O.E> where O : ObservableConvertibleType {
        return Observable<O.E>.create { result in
            var bag: DisposeBag! = DisposeBag()
            var current: Observable<O.E>? = nil
            var last: E? = nil
            var innerComplete: Bool = false
            func handleSub(_ element: E) {
                do {
                    current = try selector(element).asObservable()
                    current!.subscribe { subEvent in
                        switch subEvent {
                        case .completed:
                            current = nil
                            if let next = last {
                                handleSub(next)
                                last = nil
                            }
                            else if innerComplete {
                                result.onCompleted()
                                bag = nil
                            }
                        case .error(let error):
                            result.onError(error)
                        case .next(let sumElement):
                            result.onNext(sumElement)
                        }
                    }.disposed(by: bag)
                }
                catch {
                    result.onError(error)
                }
            }
            self.subscribe { event in
                switch event {
                case .completed:
                    innerComplete = true
                case .error(let error):
                    result.onError(error)
                case .next(let element):
                    if current == nil {
                        handleSub(element)
                    }
                    else {
                        last = element
                    }
                }
            }.disposed(by: bag)
            return Disposables.create {
                bag = nil
            }
        }
    }
}


text:
Q: Unable to get desired output using Dense Rank Can you please help me how to get the expected output as shown in the screenshot below?
DECLARE @TT TABLE  ( CUSTOMERID INT, TYPE VARCHAR(100) , D1 DATE)
INSERT INTO @TT VALUES ( 15001,'TYPE1', '4/1/2017')
INSERT INTO @TT VALUES ( 15001,'TYPE1', '4/2/2017')
INSERT INTO @TT VALUES ( 15001,'TYPE1', '4/3/2017')
INSERT INTO @TT VALUES ( 15001,'NON TYPE1', '4/4/2017')
INSERT INTO @TT VALUES ( 15001,'NON TYPE1', '4/5/2017')
INSERT INTO @TT VALUES ( 15001,'NON TYPE1', '4/6/2017')
INSERT INTO @TT VALUES ( 245,'Non TYPE1', '4/1/2017')
INSERT INTO @TT VALUES ( 245,'Non TYPE1', '4/2/2017')
INSERT INTO @TT VALUES ( 245,'Non TYPE1', '4/3/2017')
INSERT INTO @TT VALUES ( 245,'TYPE1', '4/4/2017')
INSERT INTO @TT VALUES ( 245,'TYPE1', '4/5/2017')
INSERT INTO @TT VALUES ( 245,'TYPE1', '4/6/2017')

A query is:
SELECT * ,
       DENSE_RANK() OVER ( PARTITION BY CUSTOMERID ORDER BY CUSTOMERID,TYPE) DR
FROM @TT
WHERE CUSTOMERID = 15001
ORDER BY CUSTOMERID,D1

SELECT *,
       DENSE_RANK() OVER ( PARTITION BY CUSTOMERID ORDER BY CUSTOMERID,TYPE) DR
FROM @TT
WHERE CUSTOMERID = 245
ORDER BY CUSTOMERID,D1

Thank you for the help.

A: You want to order groups by the minimum date.  I think it is something like this:
SELECT t.*,
       DENSE_RANK() OVER ( PARTITION BY CUSTOMERID ORDER BY mind1, TYPE) DR
FROM (SELECT t.*, MIN(d1) OVER (PARTITION BY CUSTOMERID, TYPE) as mind1
      FROM @TT t
     ) t
WHERE CUSTOMERID = 15001
ORDER BY CUSTOMERID, D1;

This sort of assumes that the types are not interleaved (as in your examples).  If that is the case, then please ask another question.  That significantly changes the question.  That question should also provide better sample data and desired results.


text:
Q: Azure DevOps - can't find Azure Artifacts Settings - unable to remove inheritance I screwed up my Feed settings trying to do cross-project pushes. I think I know how to fix it, but I can't seem to get to a setting that I had changed in order to change it back. Long story short, I have inherited permissions that are blocking me, but I can't get to the screen to un-set it:

Now these are set in a right side slide-out that has the option:
Only administrators and these users can create feeds
Which I believe is in Azure Artifacts settings according to all the documentation, but for the life of me I can't seem to find it again. Maybe I am just being dumb, but someone please help me un-set this! Thank you.
UPDATE:
I can get to the artifact and I see this:

I checked and even made sure I have rights over everything:

But nowhere do I see "Azure Artifacts settings" so I can get rid of this inheritance - what am I missing?

A:
Azure DevOps - can't find Azure Artifacts Settings - unable to remove inheritance

The solution is that searching the User/Group with Inherited in the option Only administrators and these users can create feeds of Azure Artifacts settings, then remove it:

After saving, we could delete the Project Collection Valid Users group now.
Reproduce steps:

*

*Add the Project Collection Valid Users group as Reader on the Feed settings.

*Add above group in the option Only administrators and these users can create feeds of Azure Artifacts settings.

Now, the group Project Collection Valid Users group marked as Inherited and we could not remove it:

Solution:
Searching the User/Group with Inherited in the option `Only administrators and remove it, then we could delete that group in the feed setting:

Update:

The info below is what I am looking for, but I can't seem to find out
  how to get to the 'Azure Artifacts Settings' - wherever it was before,
  its either well hidden, or gone for me now?

You should check if you are an administrator for the artifact, if not, you will not see that option. As solution, you can add your account as administrator for the artifact by the administrator account.
Without administrator for the artifact, Azure Artifacts Settings missing:

Add it by Admin account:

Then, we could see that settings:

Hope this helps.


text:
Q: conditions for a field to appear in odoo 14 I'd like field A to appear only if field B has a given value
field B doesn't belong to the same model, it belongs to a model connected through a many2one relationship
How do I write the contents of the attrs attribute for field A in the form ?
Until now I used
<field name="A"...
attrs="{'invisible': [('B', '=', 'some_value')

But until now both A and B belonged to the same model

A: Field used in attrs must be present in view
You can't use dotted field names because Odoo will raise an error if the field name contain . when validating the view definition:
Invalid composed field %(definition)s in %(use)s (attrs.invisible ...)

There is an exception for list sub-views (One2many/Many2many display in a form view) where you can use parent.field_name

A: ok, I reply to myself
First, in the model:
field_B = field.fieldtype(related='many2one_field.field_b')

Then, in the form view:
<field name="field_B" invisible="1"/>

and then
<field name="field_A" ...
        attrs="{'invisible': [('field_B', '=', 'some_value')]}">


text:
Q: is there a syntax to search for only training entries that are "not learned"? https://bixbydevelopers.com/dev/docs/dev-guide/developers/training.intro-training#searching-through-training-examples
I want to find only entries that are not learned status, but do not see a way.

A: Bixby currently does not support this functionality.
I would recommend that you raise a Feature Request in our community. This forum is open to other Bixby developers who can upvote it, leading to more visibility within the community and with the Product Management team.


text:
Q: an unusual List Comprehensions execution order I come across a list comprehension that is not quite the same as usual. So I am confused about the list-compresion execution order.
import re

folders = ['train_frames001', 'train_masks002',
'val_frames003','val_masks004', 'test_frames005', 'test_masks006']

folders.sort(key=lambda var:[int(x) if x.isdigit() else x
                    for x in re.findall(r'[^0-9]|[0-9]+', var)])

print(folders)
#Whether the list compresion part means
#for x in re.findall(r'[^0-9]|[0-9]+', var):
#  if x.isdigit():
#    int(x)
#  else:
#    x

I did't find related samples and docs.

A: I think you are confused between order of if-else.
a = [1,2,3,4,5,6,7,8]

If you want simply square of each number
b = [i**2 for i in a]
# [1,4,9,16,25,36,49,64]

If you want even numbers (if statement in list-comprehension)
c = [i for i in a if i%2==0]
# [2,4,6,8]

If you want to square only even numbers(if-else statement ternary operator)
c = [i**2 if i%2==0 else i for i in a]
# [1,4,3,16,5,36,7,64]

A: I run the code, and get ['test_frames005', 'test_masks006', 'train_frames001', 'train_masks002', 'val_frames003', 'val_masks004'], I think the result is right.
If you want get result like ['train_frames001', 'train_masks002', 'val_frames003', 'val_masks004', 'test_frames005', 'test_masks006'], which sorted by the end number. Maybe you should change your code like below.
import re

folders = ['train_frames001', 'train_masks002',
           'val_frames003', 'val_masks004', 'test_frames005', 'test_masks006']

folders.sort(key=lambda var: [int(x)
                              for x in re.findall(r'[^0-9]|[0-9]+', var) if x.isdigit()])

print(folders)


text:
Q: why sometimes space is + and sometimes is %20 in the URL? I have two page that each of them has one form. something like this:
// index.php

<form name="SampleForm" method="get"  action="search.php">
<input id="q" name="q" type="text"/>  //  text field
<input name="" type="submit" />       //  button
</form>

// search.php

<form name="SampleForm" method="get"  action="">
<input id="q" name="q" type="text"/>  //  text field
<input name="" type="submit" />       //  button
</form>

Now, when I submit index.php the URL is something like this:
www.example.com/search.php?q=foo+bar

but when I submit search.php the URL is something like this:
www.example.com/search.php?q=foo%20bar

Why ? and how can I fix it ? (I want just +)

Edit:
index.php to search.php is not ajax, but search.php to search.php is ajax. that's true, the reason of changing + to %20 is redirecting. so, is it possible to I convert  from %20 to + in a redirected page ?

A: I don't see why the form in search.php would generate a URL including resutl.php, as that action was not specified.
The only way I see this happening is if search.php has code in it that builds a redirect URL, and that code uses the %20 encoding form.
Have a look at how search.php ends up redirecting to resutl.php.  The answer lies there.
UPDATE
Based on the comments, you seem to be accessing this URL via Ajax.  Look at where the URL is formed for the Ajax call.

A: Well, by default a web form will use + for a GET form.
The difference is in index.php you are directly sending the data to result.php and hence the browser gives it as +
But in search.php, the result is given first to search.php (as action is "") and then I am guessing you are redirecting to result.php. This extra redirection is converting the  + to %20
Finally, they both are equivalent - it doesnt really matter which one you use.

A: Those two encoding forms are equivalent. The older RFC standard defined that the space should be encoded as a plus sign "+", the newer RFC standard defined to use percent encoding with the hexadecimal ASCII value.
All internet clients, search engines, spiders etc. know how to deal with it.


text:
Q: How to run visual studio build in azure devops I want to build my solution file in azure devops. I have added this to build pipeline, I see this step doesn't succeed. It tells " MSBUILD : error MSB1008: Only one project can be specified." I suspect I am making some mistake in specifyning
msbuild args
msbuild $(Build.SourcesDirectory)\ansysfnonet\ansysfnonet.vs2017.sln /t:$(Build.SourcesDirectory)\ansysfnonet\ansysfnonet.csproj:Rebuild;

I tried specify only proj file as msbuild arg it didn't work for me

I tried without specifying msbuild it throws me whole lot of errors.
Someone please help me , why I am failing in this step and how to solve this error.
Thanks

A: You don't need to specify an msbuild command line in the MSBuild Arguments field. You need to specify any additional MSBuild parameters beyond the defaults.
Clear that field. That should fix the problem you're encountering.


text:
Q: Navigation in react native router flux I have this configuration of the routers in my app --
<Router navigationBarStyle={styles.navBar}
                titleStyle={styles.navBarTitle}
            >
                <Scene key="modal" component={Modal}>
                    <Scene key="drawer" component={Drawer} open={false} type="replace" initial={this.state.flag ? false : true}>

                        <Scene key="mywishlist" component={MyWishlist} title="WISHLIST" type="replace" />
                        <Scene key="faq" component={FAQ} title="FAQ" type="replace" />
                        <Scene key="profilepic" component={ProfilePic} />
                        <Scene key="changepassword" component={ChangePassword} panHandlers={null} />
                        <Scene key="addressmanage" component={AddressManage} />
                        <Scene key="dishsearch" component={DishSearch} />
                        <Scene key="feedback" component={Feedback} hideNavBar type="replace" />
                        <Scene key="logout" component={Logout} hideNavBar type="replace" />
                    </Scene>
                    <Scene key="auth" initial={this.state.flag ? true : false} >
                        <Scene key="login" panHandlers={null} component={Login} title="Login" hideNavBar={true} type="replace" />
                        <Scene key="otp" panHandlers={null} component={OTP} title="OTP" hideNavBar={true} />
                        <Scene key="signup" panHandlers={null} component={SignUp} title="SignUp" hideNavBar={true} type="replace" />

                        <Scene key="coachmark" component={Coachmark} hideNavBar />
                    </Scene>
                    <Scene key="popUpImagePicker" panHandlers={null} component={PopUpImagePicker} title="PopUpImagePicker" hideNavBar={true} />
                    <Scene key="appModal" component={AppModal} />
                </Scene>

            </Router >

As soon as I come in logout I call Actions.auth() in my componentWillMount() to come to login screen but it is not working. Any suggestions on why not working and how can I route to login from any screen inside "drawer"?

A: what do you mean by not working? Is it a routing problem? In my project, I put a TouchableOpacity then if it is onPress, it will trigger logout service that using AsyncStorage to multiget and multiremove all info from user. And then to go back again into login page I use Actions.login({ type: 'reset' }); to reset history like a discussion in this link.


text:
Q: Connecting to different networks to access database information Any suggestions would help. The issue is, I have ETL applications that need to access database information located on a different network. So one C# application needs to query a database located on a different server.  Now I know the options are to open up a tcp port on the host and open up the firewall but I don't think we will go for that.  Other option I was thinking was to create a web service WCF and pass query string to the service and then connect to the database and return the info.
Another application needs to access dynamics AX to a AIF web service. Can aif web services be accessed across different networks or would I have to use a web service or something and then connect to the AIF service to retrieve information.

A:
Another application needs to access dynamics AX to a AIF web service.
  Can aif web services be accessed across different networks or would I
  have to use a web service or something and then connect to the AIF
  service to retrieve information.

IF you need to access AIF only in Intranet, you can do that with normal AIF services (They use RCP, I think but cannot assure just now).
If you need to access AIF via extranets or Internet, the best option is usually to create and Advanced AIF Port of HTTP type. This will create a standard Web Service, with SOAP protocol and a proper WSDL available for it. Be careful in securing these webservices properly, specially in production environments.


text:
Q: How to add custom TFS CheckinNoteDefinitions? Using TFS 2012 client C# API, I can add CheckinNotes to each commit; CheckinNotes need a suitable CheckinNoteFieldDefinition for each CheckinNoteFieldValue, or the checkin will be rejected and an exception is thrown.
How can I add additional (custom) CheckinNoteFieldDefinitions to the tfs server?
I am not really getting any useful information out of the MSDN documentation.
Related MSDN links:

*

*CheckinNoteFieldValue

*CheckinNoteFieldDefinition

A: It's created dynamically by the server once you check-in with any custom check-in notes:
var checkinNoteFieldValues = new[]
{
    new CheckinNoteFieldValue("Custom Note", "some value"),
    new CheckinNoteFieldValue("Other Note", "other value")
};
var checkinNote = new CheckinNote(checkinNoteFieldValues);
var pendingChanges = workspace.GetPendingChanges(); // workspace is Microsoft.TeamFoundation.VersionControl.Client.Workspace
workspace.CheckIn(pendingChanges, "comment", checkinNote, null, null); // checkinNote will trigger a new CheckinNoteFieldDefinition


text:
Q: Is this element-of_{ij} - looking symbol the Levi-Civita symbol? I'm reading this formula:

from a page
Is the symbol that looks like an element-of symbol with two indices i and j the Levi-Civita symbol?
Mathematics is my weak-side so I'm not sure.
Actually I guessed on Levi-Civita not based on my expertise but by tried to look up the symbol from the wikipedia table of mathematical symbols. As it didn't help, so I thought I look up Einstein-notation and Kronecker delta although I knew it's not them... but the wikipedia footer lists Kronecker as "notable tensors" and by checking the whole list I've got Levi-Civita which seem to make sense in the context.

A: The line following the equation in your link to the page says

The $\epsilon_{ij}$ is a constant known factor

A: The $\epsilon_{ij}$ is just a constant factor. The larger it is, the larger the change in synaptic strength during the learning session. Because the constant will be different for different synapses, there's a subscript $i$ and $j$.
It is not a Levi-Civita or any other standard function.
And by the way the name for that letter is "lunate epsilon".


text:
Q: How to resolve unfound module in Angular? I'm working on Angular's Tour de Heroes and am having an issue when importing from 'angular-in-memory-web-api'.
The line of code:

import { InMemoryWebApiModule } from 'angular-in-memory-web-api';

The error:

ERROR in C:/angularProjects/my-app/src/app/app.module.ts (1,35): Cannot find module 'angular-in-memory-web-api'

 How can I resolve this issue?
I'm new to the framework and as far as I can tell the 'angular-in-memory-web-api' is the updated 'angular2-in-memory-web-api' and should work.
Edit:
The below comments have answered the question. Be sure to download the package -

npm install angular-in-memory-web-api


text:
Q: drawable-w2560dp and drawable-1600dp Do Not Work I am using the new wdp qualifiers in my application for various phone/tablet sizes. They work for 600, 720, 800, 1200, but not for 1600 and 2560. Google Nexus 10 tablets have 2560 x 1600 resolutions. Why do drawable-w2560dp and drawable-w1600dp not work? How do I define assets for Google Nexus 10?

A: These qualifiers do not work because the Google Nexus does not fall under them. w2560dp stands for "Width of 2560dp". DP or Density-independent pixels are different than regular pixels. The Nexus 10 may have a resolution of 2560px x 1600px (i.e. pixels) but its dp dimensions are going to be more like 960dp x 720dp (or something like that. I can't give you any exact numbers).
Take a look at these design guidelines for supporting multiple screens to get a feel for the difference between pixels and dp and how you can better design your layouts.


text:
Q: Find documents in which a certain id inside an array exists in firestore (React)
Im trying to check if the current user id is in the participants array.How do i do it in firestore.Tried using 'array-contains'>please check the image


text:
Q: How to draw lines on the screen for an iOS game I am working on a game where I need to draw a bunch of lines to create a wireframe sort of object, I can do this in sprite kit using nodes but adding a bunch of nodes to the screen will drop the frame rate down a lot. I don't know how to use OpenGL Es at all so that's not an option for me. Is there anything that would just allow me to draw lines on the screen in Sprite kit without adding nodes or is there another framework that will allow me to do that?

A: If you want a 3D wireframe then your choices are sprite kit (which is built on top of OpenGL), OpenGL, or Metal. Or I guess you could use somebody's 3rd party framework that is also built on top of OpenGL or Metal.
I tend to agree with nhgrif's comment that you're "I don't know xyz so I can't do that" is needlessly limiting. If you can't do anything that involves learning new APIs then you're never going to get very far as a developer.


text:
Q: dns lookup with multiple ip to one name I have a server that monitors other systems across two VLANs. It is connected to them by using two NICs. nslookup from a client on either VLAN reports the IP from network B but not A. Is there something I can do so that it favors one IP instead of the other or even not have nslookup report network B's address and only show A's IP? The best case I think would for DNS to show both IPs so that both networks can reach the server by name but I'm not sure if that would cause more problems.
The intent is for admins (who sit in net A) to type the hostname into the browser or ssh to access it and not the IP.
They are both internal networks and
I don't have control over the DNS server (windows based I believe)
Server: ubuntu LTS 18.04.1

A: Possible solutions:

*

*You could force your monitoring to IP and not DNS/Hostname

*If your application reads it; update your /etc/hosts

*run your own DNS server with your custom records or a split horizon

But we would need more information; what monitoring system are you using?


text:
Q: How to add a table to my preexisting database using laravel? Hi guys I am new to laravel.
I just started my project for a login
I create a project and made a successful login using the command php artisan make:auth.
Now i am trying to create a comment system.I want guide to create it.
Please tell me how can i send the data with a button from the textarea to a new table in my preexisting database and to receive that data to my
commentarea.

Thank you

A: *

*Create a migration using php artisan make:migration <name of the file>. For eg. i am using name of the file as conor.

*php artisan make:migration conor

*open your conor.php file in databse/migrations

*In the up() function you can see there is an already created Schema::create

*In it you can also see $table->increments('id'); something like this also

*Just keep adding $table->+<name of the tabel structure>+('<name of the column>');

*Just before php artisan serve do an one time php artisan migrate to register the table


text:
Q: Где найти иконки для Android приложений в стиле Material? У меня в приложении есть блок информации - RelativeLayout. Все работает хорошо, но дизайн просто ужасен. Дайте пару советов на счет дизайна.
Или подскажите где найти иконки в Material стиле?
Мой блок

A: Помогло использование MaterialDesign стандартов и иконок. Ссылки:

*

*Иконки

*Стандарты

*Постоянно обновляемый репозиторий с иконками от гугла

*Удобный способ их скачать с предпросмотром (тоже от гугла)

A: Также существует отличный плагин c открытым исходным кодом для AndroidStudio. Позволяет выбрать цвет иконки, разрешение. Есть предпросмотр и автоматическое копирование по разным dpi папкам в проект.


text:
Q: Is the system of parallel springs always have a same extensions? In a normal system of parallel springs,

We say that their extension of the each spring is same, so the equivalent spring constant k is the sum of all k of spring.
But how can this make sense if one spring in a system of two springs, has a very large k1, and one has a very small k2? Wouldn't the system, like a load,when force is applied, "turns over" and "slanted" ?

A: Yes; a resultant torque causes rotation. If you don't see this addressed in a problem, it's because the block is being assumed to translate only, not rotate (e.g., perhaps it's riding on frictionless tracks).
Other likely assumptions for this problem are that the wall and block are rigid, the springs are ideal, the system doesn't sag from gravity, and that no out-of-plane motion occurs, for instance. Sometimes the problem will state these assumptions, and sometimes you have to deduce and apply them through experience.


text:
Q: AuthenticateAsServer won't accept PEM format certificates X509CertificateCollection certCollec =
new X509CertificateCollection(new X509Certificate[1] { xcert});

X509CertificateCollection certCollecpfx =
new X509CertificateCollection(new X509Certificate[1] { pfxCert });

SSLStream.AuthenticateAsClient(apsHost, certCollec, SslProtocols.Default, false);

certCollec contains a certificate in PEM Format
certCollecpfx contains a certificate in PFX Format
AuthenticateAsClient server only works with PFX Format even though the X509Certificate2 object for the pem and the pfx has exactly the same raw data.
Why is this? It keeps telling me A call to SSPI Failed: The data was badly formatted.
Why won't it accept pem format?
I then tried to export the pem format into pfx and it still didn't accept it - same error, even though I exported it to pfx.
byte[] pemCertBytes = pemCert.Export(X509ContentType.Pfx, "620fpass");
            File.WriteAllBytes(@"C:\test\MyCert.pfx", pemCertBytes);

A: even though the X509Certificate2 object for the pem and the pfx has exactly the same raw data.

I think that is true only in cases when the pem certificate contains the actual certificate along with the private key. Moreover, it has specific headers namely BEGIN-CERTIFICATE and END-CERTIFICATE enclosing the actual contents. pfx or pkcs#12 certificates contain certificates and private keys which can optionally be encrypted using passwords. If you have ever imported a certificate to Windows Certificate Store, you may have noticed that it prompts you to enter a password while doing this, this is essentially used to encrypt the private key of the certificate.
I then tried to export the pem format into pfx and it still didn't accept it

I would suggest using openssl for doing this. The general syntax is
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt


text:
Q: Send to multiple database input type = "radio" I need to create a input type = "radio", where it will be multiple polls and will store the answers in the database according to the selected option.
How could I do to insert all polling responses into a same table.
Below is the HTML code with the radios.

  <input type="hidden" id="questao" name="questao" value="84">
 <input type="radio" value="291" name="84">Ótimo
<input type="radio" value="292" name="84">Bom
<input type="radio" value="293" name="84">Regular
<input type="radio" value="294" name="84">Fraco

 <input type="hidden" id="85" name="85" value="85">
 <input type="radio" value="295" name="85">Ótima
 <input type="radio" value="296" name="85">Boa
    <input type="radio" value="297" name="85">Regular
 <input type="radio" value="298" name="85">Fraca

 <input type="hidden" id="86" name="86" value="86">
 <input type="radio" value="299" name="86">Ótimo
 <input type="radio" value="300" name="86">Bom
       <input type="radio" value="301" name="86">Regular
    <input type="radio" value="302" name="86">Fraco

  <input type="hidden" id="87" name="87" value="87">
  <input type="radio" value="303" name="87">Ótimo
  <input type="radio" value="304" name="87">Bom
  <input type="radio" value="305" name="87">Regular
     <input type="radio" value="306" name="87">Fraco

Below a function made in laravel inside a controller
public function enviando(Request $request)
            {
                $date = date("Y-m-d h:m:s");
                $pegar_ip = $_SERVER["REMOTE_ADDR"];

                if($_POST = '84'){
                    $questao_id = '84';
    }
    if($_POST = '85'){
        $questao_id = '85';
    }
    if($_POST = '86'){
        $questao_id = '86';
    }
    if($_POST = '87'){
        $questao_id = '87';
    }

                DB::table('eventos_avaliacoes_participantes')
                        ->insert(['avaliacao_id' => "2",
                                 'nome' => $request->input('nome'),
                                 'email' => $request->input('email'),
                                 'sexo' => $request->input('sexo'),
                                 'comentarios' => $request->input('comentarioevento'),
                                 'ip' => $pegar_ip,
                                 'created' => $date]);

                $id = '171';
                $opcao = $request->input('84');
                DB::table('eventos_avaliacoes_participantes_opcoes')
                        ->insert(['opcao_id' => $opcao,
                                 'questao_id' => $questao_id,
                                 'participante_id' => $id+1]);

            return redirect('sucesso');

            }


text:
Q: Regex optional matching for multiline patterns I'm trying to figure out how to come up with one regex that supports the following 2 use cases:
Use Case 1:
-- File 1 (input) --
keepthis

junkhere:
this should be removed

Use Case 2:
-- File 2 (input) --
keepthis

------------
junkhere:
this should be removed

Essentially I'm building one regex to remove everything from "junkhere:" and down.  However, in use case 2 there is an optional "------------" that gets included on the line before "junkhere:" sometimes but not always (not sure of the exact of -'s).
Output should be:
-- File 3 (output) --
keepthis

I have the following regex and it works for use case 1 but not for use case 2:
Pattern JUNKHERE_REGEX = Pattern.compile("^(((-+)(.*))?junkhere:(.*))$", Pattern.MULTILINE | Pattern.DOTALL);

    Matcher m = JUNKHERE_REGEX.matcher(<input from either file1 or file2>);
    if (m.find()) || (n.find() || (o.find()) { // there could be other matchers here n and o in this case so I would like to keep the replaceall code below the same so I don't have to create a new if statement
      text = m.replaceAll("");
      text = text.replaceAll("[\n]+$", ""); // replace and delete any newlines
    }
    System.out.println(text); // should echo "keepthis"

I'm not that good with regex's but what do I need to make this work for use case 2 (and use case 1)?
Thanks!

A: Replace match of [\n\r]+(?:[-]+[\n\r]+)?\s*junkhere:\s*[\n\r][\s\S]* with empty string.

Test it here: http://regexr.com?37edu and here: http://regexr.com?37ee1

In Java you have to double escape characters:
= text.replaceAll("[\\n\\r]+(?:[-]+[\\n\\r]+)?\\s*junkhere:\\s*[\\n\\r][\\s\\S]*", "");


text:
Q: Dojo: Override Pre-Loaded Module I working with a pre-built client application all written with Dojo 1.8 (AMD style) which I need to extend.
I have access to the source code but want to leave it unchanged where possible and instead favor overrides (that's how the application plug-in framework works, anything else would be a hack).
My script loads only after the base application script. I cannot modify djConfig for example, nor anything else that would occur before the base application modules are loaded.
Here is my question: I would like to extend one of the base application classes (created with declare) and apply my overrides globally -- even on pre-loaded modules which already required the module containing this class (but not yet instantiated it).
So far, the best solution that I found is to use require() to alias the module containing the class. But this only works with modules that require the class after I could register the alias.

A: The Dojo AMD Loader documentation states:

Once a module value has been entered into the module namespace, it is
  not recomputed each time it is demanded. On a practical level, this
  means that factory is only invoked once, and the returned value is
  cached and shared among all code that uses a given module. (Note: the
  dojo loader includes the nonstandard function require.undef, which
  undefines a module value.)

This means that if you modify the prototype of the module, the change will propagate throughout the application, even to the instances created before the change, because this is how JavaScript works.
To modify a prototype of class created via dojo/_base/declare, there is an extend() method defined on the constructor:
require(['App'], function(App) {
    App.extend({
        run: function() {
            // override `run` method here
        }
    });
});

See it in action: http://jsfiddle.net/phusick/HxkFs/


text:
Q: Can't filter custom metrics in google cloud monitoring with tags I registered stats with opencensus and attached tags thanks to a StackDriver exporter:
ctx, err = tag.New(ctx, tag.Upsert(key, val))
stats.Record(ctx, []stats.Measurement{csqAverage.M(m)}...)

In the metric explorer, I can see the metrics, but I can't see or filter with the associated tag. When I retrieve the resources thanks to the REST API, I don't see tags at all, and this kind of property is not mentionened in the documentation describing a metric. However, the gcloud documentation indicates that opencensus tag can be exported to filter the metrics.

A: TagKeys must be declared in the registered view.


text:
Q: Confusion about the meaning of Bandwidth-limited pulse I am quoting Wikipedia: "A bandwidth-limited pulse (also known as Fourier-transform-limited pulse, or more commonly, transform-limited pulse) is a pulse of a wave that has the minimum possible duration for a given spectral bandwidth."
But every pulse has minimum possible duration, so does that mean all pulses are bandwidth limited? Im superconfused here. Can you give me an example which illustrates the difference between bandwidth limited and not bandwidth limited pulse?

A: The more correct term is transform limited. That refers to a pulse that has the shortest possible duration for it's bandwidth.
Not all pulses are transform limited. Think of a burst of static for example. It has many random fluctuations up and down. Compare to a short gaussian pulse that rises up smoothly and then back down. If both have the same bandwidth, the latter pulse will be much, much shorter. This process can be understood formally using Fourier analysis, but that is the basic idea.

A: Yes, every pulse in the real world is bandwidth limited.
For example, an ideal square wave does not exist, as the vertical edge steps would require infinite bandwidth and thus infinite power to achieve.

A: Roughly, the narrower a pulse is in one domain, the wider it is in the other FT domain.  In theory, any function with limited (finite) support in one domain is infinitely wide in the other domain. In practice, for Gaussian pulses and others, we ignore that tails that drop below some noise floor or numerical budget, and call some other property the width.
And a smooth Gaussian shaped pulse in one domain (of some "width") will have the most compact width in the other domain (for certain definitions of "width" and "compact").


text:
Q: How to remove edge cases for string and number expressions I'm building a rock, paper, scissors game and working on excluding edge cases.
The function is setPlayerMoves(), which is supposed to set previously undefined global variables for player moves and give them a 'value' between 1-99. how do I excluded edge cases like wrong move type (eg. 'rok') or wrong value (eg. 100).
Here is my incorrect code:
function setPlayerMoves(player, moveOneType, moveOneValue, moveTwoType, moveTwoValue, moveThreeType, moveThreeValue) {
    if (player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99))) {
        playerOneMoveOneType = 'rock';
        playerOneMoveTwoType = 'paper';
        playerOneMoveThreeType = 'scissors';
        playerOneMoveOneValue = 11;
        playerOneMoveTwoValue = 33;
        playerOneMoveThreeValue = 55;
    } else if (player === 'Player Two') {
        playerTwoMoveOneType = 'rock';
        playerTwoMoveTwoType = 'paper';
        playerTwoMoveThreeType = 'scissors';
        playerTwoMoveOneValue = 11;
        playerTwoMoveTwoValue = 33;
        playerTwoMoveThreeValue = 55;
    }
}

A: Problem
Code for checking edge cases are wrong.
(player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99)))

Also you are checking the edge cases for only 'player one'
Solution
Check the values seperately before assigning values and create a valid variable
let valid  = false
let states = ['rock','paper','scissors'];
if((states.indexOf(moveOneType) != -1) && (states.indexOf(moveTwoType) != -1) && (states.indexOf(moveThreeType) != -1)){
 // valid state
valid = true;
}else{
valid = false;
}

if((moveOneValue >=1 && moveOneValue <= 99) && (moveTwoValue >=1 && moveTwoValue <= 99) && (moveThreeValue >=1 && moveThreeValue <= 99)){
 //valid value
 valid = true;
}else{
valid = false
}

Then assign the values.
if ((player === 'Player One') && valid) {
        playerOneMoveOneType = moveOneType;
        playerOneMoveTwoType = moveTwoType;
        playerOneMoveThreeType = moveThreeType;
        playerOneMoveOneValue = moveOneValue;
        playerOneMoveTwoValue = moveTwoValue;
        playerOneMoveThreeValue = moveThreeValue;
    } else if ((player === 'Player Two') && valid) {
        playerTwoMoveOneType = moveOneType;
        playerTwoMoveTwoType = moveTwoType;
        playerTwoMoveThreeType = moveThreeType;
        playerTwoMoveOneValue = moveOneValue;
        playerTwoMoveTwoValue = moveTwoValue;
        playerTwoMoveThreeValue = moveThreeValue;
    }

Also if possible
Create an object each for player1 and player2 like below and use.
let player1 = {
  moveOneType:'rock'
  moveTwoType:'paper'
  moveThreeType:'scissors'
  moveOneValue: 23
  moveTwoValue: 33
  moveThreeValue: 98
}


text:
Q: .Net SyndicationFeed serialization error when adding extensions to the RSS feed I create a .NET Framework SyndicationFeed:
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);

Then I create a new item:
var newItem = new SyndicationItem();
newItem.Id = sourceFeedItem.ItemID;
newItem.Title = new TextSyndicationContent(sourceFeedItem.ItemTitle);

Then I add some iTunes item extensions:
var iTunesExt = newItem.ElementExtensions;
iTunesExt.Add(new XElement("MyElement", "Whatever");
newItem.ElementExtensions.Add(iTunesExt);

Then I add the item to the items list:
List<SyndicationItem> items = new List<SyndicationItem>();
items.Add(newItem);

and set the feed's Items property.
feed.Items = items;

and finally I write the SyndicationFeed feed to an XmlWriter.
feed.SaveAsRss20(xmlWriter);

All goes well if the extensions aren't added, in other words if the newItem.ElementExtensions.Add(iTunesExt); line doesn't execute.  But if the line executes, I get the following error upon execution of feed.SaveAsRss20(xmlWriter);.

Type 'System.ServiceModel.Syndication.SyndicationElementExtension'
  cannot be serialized. Consider marking it with the
  DataContractAttribute attribute, and marking all of its members you
  want serialized with the DataMemberAttribute attribute.  If the type
  is a collection, consider marking it with the
  CollectionDataContractAttribute.

How can I mark iTunesExt with the DataContractAttribute attribute?  Or am I misunderstanding it?

A: iTunesExt.Add(new XElement("MyElement", "Whatever");

Try modifying this to:
iTunesExt.Add(new XElement("MyElement", "Whatever"),
    new DataContractSerializer(typeof(XElement)));

That allows you to specify use of the DataContractSerializer.


text:
Q: MySQL: Hundreds of tables or one big table? I want to create a webpage where user can organize things they collect. As everyone collects something else I want to have the users create their own datamodell (with strict limitations). If two people are collection the same "things" they can share a datastructure.
My idea was to give every collection an ID and all the tables belonging to that collection will have the ID as a prefix.
Table: Collections
ID | Collection
 1 | Poststamps
 2 | Barbie Dolls

Table: 1_Base
ID | StampValue | StampPic
....

Table: 2_Base
ID | EAN | Pic
....

Thus I would create many tables as each user could in theory create their own collection. I could also use only one very big table and a mapping table. Example:
Table: Colleactions
ID | Collection
 1 | Poststamps
 2 | Barbie Dolls

Table: Mapping
fkCollection | FieldName    | Mapping
1            | DoubleField1 | StampValue
1            | BlobField1   | StampPic
2            | StringField1 | EAN
2            | BlobField1   | StampPic

Table: CollectionData
fkCollection | DoubleField1 | ... | DoubleField10 | StringField1 | ... | Stringfield10 | BlobField1 | ...
1            | 30           |     |               |              |     |               | ...        |
2            |              |     |               | 21312412414  |     |                | ...        |

Any other ideas?
Thanks for your help!

A: From what I can see, your second way of attempting this is going to be the easiest way... your queries will be ten fold simpler to handle, and you wouldn't need to programmably create tables on the fly... so my suggestion would be to modify your second idea slightly... Just to clarify something also, A blob will slow down the query speed so I am changing the block to hold the source link to the image instead.
TABLE: Collections
ID| Collection
1 | Poststamps
2 | Barbie Dolls

Table: CollectionData
fkCollection | DataType    | VALUE  | FieldName  |
1            | Double      | 30     | StampID    |
1            | String      | London | StampName  |
1            | ImgSrc      | ../loc | StampPic   |
2            | String      | Ken    | BarbieName |
2            | ImgSrc      | ../loc | BarbiePic  |


text:
Q: Error when attempting to loop through multiple layers of an API with custom function in Power BI I'm pretty new to Power BI, and am following this tutorial (https://youtu.be/MCTXMUuH3gk?t=208) on looping through multiple pages of an API programmatically. Total process is from 3:28 to about 16:30 in the video.
I've went ahead and pulled my first query which contains all the id's I'll need. I also created a second query which is one layer deeper in the API url (which contains all the end data I want), and transformed it in the advanced editor per the tutorial. Here's the result of the portion of the code I edited, sanitized a bit:
(client_id as text) as table=>
let
Source = Json.Document(Web.Contents("https://examplewebsite.com/rest/v7",
[RelativePath = "/project/13/clients/"&(client_id)], [Headers=[Accept="application/JSON",
Authorization="BearerExampleToken38e7jk2",
#"api-client"="msbi_integration"]])),
The rest of my code after this is left unchanged, and is very similar to the unchanged portion of the tutorial's code at 8:35.
The code is accepted with no errors at creation, and and the custom function shows in power query. Per the tutorial, I then duplicated the first query and reduce it to just the column with the id's I need, change the column to text (as needed by the code), and 'Add Column'->'Invoke Custom Function', with my id selected to join everything. However, when I hit enter for that, or just try running my function at all, I get the following error:
Expression.Error: 3 arguments were passed to a function which expects between 1 and 2.
Details:
Pattern=
Arguments=[List]
So then I tried the following instead:
(client_id as text) as table=>
let
Source = Json.Document(Web.Contents("https://examplewebsite.com/rest/v7",
[RelativePath = "/project/13/clients/"&(client_id), Headers=[Accept="application/JSON",
Authorization="BearerExampleToken38e7jk2",
#"api-client"="msbi_integration"]]))
but instead get the following error:
DataSource.Error: Web.Contents failed to get contents from 'https://examplewebsite.....' (400): Bad Request
Any ideas what I'm doing wrong? Any help is appreciated.


text:
Q: What is the correct way to define functions with a bound variable in Python? I want to create a family of functions each with a different parameter. In trying to doing so I encountered an issue which I demonstrate below using a dummy code (in python):
Suppose I want 4 functions such that the i-th function prints i when called.
A Naive code to do this would be:
#------ Prepare the functions----
func_list =[]
for i in range(1,5):
    def dummy():
        print("Dummy no:", i)
    func_list.append(dummy)

#----- Call the functions -------
for func in func_list:
    func()

But it results in the wrong output:
Dummy no: 4
Dummy no: 4
Dummy no: 4
Dummy no: 4

I figured the correct way is:
#------ Prepare the functions----
def return_a_func(k):
    def dummy():
        print("Dummy no:", k)
    return dummy

func_list =[]
for i in range(1,5):
    func_list.append(return_a_func(i))

#----- Call the functions -------
for func in func_list:
    func()

This gives the correct output:
Dummy no: 1
Dummy no: 2
Dummy no: 3
Dummy no: 4

I vaguely understand that this has to do with closures. But I could not reason it out clearly and completely. Specifically why did the Naive approach fail? Why couldn't Python detect that 'i' must be bound to the function 'dummy'?
Edit: The following answer suggested in the comment is very useful: Creating functions in a loop
However, It would also be great to know the rationale behind having 'late binding' as a design choice. Also, when exactly does binding happen? For instance, this does not create a binding, although one would expect it to:
    i=1
    def dummy():
        p = i
        print("Dummy no:", p)
    f= dummy

    i=2
    f()
    # this print : Dummy no: 2


text:
Q: Добавляет ненужный элемент в отображение TreeMap Код:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
try{
       output.write("Input first and last name of students(q for exit): \n");
       output.flush();
       String str; int b = 0;
       do{
            str = input.readLine();
            if (str!="q") mStudents.put(str, b);
       } while (str!="q");
       input.close();
} catch (IOException e){
}

В отображение вводится элемент "q", из-за чего в функции-сравнении объектов возникает исключение:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Если добавить в цикл do{}while() вывод введенного значения, то "q" там присутствует. В чем ошибка?

A: Строки в Java это ссылочный тип. Сравнение == разных строковых переменных всегда дает отрицательный результат. Надо:
!str.equals("q")


text:
Q: PDF and CDF distribution looking for feedback on my work Given $$X_i ∼ Uniform[0, 1] $$for $$i = 1, .., n.$$
What is the distribution of $$M := min(X_1, ...., X_n)?$$
You may assume that $$X_1,X_2, ... ,X_n are independent.$$
My solution:
$$X_1 ∼U [0,1]$$
$$PDF f(x)=1, 0≤ x≤ 1$$
$$ F(x)= \int_0^{x} f_x(x)\,dx$$
$$=\int_0^{x} 1\,dx$$
$$x, 0≤ x≤ 1$$
CDF of min
$$= 1-[1-x]^n $$
PDF of min
$$=n(1-x)^{n-1}$$
This is my solutions, and just wanted to check my answers with you guys


text:
Q: Event to find out all feature successfully loaded to the layer I am using OpenLayers6 to load the map on my website. How can I know if all the features in the geojson file completed the loading to the layer?
 var layer = new ol.layer.Vector({
        source: new ol.source.Vector({
            url: "test.geojson",
            format: new ol.format.GeoJSON(),
        }),
        style: function(feature) {
            return style;
        }
    });
    map.addLayer(layer);

Is there any event to know that I have completed the loading of all feature inside the "test.geojson" to the layer?


text:
Q: Eloquent json field- get records higher/lower than some value I have column data with json type in my table. That query doesn't work:
Advert::where('data->price', '>', 2000)->get();

In response I got elements with price lower than 2000. QueryBuilder run this on db:
SELECT * FROM "adverts" WHERE "data"->>'price' > '2000'

I have no idea what is wrong. It looks like price is casting to string but in database is saved as integer.
{"price": 500}

A: PostgreSQL compares the values as strings, beginning with the first character. That's why 500 is "higher" than 2000. You need to convert the price to an integer using a raw expression:
Advert::where(DB::raw('("data"->>\'price\')::int'), '>', 2000)->get();


text:
Q: Increase Intensity of SCNLights Hello I have a SCNScene that is the basis of my game. The lighting was tricky and to get the effect I wanted I ended up duplicating three lights three times. This increased the intensity of the lights to create the affect and colors I wanted. However I know that 9 lights all casting shadows has been taking a toll on my fps. Is there any way to increase the intensity of the lights like i did by duplicating them without destroying my fps?
Thanks!

A: what type of light do you have ? Do they have non-default attenuation values ? (see attenuationStartDistance, attenuationEndDistance and attenuationFalloffExponent).
You can try to increase the brightness of your lights colors if that's possible (if they're aren't already 100% white for instance).
Otherwise you can use shader modifiers. The SCNShaderModifierEntryPointLightingModel entry point will let you customize the effect of each light.

A: In iOS 10 & macOS 10.12, SCNLight now has an intensity: CGFloat property which'll let you multiply the brightness of each light.  Assuming you're not using PBR/IES, intensity acts as a permille multiplier— 1000 = 1×, 3000 = 3×, 100 = 0.1×, etc.  (When using PBR or IES lighting, intensity instead controls the luminous flux of the light.)
To triple the brightness of each SCNLight, simply do:
myLight1.intensity = 3000


text:
Q: ChromeHeadless hangs when running karma tests inside Jenkins agent docker image (with Kubernetes plugin) I have an angular application which runs with the default test suite (using karma to start a headless chrome). Jenkins runs with the kubernetes plugin to start up new instances of jenkins agents every time a job is submitted. (If this bug is fixed, I'll create an article in stackoverflow just about running headless chrome tests in docker containers, as this appears to be a common issue).
I based the build off of this (minus the protractor parts, as protractor is not used).
Everything builds and runs properly until the browser tests complete.
+ npm run test:vt --watch=false --progress=false --browsers=ChromeHeadless --headless --disable-gpu --window-size=800x600 --disable-dev-shm-usage --no-sandbox

> {my_company}/{my_project}docs@0.0.0-PLACEHOLDER test:vt /home/jenkins/agent/workspace/UI_{my_project}_PR-192
> ng test {my_project}

[33m04 09 2019 16:00:58.826:WARN [karma]: [39mNo captured browser, open http://localhost:9876/
[32m04 09 2019 16:00:58.832:INFO [karma-server]: [39mKarma v3.1.4 server started at http://0.0.0.0:9876/
[32m04 09 2019 16:00:58.832:INFO [launcher]: [39mLaunching browsers ChromeHeadlessNoSandbox with concurrency unlimited
[32m04 09 2019 16:00:58.839:INFO [launcher]: [39mStarting browser ChromeHeadless
[33m04 09 2019 16:01:16.236:WARN [karma]: [39mNo captured browser, open http://localhost:9876/
[32m04 09 2019 16:01:16.432:INFO [HeadlessChrome 76.0.3809 (Linux 0.0.0)]: [39mConnected on socket FcDILSSqmJFawfnrAAAA with id 26860248
HeadlessChrome 76.0.3809 (Linux 0.0.0): Executed 0 of 863 SUCCESS (0 secs / 0 secs)
...{bunches 'o lines}...
[1A[2KHeadlessChrome 76.0.3809 (Linux 0.0.0): Executed 796 of 863 (skipped 67) SUCCESS (0 secs / 32.499 secs)
[1A[2KHeadlessChrome 76.0.3809 (Linux 0.0.0): Executed 796 of 863 (skipped 67) SUCCESS (33.59 secs / 32.499 secs)
TOTAL: 796 SUCCESS
TOTAL: 796 SUCCESS

Then the terminal just appears to hang here. I let it sit for 24 hours with no change.
I put a monitor on the memory and cpu usage. The cpu drops to noise level (<10mcpu) as though it's waiting for an input. So, I added the flag "--password-store=basic" in order to prevent ChromeHeadless from hanging while waiting for input (I tried finding the karma github bug report that recommended this, but couldn't find it again). Unfortunately, this was unsuccessful.
Any ideas on how I can trouble shoot this, or fix it?
The docker image is built as such (with the last two RUN commands being used to setup the Chrome binaries):
FROM jenkins/jnlp-slave:3.29-1

ARG DOCKER_VERSION=18.06.1~ce~3-0~debian
ARG DC_VERSION=1.24.1

USER root
RUN apt-get update && \
    apt-get install -qq -y --no-install-recommends \
      apt-transport-https \
      ca-certificates \
      curl \
      gnupg2 \
      software-properties-common && \
    curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add - && \
    apt-key fingerprint 0EBFCD88 && \
    add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian stretch stable" && \
    add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian stretch stable" && \
    apt-get update && \
    apt-get install -qq -y --no-install-recommends docker-ce=${DOCKER_VERSION} && \
    curl -L https://github.com/docker/compose/releases/download/${DC_VERSION}/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose && \
    chmod +x /usr/local/bin/docker-compose && \
        curl -sL https://deb.nodesource.com/setup_12.x | bash - && \
        apt-get install nodejs && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
RUN apt-get install -qq -y --no-install-recommends nodejs npm

# Set the Chrome repo.
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
# Install Chrome.
RUN apt-get update && apt-get -y install google-chrome-stable

ENTRYPOINT ["jenkins-slave"]

My karama.conf is setup as such:
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
        browsers: ['ChromeHeadlessNoSandbox'],
        customLaunchers: {
            ChromeHeadlessNoSandbox: {
                base: 'ChromeHeadless',
                flags: [
            "--no-sandbox",
             // required to run without privileges in Docker
            "--disable-web-security",
            "--disable-gpu",
            "--remote-debugging-port=9222"
                ]
            }
        },
    singleRun: false,
        junitReporter:{
           outputDir:'test-reports',
           // results will be saved as $outputDir/$browserName.xml
                outputFile:'junit-report.xml',
           // if included, results will be saved as $outputDir/$browserName/$outputFile
                suite:'',
           // suite will become the package name attribute in xml testsuite element
                useBrowserName:false,
           // add browser name to report and classes names
                nameFormatter:undefined,
           // function (browser, result) to customize the name attribute in xml testcase element
                classNameFormatter:undefined,
           // function (browser, result) to customize the classname attribute in xml testcase element
                properties:{
           }   // key value pair of properties to add to the section of the report
        }
  });
};

The Jenkinsfile section that runs the test is:
  stage('Test') {
    echo "Running tests"
    sh 'npm run test:vt --watch=false --progress=false --browsers=ChromeHeadless  --headless --disable-gpu --window-size=800x600 --disable-dev-shm-usage --no-sandbox --password-store=basic'
  }

A: I use karma and CromeHeadless installed on the same machine as Jenkins (small projects and sites). With this configuratios I have never watch a Chrome instance that keeps working once the tests are finished. You could try to add this to your karma.conf:
    browsers: ['ChromeHeadless'],
    singleRun: true,
    restartOnFileChange: true

For example, my karma.conf looks like this (sending important lines only):
    customLaunchers: {
      ChromeHeadless: {
        base: 'Chrome',
        flags: [
          '--headless',
          '--disable-gpu',
          '--no-sandbox',
          '--remote-debugging-port=9222',
        ]
      }
    },
    browsers: ['ChromeHeadless'],
    singleRun: true,
    restartOnFileChange: true

The single run option means that "If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending on whether all tests passed or any tests failed." (from the karma config file site)


text:
Q: table-layout: fixed issue with column widths We're using the CSS table-layout: fixed property for our mobile app. (I don't recall the full reason, but I believe it had to do with enabling word wrapping of some sorts)...
I've run into an issue where we need to size one of the two columns of the two column table. Not a big deal, usually we do this:

      hello world
      hello world

That works fine.
However, if we need to create a row that spans both columns BEFORE this one:

      hello world

      hello world
      hello world

What happens, at least in Chrome, is that the two columns snap to 50% widths. I have a jsbin sample here:
http://jsbin.com/ejovut/3
Is this normal behavior? A Chrome bug? A way to work around this issue?

A: This is not a bug.  table-layout:fixed means that the browser is allowed to optimize table-layout computations by assuming only the first row and column specifications matter.  In particular, it does NOT need to inspect and do layout computations on later table content, which can make a large difference in layout performance.
The right solution is to use the <col> and <colgroup> elements to explicitly specify column widths, rather than using the first row.

A: first table row should contain all
also, Chrome bugs does not allow to use  for this.


text:
Q: Transition does not work on :before I'm designing a navigation bar for my portfolio page. Now when I hover one div element, the :before element should extend it's width in 0.4s seconds. But this is not the case, the :before just pops up with no transition. Hope someone of you knows the problem. Here is my source code.

.header__navigation {
  display: flex;
}
.header__navigation .nav {
  margin: 0 30px;
}
.header__navigation .nav > div {
  position: relative;
}
.header__navigation .nav > div:before {
  transition: width 0.4s;
  position: absolute;
  content: "";
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  transition: all 0.3s;
}
.header__navigation .nav > div:hover {
  cursor: pointer;
}
.header__navigation .nav > div:hover:before {
  height: 2px;
  width: 100%;
}

   Home

   About

   Contact

A: I had some success by setting an initial width of zero.
This gives the transition distinct values to animate.
Also, there are no elements in your HTML that match .nav > div.
I changed the CSS to .nav > span.
I also moved height:2px out of the :hover definition.
This allows the transition to work on both mouseenter and mouseleave.

.header__navigation {
  display: flex;
}

.header__navigation .nav {
  margin: 0 30px;
}

.header__navigation .nav>span {
  position: relative;
}

.header__navigation .nav>span:before {
  transition: width 0.4s;
  position: absolute;
  content: '';
  bottom: 0;
  left: 0;
  right: 0;
  background: tomato;
  transition: all 0.3s;
  width: 0;
  height:2px;
}

.header__navigation .nav>span:hover {
  cursor: pointer;
}

.header__navigation .nav>span:hover:before {
  width: 100%;
}

      Home

      About

      Contact


text:
Q: Testfor block with custom name I'm making "magic blocks": if you are standing on a specific block you get a potion effect like speed, instant health, strength, etc. The only problem is while trying to make it survival friendly I want the player to have to rename a diamond block to the certain name to make the potion effects work. /execute @a ~ ~ ~ detect ~ ~-1 ~ minecraft:diamond_block 0 /effect @a minecraft:strength 5 30
So that's what I use currently but is there an NBT tag that makes it so the detect part can testfor a diamond block that's been named in an anvil?

A: When you place a named block, it loses its name tag, making it impossible to detect if it was ever named. What you can do, however, is set a custom data value:
/setblock ~ ~ ~ diamond_block 1

Then, replace detect ~ ~-1 ~ diamond_block 0 with diamond_block 1. You can use values 1 through 15, but values above 15 are not supported.
Note: In some versions of the game (and possibly the latest updates), blocks with custom data may have a missing texture, and the custom data may not be saved properly. You'll have to look into this yourself as I can't test it at the moment.

A: Blocks cannot have names.  If you use an anvil, that only renames the item stack.  Instead of trying to detect the block, try spawning an invisible marker armor stand with a custom name.
e.g. /summon ArmorStand ~ ~-1 ~ {Invisible:1, Marker: 1, CustomName: "Magic Block"}.  You could then use the execute command to do things based on that armor stand.


text:
Q: flutter, RenderBox was not laid out: RenderRepaintBoundary#4de33 relayoutBoundary=up14 NEEDS-PAINT I use tabBar,
I want to change appBar title when a tab is selected, but I get a error.
code that I get error.
  Scaffold(
    appBar: AppBar(
      leading: IconButton(
        icon: Icon(Icons.clear, color: Colors.black),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      title: TabBarView(
        children: [Text("Album"), Text("사진"), Text("동영상")],
      ),
      backgroundColor: Colors.white,
    ),
    bottomNavigationBar: TabBar(
      tabs: [
        Tab(text: "앨범"),
        Tab(text: "사진"),
        Tab(text: "동영상"),
      ],
      labelColor: Colors.black,
      indicatorColor: Colors.black,
      unselectedLabelColor: Colors.black26,
    ),
  ),

If I get rid of appBar title, I don't get error.
How to solve this problem?

A: You can add TabController and add a listener so that whenever you are switching the Tab, the setState() kicks in and the appBar title change.
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  TabController _controller;
  final List<Tab> _tab = [new Tab(text: "First",), Tab(text: "Second",), Tab(text: "Third",)];
  var _currentTab;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = new TabController(length: _tab.length, vsync: this);
    _currentTab = _tab[0];
    _controller.addListener(_selectedTab);
  }

  void _selectedTab() {
    setState(() {
      _currentTab = _tab[_controller.index];
    });
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text(_currentTab.text),
      ),
      bottomNavigationBar: TabBar(controller: _controller,tabs: _tab),
    );
  }
}


text:
Q: TensorFlow: Cannot save trained model (AssertionError) My model uses pre-processed data to predict if a customer is a private or a non-private customer. The pre-processing-step is using steps like feature_column.bucketized_column(…), feature_column.embedding_column(…) and so on.
After the training I am trying to save the model but I get the following error:

AssertionError: Tried to export a function which references untracked object Tensor("14867:0", shape=(), dtype=resource).TensorFlow objects (e.sg. tf.Variable) captured by functions must be tracked by assigning them to an attribute of a tracked object or assigned to an attribute of the main object directly.

Here is the relevant code:
(feature_columns, train_ds, val_ds, test_ds) = preprocessing.getPreProcessedDatasets(args.data, args.zip, args.batchSize)

feature_layer = tf.keras.layers.DenseFeatures(feature_columns, trainable=False)

model = tf.keras.models.Sequential([
        feature_layer,
        tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)
    ])

model.compile(optimizer='sgd',
        loss='binary_crossentropy',
        metrics=['accuracy'])

...

 model.fit(train_ds,
              validation_data=val_ds,
              epochs=args.epoch,
              callbacks=[tensorboard_callback])

 model.summary()

 if args.saveModel:
        filepath = "./saved_models/logReg" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + "-e{}-b{}-a{}".format(args.epoch, args.batchSize, accuracy)
        model.save(filepath)


text:
Q: Not able to start apache2 in ubuntu Error i get is:

Job for apache2.service failed because the control process exited with error code.
  See "systemctl status apache2.service" and "journalctl -xe" for details.

After running command systemctl status apache2.service i get :
    apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset:
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Fri 2020-05-08 13:27:50 IST; 2min 12
  Process: 12058 ExecStart=/usr/sbin/apachectl start (code=exited, status=127)

May 08 13:27:50 kaushal systemd[1]: Starting The Apache HTTP Server...
May 08 13:27:50 kaushal apachectl[12058]: /usr/sbin/apachectl: 174: /usr/sbin/ap
May 08 13:27:50 kaushal apachectl[12058]: Action 'start' failed.
May 08 13:27:50 kaushal apachectl[12058]: The Apache error log may have more inf
May 08 13:27:50 kaushal systemd[1]: apache2.service: Control process exited, cod
May 08 13:27:50 kaushal systemd[1]: apache2.service: Failed with result 'exit-co
May 08 13:27:50 kaushal systemd[1]: Failed to start The Apache HTTP Server.

After running journalctl -xe i get:
May 08 13:27:50 kaushal systemd[1]: apache2.service: Failed with result 'exit-co
May 08 13:27:50 kaushal sudo[12024]: pam_unix(sudo:session): session closed for
May 08 13:27:50 kaushal systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit apache2.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit apache2.service has failed.
--
-- The result is RESULT.
May 08 13:27:53 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:27:54 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:27:55 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:27:56 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:28:21 kaushal /usr/lib/gdm3/gdm-x-session[2772]: (EE) client bug: time
May 08 13:28:26 kaushal kernel: psmouse serio4: Touchpad at isa0060/serio4/input
May 08 13:28:26 kaushal kernel: psmouse serio4: Touchpad at isa0060/serio4/input
May 08 13:28:36 kaushal kernel: psmouse serio4: Touchpad at isa0060/serio4/input
May 08 13:28:36 kaushal kernel: psmouse serio4: Touchpad at isa0060/serio4/input
May 08 13:29:53 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:29:54 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:29:55 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
May 08 13:29:56 kaushal kernel: [UFW BLOCK] IN=wlp3s0 OUT= MAC=00:08:ca:f0:27:04
lines 1328-1350/1350 (END)


text:
Q: ClassNotFoundException when app launch I created an Andriod app for a Chinese Newspaper Company.
From the Exception/ANR report of Google Play Store, it was found that some users encountered the problem of ClassNotFoundException when they launch the app.
The app cannot found the activity marked as
<category android:name="android.intent.category.LAUNCHER" />

The frequency is about every 3 sessions out of 500000.
What are the possibilities leading to ClassNotFoundException?
Remakrs:
 I doubt if this related to the package name.
In the first few lines of AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.abc.news"

the source code are stored in different folder name (Real file storage place)
com.anotherCompany.abc

so.. in the activity tag (AndroidManifest)
<activity
   android:name="com.anotherCompany.abc.MainActivity"
   android:label="@string/app_name"

Thank you for your time

A: If this happens rarely, I think you shouldn't worry too much about it.
It can be due to a bad installation, a bad phone backup, or some android mods. But probably not something related to your code.


text:
Q: python extract xml element value to csv I'm a new to python so please bear with me as I try to explain what I am trying to do
here is my xml
<?xml version="1.0"?>
<playlist>
    <list>
        <txdate>2015-10-30</txdate>
        <channel>cake</channel>
        <name>Play List</name>
    </list>
    <eventlist>
        <event type="MEDIA">
            <title>title1</title>
            <starttype>FIX</starttype>
            <mediaid>a</mediaid>
            <onairtime>2015-10-30T13:30:00:00</onairtime>
            <som>00:00:40:03</som>
            <duration>01:15:47:15</duration>
            <reconcilekey>123</reconcilekey>
            <category>PROGRAM</category>
            <subtitles>
                <cap>CLOSED</cap>
                <file>a</file>
                <lang>ENG</lang>
                <lang>GER</lang>
            </subtitles>
        </event>
        <event type="MEDIA">
            <title>THREE DAYS AND A CHILD</title>
            <mediaid>b</mediaid>
            <onairtime>2015-10-30T14:45:47:15</onairtime>
            <som>00:00:00:00</som>
            <duration>01:19:41:07</duration>
            <reconcilekey>321</reconcilekey>
            <category>PROGRAM</category>
            <subtitles>
                <cap>CLOSED</cap>
                <file>b</file>
                <lang>ENG</lang>
                <lang>GER</lang>
            </subtitles>
        </event>
    </eventlist>
</playlist>

I would like to print all the mediaid values to a file
this is my code so far
import os
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
wfile = 'new.csv'
for child in root:
    child.find( "media type" )
    for x in child.iter("mediaid"):
        file = open(wfile, 'a')
        file.write(str(x))
    file.close

I tried this with a few other nonstandard libraries but I didn't have much success

A: For your requirement (as mentioned in the comments) -

just the mediaid from each <event type="MEDIA">

You should use findall() method of ElementTree to get all the event elements with type="MEDIA" , and then get the child mediaid element from it. Example -
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
with open('new.csv','w') as outfile:
    for elem in root.findall('.//event[@type="MEDIA"]'):
            mediaidelem = elem.find('./mediaid')
            if mediaidelem is not None:
                    outfile.write("{}\n".format(mediaidelem.text))


text:
Q: Arrangements in which only two of the three empty chairs are next to each other While studying, I got stuck on this problem: "Seven identical chairs in a row are to be seated by four students. How many arrangements are there such that the only two of the three empty chairs are next to each other?"
The answer key showed the answer as being 480, but I got 720. Could anyone explain how to get the correct answer of 480?

A: Let's choose the empty chairs first:
Suppose they are at either end of the row (the empty chairs are 1 and 2, or 6 or 7... 2 possibilities). There are 4 ways of choosing the third empty chair, because the seat immediately next to the two empty chairs must be seated by a student.
Suppose the two empty chairs are somewhere in the middle of the row (the empty chairs are 2 and 3, or 3 and 4, or 4 and 5, or 5 and 6... 4 possibilities). Then the chair to the either side of the two empty chairs must be seated by students, and there are three chairs to choose from for the next empty chair.
So there are $2*4+4*3=20$ ways to choose the three empty chairs.
Now, for each of the 20 ways, there are 4 chairs that the students must be seated in. There are $4!=24$ ways to arrange 4 students in those 4 chairs.
By the multiplication principle, the total number of ways is $20*24=480.$

A: I think you should learn another method, which you may find simpler.

*

*Club 2 empty chairs to be together as one big chair. So  empty chairs now form  2 objects.

*Seat the students in 4 chairs in 4! = 24 ways

*The 2 empty chairs (one normal, one big) can be placed in the 5 gaps between the students (including the ends) in $^5P_2$ = 20 ways

*Multiply to get ans = $24\times 20$ = 480


text:
Q: Complex number modulo real number I get that
a = b (mod x) means a and b have to same remainder when divided by x. But when we are dealing with complex number, what does mod even mean? if a = 3+4i, what does 3+4i mod 5 mean? how do you divide complex number by real number and have a remainder?
Particularly, how do we prove that
$$(3+4i)^n\equiv 3+4i \pmod 5$$
where $n>0$?
I am just trying to grasp what it means to have a remainder when you divide a complex number by a real number.
Thanks in advance for your help