text:
Q: Is it possible to change the /resources folder name which is used by h:outputStylesheet and h:outputScript Is it necessary to give the folder name "resources" when making the reference of a css file and js file in h:outputStylesheet and h:outputScript?
Cause when I am giving the folder name "assets" instead of "resources" these files are not loaded.
This is how I am using these tags:
<h:head>
    <h:outputStylesheet name="css/styles.css"/>
    <h:outputScript name="js/site.js"/>
</h:head>

And here is my project structure:

In the screenshot you can see the folder name is resources. And then it is working. How can I specify a different name?

A: The folder name is fixed as per chapters 2.6.1.1 and 2.6.1.2 of the JSF specification.

2.6.1.1 Packaging Resources into the Web Application Root
The default implementation must support packaging resources in the web application root
  under the path
resources/<resourceIdentifier>

relative to the web app root. Resources packaged into the web app root must be accessed using the getResource*() methods on ExternalContext.
2.6.1.2 Packaging Resources into the Classpath
For the default implementation, resources packaged in the classpath must reside under the
  JAR entry name:
META-INF/resources/<resourceIdentifier>

Resources packaged into the classpath must be accessed using the getResource*() methods of the ClassLoader obtained by calling the getContextClassLoader() method of the current Thread.

It mentions "must" in both cases. It does not mention anything about a possible configuration option to change those paths. This applies to both JSF 2.0 and JSF 2.1.
In the upcoming JSF 2.2, however, it will as per JSF spec issue 996 be possible to change the path by the new javax.faces.WEBAPP_RESOURCES_DIRECTORY context parameter which takes a path relative to the webcontent root as parameter value:
<context-param>
    <param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
    <param-value>WEB-INF/resources</param-value>
</context-param>

This example will move the /resources folder into /WEB-INF, hereby ensuring more security (i.e. it is now not possible anymore to access those resources independently from the FacesServlet).
In your particular case, you'd thus like to use the following setting when having upgraded to JSF 2.2:
<context-param>
    <param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
    <param-value>assets</param-value>
</context-param>

Note that this only covers webapp's own resources as specified in chapter 2.6.1.1, not the JAR resources as specified in chapter 2.6.1.2. The path of JAR resources should still be META-INF/resources as this is controlled by Servlet API specification, not the JSF specification. It's namely under the covers obtained by ServletContext#getResource() method which is outside control of JSF.

A: You can't specify another directory than resources unless yiu are using
<style></style>

or
OmniFaces CombinedResourceHandler

A: It is the way that the Resource Handler has been implemented in JSF 2.0, by default it will look at the following two path:
1) /resources under the root of the web application.
2) /META-INF/resources when packaged in an external JAR on the classpath.
If you want to use a different name, As mentioned by Alexandre, use the <script> and <style> tags or write your own Resource Handler.
More info:

*

*Ryan Lubke's blog entry on JSF 2.0 Resource API

*JSF 2.0 spec


text:
Q: Как получить исключение при нарушении прав доступа при чтении Могу-ли я как-то получить искючение нарушение прав доступа при чтении в try\catch что-бы в каждом месте где мне выдаёт исключение я прописывал необходимые мне условия например что бы программа не просто вылетала а выдавала return 0; Я пробовал использовать
int main()
{
    try
    {
        my code...
    }
    catch(...)
    {
        return 0;
    }

}

Но оно не сработало есть ли иные варианты?

A: Это совершенно разные исключения, просто названы одним словом, что и сбивает с толку :),  так что одни в другие в общем случае не преобразуются.
Но в Visual C++ имеется такая возможность - использовать ключ компилятора /EHa:
/EHa включить C++ EH (с исключениями SEH)

но я бы не очень рекомендовал это делать...
Подробнее о SEH в Visual C++ можно почитать тут.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function using _.curry does not work as expected I made a function that checks whether all elements in userRequest array are in whitelist array, using lodash.
The implementation is:
var isValidRequest = function (whitelist, userRequest) {
  return _.isArray(userRequest) && _.all(userRequest, _.curry(_.contains)(whitelist));
};

And made some tests to prove the function work properly:
describe('#isValidRequest', function () {
  it('should return true if all elements in userRequest are in whitelist', function () {
    var whitelist = ['a', 'b', 'c'];
    var userRequest = ['a', 'c'];
    isValidRequest(whitelist, userRequest).should.eql(true);
  });

  it('should return false if any element in userRequest are not in whitelist', function () {
    var whitelist = ['a', 'b', 'c'];
    var userRequest = ['a', 'd'];
    isValidRequest(whitelist, userRequest).should.eql(false);
  });
}

Those two tests passed. But when I add a test using real-world data, it failed:
it('should return true if all elements in userRequest are in whitelist (with real data)', function () {
  var whitelist = [
    '88096706899774400',
    '88096698426400385',
    '88354827595032721',
    '88770059167850369',
    '88770060663799793',
    '88770086312254177',
    '88775479126833601',
    '88810673591548449',
    '88911136544698224',
    '88911143320755648',
    '89018389627510081',
    '89091351154758240',
    '89138464836818065',
    '89183114982564704',
    '89244113023388657',
    '89295369695148528',
    '89301959129114097',
    '89504545841807728',
    '89534114665094448',
    '89606610296086240',
    '89641336900131600',
    '89731870992552785',
    '89738745919815345',
    '89823303352910497',
    '89840086806894128',
    '89845003632280944',
    '89848539122007344',
    '89880345515638625',
    '89896204194964448',
    '89969897520284480',
    '90010241312333393',
    '90031501817339552',
    '90037811665186016',
    '90127246523802417',
    '90127326629435841',
    '90135603990132225',
    '90163753341695809',
    '90172844493692480',
    '90173968277693249',
    '90207288890460865',
    '90246427557475376',
    '90252073971668320',
    '90293572470161952',
    '90321398525152736',
    '90327469987102145',
    '90332817802308640',
    '90399158195724752',
    '90473400215028352',
    '90513809810131312',
    '90598738792526944',
    '90599866499311776',
    '90688910073135297',
    '90729048447052800',
    '90791709927640224',
    '90797430150059264',
    '90836502447169952',
    '90840789211604048',
    '90910679553135265',
    '90955553467111249',
    '91005194750034464',
    '91107097130270400',
    '91120121727188609',
    '91250514358592672',
    '91329569249288769',
    '91361847043080400',
    '89329608853128288',
    '89364936821344896',
    '89839796561904929',
    '89958125601566961',
    '89997339418747777',
    '90009609130378257',
    '90059530916627969',
    '90258899387578336',
    '90360966983802448',
    '90576680708221921',
    '90949316113004816',
    '90972311574832433',
    '91080503304847328',
    '91353087352736736',
    '91437504999287200',
    '89222620849510145',
    '91005234554242641',
    '88701724462867649',
    '88786970344150112',
    '89981796966546737',
    '91402887254828368',
    '89409996620502544',
    '91210948485412928',
    '89018361177929809',
    '90724949851032945',
    '90829728879723920',
    '91193135505078640',
    '90019861140866640',
    '89538475013487072',
    '89860038384233984',
    '91210548905645393',
    '89308012820785888',
    '89617667142643760',
    '89607245310211489',
    '90757935350815969',
    '89860541244171121',
    '90892725971526912',
    '90886830738859280',
    '90853461057266320',
    '90806805288251792',
    '90472888904266304',
    '89824038902302577',
    '90135219888606641',
    '91029359883680448',
    '90434994851785744',
    '90333231764534192',
    '90529509422642336',
    '90529639828432736',
    '91357318422536304'
  ];
  var userRequest = [
    '88096698426400385',
    '88096706899774400',
    '88354827595032721',
    '88770059167850369',
    '88770060663799793',
    '88770086312254177',
    '88775479126833601',
    '88810673591548449',
    '88911136544698224',
    '88911143320755648',
    '89018389627510081',
    '89091351154758240',
    '89138464836818065',
    '89183114982564704',
    '89244113023388657',
    '89295369695148528',
    '89301959129114097',
    '89504545841807728',
    '89534114665094448',
    '89606610296086240',
    '89641336900131600',
    '89731870992552785',
    '89738745919815345',
    '89823303352910497',
    '89840086806894128',
    '89845003632280944',
    '89848539122007344',
    '89880345515638625',
    '89896204194964448',
    '89969897520284480',
    '90010241312333393',
    '90031501817339552',
    '90037811665186016',
    '90127246523802417',
    '90127326629435841',
    '90135603990132225',
    '90163753341695809',
    '90172844493692480',
    '90173968277693249',
    '90207288890460865',
    '90246427557475376',
    '90252073971668320',
    '90293572470161952',
    '90321398525152736',
    '90327469987102145',
    '90332817802308640',
    '90399158195724752',
    '90473400215028352',
    '90513809810131312',
    '90598738792526944',
    '90599866499311776',
    '90688910073135297',
    '90729048447052800',
    '90791709927640224',
    '90797430150059264',
    '90836502447169952',
    '90840789211604048',
    '90910679553135265',
    '90955553467111249',
    '91005194750034464',
    '91107097130270400',
    '91120121727188609',
    '91250514358592672',
    '91329569249288769',
    '91361847043080400'
  ];

  isValidRequest(whitelist, userRequest).should.eql(true);
});

Data size has increased(whitelist: 3 -> 114, userRequest: 2 -> 65), and I verified all elements in userRequest are in whitelist. So the test should pass, but failed.
I made a function that works exactly same but implementation is different:
var isValidRequest2 = function (whitelist, userRequest) {
  return _.isArray(userRequest) && _.all(userRequest, function(elem) { return _.contains(whitelist, elem); });
};

With this new function, all tests passed.
In console of Chorme dev tools, same things happen:
> _.all(userRequest, _.curry(_.contains)(whitelist))
  false
> _.all(userRequest, function(elem) { return _.contains(whitelist, elem); })
  true

I think there's some problem with _.curry, but not sure.
It'll be great if someone explain the problem of the first function using _.curry.
FYI, I'm using lodash v2.4.1 .

A: _.all calls iterator (the second parameter) with additional parameters
_.all([1, 2, 3], function () { console.log(arguments); return true; });
[1, 0, Array[3]]
[2, 1, Array[3]]
[3, 2, Array[3]]
true

_.contains has an optional third parameter, fromIndex, which matches index given by _.all. Thus real data breaks.
Try to reorder elements in your basic tests, and you'll see the fact.
isValidRequest(['a', 'b', 'c'], ['a', 'c']) // true
isValidRequest(['a', 'b', 'c'], ['c', 'a']) // false


text:
Q: Rearranging table in JavaScript I want reorder table rows using JavaScript .
for example take the following dummy table:

    1
    2
    3
    4

    A
    B
    C
    D

    A1
    B1
    C1
    D1

I want to do this in JavaScript without using jQuery.  I want to show the A1,B1,C1,D1.. row as the first row and then 1,2,3,4 row and then A,B,C,D row.
I know that there will be some wait time on the client side but I need to do it in the client side. Is there some generic solution to do this, for any number of rows?

A: Do:
var table = ...; // Get reference to table (by ID or other means)
var lastRow = table.rows[table.rows.length - 1];
lastRow.parent.insertBefore(table.rows[0], lastRow);

A: The best way to solve this in Javascript is:
Give the Tr.. a unique name.  for eg: X_Y,X_Z,A_Y,A_Z
Now add a hidden lable or text Box which gives the sorting order from the server i.e  When the page renders I want to sort it  All the Tr's that have a ID starting with A should come first and All the Z's should come second.
<asp:label id="lblFirstSortOrder" runat="server" style="display:none;">A,X
<asp:label id="lblSecondSortOrder" runat="server" style="display:none;">Z,Y

When the page renders..the order should be A_Z,A_Y,X_Z,X_Y
Before Rendering this is table that comes from the aspx file:

  A
  B

  GH
  GH1

  HU
  HU1

  JI
  JI1

  JI
  JI1

Script:
function SortAndArrange()
{
var firstList = document.getElementById('lblFirstSortOrder').value;
var secondList = document.getElementById('lblSecondSortOrder').value;
var firstTypes = new Array();
firstTypes = firstList.split(',');
var secondLists = new Array();
secondLists = secondList.split(',');
var refNode = document.getElementById('Tbl_' + firstTypes[0] + "_" + secondTypes[0]);
for (var i = 0; i<firstTypes.length; i++)
{
  for (var j = 0; j< secondTypes.length;j++)
  {
     var TrName = 'Tbl_'+firstTypes[i]+'_'+secondTypes[j];
     var FirstSecondTrs = document.getElementById(TrName);
     if (FirstSecondTrs)
     {
       FirstSecondTrs.parentNode.removeChild(FirstSecondTrs);
       insertAfter(refNode,FirstSecondTrs);
       refNode = FirstSecondTrs;
     }
  }
 }
}
function insertAfter( referenceNode, newNode )
{
 referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

I hope you guys get the idea.. for me the sorting order will always come from the server and not from the user of the page...
Thanks a Lot for all the answers.. Apprecite it. Helped me get to this solution.
Thanks,
Ben

A: If I understand correctly, you are asking how to take the last row and make it the first row, pushing down the rest. This should do it:

...

Assuming your table does not have nested tables. At which point this would need to be a little smarter. This also assumes you're not using TBODY and THEAD nodes. But I'm sure you can get the idea and enhance it from there.


text:
Q: how to handle system.net.mail.smtpfailedrecipientsexception failed recipients I wanna send email to multiple addresses (more than 1000 users) and use the following code, when I use it to send email to less than 100 users it works, but for more than 100 users it does not work and throw smtpfailedrecipientsexception failed recipients! why? how can I send email to valid addresses and get ride of this error?
public void SendMailMessage (string[] to,string message,string subject)
    {
        MailMessage mMailMessage = new MailMessage ();
        int lenght = to.GetLength(0);
        if (lenght > 1) {
            foreach (string email in to) {
                mMailMessage.Bcc.Add ( email );
            }
        }
        else {
            mMailMessage.To.Add ( to[0] );
        }

                mMailMessage.From = new MailAddress ("no-replay@mycompany.net");
                SmtpClient mSmtpClient = new SmtpClient ();
                mMailMessage.Body = message;
                mMailMessage.IsBodyHtml = true;
                mMailMessage.Priority = MailPriority.Normal;
                mMailMessage.Subject = subject;
                mSmtpClient.EnableSsl = true;
                ServicePointManager.ServerCertificateValidationCallback = delegate(object s,X509Certificate certificate,X509Chain chain, SslPolicyErrors sslPolicyErrors) {return true;};
            try {
                mSmtpClient.Send (mMailMessage);
        }
        catch (SmtpFailedRecipientsException ex){
            for (int i = 0; i < ex.InnerExceptions.Length; i++)
            {
                SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                if (status == SmtpStatusCode.MailboxBusy ||
                    status == SmtpStatusCode.MailboxUnavailable)
                {
                    Logger.Debug("Delivery failed - retrying in 5 seconds.");
                    System.Threading.Thread.Sleep(5000);
                    //client.Send(message);
                    mSmtpClient.Send (mMailMessage);

                }
                else
                {
                    Logger.Debug (string.Format ("Failed to deliver message to {0},{1}", ex.InnerExceptions[i].FailedRecipient, i));

                }

            }
        }
        catch (Exception ex)
        {
            Logger.Debug (string.Format("Exception caught in RetryIfBusy(): {0}", ex.ToString() ));
        }

    }

A: Looks like SMTP server that you are using is rejecting mails that have more then 100 recepients.
You can:

*

*use distribution lists instead of sending message to each recipient directly

*send multiple messages with no more than 100 recipients

*talk to admin of this server to change the limit

But be aware, that when you are sending messages to hundred of external recipients, spam filters would probably flag them as spam.

A: I found this in one of the Microsoft documentation that exception handled like following:
 var client = new System.Net.Mail.SmtpClient();
        try
        {
            client.Send(mailMessage);
        }
        catch (SmtpFailedRecipientsException ex)
        {
            for (int i = 0; i < ex.InnerExceptions.Length; i++)
            {
                SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                if (status == SmtpStatusCode.MailboxBusy ||
                    status == SmtpStatusCode.MailboxUnavailable)
                {
                    Console.WriteLine("Delivery failed - retrying in 5 seconds.");
                    System.Threading.Thread.Sleep(5000);
                    client.Send(mailMessage);
                }
                else
                {
                    Console.WriteLine("Failed to deliver message to {0}",
                        ex.InnerExceptions[i].FailedRecipient);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
                    ex.ToString());
        }

But i don't know how to generate exception scenario for this exception
Microsoft link - for mode details


text:
Q: Null Reference exception when accessing a singleton with Autofac I'm getting null reference exception when trying to access a singleton class from my ASP.NET MVC Controller Action. I use Autofac as the IoC Container.
Here is the code:
Register dependencies method:
public static void RegisterDependencies()
    {
        var builder = new ContainerBuilder();
        const string nameOrConnectionString = "name=DefaultConnection";
        builder.RegisterApiControllers(typeof(WebApiConfig).Assembly);
        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.RegisterModule<AutofacWebTypesModule>();

        builder.RegisterGeneric(typeof(EntityRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
        builder.RegisterGeneric(typeof(Service<>)).As(typeof(IService<>)).InstancePerLifetimeScope();
        builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerLifetimeScope();
        builder.Register<IEntitiesContext>(b =>
        {
            var logger = b.Resolve<ILogger>();
            var context = new InterfaceContext(nameOrConnectionString, logger);
            return context;
        }).InstancePerRequest();
        builder.Register(b => NLogLogger.Instance).SingleInstance();
        builder.Register(b => UserControlHelper.Instance).SingleInstance();
        builder.RegisterModule(new IdentityModule());

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver =
             new AutofacWebApiDependencyResolver(container);
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

UserControlHelper class:
public class UserControlHelper
{
    private static volatile UserControlHelper _instance;
    private static readonly object SyncRoot = new object();

    private static IService<Administrator> _service;
    private static IService<Customer> _customerService;

    private UserControlHelper() { }

    private UserControlHelper(IService<Administrator> service, IService<Customer> customerService)
    {
        _service = service;
        _customerService = customerService;
    }

    public static UserControlHelper Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (SyncRoot)
                {
                    if (_instance == null)
                        _instance = new UserControlHelper(_service, _customerService);
                }
            }

            return _instance;
        }
    }

    public static string GetUserData(int userId, string type)
    {
        var getImage = _service.GetByIdAsync(userId);

        switch (type)
        {
            case "Image":
                {
                    return getImage.GetAwaiter().GetResult().Image;
                }
            case "Name":
                {
                    return getImage.GetAwaiter().GetResult().FullName;
                }
            case "Email":
                {
                    return getImage.GetAwaiter().GetResult().Email;
                }

            case "AllUsers":
                {
                    return _customerService.GetCountAsync(userId).GetAwaiter().GetResult().ToString();
                }

            default:
                return "No Data";
        }
    }
}

I'm calling it like this:

ViewBag.FullName = UserControlHelper.GetUserData(UserId, "Name");

A: Your _service variable is going to be null all the time. Hence you maybe getting the null referece.
private static IService<Administrator> _service;

This variable is never instantiated (manually or via Autofac)
And when you call your method, this is the code that might be causing the null reference.
    var getImage = _service.GetByIdAsync(userId);

because _service is null
For all the Autofac wireup being done, there is no place we are indicating to Autofac that this class needs to be instantiated automatically. The class doesn't seem to be a controller (MVC or API) or any dependencies to the controller.
Also, the _service variable being static doesn't help with Autofac.
To solve the problem, you might want to rethink this class in terms of a controller or better, a dependency (constructor parameter) to a controller, with the _service and such variables as instance variables rather than static variables, where Autofac cannot help you much.
This way, when the controller is instantiated by Autofac, it'll automatically create an instance of 'UserControlHelper' for you.
Answering to your comment (You need a singleton of UserControlHelper):

*

*you can leverage Autofac for this.

*we'll make this class a constructor parameter of your controller.

*And let Autofac know to instantiate this as a singleton.
public class MyController: Controller
{
 public MyController(UserControlHelper helper)
 {
  ViewBag.FullName = helper.GetUserData(UserId, "Name");
 }
}

And when you register this class with Autofac, you can do:
build.RegisterType<UserControlHelper>().SingleInstance();

This would mean that you have to remove the Instance variable and any singleton-like logic in your class. And also convert the static methods to instance methods. And convert the constructor to a public one.
It is best to let Autofac/frameworks do the grunt work of Singletons/other such functionality. (Lazy variables are another such tool)
And we can focus on keeping your class relevant to the business logic.
And if you really want to do the singleton implementation yourself, you can still register it with autofac as:
builder.RegisterInstance<UserControlHelper>(singletonInstanceYouConstructed);

But in general, I have found it to be simpler to let Autofac manage the whole lifetime management.


text:
Q: quartz scheduler 2.x : When I stop tomcat server I have this error generated by Quartz In my application, i use Quartz scheduler 2.1.x version
when I stop tomcat server
I have this error :
19 mai 2014 15:52:48 org.apache.coyote.http11.Http11Protocol destroy
INFO: Arrêt de Coyote HTTP/1.1 sur http-8080
Exception in thread "Quartz Shutdown-Hook CronTriggers" java.lang.NullPointerException
Exception in thread "Quartz Shutdown-Hook CronTriggers" at org.apache.log4j.helpers.PatternConverter.spacePad(PatternConverter.java:107)
at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:80)
at org.apache.log4j.PatternLayout.format(PatternLayout.java:506)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:310)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:162)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
at org.apache.log4j.Category.callAppenders(Category.java:206)
at org.apache.log4j.Category.forcedLog(Category.java:391)
at org.apache.log4j.Category.log(Category.java:856)
at org.slf4j.impl.Log4jLoggerAdapter.info(Log4jLoggerAdapter.java:305)
at org.quartz.plugins.management.ShutdownHookPlugin$1.run(ShutdownHookPlugin.java:125)
java.lang.NullPointerException
at org.apache.log4j.helpers.PatternConverter.spacePad(PatternConverter.java:107)
at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:80)
at org.apache.log4j.PatternLayout.format(PatternLayout.java:506)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:310)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:162)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
at rg.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
at org.apache.log4j.Category.callAppenders(Category.java:206)
at org.apache.log4j.Category.forcedLog(Category.java:391)
at org.apache.log4j.Category.log(Category.java:856)
at org.slf4j.impl.Log4jLoggerAdapter.info(Log4jLoggerAdapter.java:305)
at org.quartz.plugins.management.ShutdownHookPlugin$1.run(ShutdownHookPlugin.java:125)

Any help is welcome.
Thanks

A: Don't use a shut down hook to stop quartz. Use a ServletContextListener in your web application. This will also stop (one cause of) a memory leak on web application reload.


text:
Q: Can I do anything to mitigate GDI resource leakage in Windows? There's a problem on all Windows systems that there's a limitation on graphical primitives that can be used system-wide. Which leads to the following: once I've started several (actually something like 25+) GUI-rich apps like Visual Studio or Internet Explorer I can't open any more windows - depending on how the application reacts to this either nothing happens or an error is reported.
Is there anything I can tune in Windows to at least make the upper limit on these primitives higher?

A: Take a look at this MSDN article. It explains how to increase the limit of GDI objects in your system
This MSDN article explains how to increase the limit of User object.

A: This Microsoft NTDebugging article explains at length how the Desktop Heap can be exhausted and prevent opening additional windows.  Indeed, this was THE crucial solution to my own problem of opening an extreme amount of programs on a Windows 2000 and Windows XP workstation.  I had to increase my "3072" value to "8192" before I fixed it, after that, I've NEVER run out of handles again, even with 310 Chrome Tabs open simultaneously plus about 20 other applications on a 4GB RAM WinXP 32-bit system.


text:
Q: Removing first and last item from double nested array if empty = true I'm working with prism-react-renderer, and it highlights my template string that I render in JSX inside MDX. This causes some whitespace when using it due to the spacing:
<Code>
{`
function test() {
    return "Test";
};
`}
</Code>

This causes prism-react-renderer to create an empty first and last line. I want to remove these first and last lines if they are empty. The array I'm working with has the following type:
type TokenArray = {
  types: string[];
  content: string;
  empty?: boolean;
}[][];

The outer array holds arrays which represent the lines. These inner arrays contain an object with a empty property.
I want to remove the first or last item from the outer array tokenArray if the line has its empty property set to true.
What I've tried
Look at the first item of the outer array with tokenArray[0] and get its only item ( how? ) and check whether that object has a property named empty with a value of true. If so, call tokenArray.shift()
The same can be done for the last item but I don't know how to access it with tokenArray[?].
Please help me out.

A: If you want first element in 2d array, then use like array[0][0]. (Like we are accessing by array[row][column])
For last item, it will be
array[last row][last column]

last_row = array[array.length - 1]

last item in last row = array[array.length - 1][last_row.length - 1]
Here is link for typescript playground
type TokenArray = {
  types: string[];
  content: string;
  empty?: boolean;
}[][];

const tokens: TokenArray = [
    [{ types: ['a', 'b'], content: 'abc', empty: true },
        { types: ['c', 'd'], content: 'cde', empty: false }],
    [{ types: ['p', 'q'], content: 'pqr', empty: true },
        { types: ['x', 'y'], content: 'xyz', empty: false }],
];

const first = tokens[0][0];
const last = tokens[tokens.length - 1][tokens[tokens.length - 1].length - 1];
console.log('first', first, "Is Empty true?: ", first.empty === true);
console.log('last', last, "Is Empty true?: ", last.empty === true);


text:
Q: Remove duplicate rows in my specific case? I've had to use and maintain an old database scheme for gameservers...
A really bad one. Every column with data which could've had a non-numeric character in it was stored as text.
I've converted every column to the proper data type, but now I am facing an issue with setting the primary index.
It should be id, the entry which contains the specific user's unique identification string. (it's a varchar).
Due to previous lack of indexing and an innocent, unsolvable bug due to our multiple gameservers (we have plenty, and had plenty more in the past) accessing the same tables, we have some duplicate rows, and thus are unable to set the column as primary index.
I have very little experience with MySQL or SQL in general. I don't know how to write a query to remove the duplicates.
One of our tables has two columns, id and lst (varchar). For this one, the duplicates have completely identical rows, due to a lack of limiting in the update query.
The other is a tad bit more complex. It has the same id column, and quite a lot more. There are three that matter, though: id, cur (int) and mdl (varchar). The duplicate finding rule here is a bit more complex. Firstly, whichever has a mdl other than a specific value (let it be "default.mdl", for instance) is more likely to be the latest info. Secondly, the one with the highest cur value is more likely to be the correct one.
Based on these, I only need to keep the latest (most likely to be correct) row in each (not both) of the two tables for every id.
How do I do this with only SQL?
Edit: The reason why I'm not doing this manually is that each table has ~186,000 rows, and I estimate that 1/20 (~9,000) rows are duplicates.

A: The easiest way to do this is probably through creating temporary tables, then copying and moving some data around.
It's a little hard to tell you what exactly to do since there's no schema to reference, but hopefully this will get you on the right track. It assumes that the table name of the first table you mentioned is my_table_1, the second is my_table_2, that you have permission to create / drop tables, and that you've backed up your database (if you haven't backed it up, stop now):
# First, add what will become the new id column. We'll rename it shortly.
ALTER TABLE `my_table_1`
  ADD `id_new` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

ALTER TABLE `my_table_2`
  ADD `id_new` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

# Next, build the structure to backup the existing values for future reference.
CREATE TABLE `temp_table_backup` (
  `id_orig` varchar( 255 ) NOT NULL,
  `id_new` int( 10 ) NULL DEFAULT NULL,
  `lst` varchar( 255 ) NULL DEFAULT NULL,
  `cur` int( 10 ) NULL DEFAULT NULL,
  `mdl` varchar ( 255 ) NULL DEFAULT NULL
);

# Now copy the old id values to the backup table
INSERT INTO temp_table_backup
  SELECT
    my_table_1.id,
    my_table_1.id_new,
    my_table_1.lst,
    my_table_2.cur,
    my_table_2.mdl
  FROM
    my_table_1
  INNER JOIN
    my_table_2
  ON
    my_table_1.id = my_table_2.id GROUP BY my_table_1.id;

# Create a table to use temporarily. I'm avoiding temporary tables because of the
# complexity of this whole thing.
CREATE TABLE `temp_table_1` (
  `id` int( 10 ) NOT NULL
);

# Copy values to the new table...
INSERT INTO temp_table_1
  SELECT
    p2.id
  FROM
    my_table_1 AS p1,
    my_table_1 AS p2
  WHERE
    p1.lst = p2.lst
  AND
    p1.id != p2.id
  GROUP BY p2.lst;

# Create another table (temporarily) for my_table_2. This one's kinda tricky,
# but "ranks" things according to different criteria.
CREATE TABLE `temp_table_2` (
  `id` int( 10 ) NOT NULL,
  `id_new` int( 10 ) NULL DEFAULT NULL,
  `rank` int( 10 ) NULL DEFAULT NULL,
  `cur` int( 10 ) NULL DEFAULT NULL,
  `mdl` varchar ( 255 ) NULL DEFAULT NULL
);

# Copy values to the new table...
INSERT INTO temp_table_2
  SELECT t1.id AS id,
  t1.id_new AS id_new,
  CASE
    WHEN t1.mdl = 'default.mdl' AND t1.cur >= t2.cur THEN 4
    WHEN t1.mdl = 'default.mdl' AND t1.cur < t2.cur THEN 3
    WHEN t1.mdl != 'default.mdl' AND t1.cur >= t2.cur THEN 2
    ELSE 1
  END AS rank,
  t1.cur AS cur,
  t1.mdl AS mdl
  FROM
    `my_table_2` AS t1,
    `my_table_2` AS t2
  WHERE t1.id != t2.id
  GROUP BY id HAVING MAX(rank)
  ORDER BY
    rank DESC,
    t1.cur DESC,
    id ASC;

# Update values in the old table using the values from temp_table_2.
UPDATE
  IGNORE `temp_table_2`,
  `my_table_2`
SET
  `my_table_2`.cur = `temp_table_2`.cur,
  `my_table_2`.mdl = `temp_table_2`.mdl
WHERE
  `my_table_2`.id_new = `temp_table_2`.id_new;

# Delete stale values...
DELETE
  FROM my_table_1
  WHERE id IN (SELECT id FROM temp_table_1);
# Again...
DELETE
  FROM my_table_2
  WHERE id IN (SELECT id FROM temp_table_1);

# Next, drop the old id columns and rename id_new to id
ALTER TABLE
  `my_table_1`
DROP `id`;

ALTER TABLE
  `my_table_1`
CHANGE
  `id_new` `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT;

ALTER TABLE
  `my_table_2`
DROP `id`;

ALTER TABLE
  `my_table_2`
CHANGE `id_new` `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT;

# Optional. We're done with these tables but you can drop or keep them if you want.
DROP TABLE IF EXISTS temp_table_1;
DROP TABLE IF EXISTS temp_table_2;
DROP TABLE IF EXISTS temp_table_backup;


text:
Q: How To Set global current_user on Wordpress Using PHP? I am using the following code to login a user.
$UserName and $Password is coming in via a Form. The following if statement is showing TRUE, so my user is getting logged in.
$user = get_user_by( 'login', $UserName );
if ( $user && wp_check_password( $Password, $user->data->user_pass, $user->ID) )

Now as long as the User is on the website I want his $UserName to be known by all the PHP programs he invokes.
Whenever I log someone in using the wp-admin screen the $UserName is brought in to all PHP programs by executing the following code:
global $current_user;
if ( isset($current_user) ) {
    $UserName=$current_user->user_login;
}

My question is.... using the login at the top of this post how do I save the $Username in such a way that it is brought into other PHP programs using the above isset($current_user) if statement?
I tried the following code but it does not bring the $current_user field into other PHP programs by executing the IF (isset($current_user) statement. The $user->user_login field contents is equal to $UserName.:
$user_id = $UserName;
$user = get_user_by( 'id', $user_id );
$current_user=  new WP_User( $user_id , $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login );
global $current_user;

What am I missing?  Any assistance will be greatly appreciated. Thank you


text:
Q: Why youtube api v3.0 thumb file image has black bars on top and bottom I am attempting to resolve why I get two black bars in YouTube V3.0 JSON response thumb files images.
Following is what I get in JSON response (thumbnail section). If I put this link https://i.ytimg.com/vi/YnIRfvFLiWQ/default.jpg to browser address bar I see 2 black bars on top and bottom of the picture. But if I search the video (ID YnIRfvFLiWQ) in Youtube (https://www.youtube.com/watch?v=YnIRfvFLiWQ), and if I right click the tmumb image I see this address https://i.ytimg.com/vi_webp/YnIRfvFLiWQ/mqdefault.webp as the thumb file url which shows without black bars on top and bottom of the picture. Any idea why this clean picture url does not return in JSON file below?
"thumbnails": {
 "default": {
  "url": "https://i.ytimg.com/vi/YnIRfvFLiWQ/default.jpg",
  "width": 120,
  "height": 90
 },
 "medium": {
  "url": "https://i.ytimg.com/vi/YnIRfvFLiWQ/mqdefault.jpg",
  "width": 320,
  "height": 180
 },
 "high": {
  "url": "https://i.ytimg.com/vi/YnIRfvFLiWQ/hqdefault.jpg",
  "width": 480,
  "height": 360
 },
 "standard": {
  "url": "https://i.ytimg.com/vi/YnIRfvFLiWQ/sddefault.jpg",
  "width": 640,
  "height": 480
 },
 "maxres": {
  "url": "https://i.ytimg.com/vi/YnIRfvFLiWQ/maxresdefault.jpg",
  "width": 1280,
  "height": 720
 }


text:
Q: Meaning of @Resource annotation I'm unable to understand the meaning of the @Resource annotation. I've looked at online resources, but they seem to explain the same in a way which is difficult to comprehend. Can someone please explain the meaning of @Resource in a simplistic manner, if possible?
Thanks !

A: First of all, to understand the point of @Resource you need to understand the Inversion of Control (IoC).
Inversion of Control is a principle in software development which goes that the control of objects should be transferred to a container or a framework.
Dependency Injection (DI) is a pattern of IoC implementation, where the control being inverted is the setting of object's dependencies.
The act of composing objects with other objects (injecting) is done by a container rather than by the objects themselves.
Using a DI framework (like Spring IoC or EJB) you're creating your POJOs and configuring the framework (a POJO configured such way called a Bean). A Bean may have different scopes, like singleton (1 object instance per container), prototype (creates a new instance of an object per injection or explicit call) and etc.

So far, so good. What's next? It's time to use our beans.
@Resource is the annotation that will help to extract beans from the container.
There are several lookup options to extract beans:

*

*Match by Name

*Match by Type

*Match by Qualifier

Using @Resource without any parameters will trigger Match by Type lookup type.
There is an example of usage or @Resource with field injection and Spring framework with Java-based configuration and Match by Name:
@Configuration
public class ApplicationContext {

    // Put the bean into the spring container
    @Bean(name = "userFile")
    public File userFile() {
        File file = new File("user.txt");
        return file;
    }
}

@Service
class UserService {

    // Ask the container to get the bean and 'put' it here (inject)
    @Resource(name = "userFile")
    private File userFile;

}

@Resource is usually used to inject data sources, singleton services, context configurations and etc.

A: The @Resource annotation is used to identify a class, field, or method that upon initialization, the resource will be injected. For a class-based @Resource, the "resource is looked up by the application at runtime".
Further information can be found here: https://docs.oracle.com/javaee/6/tutorial/doc/bncjk.html


text:
Q: How does Google Cloud AI Platform allocate the resources in a given region, does it follow the quota restrictions? I have a free amount of TPUs allocated for zone us-central1-a. But only for that specific zone.
When I setup Platform-ai jobs I can only specify a region (us-central).
Will the platform AI pick up a random region only based on availability? Is there a way I can restrict it to the given region?

A: First, let's clarify the naming convention: us-central1-a is a zone within us-central1 region.
It's indeed based on availability. You cannot explicitly select the zone, only the region. If your free resources are bound to a zone, one way to make sure you stay on us-central1-a is to select a TPU class that is bound to that zone. At the time of writing, this would be:

*

*v2-32 256 GiB

*v2-128 1 TiB

*v2-256 2 TiB

*v2-512 4 TiB

Based on these docs. I'd check them from time to time to avoid nasty surprises. Typically though the customer service will be able to help you if you run into billing issues (you get caught in a different zone).


text:
Q: Absolutely Minimizing Lipschitz extension Is there an analytical or even numerical way to find the Absolutely Minimizing Lipschitz extension of a given function?
I know that the extension exist and it is unique  (by Aronsson et al).
I found two schemes by Adam Oberman 2 and 3.
But the first is not realy Absolutely Minimizing
and the second is feasible only in very low euclidean dimension
Is there anything better?


text:
Q: Read more than one attribute from select list I have a component like that:
                    <lightning:select aura:id="selectedContact" onchange="{!c.onChangeFunction}">
                        <aura:iteration items="{!v.relatedContactList}" var="contact">
                            <option value="{!contact.LastName}" selectedLastName="{!contact.LastName}" selectedEmail="{!contact.Email}">{!contact.FirstName} {!contact.LastName} : {!contact.Email}</option>
                        </aura:iteration>
                    </lightning:select>

And a client side controller that is triggered on a button with the following code:
console.log(cmp.find("selectedContact").get("v.selectedEmail"));
console.log(cmp.find("subjectLine").get("v.value"));
console.log(cmp.find("rejectText").get("v.value"));

I can read the subjectLine and rejectText successfully, but not selectedEmail. It seems I can only access .value, not .anythingelse
How do I get the email in this example to my controller?

A: In Option tag, there are no attributes like selectedLastName , selectedEmail, thus you won't be able to bind it. Only Value attribute of option is what you can bind.
You have to change your strategy.  I can think up of using indexVar of aura:iteration. The idea is to store the selected index and use it in JS controller to get the contacts value.
<aura:attribute type="Integer" name="selectedContactIndex" default="0"/>
<lightning:select aura:id="selectedContact" onchange="{!c.onChangeFunction}"  value="{!v.selectedContactIndex}">
                        <aura:iteration items="{!v.relatedContactList}" var="contact" indexVar="index" >
                            <option value="{!index}" >{!contact.FirstName} {!contact.LastName} : {!contact.Email}</option>
                        </aura:iteration>
</lightning:select>

And in JS.
var contactList =component.get("v.relatedContactList");
var selectedIndex = component.get("v.selectedContactIndex");
var selectedContact = contactList[selectedIndex];
console.log(selectedContact.Email);
console.log(selectedContact.FirstName);
console.log(selectedContact.LastName});

Src: Lightning: aura:iteration - how to refer indexVar variable inside loop to access elements in List?
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/ref_tag_iteration.htm


text:
Q: Visual Studio Designer for Javascript App I'm writing an application and after some Proof-of-concept work I'm starting to design the app in UML. It will be an HTML5/Javascript app with a simple ASP.NET backend serving data over SignalR and AJAX to the front.
I want to design the C# classes and the JS "classes" in UML and I'm testing out the Visual Studio designer (2013) to see if it'll work. My problem is that the designer always create C# classes for every UML class, but some of these will be JS classes. Is there any way to turn off the code generation?
Comments on other/better tools are welcome.


text:
Q: How to do minimum pooling in tensorflow? Tensorflow has operations for average and max pooling, but not for minimum pooling.
Is there some sort of work around to get min pooling?

A: we can manually recreate MaxPooling in this way...
x = np.random.uniform(0,1, (5,30,30,3)).astype('float32')

n_channel = x.shape[-1]
patches = tf.image.extract_patches(x,
                                   sizes = [1, 3, 3, 1],
                                   strides = 4*[1],
                                   rates = 4*[1],
                                   padding = 'VALID')

channel_pool = [tf.reduce_max(patches[:,:,:,c::n_channel], keepdims=True, axis=-1) for c in range(n_channel)]
res = tf.concat(channel_pool, axis=-1)

tf.reduce_all(res == MaxPool2D(pool_size=(3, 3), strides=(1,1), padding="valid")(x)) ## TRUE !!!

given the example above, we can switch to MinPooling simply using tf.reduce_min
def min_pool(x):

    n_channel = x.shape[-1]
    patches = tf.image.extract_patches(x,
                                       sizes = [1, 3, 3, 1],
                                       strides = 4*[1],
                                       rates = 4*[1],
                                       padding = 'VALID')

    channel_pool = [tf.reduce_min(patches[:,:,:,c::n_channel], keepdims=True, axis=-1) for c in range(n_channel)]

    return tf.concat(channel_pool, axis=-1)

we can wrap the whole procedure inside a Lambda layer in order to use it inside a keras model: Lambda(min_pool)(x)


text:
Q: Error 1064: Syntax Error MySQL I'm doing sentences for an exercise and MySQL keeps bringing me that error in this sentence.
delete centros where cod_centros not in(select cod_centro from personal);

Here are the tables:
CREATE TABLE CENTROS (
 COD_CENTRO   integer NOT NULL,
 TIPO_CENTRO  CHAR(1),
 NOMBRE VARCHAR(30),
 DIRECCION VARCHAR(26),
 TELEFONO VARCHAR(10),
 NUM_PLAZAS integer,
 primary key (cod_centro)
 );

CREATE TABLE PERSONAL (
 COD_CENTRO   integer NOT NULL,
 DNI integer,
 APELLIDOS VARCHAR(30),
 FUNCION VARCHAR(15),
 SALARIO integer,
 primary key (cod_centro,dni),
 foreign key (cod_centro) references Centros(cod_centro)
);

And here are the inserts:
INSERT INTO CENTROS VALUES (10,'S','IES El Quijote',
'Avda. Los Molinos 25', '965-887654',538);
INSERT INTO CENTROS VALUES (15,'P','CP Los Danzantes', 'C/Las Musas s/n',
'985-112322',250);
INSERT INTO CENTROS VALUES (22,'S', 'IES Planeta Tierra', 'C/Mina 45',
'925-443400',300);
INSERT INTO CENTROS VALUES (45,'P', 'CP Manuel Hidalgo', 'C/Granada 5',
'926-202310',220);
INSERT INTO CENTROS VALUES (50,'S', 'IES Antoñete', 'C/Los Toreros 21',
'989-406090',310);

INSERT INTO PERSONAL VALUES (10,1112345,'Martínez Salas, Fernando',
'PROFESOR', 220000);
INSERT INTO PERSONAL VALUES (10,4123005,'Bueno Zarco, Elisa',
'PROFESOR', 220000);
INSERT INTO PERSONAL VALUES (10,4122025,'Montes García, M.Pilar',
'PROFESOR', 220000);

INSERT INTO PERSONAL VALUES (15,1112345,'Rivera Silvestre, Ana',
'PROFESOR', 205000);
INSERT INTO PERSONAL VALUES (15,9800990, 'Ramos Ruiz, Luis',
'PROFESOR', 205000);
INSERT INTO PERSONAL VALUES (15,8660990, 'De Lucas Fdez, M.Angel',
'PROFESOR', 205000);

INSERT INTO PERSONAL VALUES (22,7650000, 'Ruiz Lafuente, Manuel',
'PROFESOR', 220000);
INSERT INTO PERSONAL VALUES (45,43526789, 'Serrano Laguía, María',
'PROFESOR', 205000);

INSERT INTO PERSONAL VALUES (10,4480099,'Ruano Cerezo, Manuel',
'ADMINISTRATIVO', 180000);
INSERT INTO PERSONAL VALUES (15,1002345,'Albarrán Serrano, Alicia',
'ADMINISTRATIVO', 180000);
INSERT INTO PERSONAL VALUES (15,7002660,'Muñoz Rey, Felicia',
'ADMINISTRATIVO', 180000);
INSERT INTO PERSONAL VALUES (22,5502678,'Marín Marín, Pedro',
'ADMINISTRATIVO', 180000);
INSERT INTO PERSONAL VALUES (22,6600980, 'Peinado Gil, Elena',
'CONSERJE', 175000);
INSERT INTO PERSONAL VALUES (45,4163222, 'Sarro Molina, Carmen',
'CONSERJE', 175000);

I don't know what to do, I think the syntax of the select is fine but keeps bringing the error so I was thinking that maybe it's a bug from mysql workbench as always but I dunno what to do!

A: You're missing the from keyword, which indicates which table you're deleting from.
Correct solution:
delete from centros where cod_centros not in (select cod_centro from personal);

Here's the original, complete, single-table syntax:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]

Reference: MySQL's DELETE Syntax Single-table syntax.

A: Centros is the name of the table so you want to say "Delete FROM Centros where..."


text:
Q: Chart.js canvas and chart width gets overwritten when redrawn My charts that I made with chart.js grow each time when I redraw them and I have no idea why.
My code for the chart cavas is:

let tempChart = document.getElementById("tempChart").getContext('2d');
let pressureChart = document.getElementById("pressureChart").getContext('2d');
let O3Chart = document.getElementById("O3Chart").getContext('2d');
let PM1Chart = document.getElementById("PM1Chart").getContext('2d');
<canvas id="tempChart"></canvas>
<canvas id="pressureChart"></canvas>
<canvas id="O3Chart"></canvas>
<canvas id="PM1Chart"></canvas>

This is the code I call each time when I want to draw or redraw a chart:

function createChart(chartLabels, chartData, chart, label, backgroundcolor, beginAtZero, borderColor) {

    let LineChart = new Chart(chart, {
        type: 'line',
        data: {
            labels: chartLabels,
            datasets: [{
                label: label,
                data: chartData,
                backgroundColor: backgroundcolor,
                pointRadius: 0,
                borderColor: borderColor
        }]
        },
        options: {
            responsive: false,
            scales: {
                yAxes: [{
                        ticks: {
                            beginAtZero: beginAtZero
                        }
                }
                ]
            }
        }
    })

}

The CSS of the canvas before I run createChart once:

    width: 45%;
    padding: 20px 20px;
    border-bottom: 1px solid #dedede;

CSS after I run createChart:

    display: block;
    height: 341px;
    width: 683px;

I have tested this code with empty and full arrays for my labels and data and in both instances the chart grows each time I call the createChart function.

A: It seems like the library you're using (chart.js) is overriding those css values by default.
One option is to set those values back to their correct values at the end of createChart function.
For example:
tempChart.style.width = 45%;

Other option is add a high power to them in a stylesheet, !important, but this depends on the way (chart.js) is acting.


text:
Q: Az CLI: Cannot run pipeline with runtime parameters I'm trying to run a pipeline using AZ CLI. I have a simple pipeline:
parameters:
- name: initials
  displayName: Initials
  type: string

trigger:
- master

pool:
  vmImage: ubuntu-latest

steps:
- script: echo ${{ parameters.initials }}
  displayName: Test

And I try to run it using:
az pipelines run --organization <my org> --project <my project> --name <pipeline> --branch <my branch> --debug --variables initials=maim

Then I end up with an error:

ValidationResults":[{"result":"error","message":"A value for the parameter must be provided

Which is a bit odd since you can tell from the debug that the parameter is being set:

A: It because you need to send parameters and you send variables.
According to this GitHub issue it fixed in a new version:

*

*Need to remove old package first:

az extension remove -n azure-devops
az extension add --source https://github.com/roshan-sy/release-repo/releases/download/1/azure_devops-0.23.0-py2.py3-none-any.whl

*Initial test looks good:

az login
az pipelines run --help
...
--parameters : Space separated "name=value" pairs for the parameters you would like to set.
...
az pipelines run --name "{pipeline.name}" --parameters Param1={Value1}


text:
Q: How do I customize the shell in Multipass (on Ubuntu)? I am running Groovy Gorilla, and have installed Multipass for a dev environment.  While reading how-to docs, I've seen different setups for the shell (larger font, different font colors, etc).
How do I customize the shell?  In particular, I need to increase the font size because it's tiny.  tia

A: I'm having a similar issue when using the multipass terminal. But you can simply avoid using the multipass shell by using your default terminal and type multipass shell <your VM name>.
There are quite a lot of useful commands of multipass, you can try multipass help.


text:
Q: UINavigationBar setBackgroundImageForBarMetrics doesn't work in iOS 7 i'm trying to se an image for the background of the navigation bar, and i'm doing this like i do in iOS6:
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"Navbar.png"] forBarMetrics:UIBarMetricsDefault];

this is the image:

and this is the result when i run:

on iOS 6 works perfect, instead on iOS 7 have that problem...

A: Try to add this to your navigation Controller:
self.navigationController.navigationBar.tintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Navbar.png"]];


text:
Q: how to retrieve data from three columns into a one column in the new table SQL SELECT  Dc.Name AS Market
        ,R.Name AS Route
        ,C.Id
        ,C.ERPCusCode
        ,C.Name
        ,C.Address1 AS Address
        ,C.CustomerGradeId AS volumeClass
        ,I.ERPItemCode
        ,H.InvoiceDate
        ,D.Qty
FROM InvoiceHeader H
INNER JOIN InvoiceDetail D ON H.InvoiceNo=D.InvoiceNo
INNER JOIN ItemMaster I ON I.Id=D.ItemMasterId
INNER JOIN Customer C ON C.Id=H.CustomerId
INNER JOIN DistributionCenter Dc ON Dc.Id=H.DistributionCenterId
INNER JOIN Route R ON R.Id=H.RouteId
WHERE H.Deleted=0 AND H.InvoiceDate BETWEEN '2018/01/01' AND '2018/06/06'
AND C.Active=1

This is my SQL code and customer table has address 1 , address 2 ,address 3 , address 4 in it i want to get those all fields data into a one column as address in the above code output table.How should i get it?

A: Can you just concatenate them together?
(address1 + ' ' + address 2 + ' ' + address 3 + ' ' + address 4) as address


text:
Q: How does WiFi on a bus work? We are looking to implement WiFi on some of our private buses. We are in the early step of the process and we are gathering information.
How does WiFi works on a bus that is roaming around the country? The bus will not always be in town and we'd like the to keep the internet connection alive.
What kind of equipment would be required?
The bus should host about 20 passengers, and we assume that not all of them will be carrying a WiFi enabled device. We of course want to throttle the bandwidth so that we can control the amount of data transferred so that we don't end up with a huge end of month bill.
The bus will be travelling around North America, excluding Mexico.

A: The vehicle (or something within the vehicle) needs to have a satellite or mobile broadband uplink that provides the connection to the remote network (Internet, private LAN, whatever).  Then you have an access point that provides the WiFi to the occupants of the vehicle.  This access point is either integrated into the uplink or is somehow bridged to it, it'll depend on what devices you use.  You can do this with many modern smartphones, although I'm not sure what the limitations are as far as simultaneous connections and I'd be hesitant to provide this at this scale.
If the occupants are not all carrying a WiFi enabled device then you would want to have a switch for them to connect hardwired.
I wouldn't expect great throughput on this one at this point in the game unless you're willing to throw a lot of money at it.
[Don't forget to include the AC power source]


text:
Q: Android RecyclreView OnCLick Listener Error on android recyclerView Adapter. App will stop working while click on RecyclerView items. I want to go other activity when click any items, when i'm using Toast it working fine but if i add Intent then it stop working.
Here is my Interface :
public interface OnItemClickListener {
        void onClick(View view, int position);
}

here is my recycler Adapter calss :
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> {

    private List<Items> items;
    private Context context;

    public RecAdapter(List<Items> items, Context context )
    {
        this.items = items;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);

        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position)  {

        holder.countryname.setText(items.get(position).getCountryname());
        holder.rank.setText(items.get(position).getRank());
        Picasso.with(context)
                .load(items.get(position).getFlag())
                .into(holder.flag);
        holder.setClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(context , Main2Activity.class);
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView countryname, rank;
        ImageView flag;
        private OnItemClickListener clickListener;

        public MyViewHolder(View itemView) {
            super(itemView);
            countryname = (TextView) itemView.findViewById(R.id.capital);
            rank = (TextView) itemView.findViewById(R.id.rank);
            flag = (ImageView) itemView.findViewById(R.id.flag);
            itemView.setTag(itemView);
            itemView.setOnClickListener(this);

        }
        public void setClickListener(OnItemClickListener itemClickListener) {
            this.clickListener = itemClickListener;
        }
            @Override
        public void onClick(View view) {
            if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
        }
    }
}

A: You can not click an holder directly..... give a id to the view then re write the code as below:
holder.(someitem).setClickListener(new OnItemClickListener() {//you need a view to execute the onclicklistener
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(context , Main2Activity.class);
                context.startActivity(intent);
            }
        });

A: copying an answer of mine from a different question:
as you already know this method is no longer available in the RecyclerView class.
My approach towards implementing onClick events in a RecyclerView is something like this:
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    interface OnClickListener {
        void onClick(Item item);
    }

    private final List<Item> dataset;
    private final OnClickListener l;

    public MyAdapter(List<Item> data, OnClickListener listener) {
        this.dataset = data;
        this.l = listener;
    }

    @Override MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = //inflate layout
        MyClick click = new MyClick() {
            onClick(int position) {
                if (l != null) {
                    l.onClick(dataset.get(position));
                }
            }
        };
        return new MyViewHolder(click, v);
    }

    static class MyViewHolder {
        final MyClick l;

        public MyViewHolder(MyClick listener, View view) {
            super(view);
            l = listener;
            // inflate views
            view.setOnClickListener(new OnClickListener() {
                if (l != null) {
                    l.onClick(getAdapterPosition());
                }
            });
        }

        interface MyClick {
            void onClick(int position);
        }
    }
}

class MyActivity extends AppCompatActivity {

    @Override void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set layout
        MyAdapter adapter = new MyAdapter(getData(), new OnClickListener() {
            @Override onClick(Item item) {
                // do stuff with item
            }
        });
    }
}

A: Add click listener like this:-
View itemView;
Context context;

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view, parent, false);
    this.context=parent.getContext();
    return new ViewHolder(itemView);
}
@Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context , Main2Activity.class);
                context.startActivity(intent);
            }
        });
    }

A: Here is code which i create click listener for Recycler Item Click
Using this you will get two types of click

*

*Simple Item click.

*Item Long click.

Here is RecyclerItemClickListener.java File
public class RecyclerItemClickListener  implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener
{
    void onItemClick(View view, int position);
    void onItemLongClick(View view, int position);
}

private OnItemClickListener mListener;
private GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
{
    mListener = listener;

    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
    {
        @Override
        public boolean onSingleTapUp(MotionEvent e)
        {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e)
        {
            View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

            if(childView != null && mListener != null)
            {
                mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
{
    View childView = view.findChildViewUnder(e.getX(), e.getY());

    if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
    {
        mListener.onItemClick(childView, view.getChildPosition(childView));
    }

    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

}
How to use in Activity and Fragment
  rvcyclerView.addOnItemTouchListener(new RecyclerItemClickListener(context, rvcyclerView,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        //do you what you want tot do simple click
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                        //do you what you want tot do on long click
                    }
                }));

A: public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> implements View.OnClickListener {

    private List<Items> items;
    private Context context;
    private OnItemClickListener clickListener;

    public RecAdapter(List<Items> items, Context context )
    {
        this.items = items;
        this.context = context;
    }

    public void setClickListener(OnItemClickListener itemClickListener) {
        this.clickListener = itemClickListener;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);

        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position)  {

        holder.countryname.setText(items.get(position).getCountryname());
        holder.rank.setText(items.get(position).getRank());
        Picasso.with(context)
                .load(items.get(position).getFlag())
                .into(holder.flag);
        holder.flag.setOnClickListener(this);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView countryname, rank;
        ImageView flag;

        public MyViewHolder(View itemView) {
            super(itemView);
            countryname = (TextView) itemView.findViewById(R.id.capital);
            rank = (TextView) itemView.findViewById(R.id.rank);
            flag = (ImageView) itemView.findViewById(R.id.flag);

        }

            @Override
        public void onClick(View view) {
            if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
        }
    }
}

On Your Activity / Fragment Implement OnItemClickListener
    public class MainActivity extends AppCompatActivity implements OnItemClickListener{
    @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LinearLayoutManager layout = new
            LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false);
            mRecyclerView.setLayoutManager(layout );
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            RecAdapter adapter = new RecAdapter(items ,getContext());
            adapter.setClickListener(this);
            mRecyclerView.setAdapter(adapter );
        }

     @Override
        public void onClick(View view, int position) {
       switch(view.getId()) {
       }
 }

}


text:
Q: Pandas Dataframe groupby: apply several lambda functions at once I group the following pandas dataframe by 'name' and then apply several lambda functions on 'value' to generate additional columns.
Is it possible to apply these lambda functions at once, to increase efficiency?
import pandas as pd

df = pd.DataFrame({'name': ['A','A', 'B','B','B','B', 'C','C','C'],
                   'value': [1, 3, 1, 2, 3, 1, 2, 3, 3], })

df['Diff'] = df.groupby('name')['value'].transform(lambda x: x - x.iloc[0])
df['Count'] = df.groupby('name')['value'].transform(lambda x: x.count())
df['Index'] = df.groupby('name')['value'].transform(lambda x: x.index - x.index[0] + 1)

print(df)

Output:
  name  value  Diff  Count  Index
0    A      1     0      2      1
1    A      3     2      2      2
2    B      1     0      4      1
3    B      2     1      4      2
4    B      3     2      4      3
5    B      1     0      4      4
6    C      2     0      3      1
7    C      3     1      3      2
8    C      3     1      3      3

A: Here is possible use GroupBy.apply with one function, but not sure if better performance:
def f(x):
    a = x - x.iloc[0]
    b = x.count()
    c = x.index - x.index[0] + 1
    return pd.DataFrame({'Diff':a, 'Count':b, 'Index':c})

df = df.join(df.groupby('name')['value'].apply(f))
print(df)

  name  value  Diff  Count  Index
0    A      1     0      2      1
1    A      3     2      2      2
2    B      1     0      4      1
3    B      2     1      4      2
4    B      3     2      4      3
5    B      1     0      4      4
6    C      2     0      3      1
7    C      3     1      3      2
8    C      3     1      3      3


text:
Q: Can I force uniform transparancy on an element that's being dragged? I don't think it is (easily?) possible to style an element that's being dragged using the HTML5 draggable="true" attribute. I can live with that if I could force the element to be made uniformly transparent and not radial. It seems that Chrome select radial if the element considered "wide".
I have created a Plunker to demonstrate what I mean:
http://run.plnkr.co/plunks/Vd5DLescUxAKRg61Q9x7/
The first four boxes are uniformly transparent when dragged, but the two last are radial. It is possible to force a uniform transparency on all six boxes?
(Don't know why the Plunker doesn't work in Firefox. If you know why I will gladly fix it.)


text:
Q: Extract the background colour of a UIImageview in an array I want to determine the background colour of an imageview when it is tapped and perform an action based on the colour. I cannot fathom the syntax for getting the information from the array in which the imageviews are stored. I have tried the below but it says the stated error. Any help would be appreciated. I am new and I'm sorry if I'm wasting peoples time, I'm learning by making my own app and its throwing up a lot of questions. Kind regards.
'Value of type [UIImageView] has no member backgroundColour.
@IBAction func onTapping() {
    if squares.backgroundColor == UIColor.red {
        // code
    }
}

A: First you need to set userIteractionEnable on all your UIImageViews

Next change your method signature to:
@IBAction func onTapping(_ sender: UITapGestureRecognizer) {

Then you will need to know which image view you are tapping on by checking the sender view property:
@IBAction func onTapping(_ sender: UITapGestureRecognizer) {
    let systemRed = UIView()
    systemRed.backgroundColor = .systemRed
    if sender.view?.backgroundColor == systemRed.backgroundColor {
        print("systemRed")
    } else {
        print("systemYellow")
    }
}


text:
Q: what is the difference between readFileSync and readAsDataURL? NOTE: this is NOT a production application.  It is a small app that I am making to explore the capabilities of selecting, opening, saving and reading an image from a DB.
I do not know what method I should call to get the correct Buffer data to store image in mongodb. ( I am aware that mongoDB has a 16mb limit on documents )
In my app, I want the user to be able to select an image from a file on their pc, give the user a preview of the image, then when the user hits submit (not shown here) save the image into mongodb
I know when the user clicks the "choose file" button I can get the file like this:
    const file = event.target.files[0]

    if (!file) {
        // user has hit the cancel button
        return;
      }

    //console.log(file);

I can get information about the file:
    console.log(file.type);
    console.log(file.size);

and here is how the image is read:
    let fr = new FileReader();
    fr.readAsDataURL(file);
    fr.onload = (e) =>{
        this.productImageAdd(e.target.result);
    }

This is how the image is stored in the (react) component state
productImageAdd = (file) => {

    let temp = this.state["filesArray"] || [];
    temp.push(file);
    this.setState({"filesArray": temp});
}

Here is the state of my component
this.state = {
  filesArray: [],
};

In another component, I get a listing of all the images and then map them to an item for display:
return filesArray.map((file, index) => (
  <FileDropZoneItem key={index} id={index} file={file} />
));

In FileDropZoneItem, this is how images are "previewed":
    return (

    );

I saw this stackoverflow question and I am moving towards that to store the image in MongoDB:
Store an image in MongoDB using Node.js/Express and Mongoose
In that post, their schema is like this:
var schema = new Schema({
    img: { data: Buffer, contentType: String }
});

And they store the image like this:
var A = mongoose.model('A', schema);
var a = new A;
a.img.data = fs.readFileSync(imgPath);
a.img.contentType = 'image/png';

but I don't really know the difference between fs.readFileSync and fr.readAsDataURL.
Will storing to mongodb work using fr.readAsDataURL or do I need fs.readFileSync ?
I also saw: Difference between readAsBinaryString() and readAsDataURL() in HTML5 FileReader API

A: From the MongoDB manual GridFS
GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata. The section GridFS Collections describes each collection in detail.
For reference you can read Storing images in MongoDB
readAsDataURL permits to store the images inside the JSON document encoded as base64 characters. Given the size of the Products pictures 200px x 200px seems the best option for your hello world app.
readFileSync can have blocking issues in the server like Nodejs for image handling behavior and reads the binary file to store it as Binary Data.
IMO the best solution is to not overload mongoDB and Nodejs with the image handling and store only an URL to the image in the mongoDB document leaving the image serving process to a proxy like nginx.
The Gridfs option depends on the driver used. Following is Gridfs use in Nodejs that uses its own reader:
fs.createReadStream('./meistersinger.mp3').
pipe(bucket.openUploadStream('meistersinger.mp3')).


text:
Q: How to insert YouTube Channel banner using v3 Data Api in java? ChannelBannerResource chBannerResource = new ChannelBannerResource();
chBannerResource.setKind("youtube#channelBannerResource");
chBannerResource.setEtag("JcMoTLb1iDZi7UYDRZDsYNLPWNA/X7zrV-CaEaRAq1KbyVYs4KQu6MU");                chBannerResource.setUrl("http://myimage.com/ram/channelbaner.jpg");
YouTube.ChannelBanners.Insert  chbannerresponse  = youtube.channelBanners().insert(chBannerResource);ChannelBannerResource res= chbannerresponse.execute();

    Error :- GoogleJsonResponseException code: 400 : contentDetails
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "youtube.part",
    "location" : "part",
    "locationType" : "parameter",
    "message" : "contentDetails",
    "reason" : "unexpectedPart"
  } ],
  "message" : "contentDetails"
}

please help me ..........

A: Channel myChannel = channelListResponse.getItems().get(0);
        String channelId = myChannel.getId();
        System.out.println("channel id===" + channelId);
        URL url = new URL(imageurl248X1152);
        URLConnection conn = url.openConnection();
        InputStreamContent mediaContent = new InputStreamContent(
                "image/jpeg", conn.getInputStream());
        ChannelBannerResource chBannerResource = new ChannelBannerResource();
        YouTube.ChannelBanners.Insert chbannerresponse = youtube
                .channelBanners().insert(chBannerResource, mediaContent);
        ChannelBannerResource res = chbannerresponse.execute();
        System.out.println("res====" + res.getUrl());
        ChannelBrandingSettings channelBrandingSettings = new ChannelBrandingSettings();
        ChannelSettings channelSettings = new ChannelSettings();
        channelSettings.setDescription(des);
        channelSettings.setKeywords(keyword);
        channelSettings.setProfileColor(profilecolor);
        ImageSettings imageSettings = new ImageSettings();
        imageSettings.setBannerExternalUrl(res.getUrl());
        channelBrandingSettings.setChannel(channelSettings).setImage(
                imageSettings);
        Channel channel = new Channel();
        channel.setId(channelId);
        channel.setBrandingSettings(channelBrandingSettings);
        System.out.println("channel===" + channel);
        Channel updateChannelResponse = youtube.channels()
                .update("brandingSettings", channel).execute();


text:
Q: Why is my function refuse to store or update inputs I am unable to Create an event listener to save the entry when it changes.
I tried everything I could, from swapping var between different lines of code to add .value at end of some of my var to see if he'd work. Sorry, I am not really good on describing the issue or even coding, but normally this function should Create an event listener to save the entry when it changes.
When this change is complete, we should see items change in the 'Application' or 'Storage' tab of your browser developer tools after you type text on the page, and move the focus away from the text input (e.g. by pressing the Tab key on your keyboard or clicking elsewhere on the page). When you reload the page these entries will reappear on the page.
 /**
     * Make diary data item
     * @param type Type of item to create, either "text" or "image"
     * @param data Item data, either text or data URL
     * @returns JSON string to store in local storage
     */

     function makeItem(type, data) {
        var itemObject = { type: type, data: data };
        return JSON.stringify(itemObject);
    }

 * @param key Key of item in local storage
 * @param initialText Initial text of diary entry
 * @param isNewEntry true if this is a new entry to start typing into
 */
function addTextEntry(key, initialText, isNewEntry) {
    // Create a textarea element to edit the entry
    var textareaElement = document.createElement("textarea");
    textareaElement.rows = 5;
    textareaElement.placeholder = "(new entry)";

    // Set the textarea's value to the given text (if any)
    textareaElement.value = initialText;

    // Add a section to the page containing the textarea
    addSection(key, textareaElement);

    // If this is a new entry (added by the user clicking a button)
    // move the focus to the textarea to encourage typing
    if (isNewEntry) {
        textareaElement.focus();
    }

    // Create an event listener to save the entry when it changes
    // (i.e. when the user types into the textarea)
    function saveEntry() {
        // A new version of this function is created every time
addTextEntry is called,
        // so it can access all the variables available in this call to
addTextEntry
        console.log("saveEntry called with variables in scope:", {
            key,
            initialText,
            isNewEntry,
            textareaElement,
        });

# This is where i am stuck
        // Save the text entry:
    textareaElement = document.getElementById("text").innerHTML;

        // ...make a text item using the value
    isNewEntry = makeItem("text", textareaElement);

    // Store the item in local storage
        localStorage.setItem(key, isNewEntry);
    }
    // Connect the saveEntry event listener to the textarea element
'change' event
    var inputText = document.querySelector("textarea");
    inputText.addEventListener("change", processFile);
}
# Stuck until there


text:
Q: How to create an HTML table from an array of objects? I need to generate a table from an array of objects.
For example, the array is:
let arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}]

And the HTML output should be:

Name
Score

Player1
10

PLayer2
7

Player3
3

I could not think of a way to achieve this through vanilla JS.
Also, after the table is created, how will I apply CSS to it?
Any help would be appreciated.

A: You can loop through the array and for each element add a row to a newly forged table that will be added to the document at the end.
This is a demo:

let players = [
  {name: 'Player1',score:10},
  {name: 'Player2',score: 7},
  {name: 'Player3',score:3}
];

const newTable = document.createElement("table");
newTable.innerHTML = "
Player	Score
";
for(player of players){
    const newRow = document.createElement("tr");
    const tdPlayer = document.createElement("td");
    const tdScore = document.createElement("td");
    tdPlayer.textContent = player.name;
    tdScore.textContent = player.score;
    newRow.appendChild(tdPlayer);
    newRow.appendChild(tdScore);
    newTable.appendChild(newRow);
}

const target = document.getElementById('target');
target.appendChild(newTable);
table{
  border: solid 1px black;
}

table td{
  border: solid 1px black;
}

A: You can use something like

                player
                score


text:
Q: Sign out issue with ACS ADFS I am using ACS and ADFS for single sign on. Sign in works perfectly fine. No issues.
We are using persistent cookie.
Sign out works fine but below is the issue.
1) If I open IE, login and log out in same IE window then it works perfectly fine.
2) If I open IE, login and close browser. Again hit the same url, you will be logged in. In this case sign out does not work and it throws below error.
"The wtrealm parameter is missing or incorrect. Try clearing all of your browser cookies, and then close all browser windows."
Please note, with the same IE session it works perfectly fine.
I could sense that issue is with ACSSignout cookies but not sure how to handle this.


text:
Q: Directional derivative doubt I have two functions.
$e(t,z)=\cos(\omega t)\cos(\beta z)$, $h(t,z)=\frac{1}{\eta}\sin(\omega t)\sin(\beta z)$
Let's set the direction $\hat{u} = \hat{z} - c\hat{t}$, with $\dfrac{\epsilon_0}{c}=\dfrac{1}{\eta}$ and $\dfrac{\omega}{c}=\beta$. I can calculate $\dfrac{\partial( h-\frac{1}{\eta} e)}{\partial u}$ and I find it to be 0. So the quantity $h-\dfrac{1}{\eta} e$ is constant along that direction and since I know that for some $(t,z)$ points both $e$ and $h$ are $0$, that constant is $0$. So I'd like to say that if I change $z$ and $t$ according the $u$ direction, the ratio $\dfrac{e}{h}$ stays constant. It seems to me quite wrong but I'd like to get some comments about this misunderstanding.

A: The misunderstanding is in "since I know that for some $(t,z)$ points both $e$ and $h$ are 0, that constant is 0".
Let's see why by considering the simpler case where $\omega=\beta=\eta=1$. The function $f = h - \frac{1}{\eta} e$ is $f = - \cos(t+z)$.
Consider the point $(t,z) = (t_0,0)$ and walk along $\hat{u}$ from it. You will reach points $(t_0-r, r)$. Along this line $f=-\cos(t+z)=-\cos(t_0-r+r) = -\cos (t_0)$.
$f$ is indeed constant along this line, as you found ($\partial f / \partial u = 0$). However $f$ (the constant) is not $0$ everywhere. It is $0$ just along those lines that crosses point $(t_0,0)$ where $-\cos(t_0)=0$.
In other words, to know the value of the constant along a line, you have to evaluate $f$ on a point on this line.
Regarding the ratio $\frac{e}{h}$: for a line that crosses point $(t_0,0)$, $h - \frac{1}{\eta} e = -\cos(t_0)$, so $\frac{e}{h} = \frac{e}{f+e}$. Since $e$ is not constant along the line, and $f$ is constant but not necessarily $0$, the ratio is not constant everywhere.

A: There seems to be some confusion regarding directional derivatives vs. partial derivates.

*

*Your function $f(t,z)=h-\frac{1}{\eta} e= -\frac{1}{\eta} \cos(\beta(z+ct))$ is constant in the direction $\hat{u}=(-\frac{1}{c},1)$ in the $(t,z)$-plane, since:
$$ -\frac{1}{c} \partial_t f + \partial_z f = 0$$

*If you make a change of variables, say $u=z-ct$, $v=z+ct$, your function becomes $\hat{f}(u,v)=-\frac{1}{\eta} \cos (\beta v)$ which is independent of $u$, whence the partial derivative w.r.t. u is zero of this function in the coordiantes $(u,v)$. It seems that you are mixing the two notions.
If you happen to know that $f(t_0,z_0)=0$ then along the $\hat{u}$ direction,
$f(t_0-\frac{1}{c}s, z_0+s)=0$ for all $s\in {\Bbb R}$ implying that $h=\frac{1}{\eta} e$ along that line, so the ratio $e/h=\eta$ whenever defined (note that sometimes both vanish).
Explicitly, we have that $\beta(z+ct)=\beta z + w t$ is constant equal to $\pi/2+2\pi k$ for some integer $k$ and since $\;\cos(\pi/2-x)=\sin(x)\;$ we get  $e(t,z)= \cos(wt) \sin(wt) = \eta h(t,z)$ along that line.


text:
Q: Looking for Decent reports about current Patch level of server We are currently using WSUS on a mix of 2008 and 2008R2 servers. What I am looking for is a good way to report back to myself and Management the current state of patching on servers across several domains and sites. I know WSUS has some but they really aren't up to scratch.  How is everyone doing this?

A: The wsus reports are ok but simple and don't give anything like an overview for multiple domains. Are you aware of the wsus rollup reporting tool?
http://technet.microsoft.com/en-us/wsus/bb466192
If you can pull everything into a single server then using reporting services or even excel would allow you to put together your own reports as you wanted.
Patchaholic has some good info on doing this yourself: http://msmvps.com/blogs/athif/archive/category/2169.aspx
Other than that you are looking at an MSP type management solution like kaseya or labtech, to name just two. There are a lot of them out there but you're talking quite a bit of cash annually as they independently scan each node and not the wsus server.
Ian

A: Patch level is vague. What specifically are you looking for? Updates applied? Updates waiting to be applied? etc.
Microsoft's Baseline Security Analyzer tool may be what you are looking for. It allows you to audit what updates are applied and poll windows updates to show what's missing.
If you only need what updates were applied you can easily pull this with

Get-Hotfix -ComputerName someserver

If you wanted to do in Powershell  against a list of servers and then export the output to different text files you can use:

$serverlist = cat "serverlist.txt" foreach ($server in $serverlist)
{
Get-Hotfix -ComputerName $server >> $server".txt"
}

If pending updates are a concern it looks like there is another script that may be of use here.


text:
Q: How to open two py files in different shells I have a simple server program and simple client program
I store all my python programs in a single file i has around 30-40 py files (academic and online contest problems)
This time i created a sub-folder and stored the client and server files
when i run them simultaneously they open up in the same shell , i tried modifying code but no use,
later i got them back into main folder ....
this time they are opening in two separate shells
Why is this happening !Why programs in sub-folders are opening in same shell.
I will share my code also, Check if there any mistakes in it.
Client.py
import socket,time,sys
time.sleep(1)
s=socket.socket()
host=socket.gethostname()
port=12345
time.sleep(1)
s.connect((host,port))
print(s.recv(1024))
s.close()

server.py
time.sleep(1)
s=socket.socket()
host=socket.gethostname()
print(host)
port=12345
s.bind((host,port))
s.listen(5)
print('Waiting')
while True:
    c,addr=s.accept()
    print('Connected with',addr)
    c.send(b"Thank you for Connecting")
    c.close()


text:
Q: Using decltype with macro for explicit instantiation of class member functions I am attempting to extend upon Can I use decltype (or something similar) for explicit template instantiation without signature duplication? for use with templated member functions, but I am having no luck. Current attempts at making this work look like:
// header
struct my_class
{
    template <typename T>
    some_type my_func(T val);
};

//source
template <typename T>
some_type my_class::my_func(T val)
{
    ....
}

// attempt a
template decltype(my_class::my_func<int>) my_class::my_func<int>;

// attempt b
template std::remove_pointer<decltype(&my_class::my_func<int>)>::type my_class::my_func<int>;

Is this possible? If so, any thoughts on how I can make this work?
EDIT:
so it appears that this requires some compiler update only available in clang or gcc 6.1+. The following code provided by @yakk will work for const methods:
template <class T>
struct pointer_to_member_function{};

template <typename pmf_t>
using pointer_to_member_signature
    = typename pointer_to_member_function<pmf_t>::signature;

template <class ret_t, class class_t, class...args>
struct pointer_to_member_function<ret_t(class_t::*)(args...) const>
{
     using signature = ret_t(args...) const;
};

However, the following modification does compile across all const-ness:
template <class function_t, class class_t>
struct pointer_to_member_function<function_t class_t::*>
{
   using signature = function_t;
};

A: I do not know if this is standard compliant, but it works in clang:
template<class Pmf>
struct pmf_sig{};
template<class Pmf>
using pmf_sig_t=typename pmf_sig<Pmf>::type;
template<class R, class T, class...Args>
struct pmf_sig<R(T::*)(Args...)>{
  using type=R(Args...);
};

then const and const& and && support:
template<class R, class T, class...Args>
struct pmf_sig<R(T::*)(Args...) const>{
  using type=R(Args...) const;
};
template<class R, class T, class...Args>
struct pmf_sig<R(T::*)(Args...) const&>{
  using type=R(Args...) const&;
};
template<class R, class T, class...Args>
struct pmf_sig<R(T::*)(Args...) const&&>{
  using type=R(Args...) const&&;
};
template<class R, class T, class...Args>
struct pmf_sig<R(T::*)(Args...) &&>{
  using type=R(Args...) &&;
};
template<class R, class T, class...Args>
struct pmf_sig<R(T::*)(Args...) &>{
  using type=R(Args...) &;
};

The use:
template<> pmf_sig_t<decltype(&my_class::my_func<int>)> my_class::my_func<int>;

Or:
template pmf_sig_t<decltype(&my_class::my_func<int>)> my_class::my_func<int>;

The idea is that my_class:: is not part of the signature in some sense.
live example.


text:
Q: Simple shell with indirect input I am writing a simple code to implement the indirect input function for a unix/linux shell.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

extern void error(char* message);
void
cisshRedirectedInput(char* command[], char* inputFile)
{
  //Try to implement the RedirectInput from here
    pid_t pid;
    int status;
    int fd;
//For the child process
    if ((pid=fork())==0)
    {
        //Try to input files, failing on an error
    fd=open(inputFile,O_RDONLY);//To read input file

        if(fd < 0)
        {
            error("sampleSh: error opening standard input file");
            exit(1);
        }
        //use dup() to copy file
        close(1);
        if(dup(fd) < 0)
        {
            error("sampleSh: error duplicating standard input");
            perror("dup()");
            exit(1);
        }

        //Close file and exec()
        close(fd);
        execvp(command[0], command);
        //If failure in any case
        error("sampleSh: failure to execute command");
        exit(1);
    }
    else
    {
        /* This is the parent process.
         * Wait for the child to terminate.
         */
        if(wait(&status) < 0)
        {
            error("sampleSh: error waiting for child.");
            perror("wait");
        }

        if(status != 0)
            error("sampleSh: command exited with nonzero error status.");
    }

}

However, after compilation (no error reported), but when I try (fileList created already)
sort -r <fileList

The shell just stuck there without giving me answer, what is the problem please?

A: The standard input file descriptor is 0 (or STDIN_FILENO), not 1 (or STDOUT_FILENO).
Either use:
int fd = open(inputFile, O_RDONLY);

if (fd < 0) …
close(0);
if (dup(fd) < 0) …
close(fd);

Or:
int fd = open(inputFile, O_RDONLY);

if (fd < 0) …
if (dup2(fd, 0) < 0) …
close(fd);

It is good that your code does the close(fd) after duplicating to a standard I/O descriptor — that is almost always correct.  It's also good that you are checking that the key system calls succeed. (There isn't much you can do if close() fails.)

This simple modification of your code (key change: use close(0); instead of close(1);) works for me.  Did you null terminate your argument list?
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

static inline void error(char *message)
{
    fprintf(stderr, "%s\n", message);
}

void
cisshRedirectedInput(char *command[], char *inputFile);

void
cisshRedirectedInput(char *command[], char *inputFile)
{
    // Try to implement the RedirectInput from here
    pid_t pid;
    int status;
    int fd;
    // For the child process
    if ((pid = fork()) == 0)
    {
        // Try to input files, failing on an error
        fd = open(inputFile, O_RDONLY); // To read input file

        if (fd < 0)
        {
            error("sampleSh: error opening standard input file");
            exit(1);
        }
        // use dup() to copy file
        close(0);
        if (dup(fd) < 0)
        {
            error("sampleSh: error duplicating standard input");
            perror("dup()");
            exit(1);
        }

        // Close file and exec()
        close(fd);
        execvp(command[0], command);
        // If failure in any case
        error("sampleSh: failure to execute command");
        exit(1);
    }
    else
    {
        /* This is the parent process.
         * Wait for the child to terminate.
         */
        if (wait(&status) < 0)
        {
            error("sampleSh: error waiting for child.");
            perror("wait");
        }

        if (status != 0)
            error("sampleSh: command exited with nonzero error status.");
    }
}

int main(void)
{
    char *args[] = { "sort", "-r", 0 };
    cisshRedirectedInput(args, "fileList");
    return 0;
}

Input file:
bash-assoc-arrays.sh
cissh.c
fileList
kwargs.py
makefile
posixver.h
rangeinc.c
select.c
spc.py
testcsv.py
uncrustify.bug
yield.py

Output:
yield.py
uncrustify.bug
testcsv.py
spc.py
select.c
rangeinc.c
posixver.h
makefile
kwargs.py
fileList
cissh.c
bash-assoc-arrays.sh


text:
Q: How many subsets of $A=\{0,1,2,...,n\}$ are there such that no consecutive numbers come together It is likely a duplicate, but I couldn't find an original question, so creating a new one.

Given a set $A=\{1,2,...,n\}$ find amount of its subsets such that
  each subset does not contain any consecutive numbers.

For example, $\{1,3\}, \varnothing, \{1,3,5\}$ are OK, but $\{1,2\}, A, \{1,3,n-1,n\}$ are not OK.
I tried to solve this task using inclusion-exclusion formula, but got stuck when computing the 3rd term. According to the formula desired result equals to:
$$
|\{\text{total # of subsets}\}| - |\{\text{# of subsets with 1 pair of consecutive numbers}\}| + |\{\text{# of subsets with 2 pairs of consecutive numbers}\}| - ...
$$
First term is easy, it equals to $2^n$.
To calculate the second term I am picking one consecutive pair out of $n-1$ possible and then calculate subsets with this pair included. So it equals $(n-1) \cdot 2^{n-2}$.
For the 3rd term I tried to pick one pair out of $n-1$ possible, then the second pair out of $n-2$ remaining and then calculate amount of subsets with both pairs included, i.e. it would equal something like $(n-1)(n-2)\cdot 2^{n-4}$. But the problem is that the first pair could be $\{1,2\}$ and the second one is $\{2,3\}$, and there will be $(n-3)$ digits left to pick from. To account for this we'll have to split the variants into these two cases. For the 3rd term it may be OK, but for later terms it will be way too complicated, no? Is there a nicer solution?

A: Let $A_n = \{1,2,3,\dots,n\}$. Let $G_n$ be the number of "good" subsets of $A_n$. Here I will consider the empty set to be a "good" subset of each $A_n$.
For each subset, $S$ of $A_n$ there is a function $f_{n,S}:A_n \to \{0,1\}$ define by $f_{n,S}(x)=
\begin{cases}
   0 & \text{If $x \not \in S$} \\
   1 & \text{If $x \in S$} \\
\end{cases}$

\begin{array}{c}
                & f \\
  \text{subset} & 1 & \text{good?} \\
\hline
   & 0 &\checkmark \\
 1 & 1 &\checkmark \\
\hline
\end{array}
So $A_1=2$.

\begin{array}{c}
                & f \\
  \text{subset} & 12 & \text{good?} \\
\hline
   & 00 &\checkmark \\
 1 & 10 &\checkmark \\
 2  & 01 &\checkmark \\
 12 & 11  \\
\hline
\end{array}
So $A_2=3$.

\begin{array}{c}
                & f \\
  \text{subset} & 123 & \text{good?} \\
\hline
     & 000 &\checkmark &\text{Compare to $A_2$}\\
   1 & 100 &\checkmark \\
   2 & 010 &\checkmark \\
  12 & 110 \\
\hline
   3 & 001 &\checkmark &\text{Compare to $A_1$}\\
  13 & 101 &\checkmark \\
  23 & 011 &  \\
 123 & 111  \\
\hline
\end{array}
So $A_3=A_1+A_2=5$.

\begin{array}{c}
                & f \\
  \text{subset} & 1234 & \text{good?} \\
\hline
     & 0000 &\checkmark &\text{Compare to $A_3$}\\
   1 & 1000 &\checkmark \\
   2 & 0100 &\checkmark \\
  12 & 1100  \\
   3 & 0010 &\checkmark \\
  13 & 1010 &\checkmark \\
  23 & 0110 &  \\
 123 & 1110  \\
\hline
   4 & 0001 &\checkmark &\text{Compare to $A_2$}\\
  14 & 1001 &\checkmark \\
  24 & 0101 &\checkmark \\
 124 & 1101  \\
  34 & 0011 &  \\
 134 & 1011 &  \\
 234 & 0111 &  \\
1234 & 1111  \\
\hline
\end{array}
So $A_4=A_2+A_3=8$.

So it seems that $A_1=2, \quad A_2=3, \quad$ and $A_{n+2}=A_n + A_{n+1}$ Thus $A_n = F_{n+2}$, the $(n+2)^{th}$ fibonacci number.

A: Supposing the subset is not the empty set we first choose the smallest
value:
$$\frac{z}{1-z}.$$
Then we add in at least two several times to get the remaining values:
$$\frac{z}{1-z} \sum_{m\ge 0} \left(\frac{z^2}{1-z}\right)^m
= \frac{z}{1-z} \frac{1}{1-z^2/(1-z)}
= \frac{z}{1-z-z^2}.$$
Finally we collect the contributions that sum to at most $n$ and add one
to account for the empty set:
$$1+ [z^n] \frac{1}{1-z} \frac{z}{1-z-z^2}
\\ = [z^n] \frac{1}{1-z} +  [z^n] \frac{1}{1-z} \frac{z}{1-z-z^2}
\\ = [z^n] \frac{1}{1-z} \frac{1-z^2}{1-z-z^2}
\\ = [z^n] \frac{1+z}{1-z-z^2}.$$
Calling the OGF $G(z)$ we have
$$G(z) (1-z-z^2) = 1 + z$$
so that for $[z^0]$ we get
$$[z^0] G(z) (1-z-z^2) =  1$$
or $g_0 = 1.$ We also get
$$[z^1] G(z) (1-z-z^2) =  1$$
or $g_1-g_0 = 1$ or $g_1=2.$ We have at the end for  $n\ge 2$
$$g_n-g_{n-1}-g_{n-2} = 0,$$
which is the Fibonacci number recurrence. With these two initial
values we obtain
$$\bbox[5px,border:2px solid #00A000]{
F_{n+2}.}$$