text:
Q: How to pass a service from .net core di container to a new object created with automapper I'm facing a scenario where I need to inject a service from asp.net core DI container to the constructor of an object created using automapper.
I don't know if this is the best practice but let me explain what I'm trying to accomplish.
I've an asp.net core mvc controller that receives a model parameter, just a POCO, that model needs to be converted into a ViewModel class that contains some business logic, data access etc, in that class object I want to get some info from the injected service, that is the part where I'm having problems, cant figure out how to inject the service from controller to the final ViewModel.
My code at this moment looks something like this.
NewGameModel.cs
namespace MyProject.Shared.Models
{
    public class NewGameModel
    {
        public List<PlayerModel> Players { get; set; }

        public bool IsValid => Players.Any();

        public NewGameModel()
        {
            Players = new List<PlayerModel>();
        }
    }
}

NewGameViewModel.cs
namespace MyProject.Core.ViewModels
{
    public class NewGameViewModel
    {
        private Guid Token = Guid.NewGuid();
        private DateTime DateTimeStarted = DateTime.Now;
        private readonly IConfiguration _configuration;

        public List<PlayerModel> Players { get; set; }

        public NewGameViewModel(IConfiguration config)
        {
            _configuration = config;
        }

        public string DoSomething()
        {
            //Do something using _configuration

            //Business Logic, Data Access etc
        }
    }
}

MapperProfile.cs
namespace MyProject.Service
{
    public class MapperProfile : Profile
    {
        public MapperProfile()
        {
            CreateMap<NewGameModel, NewGameViewModel>();
        }
    }
}

ASP.NET Core project - Startup.cs
namespace MyProject.Service
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton(Configuration);

            var autoMapperConfig = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MapperProfile());
            });

            var mapper = autoMapperConfig.CreateMapper();

            services.AddSingleton(mapper);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

ASP.NET Core project - GameController.cs
namespace MyProject.Service.Controllers
{
    [Route("api/[controller]")]
    public class GameController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly IMapper _mapper;

        public GameController(IConfiguration config, IMapper mapper)
        {
            _configuration = config;
            _mapper = mapper;
        }

        [HttpPost]
        public IActionResult CreateNewGame([FromBody]NewGameModel model)
        {
            if (!model.IsValid) return BadRequest();

            //Throws error because no constructor parameter was passed
            //How to pass the IConfiguration to the destination NewGameViewModel object?

            var viewModel = _mapper.Map<NewGameModel, NewGameViewModel>(model);

            var result = viewModel.DoSomething();

            return CreatedAtRoute("GetGame", new { token = result.GameToken }, result);
        }
    }
}

I will appreciate your help

A: For those coming later, the method above is not preferred, as it has state inside profiles. Instead, use the AutoMapper.Extensions.Microsoft.DependencyInjection package and inside your startup:
services.AddAutoMapper();

Then in your profile, just tell AutoMapper that you want your destination object constructed with the container:
public class MapperProfile : Profile
{
    public MapperProfile()
    {
        CreateMap<NewGameModel, NewGameViewModel>()
            .ConstructUsingServiceLocator();
    }
}

Your controller can then depend in IMapper and AutoMapper will use the DI container to construct the view model, and your configuration to ASP.NET Core will just be the one line to services.AddAutoMapper();

A: Update the profile to take the configuration as an injected dependency and use ConstructUsing when creating the mapping.
public class MapperProfile : Profile {
    public MapperProfile(IConfiguration config) {
        CreateMap<NewGameModel, NewGameViewModel>()
          .ConstructUsing(_ => new NewGameViewModel(config));
    }
}


text:
Q: how to mask all the div items in single parent div in css3 I created a list of animations through CSS animations and animations are like left to right and i.e object comes from left and stays in box(parent div) some time then goes to right in window. I did list of animations like these example. But I don't wanted to show the animations out of the box, animations  should be visible in the box only.

A: The simplest way to achieve this is use overflow: hidden; on the parent element to mask the elements outside the box

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making nhibernate do a join on a many-to-many relationship I have the following situation I am am stuck.
I have an entity called ContactAssociation which has(among others) the properties Client and a Contact.
I have to get all the Contacts for a Client that fulfill some condintions.
The conditions are:
Each Client has property BusinessEntities which is a collection of BusinessEntity, each BusinessEntity has a BusinessLevel.
This is the code, I am sure will make this more understandable:
link.Session.QueryOver<ContactAssociation>(() => ca)
                                       //.Fetch(asoc => asoc.Client)
                                       .JoinAlias(() => ca.Client, ()=> client)

.Left.JoinQueryOver<BuEntry>(() => client.BuEntries, () => be)
                                       .Where(() => client.ID == clientKey)
                                       .Where(() =>    be.BuLevel.LevelNo > buLevel);

Ok so I wrote the thing like this and I keep getting an error that the property BuLevel.LevelNo cannot be found
But it is there in the model
I tried criteria but I saw the same error only it was in NHProfiler instead of Visual Studio and there was a more cryptic error in Visual Studio.
Anyway ...
I eventually solved the problem with a sql query but how should I write the QueryOver and/or Criteria to get the proper results?
Thank you in advance
P.S.
Here is my SQL Query:
 careTeamMembers = link.Session.CreateSQLQuery(@"select c.* from ContactAssociation ca
                                inner join Contact c
                                on ca.contactkey = c.contactkey
                                left join ContactBu cb
                                on cb.contactkey = c.contactkey
                                left join BuEntry be
                                on cb.entrykey = be.entrykey
                                left join BuLevel bl
                                on be.levelkey = bl.levelkey
                                where ca.clientkey = :clientkey
                                and bl.levelno > :level")
            .AddEntity(typeof(Contact))
            .SetInt32("clientkey", clientKey)
            .SetInt32("level", buLevel)
            .SetMaxResults(1000)
            .List<Contact>();

A: You're missing a join on BULevel
link.Session.QueryOver<ContactAssociation>(() => ca)
                                       //.Fetch(asoc => asoc.Client)
                                       .JoinAlias(() => ca.Client, ()=> client)

.Left.JoinQueryOver<BuEntry>(() => client.BuEntries, () => be)
                                       .Where(() => client.ID == clientKey)
                                       .JoinQueryOver<BuLevel>(() => be.BuLevel)
                                       .Where(bu => bu.LevelNo > buLevel);


text:
Q: Mutating ndb repeated property I have two classes, Department and Employee. Department has a property declared as
employees = ndb.KeyProperty(kind=ClassB, repeated=True)
The problem is,when i delete the entity whose key is held in the employees list, the entity is deleted in the Employee datastore, but the list in Department datastore remains the same (with the key of the deleted employee still in it).
How do i make sure that when the Employee is deleted, all references to it in the Department datastore is deleted as well?

A: There is no automatic way of doing this.
You need to perform queries for all types that could hold the key and then delete them in code.
If there could be a lot and/or it could take a long time you might want to consider using a task.

A: I finally found a way to do this.I created a method in class A (Department) like this
def deleteEmployee(self, employee):
    employee_to_delete = employee.key
    if employee_to_delete in self.employees:
        idx=self.employees.index(employee_to_delete)
        del self.employees[idx]
        self.put()

and then from the Handler(could also be another method somewhere) where i am deleting the key from the list,i did something like this
class DeleteEmployeeHandler(webapp2.RequestHandler):
def post(self):
    employee_name = self.request.get('employee_name')
    employee=Employee.get_by_id(employee_name)
    emp_dept=employee.department
    dept=Department.get_or_insert(emp_dept)
    dept.deleteEmployee(employee)  #delete employee key from list
    employee.key.delete()  #then finally delete employee entity


text:
Q: Send Command to CMD.exe using Batch file Hi I'm trying to send the command "shutdown" to an already open command prompt called Administrator:  Transaction Server using a BAT file but when i run the BAT file nothing happens.
I followed this question - How to execute a command in already open CMD window using VBScirpt
Does anyone know why?
Here's my code:
:: s
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:115 /lparam:1
:: h
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:104 /lparam:1
:: u
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:117 /lparam:1
:: t
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:116 /lparam:1
:: d
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:100 /lparam:1
:: o
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:111 /lparam:1
:: w
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:119 /lparam:1
:: n
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:110 /lparam:1
:: ENTER
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:13 /lparam:1

:: ENTER
SendMessage-1.1.2.exe /windowtitle:"Test Server" /message:WM_CHAR /wparam:13 /lparam:1

:: wait for some time (~3 sec) till the program shuts down, if necessary
PING -n 4 localhost 1>NUL

pause
...

A: I don't know which sendmessage you are using. I downloaded this
SendMessage.exe: Access to advanced Windows features from Dostips.com author:aacini
And with this batch I managed to run shutdown in another cmd window titled Test-Msg:
@ECHO OFF

Set /A WM_CHAR=0x0102
Set Msg=%WM_CHAR%

Set Win="Test-Msg"
::          s   h   u   t   d   o   w   n   ret
For %%A in (115 104 117 116 100 111 119 110 13) Do (
echo SendMessage.exe %Win% %Msg% %%A 1
     SendMessage.exe %Win% %Msg% %%A 1
)
Pause
SendMessage.exe %Win% %Msg% 13 1


text:
Q: Membership provider - 2 different databases I have been researching a way to use membership provider when 2 different databases are involved in MVC3.
Here is the problem.
When the user logs in, Database A is used to get the roles and permissions
After successful login the data is handled from Database B. I have a custom provider.
When looking one of the solutions was to change the connection string during run time in the custom provider. But I am not sure when and where to do it.
If there are any other elegant way of handling roles and permission please point to me in that direction.
Thank you


text:
Q: robots.txt and htaccess (while CMS is in sub-folder) My CMS is placed in a subfolder, so via .htaccess I forward everything. Good for the cms and that following snippet works without any problems, but bad for files like robots.txt, which have to be stored in the web root (e. g. https://domain.xyz/robots.txt). If I call that URL the browser and the crawlers will be (of course) forwarded to https://domain.xyz/TEST
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://domain.xyz%{REQUEST_URI} [L,R=301]

    RewriteCond %{HTTP_HOST} !^domain\.xyz$ [NC]
    RewriteRule ^ https://domain.xyz/TEST [L,R=301]

    RewriteCond %{REQUEST_URI} !^/TEST
    RewriteRule ^ https://domain.xyz/TEST [L,R=301]
</IfModule>

So I have to skip that file(s) and I would add
RewriteCond %{THE_REQUEST} !/(robots\.txt|sitemap\.xml)\s [NC]

for the files robots.txt and sitemap.xml before the RewriteRule, but it doesn't work. What's wrong? Could somebody please help me with that? Thank you.

A: Arguably, this is not "forwarding", this is "redirecting", as in an external redirect. Forwarding would more commonly be used to describe an internal rewrite (where the URL does not change).

but bad for files like robots.txt, which have to be stored in the web root

Not necessarily. They don't need to be stored in (and accessed from) the web root. Google and other search engines do follow redirects when requesting robots.txt, XML sitemaps and similar files. From the Google Docs for robots.txt - "Handling of errors and HTTP status codes":

3xx (redirection)
Google follows at least five redirect hops as defined by RFC 1945 and then stops and treats it as a 404 for the robots.txt.

However, you can still include an exception if you wish, but you have an error in your regex...

RewriteCond %{THE_REQUEST} !/(robots\.txt|sitemap\.xml)\s [NC]

You have an erroneous \s (literal space character) at the end of the CondPattern - so this will never match and the condition is always successful. Perhaps you meant to write $ (end-of-string anchor)? You are also missing the start-of-string anchor.
For example, it should be:
RewriteCond %{THE_REQUEST} !^/(robots\.txt|sitemap\.xml)$ [NC]

OR, include a positive matching rule before your existing rules that prevents any later rule (ie. redirects) from occurring when a request for one of these files are made:
# Prevent further processing if "robots.txt" or "sitemap.xml" requested
RewriteRule ^(robots\.txt|sitemap\.xml)$ - [NC,L]

RewriteRule ^ https://domain.xyz/TEST [L,R=301]

Since TEST is a physical directory you should append a trailing slash to the redirected URL, ie. /TEST/, otherwise Apache (mod_dir) will append the trailing slash with a second redirect.
You will need to clear your browser cache before testing since the 301 (permanent) redirects will have been cached by the browser.


text:
Q: Android Dex: UNEXPECTED TOP-LEVEL EXCEPTION: Already added My app depends on a library project. This library project depends on the Android Compatibility Package V4. I have NOT exported the library project's dependency. In my own project, I've added ACL V13 as a dependency, but when compiling I get the error that essentially there's a duplicate dependency. I thought not exporting the library project's dependency would resolve this issue, but it's not.
How can I resolve this?
EDIT
Also, according to Android tools docs:

Special case for android-support-v4.jar and android-support-v13.jar.
We make a special case for these two libraries because -v13 contains a
  full version of -v4 inside. If both are found, then only -v13 will be
  used.

So it should just work...

A: Delete the v4 package from the library.
Clean the Projects.

A: In my case, I had just updated one of the JARs in the libs/ folder to a new version.
All it took to fix it was to run Build -> Rebuild Project, i.e. issue a 'clean' task before the 'assembleDebug' etc.

A: Well, in my story I had to delete module dependencies which were the same, add it in library, and then add this library to each module as a dependence.
So:

*

*Module a : Depends on android-v4 (and has it in it's lib folder)

*Module b : Depends on android-v4 (and has it in it's lib folder)

*

*Add to libraries of project "android-v4" (for ex from 1st module). Delete it in module b lib folder.

*Delete in modules a and b dependence of android-v4

*Add to each module dependence -> library -> android-v4 (which you created in 2 step)
I'm not sure if it is the right solution but it works.

A: If you use exactly the same lib jar in different projects (libs project or standard projects), the apk tools get rid automatically of the duplicate ones.
The problem starts when you have two libs with the same name but not at the same revision.
The android-support-v4.jar and android-support-v13.jar files can be from different revision since there always have the same name in different  support package release (http://developer.android.com/tools/extras/support-library.html#Notes)
I would check that you use exactly the same revision of the support libs in your main project and in your lib project.
To make sure, copy the two support libraries jars (located in the android-sdk folder) to your projects libs folder.
{android-sdk}/extras/android/support/v4/android-support-v4.jar
AND
{android-sdk}/extras/android/support/v13/android-support-v13.jar

It should get rid of the problem.

A: Have you tried to change the dependency of the library from v4 to v13 and export it?

A: Sometimes simply removing v4 support library does not work, you also need to rebuild or the project.


text:
Q: jQuery: Find first two children Using jQuery, what would be the most efficient way to find the first two children of a parent element, if one is an h1 and the other is a p. My code isn't working right now, and I would like to accomplish this using best practices.
CSS
div > *{
    display: none;
}

HTML

Heading

Paragraph 1

Paragraph 2

Heading

Paragraph 1

Paragraph 2

Javascript
$('div h1').show();
$('div p:first-child').show();

Edit I'm actually working with multiple DIVs. I didn't think it would make a difference, but it looks like I was wrong.

A: an alternative way to slice() method:
$('div').children(':lt(2)').show()

(but I recommend the slice too, especially for large collections)

A: Try,
$('div').children().slice(0,2).show();

Incase if you have more that 1 div, then try like below,
$('div').each (function () {
    $(this).children().slice(0,2).show();
});

A: http://jsfiddle.net/94EU7/
$('div :lt(2)').show();

A: $('div').children().slice(0, 2).show();

A: You can user the less than selector like following
$('div > *:lt(2)').show();

Working fiddle

A: A descriptive selector would be
$('div').find('h1:first, p:first').show();

This makes it clear what your intent is and what elements you're selecting.

A: $('div p:first-child,div p:nth-child(2)').show();

A: I think you'll want the eq() function, like this:
$("div").children().eq(0); // first child
$("div").children().eq(1); // second child

A: Not sure why you need to use jQuery for this.
var firstChild = div.firstChild;
firstChild.style.display = 'initial';
firstChild.nextSibling.style.display = 'initial';


text:
Q: How to merge a DataFrame for both column-wise and row wise into 1D array? Guys,
I have a DataFrame read from csv, it looks like as following (use simple number and X to simplify) :
X,X,X,X,X,X,X,X,X,X
X,1,2,3,4,5,6,7,8,X
X,1,2,3,4,5,6,7,8,X
X,1,2,3,4,5,6,7,8,X
X,1,2,3,4,5,6,7,8,X

Here it is my needs - I want to generate a 1D array/list from the DataFrame above with :

*

*I need to remove all X values (which is only happened in first row, first column, and last column)

*Create a column wise array - 1,1,1,1,2,2,2,2,3,3,3,3,...,8,8,8,8

*Create a row wise array - 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,...

I want to know the simplest code for those purpose, really appreciate.
Regards,
Wangyang

A: 1 : iloc
df.iloc[1:, 1:-1]

   1  2  3  4  5  6  7  8
1  1  2  3  4  5  6  7  8
2  1  2  3  4  5  6  7  8
3  1  2  3  4  5  6  7  8
4  1  2  3  4  5  6  7  8

2 : unstack
For column-wise
df.iloc[1:, 1:-1].unstack()

3: stack
For row-wise
df.iloc[1:, 1:-1].stack()

____________________________________________
A Numpy take
a = np.array([center for left, *center, right in zip(*map(df.get, df))][1:], dtype=int)
a

array([[1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8],
       [1, 2, 3, 4, 5, 6, 7, 8]])

Column-wise
np.ravel(a, order='F')

[1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8]

Row-wise
np.ravel(a)
# np.ravel(a, order='C')

[1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8]

A: For your row-wise array use,
df.iloc[1:,1:-1].stack().values

For your column-wise array use,
df.iloc[1:,1:-1].unstack().values


text:
Q: Deleting rows in a dataset when they are missing data in a specific column using Python I'm trying to identify which rows have a value of nan in a specific column (index 2), and either delete the rows that have nan or move the ones that don't have nan into their own dataframe. Any recommendations on how to go about either way?
I've tried to create a vector with all of the rows and specified column, but the data type object is giving me trouble. Also, I tried creating a list and adding all of the rows that != 'nan' in that specific column to the list.
patientsDD = patients.iloc[:,2].values

ddates = []
for value in patients[:,2]:
    if value != 'nan':
        ddates.append(value)

I'm expecting that it returns all of the rows that != 'nan' in index 2, but nothing is added to the list, and the error I am receiving is '(slice(None, None, None), 2)' is an invalid key.
I'm a newbie to all of this, so I really appreciate any help!

A: You can try this (assuming df is the name of your data frame):
import numpy as np
df1 = df[np.isfinite(df['index 2'])]

This will give you a new data frame df1 with only the rows that have a finite value in the column index 2. You can also try this:
import pandas as pd
df1 = df[pd.notnull(df['index 2'])]

If you want to drop all the rows that have NaN values in any of the columns, you can use this:
df1 = df.dropna()

A: You can use .isna() of pandas:
patients[!patients.iloc[:, 2].isna()]

Instead of delete rows are nan, you can select only rows that are not nan.


text:
Q: Python 2.7.12 + dev_appserver.py does not suports java8 I'm trying to run an appengine module with the command below:

*

*$ python /usr/lib/google-cloud-sdk/platform/google_appengine/dev_appserver.py --max_module_instances = 1 --jvm_flag = "- agentlib: jdwp = transport = dt_socket, server = y, suspend = n, address = 9999 "target / security-authentication-1.0.0-SNAPSHOT --dev_appserver_log_level = debug

But I'm getting this error:

*

*DEBUG 2018-02-22 14: 15: 27,450 appengine_rpc.py:170] Server: appengine.google.com

*ERROR 2018-02-22 14: 15: 27,452 sdk_update_checker.py:201] The requested api_version (1.0) is not supported by the java8 runtime in this release of the SDK. The supported api_versions are ['1'].

How do I solve this problem?
Here is some information:
$ gcloud -v

*

*Google Cloud SDK 190.0.0

*alpha 2017.12.08

*app-engine-java 1.9.62

*app-engine-python 1.9.67

*beta 2017.12.08

*bq 2.0.29

*core 2018.02.16

*gsutil 4.28

$ python --version

*

*Python 2.7.12

A: The error message suggests you may have used an api_version other than 1. From the api_version row in the Syntax table:

At this time, App Engine has one version of the python27 runtime
  environment: 1

Make sure you have this in your app.yaml, not something else:
api_version: 1

You also have both the Python and Java development tools installed in your SDK and using some arguments which are specific to the Java development server, that might not work (well) with the Python development server you're attempting to invoke. See the Python Using the Local Development Server and Local Development Server Options vs Using the Java Local Development Server.


text:
Q: Why was the boolean data type not implemented in C One of my friends asked a question, why is there no Boolean data type in the C programming language. I did a bit of searching and reading. I got few questions and answers in stack overflow saying that,

*

*All data types should be addressable, and a bit cannot be addressed.

*The basic data structure at the hardware level of mainstream CPUs is a byte. Operating on bits in these CPUs require additional processing.

We can use a bool in this manner
#define bool int
#define TRUE 1
#define FALSE 0

or use typedefs.
But my question is this: why wasn't it implemented as a data type in C, even after  so many years. doesn't it make sense to implement a one byte data type to store a boolean value rather than using int or short explicitly.

A: C99 added support for boolean type _Bool, is not simply a typedef and does not have to be the same size as int, from the draft C99 standard section 6.2.5 Types:

An object declared as type _Bool is large enough to store the values 0 and 1.

We have convenience  macros through the stdbool.h header. we can see this from going to the draft C99 standard section 7.16 Boolean type and values  whcih says:

The header  defines four macros.
The macro

bool

expands to _Bool.
The remaining three macros are suitable for use in #if preprocessing directives. They
  are

true

which expands to the integer constant 1,

false

which expands to the integer constant 0, and

__bool_true_false_are_defined

which expands to the integer constant 1.

A: That's not true any more. The built-in boolean type, aka _Bool is available since C99. If you include stdbool.h, its alias bool is also there for you.

_Bool is a true native type, not an alias of int. As for its size, the standard only specifies it's large enough to store 0 and 1. But in practice, most compilers do make its size 1:
For example, this code snippet on ideone outputs 1:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
    bool b = true;
    printf("size of b: %zu\n", sizeof(b));
    return 0;
}

A: Since the data types are predefined ,we cannot use the "bool" data type as it is not present in the documentation


text:
Q: Does not contain definition of button in asp.net application I would like to use id in code behind in aspx.cs. Not sure how to use it.
<input name="SelectAllButton" type="button" id="SelectAllButton"  value="DeSelect All" class="EButton" title="DeSelect All" />

aspx.cs code
SelectAllButton.ID = "SelectAllButton";

But If use webbutton then it works but I do not want to use it.
<cc1:WebButton ID="SelectAllButton" runat="server"></cc1:WebButton>

A: For ASP Web Forms, you should use the ASP input types. <input /> is a client-side HTML input and won't be seen by the server.
I believe you will want to use asp:Button type.
E.g.
<asp:Button id="SelectAllButton" Text="DeSelect All" class="EButton" runat="server" />


text:
Q: Kibana navigate from one dashboard to other I have 2 dashboards: an advanced and a basic dashboard. I want to provide link(url) of advanced dashboard in basic dashboard from the data saved in elasticsearch (which varies for each of the index pattern).
I tried using markdown (Text) but there I am not able to add any data from elastic search.
I am using elastic and kibana version 7.16


text:
Q: Are legs a choice?
Legs are a choice in that we could choose not to have them by cutting them off.

Is it correct here to use the word choice meaning "an option"?
Is it correct to say that legs are a choice I could use to get to work instead of using the choice of a car?

A: Yes to both of your questions. People say those things.
Strictly speaking, choices and options are different things, but in normal spoken and written English, they're usually considered interchangeable. Only peevish pedants would dispute that, except where stipulated that they're different.
You can replace "legs" with "shank's mare".
I don't think I'd say "Legs are a choice I could use to get to work instead of using the choice of a car". It's verbose and a bit awkward. I'd probably write "Legs, instead of a car, are an option for getting to work".


text:
Q: WPF interoperability - how can I get the including Form object from the WPF control? I have a form of Form1 class and a WPF user control inside it (inside ElementHost). How can I get the Form1 object from this control's code-behind?
Here is the code:
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{

    public UserControl1()
    {
        InitializeComponent();
    }

    private void Btn_Click(object sender, RoutedEventArgs e)
    {
         // I'd like to access the form here
    }
}


text:
Q: Mathematics behind this card trick

*

*Suppose I have $21$ playing cards. I distribute them in $3$ columns and tell you to choose mentally a card. Then just indicate in which column the card is.

*I pick up one of the columns which doesn't contain your card, then the column which contains your card then the remaining column.

*Now I deal the cards in $3$ columns again, starting from the left to the right, and repeating the process until there are no cards left in
  my hand. I ask you to indicate to me in which column your card is.

*I repeat step 2 then 3.

*I repeat step 2.
Now by counting either way in the deck of $21$ cards, your card will be the 11th card.

I've tried using modulo to understand the problem but I'm stuck doing integer divisions. So does anyone have a simpler way to explain the trick.
Also could anyone explain why it works only for odd number of cards in each column and why it requires additional steps for more cards. e.g for $17 \cdot 3 = 51$ requires an additional step compared with $21$ cards?
EDIT: I forgot to add that the number of cards you have to count for the final step equals
$$1.5\text{ times the number of cards in each column} + 0.5$$

A: Let's go step by step. After steps i) and ii) we already know that the chose card is in position $8,9,10,11,12,13,14$ in the pile. Then after dealing all the cards again in the given manner we know that the cards that were in the positions $8,9,10,11,12,13,14$ before dealing are now in places $3,4,5$ (actually it depends on the pile, but we can be sure that each of the mentioned cards is now at a position $3,4$ or $5$ in one of the three piles. So eventually after the second step we narrowed the choice to three cards.
After putting the cards in one pile again then we know that the chosen card will be in position $10,11,12$. And in the last deal obviously each of the cards will be in dealt in different pile, so we should be able to find out which one is the card for sure. But during the last deal the cards in positions $10,11,12$ are all in position $4$ in each of the new piles, hence after collecting all the cards, the chosen card will be in position $11$.
Eventually as you can see with each dealing we lower the number of possibilities from $n$ to $\lfloor\frac{n-1}{3}\rfloor + 1$.

A: Suppose that, when you first lay the cards on the table, the card I choose is at position $x$ in its column. You don't know $x$, but you know that $1\leq x\leq 7$.
Now, when you pick up the cards, my card will be at position $7+x$ in the full stack. The second time you lay the cards on the table, my card will appear at position $p_1=\lceil\frac{7+x}{3}\rceil$ in its column.
The second time you pick up the cards, my card will be at position $7+p_1$ in the full stack. The third time you lay the cards on the table, my card will appear at position $p_2=\lceil\frac{7+p_1}{3}\rceil$ in its column.
Finally, when you pick up the cards for the third time, my card will be at position $7+p_2$ in the full stack. Putting this all together, my card will be at position
$$7+p_2=7+\left\lceil\frac{7+\lceil\frac{7+x}{3}\rceil}{3}\right\rceil$$
in the full stack. The trick is that this is equal to $11$ for all $x$ in the range $1\leq x\leq 7$.
For a proof of this last statement, as jpmc26 mentions, one can apply the identities $\lceil\frac{m+\lceil x\rceil}{n}\rceil=\lceil\frac{m+x}{n}\rceil$ and $\lceil n+x\rceil = n+\lceil x\rceil$ (for real $x$, integer $m$, and positive integer $n$) to show that
$$7+\left\lceil\frac{7+\lceil\frac{7+x}{3}\rceil}{3}\right\rceil = 7+\left\lceil\frac{7+\frac{7+x}{3}}{3}\right\rceil =  7 + \left\lceil 3 + \frac{x+1}{9}\right\rceil = 10 + \left\lceil\frac{x+1}{9}\right\rceil \enspace,$$
which is clearly equal to $11$ for $1\leq x\leq 7$.

A: You can find a full explanation of this trick and related ones at
Gergonne's Card Trick, Positional Notation, and Radix Sort
(Mathematics Magazine, February, 2010)
http://www.maa.org/sites/default/files/Bolker-MMz-201053228.pdf
The classic trick uses $27 = 3^3$ cards. Your $21$ card version is discussed on page 48.

A: I've wondered this for years idly, and your asking has made me think about it. Here's an answer.
After one deal-and-gather phase, your card is in the middle third of the deck, right?
When you deal out the cards again, where does that middle third end up? In the middle third (looking top-to-bottom) of the tableau.
To see this: on the first deal, pick a card, say, the 3 of hearts. Replace everything else in its column with red cards, and everything else in the other two columns with black cards. Gather and re-deal. You'll see a red "band" in the middle (top to bottom) of the new tableau.
Now you identify your card in that middle band. When you gather up the other cards, it'll once again be in the middle third of the deck, because there's one entire column-worth of cards in front of it, and one entire column-worth of cards behind it.
But you can say more than that: suppose your card was in the first column. Well, then, it was in the middle third of the first column, wasn't it? So if each column has $k$ cards, you've got $k$ cards in front of it (from one of the other piles), and another k/3 cards (from its own pile) in front of it, and the same for cards behind it. So now it's in the middle 1/9th of the pile.
And the next time it'll be in the middle 1/27 of the pile. And so on.
Now that analysis isn't QUITE right, because $k$ might not be divisible by 3. So instead of having k + k/3 cards in front of it after two deals, you have k + floor(k/3). For instance, if $k = 8$, then you'd have $8 + floor(8/3) = 8 + floor(2.66...) = 8 + 2 = 10$ cards in front of it. But aside from this minor glitch, what you get is the following:
after $p$ "passes" on a deck of $N$ cards, your card is in the middle (roughly) $(N/3^p)$ cards of the deck. When $3^p > N$, this means that your card is the middle card of the deck.


text:
Q: Detect connection protocol (HTTP/2, spdy) from javascript Is it possible to get the protocol that the browser used to get the active page?
Something like:
performance.navigation.protocol // e.g. "HTTP/2" or "SPDY/3.1" or "HTTP/1.1"

I know that it's possible to detect the protocol server side and then pass the info, but I'm looking for a JS solution.
(a similar question contains a broken link and no answer)

A: It is being standardised as performance.timing.nextHopProtocol, but chrome has a non-standard implementation already under window.chrome.loadTimes().connectionInfo:
if ( window.performance && performance.timing.nextHopProtocol ) {
    console.log('Protocol:' + performance.timing.nextHopProtocol);
} else if (window.performance && window.performance.getEntries) {
    console.log(performance.getEntries()[0].nextHopProtocol);
} else if ( window.chrome && window.chrome.loadTimes ) {
    console.log('Protocol:' + window.chrome.loadTimes().connectionInfo);
} else {
    console.log("Browser does not expose connection protocol");
}


text:
Q: Как заблокировать пользователя discord.py Как сделать, чтобы бот заблокировал пользователя ?Не в каком либо канале, а  самом дискорде, чтобы пользователь не мог писать боту в ЛС

A: Это не может быть реализовано так как бот не умеет блокировать людей в лс. В discord.py api вообщем то даже такого метода нет.


text:
Q: Compering undefined, null and values I want to run this in my code:  if(a > b){ do something} where a and b can be sometimes undefined or null and sometimes comparable(e.g. both a number).
Is it ok in javascript to do this?
I only want the if to be true if they are comparable.

A: In general, you should never attempt to compare things of different types without defining your rules for how you want them to be compared. While there's actually a very strict set of rules defined in JS standard for comparing values of different types, you're opening the big can of worms if you try to design your code around this set.
What you might consider doing instead is separating type casting operation from comparison operation. For example:
function firstIsGreater(numA, numB) {
   if (typeof numA !== 'number') return false;
   if (typeof numB !== 'number') return false;

   return numA > numB;
}

Strictly speaking, those checks are not required here. For example, when you compare with undefined, that gets cast to NaN, and any comparison involving NaN results in false.
The problem is that usually mixture of types is a sign of much bigger problems in your outlying code - and instead of returning false you might consider throwing errors, or at least triggering some warnings.
In general you should validate the values and cast them to the types you're completely aware of at the very moment those values arrive into your system from some external components - server-side calls, user input etc.

A: if(typeof a == 'number' && typeof b == 'number' && a > b){ do something}

This will only run "do something" if a and b are both numbers and a is greater than b.

A: Any undefined value in combination with a comparison of less than <, greater than > or less than or equal or graater than or equal yields false.
Any null value is converted to zero in an number like environment.
Maybe this table helps: Loose equality using ==

if (undefined < 3) console.log('undefined < 3');
if (undefined > 3) console.log('undefined > 3');
if (undefined <= 3) console.log('undefined <= 3');
if (undefined >= 3) console.log('undefined >= 3');

if (null < 3) console.log('null < 3');
if (null > 3) console.log('null > 3');
if (null <= 3) console.log('null <= 3');
if (null >= 3) console.log('null >= 3');


text:
Q: Unity 3D Camera dot projectionMatrix To be brief,
I would like to achieve the same camera view of a MOBA like game, If you ever noticed for example in league of legends or Dota 2, the camera is not in a perspective mode nor in a 100% orthographic.
(eventhough it's more close to an orthographic one than to a perspective one)
for example if you start moving the camera to left or right from point A to B you can see some faces of some unmoving objects (like turrets) you couldn't see from point A, but it still keeps the dimension and the size of the objects the same,
unlike an orthographic camera you can't see another face of the unmoving (or moving) object no matter how many times you try to move the camera.
I hope I was clear, I know it must be in the matrix projection I have been told that I need an "off axis projection", which I have no idea what it is, OpenGL and rendering things are not my strongest spot.
any help will be much appreciated.
here is the script I'm using with some tweaks still getting nothing :
http://docs.unity3d.com/ScriptReference/Camera-projectionMatrix.html
Edit :
For the script : I'm using the script I linked earlier I didn't come up with anything new here that's why I'm here.

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ExampleClass : MonoBehaviour {
    public float left = -0.2F;
    public float right = 0.2F;
    public float top = 0.2F;
    public float bottom = -0.2F;
    void LateUpdate() {
        Camera cam = camera;
        Matrix4x4 m = PerspectiveOffCenter(left, right, bottom, top, cam.nearClipPlane, cam.farClipPlane);
        cam.projectionMatrix = m;
    }
    static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far) {
        float x = 2.0F * near / (right - left);
        float y = 2.0F * near / (top - bottom);
        float a = (right + left) / (right - left);
        float b = (top + bottom) / (top - bottom);
        float c = -(far + near) / (far - near);
        float d = -(2.0F * far * near) / (far - near);
        float e = -1.0F;
        Matrix4x4 m = new Matrix4x4();
        m[0, 0] = x;
        m[0, 1] = 0;
        m[0, 2] = a;
        m[0, 3] = 0;
        m[1, 0] = 0;
        m[1, 1] = y;
        m[1, 2] = b;
        m[1, 3] = 0;
        m[2, 0] = 0;
        m[2, 1] = 0;
        m[2, 2] = c;
        m[2, 3] = d;
        m[3, 0] = 0;
        m[3, 1] = 0;
        m[3, 2] = e;
        m[3, 3] = 0;
        return m;
    }
}

For the screens : Focus your eyes on the turrets of course, here is the Screens, since I don't have much reputation I can't post pictures or more than two links, so
here is a dropbox link containing only pictures (4).
2 of unity3d environement,
and 2 of League Of Legends Camera,
observe the Turret in the LoL's Screenshots, and the Pillars in Unity3d with an isometric camera, You can tell that these are using the same matrix, if I move the camera to the right I can see the face of the turret that I could not see from my previous standing point, and that's the effect I'm looking to achieve.
Assuming that everyone agrees that League of Legends is using an isometric camera or at least something close to it.
Thanks for your time.
Pictures in dropbox link is here.


text:
Q: HTML entity in JavaScript (XML and PHP) Newbie in troubles again))) Need yr help guys!
I have an XML file with the data like this:
<Page>
<Content>
Article content

HEADER

&nbsp;

</Content>
</Page>

now I want to extract this data via PHP & replace html by jQ.
<?php
$file = '111.xml';
$XML = simplexml_load_file($file);
$str =$XML->Content;
$str = htmlspecialchars($str, ENT_QUOTES);
JS('var CONV = "'.$str.'"'); //JS function just puts its parametr between

so the result is NOTHING... if i do Echo - it works, if i replace CONV value with smth like "bla bla bla" - it works either. But with encoded or decoded HTML it shows none...
UPDATE:
i still dont know where's the problem. I use "buffer" file as a temporary soultion:
file_put_contents('../plugins/'.pl_DIR().'/buffer.db', $str, LOCK_EX);
JS('$("#editor").load("../../plugins/"+PATH+"/buffer.db")');

Via AJAX the content loads perfectly but anyway Im sure that's diffenetley not the best idea...

A: You should try replace
$str = htmlspecialchars($str, ENT_QUOTES);

with
$str = htmlspecialchars_decode($str, ENT_QUOTES);

see http://php.net/manual/en/function.htmlspecialchars-decode.php
I had similar problem the other day, and that solved it for me.


text:
Q: Can you create a custom view? I am trying to recreate a screen from one application (see picture). The problem I am facing is focused on the grid elements of the screen. Is it possible to create a custom view which is a combination of an image and a text view (like in the picture) or should I add the image view and text views separately in each row of the grid view?

A: step 1 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="134dp"
    android:layout_height="154dp"
    android:background="@drawable/grey_rounded_background"
    android:gravity="center"
    android:padding="16dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="80dp"
        android:layout_height="70dp"
        android:layout_marginBottom="8dp"
        tools:src="@color/colorPrimary" />

    <TextView
        android:id="@+id/caption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:text="Caption of the Image"
        android:textAlignment="center"
        android:textColor="#666"
        android:textSize="12sp"/>

</LinearLayout>

step 2

<declare-styleable name="BenefitView">
    <attr name="image" format="reference"/>
    <attr name="text" format="string"/>
</declare-styleable>

step 3
class BenefitView(context: Context, attrs: AttributeSet): LinearLayout(context, attrs) {

    init {
        inflate(context, R.layout.benefit_view, this)

        val imageView: ImageView = findViewById(R.id.image)
        val textView: TextView = findViewById(R.id.caption)

        val attributes = context.obtainStyledAttributes(attrs, R.styleable.BenefitView)
        imageView.setImageDrawable(attributes.getDrawable(R.styleable.BenefitView_image))
        textView.text = attributes.getString(R.styleable.BenefitView_text)
        attributes.recycle()

    }
}

use :
<com.iacovelli.customview.BenefitView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:text="Apply and chat with our hosts"
      app:image="@drawable/first_image"
      android:layout_marginEnd="12dp"/>


text:
Q: How to add data to all log records in Laravel 5.6? How to add data to all log records in Laravel? answers how to add data to all log records in Laravel 5.5 and earlier. e.g. the following is added to AppServiceProvider::register():
$monolog = \Log::getMonolog();
$monolog->pushProcessor(function ($record) {
    $record['extra']['ip'] = \Request::getClientIp();
    $record['extra']['path'] = \Request::path();
    return $record;
});

This doesn't work for Laravel 5.6. I looked through the documentation for 'creating custom channels' but didn't see any obvious way to get the above behavior.
The error occurs from

@php artisan package:discover -v

Symfony\Component\Debug\Exception\FatalThrowableError  : Call to undefined method Monolog\Logger::getMonolog()

at ...\vendor\laravel\framework\src\Illuminate\Log\Logger.php: 273
269:      * @return mixed
270:      */
271:     public function __call($method, $parameters)
272:     {
273:         return $this->logger->{$method}(...$parameters);
274:     }
275: }
276:

Exception trace:

1   Illuminate\Log\Logger::__call("getMonolog", [])

...\vendor\laravel\framework\src\Illuminate\Log\LogManager.php : 609

2   Illuminate\Log\LogManager::__call("getMonolog", [])

...\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php : 223

Please use the argument -v to see more details.

I am far from an expert at this so any help is appreciated.

A: Here is how I solved this.

*

*In .env, use the 'stack channel' for logging (i.e. 'LOG_CHANNEL=stack')

*Add a 'tap' to a driver in config\logging.php
'single' => [
    'driver' => 'single',
    'tap' => [App\Logging\CustomizeFormatter::class],
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
]

*Create App\Logging\CustomizeFormatter:
namespace App\Logging;

class CustomizeFormatter
{
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->pushProcessor(function ($record) {
                $record['extra']['ip'] = \Request::getClientIp();
                $record['extra']['path'] = \Request::path();

                return $record;
            });
        }
    }
}


text:
Q: ReportViewer & SSRS RDL Right-to-Left Export I am working on an ASP.Net project where we use SSRS RDL reports with the ReportViewer control.
The project is in Arabic language so the layout should be right to left.
I managed to display right to left reports in the ReportViewer using CSS direction on the rendered HTML of the report, but I'm having trouble controlling the report export direction.
I googled around but I could not find anything that can control the exported file.
Solutions I tried:

*

*Using a Matrix in the RDL with LayoutDirection set to RTL.

*Reversing the order of the fields and the tables of the RDL.

*Setting the report page's Culture and UICulture to ar-JO/ar-SA but it did not change anything.
So if anyone has any solution to achieve the RTL layout of the report and of the exported file, it'll be much appreciated.
Any solution using C#/VB.Net/SSRS/ReportViewer/Configs/CSS/Javascript is more that welcome.

A: Tested:
set every textbox's direction property to RTL. Worked for me.


text:
Q: input checkbox : Not able to call controller function I have below component, however I am not getting console logs from the  method, I need to get the value of the checkbox getting called.

<input type="checkbox" id="checkboxOne" value="Paid"  />Paid

<input type="checkbox" id="checkboxTwo" value="Pending" onchange="{!c.addStatusFilter}" />Pending

<input type="checkbox" id="checkboxThree" value="Rejected" onchange="{!c.addStatusFilter}" />Rejected

<input type="checkbox" id="checkboxFour" value="Declined" onchange="{!c.addStatusFilter}" />Declined

I have tried:
span
onchange
onclick
Below is code from controller js
addStatusFilter:function(component,event,helper){
    alert('Add filter');
    console.log('Inside add Status Filter');
    //var btnValue = event.getSource().get("v.value");
    console.log('btnValue---->'+btnValue);
    applyStatusFilter(component,event,helper);
},
addStatusFilter:function(component,event,helper){
}


text:
Q: Loop Statement Logic 1) The first loop I need to use is a do/while. In this loop the user is prompted to type in a word. If the user types in the wrong word they get an error message:
Invalid! Try Again! 2 attempt(s) left!
Invalid! Try Again! 1 attempt(s) left!
Sorry!  You have no more attempts left!
This output works as long as the wrong word is entered each time, but if the correct word is entered after 1 failed attempt it still applies the error message
2) Within my second loop (for loop) the user is asked to enter "3 * 8 = " This portion of the loop works fine if a wrong number is entered all 3 times or if 24 is entered on any attempt.
The problem lies in the loop after 24 is entered. The output is as follows:
Thank you blah blah. We'll call you at 5555555555 if you're a winner. 3 * 8 = Where the 3 * 8 should not be showing. I realize I could enter a break; after this statement, but the instructions specifically say that I cannot use the break command.
The correct output should read: Thank you blah blah. We'll call you at 5555555555 if you're a winner.
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);

    int attempt = 2;
    int answer = 24;
    long phoneNumber = 0;
    String firstName = "";
    String lastName = "";
    String wordOfTheDay = "";

    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();

    if(wordOfTheDay.equals("tired"))
    {
        for( attempt = 2; attempt >= 0; --attempt)
        {
            System.out.print(" 3 * 8 = ");
            answer = input.nextInt();
            input.nextLine();

            if( answer == 24)
            {
                System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

                firstName = input.next();
                lastName = input.next();
                phoneNumber = input.nextLong();

                System.out.printf(
                    "Thank you %s %s. We'll call you at %d if you're a winner.",
                    firstName,
                    lastName,
                    + phoneNumber);
            }

            else if( answer != 24)
            {
                if(attempt!=0)
                {
                    System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
                    continue;
                }
                else
                {
                    System.out.print( "Sorry!  You have no more attempts left!" );
                }
            }
        }
    }
    else
    {
        do
        {
            System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
            --attempt;
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();
        } while (attempt >= 1);

        if( attempt == 0)
        {
            System.out.print( "Sorry!  You have no more attempts left!" );
        }
    }
}

I hope I made this clear enough.
To recap, I need to fix the problem with my do/while not letting me enter the correct word after a failed attempt.
Also, I need to get rid of the 3 * 8 = showing up after the users enters the correct input.

A: I think you're trying to do this.!
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int answer = 0;
        long phoneNumber = 0;
        String firstName = "";
        String lastName = "";
        String wordOfTheDay = "";

        int mainMenuAttempt = 3;
        do {
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();

            if (wordOfTheDay.equals("tired")) {

                int answerAttempt = 3;
                do {
                    System.out.print(" 3 * 8 = ");
                    answer = input.nextInt();
                    input.nextLine();
                    answerAttempt--;

                    if (answer != 24 && answerAttempt >0)
                        System.out.printf(
                                "Invalid! Try Again! %d attempt(s) left!\n ",
                                answerAttempt);

                } while (answerAttempt >0 && answerAttempt < 3 && answer != 24);

                if (answer == 24) {
                    System.out
                            .printf("Please enter your first name, last name, and phone number (no dashes or spaces)\n"
                                    + "in a drawing for an all-expenses-paid vacation in the Bahamas: ");

                    firstName = input.next();
                    lastName = input.next();
                    phoneNumber = input.nextLong();

                    System.out
                            .printf("Thank you %s %s. We'll call you at %d if you're a winner.",
                                    firstName, lastName, +phoneNumber);
                }

            }

            mainMenuAttempt--;

        } while (mainMenuAttempt >0 && mainMenuAttempt < 3 && !wordOfTheDay.equals("tired") && answer!=24);
        System.exit(0);
    }
}

A: Try breaking the whole thing down into very small functions that do one specific thing each. For example, you might have a function that just checks if a word is the correct one, returning 0 if it is, or the number of attempts made if it isn't.
private int checkWord(String correctWord, String wordToCheck, int attempts)
{
    if(wordToCheck.equals(correctWord))
    {
        return 0;
    }
    return attempts;
}

You could then make a function which takes user input, and calls this function to check said input. It could then output an error message dependant on the return code of the previous function. The function would then return a code to tell the function above it the situation.
public int checkWordVerbose(String question, String correctWord, int attempts)
{
    if(attempts <= 3)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print(question);
        String input = scan.nextLine();
        int failureCode = checkWord(correctWord, input, attempts);

        if(failureCode == 0)
        {
            return 0;
        }
        else
        {
            System.out.println("Invalid! Attempts left: " + (3 - failureCode));
            return 1;
        }
    }
    else
    {
        System.out.println("Sorry! You have no more attempts left!\n");
        return 2;
    }
}

Lastly, you could make a function which simply contains the loop, and holds the logic for maintaining that loop:
public int checkWord(String correctWord)
{
    int failureCode = 1;
    int attempts = 1;
    do
    {
        failureCode = checkWordVerbose("Enter the word of the day: ", correctWord, attempts);
        attempts++;
    } while(failureCode == 1);
    return failureCode;
}

Then in main, all you need to do is check if checkWord(String correctWord) returned 0. Repeat the same thing for your other check (Or you might even be able to use some of the same functions), performing another if inside the first, eg:
if(checkWord("tired") == 0)
{
    if(checkMath("24") == 0)
    {
        // Success!
    }
}

A: Unless I'm missing something, you are waiting for the first input and if it's wrong, you are going in a do-while loop and then never checking again if the input is correct.
You have to move the if inside the do-while loop:
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int attempt = 2;
    int answer = 24;
    long phoneNumber = 0;
    String firstName = "";
    String lastName = "";
    String wordOfTheDay = "";

    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();
    do {
        if (wordOfTheDay.equals("tired")) {

            for (attempt = 2; attempt >= 0; --attempt) {
                System.out.print(" 3 * 8 = ");
                answer = input.nextInt();
                input.nextLine();

                if (answer == 24) {
                    System.out
                            .printf("Please enter your first name, last name, and phone number (no dashes or spaces)\n"
                                    + "in a drawing for an all-expenses-paid vacation in the Bahamas: ");

                    firstName = input.next();
                    lastName = input.next();
                    phoneNumber = input.nextLong();

                    System.out
                            .printf("Thank you %s %s. We'll call you at %d if you're a winner.",
                                    firstName, lastName, +phoneNumber);
                }

                else if (answer != 24) {

                    if (attempt != 0) {

                        System.out
                                .printf("Invalid! Try Again! %d attempt(s) left!\n ",
                                        attempt);
                        continue;
                    } else {

                        System.out
                                .print("Sorry!  You have no more attempts left!");
                    }
                }

            }

        } else {

            System.out.printf("Invalid! Try Again! %d attempt(s) left!\n ",
                    attempt);
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();
            if (!wordOfTheDay.equals("tired")) --attempt;

        }

    } while (attempt >= 1);

    if (attempt == 0) {

        System.out.print("Sorry!  You have no more attempts left!");
    }

    System.exit(0);

}

A: Normally, you would use the break statement, but as you are not allowed setting attempt = -1 will have the same effect:
if( answer == 24)
{
    ...
    attempt = -1; // An ugly 'break'
}

EDIT:
Move the do { } while(); to before if check:
    // These two lines of code are no longer required.
    //System.out.printf("Enter the word of the day:  ");
    //wordOfTheDay = input.nextLine();

    do
    {
        System.out.printf("Enter the word of the day:  ");
        wordOfTheDay = input.nextLine();

        if(!wordOfTheDay.equals("tired"))
        {
            System.out.printf(
                "Invalid! Try Again! %d attempt(s) left!\n ", --attempt);
        }
        else
        {
            attempt = 0; // Another ugly 'break'
        }
    } while (attempt >= 1);

    if(wordOfTheDay.equals("tired"))
    {
    }
    // Remove else branch as not required.

A: When you get a correct result, you need to get out of the loop. this is done using the break statement:
if( answer == 24)
{
    System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n" +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );
    firstName = input.next();
    lastName = input.next();
    phoneNumber = input.nextLong();
    System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);
    break;
    // that's the break statement
}

A: Well, obviously you have to break the outer loop.
When you have correct answer (i.e. 'answer == 24') in the if block set some boolean variable 'haveAnswer' to 'true' (which is initialized to 'false' and check in the outer loop before the 'System.out.print(" 3 * 8 = ");' for 'if (haveAnswer) {break;}'
 enter code here`public static void main(String[] args)
 {

 Scanner input = new Scanner(System.in);

int attempt = 2;
int answer = 24;
long phoneNumber = 0;
String firstName = "";
String lastName = "";
String wordOfTheDay = "";

System.out.printf("Enter the word of the day:  ");
wordOfTheDay = input.nextLine();

if(wordOfTheDay.equals("tired"))
{
    boolean haveAnswer = false;
    for( attempt = 2; attempt >= 0; --attempt)
      {
        if (haveAnswer)
            break;
        System.out.print(" 3 * 8 = ");
        answer = input.nextInt();
        input.nextLine();

      if( answer == 24)
         {
            System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

        firstName = input.next();
        lastName = input.next();
        phoneNumber = input.nextLong();

        System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);

          haveAnswer = true;
          break;
         }

        else if( answer != 24)
        {

            if(attempt!=0)
            {

                System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
                    continue;
            }
            else
            {

                System.out.print( "Sorry!  You have no more attempts left!" );
            }
       }

     }

}
else
{
do
{

    System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
    --attempt;
    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();
} while (attempt >= 1);

  if( attempt == 0)
  {

     System.out.print( "Sorry!  You have no more attempts left!" );
  }
}

System.exit(0);

}
}

A: this code is incomplete, but it has the ide that you needed,. have a try,.
boolean firstTry = true;
boolean keepLooping = true;
do
    {
    if(!firstTry){
            System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
    }

        System.out.printf("Enter the word of the day:  ");
        wordOfTheDay = input.nextLine();
    if(wordOfTheDay.equals("hey!")){
        keepLooping = false;
    }
    --attempt;
    } while (attempt >= 1 && keepLooping);

A: You'd better user a break to jump out of the loop.Otherwise the loop will continue,print the "3*8=" and wait for your input.
If you don't wan't use a break, make the attemp = -1 is also make sense.
if( answer == 24)
         {
            System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

        firstName = input.next();
        lastName = input.next();
        phoneNumber = input.nextLong();
        attempt = -1;
        System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);

         }


text:
Q: slicing of data into separate Dataframe I have a dataframe:
entry_df <- data.frame(date = seq(as.Date("2018/01/01"), as.Date("2018/01/07"),
                       "days"),diff = c(1,0,-1 , 0,0 ,1,-1))

entry_df

        date diff
1 2018-01-01    1
2 2018-01-02    0
3 2018-01-03   -1
4 2018-01-04    0
5 2018-01-05    0
6 2018-01-06    1
7 2018-01-07   -1

I want to rbind the rows that are betwen 1 and -1 in a dataframe and push it on a list.
Steps:

*

*2018-01-01 is equal 1 so it will be my first element of my dataframe
2018-01-02 is equal to 0 so I need to rbind it to the first dataframe
2018-01-03 is equal to -1 so I need to rbind it to the first dataframe and that will constitue the first element of the list

*2018-01-04 and 2018-01-05 is equal to 0 so i don't do anything ...

*2018-01-06 is equal to 1 so i create a dataframe  at it will be the first element of it. 2018-01-07 is equal to -1 so i will rbind to the dataframe and that will constitute the second element of the list
Expected output is something like this
output_list[[1]] <- data.frame(date = seq(as.Date("2018/01/01"),
                               as.Date("2018/01/03"), "days"))
output_list[[2]] <- data.frame(date = seq(as.Date("2018/01/06"),
                               as.Date("2018/01/07"), "days"))

output_list

[[1]]
        date
1 2018-01-01
2 2018-01-02
3 2018-01-03

[[2]]
        date
1 2018-01-06
2 2018-01-07

A: Assuming that the number of 1's and -1s are the same, get the index of row with == and which, then loop over the indexes using Map and subset the 1st column of 'entry_df'
Map(function(i, j) entry_df[i:j, 1, drop = FALSE],
           which(entry_df$diff == 1), which(entry_df$diff == -1))
#[[1]]
#        date
#1 2018-01-01
#2 2018-01-02
#3 2018-01-03

#[[2]]
#        date
#6 2018-01-06
#7 2018-01-07


text:
Q: NSPredicate(Swift) : SUBQUERY not working I have two model like below:
class Topic : NSObject {

    var subTopics : [SubTopic]!
    var topicId : Int!
    var topicName : String!

class SubTopic : NSObject {

    var subTopicDesc : String!
    var subTopicDescText : String!
    var subTopicId : Int!
    var subTopicName : String!
}

and array of Topic defined in my viewcontroller :
var rightsDataArray: [Topic] = []

And here is my Search logic :
let pred = NSPredicate(format: "topicName CONTAINS %@ OR SUBQUERY(subTopics, $SubTopics, $SubTopics.subTopicDescText CONTAINS %@).@count > 0 OR SUBQUERY(subTopics, $SubTopics, $SubTopics.subTopicName CONTAINS %@).@count > 0",searchBar.text!,searchBar.text!,searchBar.text!)
let filteredArray =  (self.rightsDataArray as NSArray).filtered(using: pred)

And here is the result if search string is Health:

If the searchedText is present in subTopic[0], then I want to remove subTopic[1],subTopic[2],subTopic[3] from resulting subTopics Array, and only retrieve subTopic[0].

A: You are filtering the top level Topic array, and nothing in you code will touch the subTopics subarray.  The predicate is deciding whether or not to add a particular Topic (the top level object) to the filtered array based on its subTopics. But once a Topic matches the criteria (ie having at least one subTopic that has the search terms) the Topic is added.
It seems like you want to modify the Topic's subTopics array to contains less objects.  For that you have to iterate through every Topic and modify it's  subTopics property.


text:
Q: Modularizar código jquery Tengo todo un código javascript auxiliado en la librería jquery, funciona bien en la manera cómo está escrito (de hecho la aplicación está en producción) y no es tan extenso a decir verdad, pero haciendo un repazo del mismo me doy cuenta que el código en sí es básicamente toda una asociación de eventos a elementos html (identificados por su id o clase) que funcionan como botones o diálogos modals, y dan la posibilidad un tanto de reutilización por descirlo de alguna manera, ejecutando peticiones AJAX que me garantizan la carga asíncrona de prácticamente todo el contenido de las vistas.
Toda el código está escrito dentro de un único bloque $(document).ready(function{}); he visto códigos de páginas o aplicaciones que implementan todo el código javascript en el fichero correspondiente, y luego dentro del html de la página hacen un App.init(); y como que todo está corriendo.
Qué conceptos debo estudiar y aplicar para tener un código más modularizado si se pudiera expresar de esta manera?? estoy algo perdido en este tema. ya se que tal vez sea una pregunta basada en opiniones.
Este es parte de mi código, el resto de los eventos están escritos de manera similar.
$(document).ready(function() {
    var _HOMEPAGE = Routing.generate('app_homepage');

    var elMenuPrincipalUsuarios = $('#menuPrincipalUsuarios');
    if (elMenuPrincipalUsuarios !== null) {
        $(elMenuPrincipalUsuarios).on('click', function(e) {
            e.preventDefault();
        });
    }

    $('#vistas').on('click', '#lnkRecargaRegistros', function(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        $.ajax({
            dataType: 'html',
            type: 'GET',
            url: url,
            beforeSend: function() {
                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
            }
        }).done(function(data) {
            $('#tablaDatos tbody').html(data);
        }).fail(function(jqXHR) {
            if (jqXHR.status === 401) {
                window.location = _HOMEPAGE;
            } else {
                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
            }
        }).always(function() {
            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                setTimeout(function() {
                    $('#indicador').fadeOut('fast', function() {
                        $(this).removeClass('cargando-error').html(" Cargando...");
                    });
                }, 3000);
            } else {
                $('#indicador').fadeOut('fast', function() {
                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                });
            }
        });
    });

    /**
     * Retorna a la vista principal del nodo seleccionado
     * **/
    $('#vistas').on('click', '#lnkAtras', function(e) {
        e.preventDefault();
        var arbol = $('#arbol').jstree(true);
        if (arbol) {
            var nodoSeleccionado = arbol.get_selected(true)[0];
            if (nodoSeleccionado) {
                cargarVistaCentral(nodoSeleccionado);
            } else {
                e.preventDefault();
            }
        }
    });

    /**
     * Muestra ventana de impresion del navegador, lista para imprimir el contenido
     * del area de impresion.
     * **/
    $('#vistas').on('click', '#lnkImprimir', function(e) {
        e.preventDefault();
        var areaImprimir = $('#vistas').find('#areaImprimible');
        if (areaImprimir) {
            $(areaImprimir).print({
                globalStyles: true,
                mediaPrint: false,
                stylesheet: null,
                iframe: true,
                append: null,
                prepend: null,
                noPrintSelector: ".noprint",
                deferred: $.Deferred(),
                timeout: 750
            });
        }
    });

    /**
     * Carga cualquier recurso indicado
     * Asociada a etiquetas  por su clase.
     * @param {} Direccion del recurso a cargar
     * **/
    $('#vistas').on('click', 'a.lnkCargarVista', function(e) {
        e.preventDefault();
        $.ajax({
            url: $(this).attr('href'),
            beforeSend: function() {
                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
            }
        }).done(function(data) {
            $('#vistas').html(data);
        }).fail(function(jqXHR) {
            if (jqXHR.status === 401) {
                window.location = _HOMEPAGE;
            } else {
                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
            }
        }).always(function() {
            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                setTimeout(function() {
                    $('#indicador').fadeOut('fast', function() {
                        $(this).removeClass('cargando-error').html(" Cargando...");
                    });
                }, 3000);
            } else {
                $('#indicador').fadeOut('fast', function() {
                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                });
            }
        });
    });

    /**
     * Carga cualquier recurso indicado
     * Asociada a una etiqueta  por su id.
     * @param {} Direccion del recurso a cargar
     * **/
    $('#vistas').on('click', '#lnkCargarVista', function(e) {
        e.preventDefault();
        $.ajax({
            url: $(this).attr('href'),
            beforeSend: function() {
                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
            }
        }).done(function(data) {
            $('#vistas').html(data);
        }).fail(function(jqXHR) {
            if (jqXHR.status === 401) {
                window.location = _HOMEPAGE;
            } else {
                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
            }
        }).always(function() {
            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                setTimeout(function() {
                    $('#indicador').fadeOut('fast', function() {
                        $(this).removeClass('cargando-error').html(" Cargando...");
                    });
                }, 3000);
            } else {
                $('#indicador').fadeOut('fast', function() {
                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                });
            }
        });
    });

    $('#vistas').on('click', '#lnkCMFxCP', function(e) {
        e.preventDefault();
        var elementoClickeado = $(this);
        $(document.body).find('#modalVincularCMF').remove();
        $.ajax({
            url: elementoClickeado.attr('href'),
            beforeSend: function() {
                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
            }
        }).done(function(data) {
            $(document.body).append("

<button type='button' class='close' data-dismiss='modal' aria-label='Cerrar'>×</button>
CMFs por Consejo Popular

<button type='button' class='btn btn-default' data-dismiss='modal'>Cerrar</button>

");

            $(document.body).find('#modalVincularCMF').find("#contenidoModal").html(data);
            $(document.body).find('#modalVincularCMF').modal({
                keyboard: false,
                backdrop: 'static'
            }).on('shown.bs.modal', function(e) {
                e.preventDefault();
                var dialogo = $(this);
                $(dialogo).find('#btnVincular').on('click', function(e) {
                    e.preventDefault();
                    var btn = $(this);
                    var consejoPopularId = $(dialogo).find('#consejosPopulares option:selected').val();

                    if (consejoPopularId !== "-1") {
                        var arregloCMFs = [];
                        $(dialogo).find("#cmfDesvinculados option:selected").each(function() {
                            arregloCMFs.push($(this).val());
                        });

                        if (arregloCMFs.length > 0) {
                            if (!btn.hasClass('disabled')) {
                                $.ajax({
                                    type: 'POST',
                                    url: Routing.generate('consejoPopular_vincularCMFs', {'consejoPopularId': consejoPopularId}),
                                    data: {'cmfs': arregloCMFs},
                                    beforeSend: function() {
                                        btn.toggleClass('disabled');
                                        $('#btnVincular').find('span').removeClass('glyphicon glyphicon-chevron-right').addClass('glyphicon glyphicon-refresh');
                                    }
                                }).done(function(data) {
                                    if (data === "success") {
                                        $("#cmfDesvinculados option:selected").each(function() {
                                            $('#cmfVinculados').append($("<option></option>")
                                                    .attr("value", $(this).val())
                                                    .text($(this).text()));
                                            $('#cmfDesvinculados').find("option[value='" + $(this).val() + "']").remove();
                                        });
                                    }
                                }).fail(function(jqXHR) {
                                    if (jqXHR.status === 401) {
                                        window.location = _HOMEPAGE;
                                    } else {
                                        return;
                                    }
                                }).always(function() {
                                    btn.toggleClass('disabled');
                                    $('#btnVincular').find('span').removeClass('glyphicon glyphicon-refresh').addClass('glyphicon glyphicon-chevron-right');
                                });
                            } else {
                                return false;
                            }
                        }
                    }
                });

                $(document.body).find('#btnDesvincular').on('click', function(e) {
                    e.preventDefault();
                    var btn = $(this);
                    var consejoPopularId = $('#consejosPopulares option:selected').val();

                    if (consejoPopularId !== "-1") {
                        var arregloCMFs = [];
                        $("#cmfVinculados option:selected").each(function() {
                            arregloCMFs.push($(this).val());
                        });

                        if (arregloCMFs.length > 0) {
                            if (!btn.hasClass('disabled')) {
                                $.ajax({
                                    type: 'POST',
                                    url: Routing.generate('consejoPopular_desvincularCMFs', {'consejoPopularId': consejoPopularId}),
                                    data: {'cmfs': arregloCMFs},
                                    beforeSend: function() {
                                        btn.toggleClass('disabled');
                                        $('#btnDesvincular').find('span').removeClass('glyphicon glyphicon-chevron-left').addClass('glyphicon glyphicon-refresh');
                                    }
                                }).done(function(data) {
                                    if (data === "success") {
                                        $("#cmfVinculados option:selected").each(function() {
                                            $('#cmfDesvinculados').append($("<option></option>")
                                                    .attr("value", $(this).val())
                                                    .text($(this).text()));
                                            $('#cmfVinculados').find("option[value='" + $(this).val() + "']").remove();
                                        });
                                    }
                                }).fail(function(jqXHR) {
                                    if (jqXHR.status === 401) {
                                        window.location = _HOMEPAGE;
                                    } else {
                                        return;
                                    }
                                }).always(function() {
                                    btn.toggleClass('disabled');
                                    $('#btnDesvincular').find('span').removeClass('glyphicon glyphicon-refresh').addClass('glyphicon glyphicon-chevron-left');
                                });
                            } else {
                                return false;
                            }
                        }
                    }
                });

                $('#consejosPopulares').on('change', function(e) {
                    e.preventDefault();
                    var seleccionado = $(this).val();
                    if (seleccionado !== "-1") {
                        $.ajax({url: Routing.generate('consejoPopular_CMFs', {'id': seleccionado}),
                            beforeSend: function() {
                                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
                            }
                        }).done(function(data) {
                            $('#cmfVinculados').html(data);
                        }).fail(function(jqXHR) {
                            if (jqXHR.status === 401) {
                                window.location = _HOMEPAGE;
                            } else {
                                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
                            }
                        }).always(function() {
                            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                                setTimeout(function() {
                                    $('#indicador').fadeOut('fast', function() {
                                        $(this).removeClass('cargando-error').html(" Cargando...");
                                    });
                                }, 3000);
                            } else {
                                $('#indicador').fadeOut('fast', function() {
                                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                                });
                            }
                        });
                    } else {
                        $('#cmfVinculados').html('');
                    }
                });

            }).on('hidden.bs.modal', function(e) {
                e.preventDefault();
                $(document.body).find('#modalVincularCMF').remove();
            });
        }).fail(function(jqXHR) {
            if (jqXHR.status === 401) {
                window.location = _HOMEPAGE;
            } else {
                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
            }
        }).always(function() {
            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                setTimeout(function() {
                    $('#indicador').fadeOut('fast', function() {
                        $(this).removeClass('cargando-error').html(" Cargando...");
                    });
                }, 3000);
            } else {
                $('#indicador').fadeOut('fast', function() {
                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                });
            }
        });
    });

    $('a.lnkCambiarContrasenha').on('click', function(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        $.ajax({
            dataType: 'html',
            type: 'GET',
            url: url,
            beforeSend: function() {
                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
            }
        }).done(function(data) {
            $(document.body).find('#modalCambiarContrasenha').remove();
            $(document.body).append("

<button type='button' class='close' data-dismiss='modal' aria-label='Cerrar'>×</button>
Cambiar contraseña

<button type='button' class='btn btn-default' data-dismiss='modal'>Cerrar</button><button id='btnSalvar' type='button' class='btn btn-primary'>Salvar</button>

");

            $("#contenedorForm").html(data);
            $('#modalCambiarContrasenha').modal({
                keyboard: false,
                backdrop: 'static'
            }).on('shown.bs.modal', function(e) {
                e.preventDefault();
                $('#contenedorForm form').on('submit', function(e) {
                    e.preventDefault();
                    return false;
                });
                var dialogo = $(this);
                $("#btnSalvar").on('click', function(e) {
                    e.preventDefault();
                    var btn = $(this);
                    if (!btn.hasClass('disabled')) {
                        $.ajax({
                            dataType: 'json',
                            type: 'POST',
                            url: $("#modalCambiarContrasenha").find("form").attr('action'),
                            data: $("#modalCambiarContrasenha").find("form").serialize(),
                            beforeSend: function() {
                                btn.toggleClass('disabled');
                                $('#indicador').addClass('cargando-satisfactorio').fadeIn('fast');
                            }
                        }).done(function(data) {
                            $(dialogo).modal('hide');
                            $('#indicador').html(data.msg);
                        }).fail(function(jqXHR) {
                            if (jqXHR.status === 401) {
                                window.location = _HOMEPAGE;
                            }
                            btn.toggleClass('disabled');
                            if (jqXHR.status === 406) {
                                $(dialogo).find('#contenedorForm').html(jqXHR.responseText);
                            } else {
                                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
                            }
                        }).always(function() {
                            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                                setTimeout(function() {
                                    $('#indicador').fadeOut('fast', function() {
                                        $(this).removeClass('cargando-error').html(" Cargando...");
                                    });
                                }, 3000);
                            } else {
                                setTimeout(function() {
                                    $('#indicador').fadeOut('fast', function() {
                                        $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                                    });
                                }, 2500);
                            }
                        });
                    } else {
                        return false;
                    }
                });
            }).on('hidden.bs.modal', function(e) {
                e.preventDefault();
                $(document.body).find('#modalCambiarContrasenha').remove();
            });
        }).fail(function(jqXHR) {
            if (jqXHR.status === 401) {
                window.location = _HOMEPAGE;
            } else {
                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
            }
        }).always(function() {
            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                setTimeout(function() {
                    $('#indicador').fadeOut('fast', function() {
                        $(this).removeClass('cargando-error').html(" Cargando...");
                    });
                }, 3000);
            } else {
                $('#indicador').fadeOut('fast', function() {
                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                });
            }
        });
    });

    $(document.body).on('click', '#lnkCalculadora', function(e) {
        e.preventDefault();
        var elemento = $(this);
        $(document.body).find('#modalCalculadora').remove();
        $(document.body).append("

<button type='button' class='close' data-dismiss='modal' aria-label='Cerrar'>×</button>
Calculadora

<button type='button' class='btn btn-default' data-dismiss='modal'>Cerrar</button>

");
        $.ajax({
            url: elemento.attr('href'),
            beforeSend: function() {
                $('#indicador').addClass('cargando-satisfactorio').slideDown('fast');
            }
        }).done(function(data) {
            $("#contenedorForm").html(data);
            $(document.body).find('#modalCalculadora').modal({
                keyboard: false,
                backdrop: 'static'
            }).on('shown.bs.modal', function() {
                $('#contenedorForm form').on('submit', function(e) {
                    e.preventDefault();
                    return false;
                });
            }).on('hidden.bs.modal', function(e) {
                e.preventDefault();
                $(document.body).find('#modalCalculadora').remove();
                $(document.body).find("div[class='datepicker datepicker-dropdown dropdown-menu']").remove();
            });
        }).fail(function(jqXHR) {
            if (jqXHR.status === 401) {
                window.location = _HOMEPAGE;
            } else {
                $('#indicador').removeClass('cargando-satisfactorio').addClass('cargando-error').html(jqXHR.responseText);
            }
        }).always(function() {
            if (!$('#indicador').hasClass("cargando-satisfactorio")) {
                setTimeout(function() {
                    $('#indicador').fadeOut('fast', function() {
                        $(this).removeClass('cargando-error').html(" Cargando...");
                    });
                }, 3000);
            } else {
                $('#indicador').fadeOut('fast', function() {
                    $(this).removeClass('cargando-satisfactorio').html(" Cargando...");
                });
            }
        });
    });

});

A: Hola espero esto te oriente con lo que buscas,
lee sobre Ingeniería de software basada en componentes.
https://es.wikipedia.org/wiki/Ingenier%C3%ADa_de_software_basada_en_componentes
Algunos de los Framework populares para FrondEnd son Angular, vue y react, aparte de ser basados en componentes esto son reactivos.
En lo personal aun no entiendo la filosofía de react, vue es muy intuitivo y lo mejor que puedes usar html javascript css sin más conocimientos extra, en el caso de angular es intuitivo pero tienes que aprender typescript.


text:
Q: Drawing video with text on top I am working on an application and I have a problem I just cant seem to find a solution for. The application is written in vc++. What I need to do is display a YUV video feed with text on top of it.
Right now it works correctly by drawing the text in the OnPaint method using GDI and the video on a DirectDraw overlay. I need to get rid of the overlay because it causes to many problems. It wont work on some video cards, vista, 7, etc.
I cant figure out a way to complete the same thing in a more compatible way. I can draw the video using DirectDraw with a back buffer and copy it to the primary buffer just fine. The issue here is that the text being drawn in GDI flashes because of the amount of times the video is refreshed. I would really like to keep the code to draw the text intact if possible since it works well.
Is there a way to draw the text directly to a DirectDraw buffer or memory buffer or something and then blt it to the back buffer? Should I be looking at another method all together? The two important OS's are XP and 7. If anyone has any ideas just let me know and I will test them out. Thanks.

A: Try to look into DirectShow and the Ticker sample on microsoft.com:
DirectShow Ticker sample
This sample uses the Video Mixing Renderer to blend video and text. It uses the IVMRMixerBitmap9 interface to blend text onto the bottom portion of the video window.
DirectShow is for building filter graphs for playing back audio or video streams an adding different filters for different effects and manipulation of video and audio samples.

A: Instead of using the Video Mixing Renderer of DirectShow, you can also use the ISampleGrabber interface. The advantage is, that it is a filter which can be used with other renderers as well, for example when not showing the video on the screen but streaming it over network or dumping it to a file.


text:
Q: One-to-one mapping of git commits to TFS changesets using git-tfs rcheckin The Context

*

*We have a git repository with a release branch.

*We have a TFS repo (currently empty).

My task is to mirror the release branch of the git repo into TFS so that every commit in git maps to a changeset in TFS. All the developers only commit to git and (lets assume) are unaware of TFS.
Reading the documentation for rcheckin and the answer to this related issue makes me believe that rcheckin is capable of doing that.
The Problem
All the commits in git are squashed into a single changeset.
Reproduction sequence:
git tfs clone http://tfs:8080 $/tfsrepo
cd tfsrepo
git remote add github git@github.com:REPO/Repo.git
git fetch github
git merge github/release
git tfs rcheckin

This results in a single checkin into TFS that contains all the commits.
Other attempts at solving the problem

*

*After clone, merge the first commit from the source (git) repo, rcheckin to create a shared base

*

*This worked, but subsequent git pull github release followed by git-tfs rcheckin led to commit squashing again.

*For the first few commits in the origin repo, I merged them one-by-one into the git-tfs shared repo and rcheckin'd after each.

*

*This kind of worked, as for every commit, there was one changeset in TFS. However, the original commit message second underneath a "merged c02436de4f.." message.

*It is not realistic to do for every changeset, even with scripting.

*As pointed out by patthoyts, this would make me the commiter for that change as far as TFS is concerned.

My question
What do I have to do to keep TFS up-to-date with the release branch from the git-repo so that every commit in git has a corresponding TFS changeset?
Additional info
I do have administrative control of both repos, and I would be able to rebase the git repo if necessary, with all the consequences this implies. I just don't want to lose the history we already created.

A: I think what you're seeing is git-tfs using only commits along the shortest path between HEAD and tfs/default. TFS's history is a list of changes, while git's is a graph, and you're hitting the impedance mismatch between the two. To get a picture of what git-tfs is seeing, try git log --graph --oneline --decorate HEAD tfs/default before you use rcheckin.
If you want the 1:1::commit:changeset thing, try this:
git tfs clone http://tfs:8080 $/tfsrepo
cd tfsrepo
git remote add github git@github.com:REPO/Repo.git
git fetch github
git tfs rcheckin github/release

Another approach is to use cherry-pick or rebase.
git tfs clone http://tfs:8080 $/tfsrepo
cd tfsrepo
git remote add github git@github.com:REPO/Repo.git
git fetch github
git checkout -b about-to-be-rewritten-twice github/release
git rebase tfs/default
git tfs rcheckin

Check out the rebase docs for more examples of things rebase can do.
And don't git push github about-to-be-rewritten-twice:release.

A: I don't think this is going to come out well. If you do fix making the commits, each one will have the timestamp and user id of the moment you comitted to TFS. You can't preserve the original author or time when comitting these to TFS. You might be better off waiting as Microsoft have announced TFS will in future support Git. So before too long anyone needing to use tfs can upgrade their tools and access your real git repository.
I suspect your merge made a merge commit and that is causing the squash. You might try resetting the git-tfs branch to your git master and then pushing the commits. We use git-tfs the other way around where the shared repository is TFS and we all use git with git tfs to make commits. If I create a branch and add a few commits then git tfs rcheckin does not squash these into one but makes a series matching what I have in my local git. I did find that using 'stage' and then unstaging in tfs to make a commit squashed everything into one. You didn't say why you have to mirror to TFS but I suggest you try and point them at the recent microsoft announcements and tell them git is the future! Even with TFS. :)


text:
Q: Least privilege AWS IAM policy for cloudformation For small CloudFormation and CodePipeline templates we could "try - test" to get least privilege IAM Policy for the roles required.
This usually involves:

*

*Starting with a minimal policy

*Creating the stack

*It fails with - stack doesn't have rights to someService:someAction

*Add the service action to the policy

*update stack and try again

This approach is too time consuming for larger CloudFormation Templates.
How are you developing Least Privilege IAM Policies?
Ideas:

*

*Allow "*" and then scrape cloudtrail for events and build map for listed events to their equivalent roles - then reduce the roles to only those listed in the cloudtrail logs.

*

*If you can isolate actions down to a user name this helps

*https://github.com/byu-oit-appdev/aws-cloudwatch-parse

*Access Advisor

A: Grant least privilege is a well-documented IAM Best Practice. The documentation recommends incrementally adding specific permissions, using the Access Advisor tab to determine which services are actually being used by an application (presumably using a broader set of permissions during the testing phase):

It's more secure to start with a minimum set of permissions and grant additional permissions as necessary, rather than starting with permissions that are too lenient and then trying to tighten them later.
Defining the right set of permissions requires some research to determine what is required for the specific task, what actions a particular service supports, and what permissions are required in order to perform those actions.
One feature that can help with this is the Access Advisor tab, which is available on the IAM console Summary page whenever you inspect a user, group, role, or policy. This tab includes information about which services are actually used by a user, group, role, or by anyone using a policy. You can use this information to identify unnecessary permissions so that you can refine your IAM policies to better adhere to the principle of least privilege. For more information, see Service Last Accessed Data.

This approach is similar to scraping CloudTrail for API events generated by a specific IAM Role/application, though the latter might be more difficult to filter through the entire event stream in order to find the relevant events, while the Access Advisor list is already filtered for you.