text:
Q: Running code after Spring Boot starts I want to run code after my spring-boot app starts to monitor a directory for changes.
I have tried running a new thread but the @Autowired services have not been set at that point.
I have been able to find ApplicationPreparedEvent, which fires before the @Autowired annotations are set.  Ideally I would like the event to fire once the application is ready to process http requests.
Is there a better event to use, or a better way of running code after the application is live in spring-boot?

A: Why not just create a bean that starts your monitor on initialization, something like:
@Component
public class Monitor {
    @Autowired private SomeService service

    @PostConstruct
    public void init(){
        // start your monitoring in here
    }
}

the init method will not be called until any autowiring is done for the bean.

A: You have several choices:
Using CommandLineRunner or ApplicationRunner as a Bean definition:
Spring Boot executes these towards the end of the application startup process. In most circumstances, the CommandLineRunner will do the job. Following is an example of a CommandLineRunner implementation with Java 8:
@Bean
public CommandLineRunner commandLineRunner() {
   return (args) -> System.out.println("Hello World");
}

Note that the args is the String array of arguments. You can also provide an implementation of this interface and define it as a Spring Component:
@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Hello World");
    }
}

You can use the ApplicationRunner if you need better argument management. ApplicationRunner takes an ApplicationArguments instance that has enhanced argument management options.
You can also order the  CommandLineRunner and ApplicationRunner beans using Spring's @Order annotation:
 @Bean
 @Order(1)
 public CommandLineRunner commandLineRunner() {
    return (args) -> System.out.println("Hello World, Order 1");
 }

 @Bean
 @Order(2)
 public CommandLineRunner commandLineRunner() {
    return (args) -> System.out.println("Hello World, Order 2");
 }

Using Spring Boot's ContextRefreshedEvent:
Spring Boot publishes several events at startup. These events indicate the completion of a phase in the application startup process. You can listen to the ContextRefreshedEvent and execute custom code:
@EventListener(ContextRefreshedEvent.class)
public void execute() {
    if(alreadyDone) {
      return;
    }
    System.out.println("hello world");
}

ContextRefreshedEvent is published several times. Thus, ensure to put a check whether the code execution is already finished.

A: The "Spring Boot" way is to use a CommandLineRunner. Just add beans of that type and you are good to go. In Spring 4.1 (Boot 1.2) there is also a SmartInitializingBean which gets a callback after everything has initialized. And there is SmartLifecycle (from Spring 3).

A: Try this one and it will run your code when the application context has fully started.
 @Component
public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent arg0) {
                // EXECUTE YOUR CODE HERE
    }
}

A: It is as simple as this:
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

Tested on version 1.5.1.RELEASE

A: Spring boot provides an ApplicationRunner interface with a run() method to be invoked at application startup.
However, instead of raw String arguments passed to the callback method, we have an instance of the ApplicationArguments class.
@Component
public class AppStartupRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //some logic here
    }
}

A: ApplicationReadyEvent is really only useful if the task you want to perform is not a requirement for correct server operation. Starting an async task to monitor something for changes is a good example.
If, however your server is in a 'not ready' state until the task is completed then it's better to implement SmartInitializingSingleton because you'll get the callback before your REST port has been opened and your server is open for business.
Don't be tempted to use @PostConstruct for tasks that should only happen once ever. You'll get a rude surprise when you notice it being called multiple times...

A: You can extend a class using ApplicationRunner , override the run() method and add the code there.
import org.springframework.boot.ApplicationRunner;

@Component
public class ServerInitializer implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        //code goes here

    }
}

A: just implement CommandLineRunner for spring boot application.
You need to implement run method,
public classs SpringBootApplication implements CommandLineRunner{

    @Override
        public void run(String... arg0) throws Exception {
        // write your logic here

        }
}

A: you can use @Component
@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
    //declare

    @Override
    public void run(String... args) throws Exception {
        //some code here

    }

A: If you mean running peace of code once after the application started, you can use the CommandLineRunner as below:
@SpringBootApplication
public class SpringBootApplication
  implements CommandLineRunner {

private static Logger LOG = LoggerFactory
  .getLogger(SpringBootConsoleApplication.class);

public static void main(String[] args) {
    LOG.info("STARTING THE APPLICATION");
    SpringApplication.run(SpringBootConsoleApplication.class, args);
    LOG.info("APPLICATION FINISHED");
}

@Override
public void run(String... args) {
    // enter code you want to run after app loaded here
    LOG.info("EXECUTING : command line runner");

    for (int i = 0; i < args.length; ++i) {
        LOG.info("args[{}]: {}", i, args[i]);
    }
}

}
Otherwise, you can use the DevTools dependency, which help you to run new codes without manually restarting the application.
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

don't forget to add these codes to your pom.xml to avoid version warnings:
   <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2021.0.3</spring-cloud.version>
    </properties>

 <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>

give it a thump up if this was helpful to you!

A: Try:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @SuppressWarnings("resource")
    public static void main(final String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

        context.getBean(Table.class).fillWithTestdata(); // <-- here
    }
}

A: Have you tried ApplicationReadyEvent?
@Component
public class ApplicationStartup
implements ApplicationListener<ApplicationReadyEvent> {

  /**
   * This event is executed as late as conceivably possible to indicate that
   * the application is ready to service requests.
   */
  @Override
  public void onApplicationEvent(final ApplicationReadyEvent event) {

    // here your code ...

    return;
  }
}

Code from: http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
This is what the documentation mentions about the startup events:

...
Application events are sent in the following order, as your application runs:
An ApplicationStartedEvent is sent at the start of a run, but before
any processing except the registration of listeners and initializers.
An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context
is created.
An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.
An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to
service requests.
An ApplicationFailedEvent is sent if there is an exception on startup.
...

A: Use a SmartInitializingSingleton bean in spring > 4.1
@Bean
public SmartInitializingSingleton importProcessor() {
    return () -> {
        doStuff();
    };

}

As alternative a CommandLineRunner bean can be implemented or annotating a bean method with @PostConstruct.

A: Best way to execute block of code after Spring Boot application started is using PostConstruct annotation.Or also you can use command line runner for the same.
1. Using PostConstruct annotation
@Configuration
public class InitialDataConfiguration {

    @PostConstruct
    public void postConstruct() {
        System.out.println("Started after Spring boot application !");
    }

}

2. Using command line runner bean
@Configuration
public class InitialDataConfiguration {

    @Bean
    CommandLineRunner runner() {
        return args -> {
            System.out.println("CommandLineRunner running in the UnsplashApplication class...");
        };
    }
}

A: Providing an example for Dave Syer answer, which worked like a charm:
@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);

    @Override
    public void run(String...args) throws Exception {
        logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}

A: I really like the suggestion for usage of the EventListener annotation by @cahen (https://stackoverflow.com/a/44923402/9122660) since it is very clean. Unfortunately I could not get this to work in a Spring + Kotlin setup. What does work for Kotlin is adding the class as a method parameter:
@EventListener
fun doSomethingAfterStartup(event: ApplicationReadyEvent) {
    System.out.println("hello world, I have just started up");
}

A: Best way you use CommandLineRunner or ApplicationRunner
The only difference between is run() method
CommandLineRunner accepts array of string and ApplicationRunner accepts  ApplicationArugument.


text:
Q: ContentLength not set after write I'm trying to send data to a server with this function :
public static async Task<Byte[]> sendData(Byte[] bt)
    {
        try
        {
            System.Net.HttpWebRequest myWebRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
            myWebRequest.Method = "POST";
            myWebRequest.ContentType = "text/xml";
            myWebRequest.AllowReadStreamBuffering = true;
            using (var requestStream = (Stream)(await Task<Stream>.Factory.FromAsync(myWebRequest.BeginGetRequestStream, myWebRequest.EndGetRequestStream, myWebRequest)))
            {
                requestStream.Write(bt, 0, bt.Length);
            }

            using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(myWebRequest.BeginGetResponse, myWebRequest.EndGetResponse, myWebRequest)))
            {
                using (var responseStream = response.GetResponseStream())
                {
                    bt = new byte[responseStream.Length];
                    responseStream.Read(bt, 0, bt.Length);
                    return bt;
                }
            }
        }
        catch (Exception ex)
        {
            return null;
        }

    }

I get a response from the server saying that no data was sent (ContentLength == 0). Indeed, if I look at myWebRequest.ContentLength after writing in the stream request, _ContentLength is set to 0 and ContentLengthis set to -1.
Did I miss something ?
Thanks for your help !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate CUDA program dlls under Linux I know that mingw creates a dll file under windows which can be used to create an exe file. We can execute this exe file in windows. I am working on a cuda project under Linux, but have to deliver the product for Windows as well. Is it possible to generate a dll file using some sort of method under windows?

A: On windows, MinGW is not supported for CUDA development. The only compiler which is officially supported by CUDA is cl.exe which ships with Microsoft Visual Studio.
More details can be found in System Requirements section of CUDA Getting Started Guide.
Here is an MSDN tutorial which describes how to create a C++ DLL using Visual Studio.
For compiling CUDA kernels, you would have to add CUDA Build Rules in the Build Customizations section of the Visual Studio DLL project.


text:
Q: How to Give Dynamic Routing in react js using simple array of object file const userdata = [
{
    id:1,
    name:"kuber",
    phone:"8989"
},
{
    id:2,
    name:"sahil",
    phone:"9696"
}

];
export default userdata

From this to>>> <Route path={"user/:id"} component={user} />
What code should i use in "User" component if useParams has id=1 then how to show only id 1, name kuber, phone 8989

A: In the simplest way you can do it like this:
in your User.js/jsx import the userData.
Then you can get the id from url using props.match.params.id and then you can filter from userData from that props.match.params.id .
Note: You need to do this inside so every time id changes it gets the user of that id
useEffect(()=>{

 // your code here

},[props.match]);


text:
Q: PHP query to meet a condition has to be present in a second table I have two tables.
First has the following:
id | Company       | Field  | Country
-------------------------------------
1  | Widgets Inc   | Parts  | USA
2  | Moo Corp      | Toys   | GBR
3  | Dingles S.A   | Music  | GER
4  | Deutsh Import | Import | AUT
5  | Clean Inc     | Clean  | USA

and second table
id | Employee     | Company_id | Country
----------------------------------------
1  | Paul Allen   | 2          | USA
2  | Andrew Cur   | 2          | GBR
3  | Paul Hanz    | 4          | GER
4  | Angela Dow   | 1          | AUT
5  | Dana Loconto | 4          | USA

I want to filter (mysql query on php) the first table with ONLY the companies that actually have an employee on the second table. The ones with no employees should be ignored.
Thank you for your advice
EDIT: Using INNER JOIN seems to fix this, but then I have a different problem.
If I use INNER JOIN as suggested below, it gives me one result for EACH time the occurence happens on the join table.
For example: Using my table below, it will return the company id 2 twice, and id 4 twice. To better explain, I'm using this to generate a list of the companies that actually have employees, but I don't need it to repeat itself everytime it finds a new employee of the same company. Not sure if I'm making myself clear.
SELECT C.id, C.field, C.country
FROM first_table as C
INNER JOIN second_table as E ON E.company_id = C.id

This returns the following
Moo Corp       | Toys   | USA
Moo Corp       | Toys   | USA
Deutsch Import | Import | AUT
Widgets Inc    | Parts  | USA
Deutsch Import | Import | AUT

And what I was expecting is only
Moo Corp
Deutsch Import
Widget Inc

Any extra help?

A: Try an inner join :
SELECT C.id, C.field, C.country
FROM first_table as C
INNER JOIN second_table as E ON E.company_id = C.id AND E.employee is not null

Or as suggested in the comment, if the second_table data about employee only exist if there is a company :
SELECT C.id, C.field, C.country
FROM first_table as C
INNER JOIN second_table as E ON E.company_id = C.id

It works like this :

*

*You select the element you want (here only element from table_one)

*You make your inner join based on the common field (here company_id from second_table and id from first_table)

*You add your condition on the inner_join, here E.employee is not null, adapt according to how it looks when no employee (maybe empty string, maybe 0, I don't know)

*The inner join will make you return only element that respect this condition

EDIT :
To only get one result by company, add this at the end :
GROUP BY C.company

But you need to add C.company to your SELECT before


text:
Q: Algebraic fundamental group of $X = Spec\mathbb{Z}\left[\frac{1}{2}\right]$ I'm quite new to the notion of the fundamental group of schemes and I'm reading Lenstra's notes on Galois theory for schemes.
One of the exercise asks to prove that the fundamental group $\pi(Spec\mathbb{Z}\left[\frac{1}{2}\right])$ is topologically generated by its 2-Sylow subgroups (as in the topologcal closure of the subgroup is the whole group). How do I prove this? I tried using a theorem saying that $\pi(Spec A\left[\frac{1}{n}\right]) = Gal(M/K)$ where $A$ is the ring of integers in a number field $K$ and $M$ is the maximal algebraic extension of $K$ that is unramified at all primes not dividing $n$.
In my scenario $A = \mathbb{Z}\,$, $K = \mathbb{Q}$ and $n = 2$, my guess is $M = \mathbb{Q}(i)$ since for every other algebraic extension there is at least a prime ideal $\mathfrak{p} \neq (2)$ that ramifies in that extension. In this way I would have $\pi(Spec\mathbb{Z}\left[\frac{1}{2}\right]) = \frac{\mathbb{Z}}{2\mathbb{Z}}$ and this is obviously generated by it's 2-Sylow. Is this right? It seems suspiciously easy...
Edit: my claim is obviously wrong, so my question now is, how can I compute the maximal field extension of $\mathbb{Q}$ which is unramified at every prime $\mathfrak{p} \neq (2)$

A: Let's first remark that if $G$ is a finite group, then $G$ is called a quasi-$p$-group if $G$ is generated by its $p$-Sylow subgroups. If $G$ is any finite subgroup, then the subgroup generated by all $p$-Sylow subgroups is quasi-$p$, let us denote it by $p(G)$. Clearly we have that $[G:p(G)]$ is always coprime to $p$. I claim that $p(G)$ is a characteristic subgroup of $G$, in particular it is normal. Indeed, let $H_1, \dots, H_n$ be the $p$-Sylow subgroups of $G$, then for any automorphism $\psi:G \to G$ and any $p$-Sylow subgroup $H_i$, we have that $\psi(H_i)$ is another $p$-Sylowsubgroup, so $\psi(H_i)=H_j$ for some $j$. Thus $p(G)=\psi(\langle H_1, \dots H_n\rangle)=\langle \psi(H_1), \dots, \psi(H_n)\rangle = \langle H_1, \dots, H_n\rangle$
We first prove the following:

Let $K/\Bbb Q$ be a a nontrivial finite Galois extension of odd order. Then there exists some odd prime $p$ that ramifies in $K$.

Proof By the Feit-Thompson theorem, $G=\mathrm{Gal}(K/\Bbb Q)$ is solvable. Thus there exists a proper normal subgroup $H \trianglelefteq G$ such that $G/H$ is abelian. Thus we can consider $K^H/\Bbb Q$ which is a nontrivial abelian Galois extension of odd order. Thus it suffices to prove the theorem in the abelian case, so we may assume that $G$ is itself abelian.  So we get by Kronecker-Weber $K \subset \Bbb Q(\zeta_n)$, where $n$ is the conductor $\mathfrak{f}(K/\Bbb Q)$. It's well-known that a prime $p$ ramifies in $K$ if and only if $p$ divides $\mathfrak{f}(K/\Bbb Q)$. Thus it suffices to show that $n$ is not a power of $2$. But if $n=2^m$, then $[\Bbb Q(\zeta_n):\Bbb Q)]=\varphi(2^m)=2^{m-1}$ contradicting the fact that $K\subset \Bbb Q(\zeta_n)$ has odd degree over $\Bbb Q$.
Now we can proceed

Let $K/\Bbb Q$ be a finite Galois extension that is only ramified at $2$, then $G=\mathrm{Gal}(K/\Bbb Q)$ is a quasi-$2$-group.

Proof Consider the subgroup $2(G) \subset G$. By the remarks in the beginning, we get that $2(G)$ is a normal subgroup of odd index, thus $K^{2(G)}/\Bbb Q$ is a finite odd-degree Galois extension of $\Bbb Q$ that is only ramified at $2$. Thus by the previous result $K^{2(G)}=\Bbb Q$ and so $2(G)=G$
Now we're basically done. We just have to relate this to the infinite case. For this, we have the following result:

Let $G$ be a profinite group ans suppose each quotient $G/U$ is a quasi-$p$-group, where $U$ runs over all open normal subgroups of $G$, then the subgroup generated by all $p$-Sylow subgroups in $G$ is dense.

Proof We have that a closed subgroup $H \subset G$ is a $p$-Sylow subgroup of $G$ if and only if for all open normal subgroups $U$ of $G$ with projections $\pi_U:G\to G/U$, the image $\pi_U(H)$ is a $p$-Sylow subgroup of $G/U$. Furthermore, for any $p$-Sylow subgroup $P\subset G/U$, there is a $p$-Sylow subgroup $\widetilde{P} \subset G$ such that $\pi_U(\widetilde{P})=P$. Thus if we let $p(G)$ be the closure of the subgroup generated by all $p$-Sylow subgroups, we get that $\pi_U(p(G))=G/U$ for all $U$. This implies that $p(G)=G$, using that $p(G)$ is closed.


text:
Q: Data access pattern, combining push and pull? I need some advice on what kind of pattern(s) I should use for pushing/pulling data into my application.
I'm writing a rule-engine that needs to hold quite a large amount of data in-memory in order to be efficient enough. I have some rather conflicting requirements;

*

*It is not acceptable for the engine to always have to wait for a full pre-load of all data before it is functional.

*Only fetching and caching data on-demand will lead to the engine taking too long before it is running quickly enough.

*An external event can trigger the need for specific parts of the data to be reloaded.

Basically, I think I need a combination of pushing and pulling data into the application.
A simplified version of my current "pattern" looks like this (in psuedo-C# written in notepad):
// This interface is implemented by all classes that needs the data
interface IDataSubscriber
{
    void RegisterData(Entity data);
}

// This interface is implemented by the data access class
interface IDataProvider
{
    void EnsureLoaded(Key dataKey);
    void RegisterSubscriber(IDataSubscriber subscriber);
}

class MyClassThatNeedsData : IDataSubscriber
{
    IDataProvider _provider;

    MyClassThatNeedsData(IDataProvider provider)
    {
        _provider = provider;
        _provider.RegisterSubscriber(this);
    }

    public void RegisterData(Entity data)
    {
        // Save data for later
        StoreDataInCache(data);
    }

    void UseData(Key key)
    {
        // Make sure that the data has been stored in cache
        _provider.EnsureLoaded(key);

        Entity data = GetDataFromCache(key);
    }
}

class MyDataProvider : IDataProvider
{
    List<IDataSubscriber> _subscribers;

    // Make sure that the data for key has been loaded to all subscribers
    public void EnsureLoaded(Key key)
    {
        if (HasKeyBeenMarkedAsLoaded(key))
            return;

        PublishDataToSubscribers(key);

        MarkKeyAsLoaded(key);
    }

    // Force all subscribers to get a new version of the data for key
    public void ForceReload(Key key)
    {
        PublishDataToSubscribers(key);

        MarkKeyAsLoaded(key);
    }

    void PublishDataToSubscribers(Key key)
    {
        Entity data = FetchDataFromStore(key);

        foreach(var subscriber in _subscribers)
        {
            subscriber.RegisterData(data);
        }
    }
}

// This class will be spun off on startup and should make sure that all data is
// preloaded as quickly as possible
class MyPreloadingThread
{
    IDataProvider _provider;

    MyPreloadingThread(IDataProvider provider)
    {
        _provider = provider;
    }

    void RunInBackground()
    {
        IEnumerable<Key> allKeys = GetAllKeys();

        foreach(var key in allKeys)
        {
            _provider.EnsureLoaded(key);
        }
    }
}

I have a feeling though that this is not necessarily the best way of doing this.. Just the fact that explaining it seems to take two pages feels like an indication..
Any ideas? Any patterns out there I should have a look at?

A: Unambiguously, it should be

*

*one of concurrency patterns (active
object, for example)

*producer-consumer pattern (queue)

*lazy load (data on demand)

*lazy unload pattern

*strategy pattern (to implement data access algorithms)

*multithreading access protected
resource (cache)

My vote - active object with shared queue (bus) + lazy patterns + cache

A: You can start with something simple, like a solution based on Gateway pattern. Then you can try to enhance performance by adding Cash.


text:
Q: LINQ to NHibernate: could not resolve property Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.
I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.
public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}

However, when running this method:
public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event
FWIW, I've blurred out the name of the project. ;)
Any idea how to get this query working?
Thanks!
-Steve
EDIT:
Here's my mapping class:
public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}

...and my config:
public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }

I also just tried the Criteria API:
return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();

No workie either.

A: Here is how you can fix that using the formulas. In your Event class convert those 2 properties into regular properties:
public class Event
{
    public Event() { }
    ...
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent{ get; set; }
    public virtual Int32 MonthOfEvent { get; set; }
    ...
    public virtual Boolean IsActive { get; set; }
}

Then in the mapping add formulas to populate their values.. I'm not very positive about the MySQL syntax for retrieving the year & month but you've got an idea (I used this reference):
public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.YearOfEvent).Formula("SELECT YEAR(dateOfEvent)");
        Map(x => x.MonthOfEvent).Formula("SELECT MONTH(dateOfEvent)");
        ...
        Map(x => x.IsActive, "isActive");
    }
}

Now you can query them just like any other fields using either LINQ or ICriteria:
return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();

A: You can query over properties that really exists in database or introduced in the mappings. As YearOfEvent just exists in your entity, you can not use it in your queries either in LINQ-to-NH or ICriteria.

A: The technique that I use is to force execution of NHLinq and then utilize LINQ to finish filtering.  This is technically what needs to happen since NH is unaware of non-mapped properties like Event.YearOfEvent.  It would look something like this:
_session.Linq<Event>()
.Where(e => e.IsActive)
.ToArray() // force evaluation of expression
.Where(e => e.YearOfEvent == DateTime.Now.Year); // evaluated by LINQ, not NHLinq

Note: You can utilize any of the other methods that force evaluation (e.g., ToList()).  This technique is not dependent upon ToArray() specifically.

A: Are you auto mapping this? Because I would suspect it's attempted to map YearOfEvent and MonthOfEvent, and it's trying to pull those columns from the database, but they don't exist.
If you're manually mapping them, then this wouldn't be an issue.

A: Your criteria query is not working, because your "YearOfEvent" property is not listed in your mapping. NHibernate does not know this property, and cannot translate it into a column name.
Try querying on properties that are actually mapped instead of calculated properties, or calculate the property directly in your query...
However, your linq query looks like it should be working, I don't see how this error can occur with that query & mapping...


text:
Q: If-if-else-expression using a variable I am trying to create a document class containing the layout for a bachelors thesis and want to keep it as general as possible. In my title page (which is defined in the document class, not the main document) a line like this shall appear:
Handed in by {\@gender} {\@author} on {\@handindate}.

The variables were created using these commands:
\newcommand{\@handindate}{\@handindate}
\newcommand{\handindate}[1]{\renewcommand{\@handindate}{#1}}

\newcommand{\@gender}{Unknown}
\newcommand{\gender}[1]{\renewcommand{\@gender}{#1}}

I want LaTeX to replace \@gender by "Mr." if \@gender=male or by "Mrs." if \@gender=female and by nothing if \@gender is anything else.
I thought of using an \ifcase-command but as far as I know this command only accepts a number as input but I would like to use the variable as input.
What I basically need is something like a " if the value is equal to male, print <text1>, if the value is equal to female print <text2> in all other cases print <> "-syntax but I am not very good at programming, so can anyone help?

A: This example uses xstring, and pgffor to create a lopp that iterates through a list of accepted phrases. Adding more phrases is as easy as adding them to the list.
\def\genderInput{%
%Input: <input gender>/<output phrase>,% (without the <>, ending by commma)
female/Mrs.,%
male/Mr.,%
boy/young Mr.,%
girl/Miss,%
none/}

Note that in british, this would be Mr and Mrs without the dot.
Output

Code
\documentclass[11pt]{article}
\usepackage{xstring}
\usepackage{pgffor}

\def\genderInput{%
%Input: <input gender>/<output phrase>,% (without the <>, ending by commma)
female/Mrs.,%
male/Mr.,%
boy/young Mr.,%
girl/Miss,%
none/}

\makeatletter
\newcommand{\@handindate}{\@handindate}
\newcommand{\handindate}[1]{\renewcommand{\@handindate}{#1}}

\newcommand{\@gender}{Unknown}
\newcommand{\gender}[1]{\renewcommand{\@gender}{#1}}

\gender{male}
\author{Joe Doe}

\newcommand{\getName}{%
\foreach \theGender/\theString in \genderInput{%
    %\theGender - \theString
    %\theGender
    \IfSubStr{\@gender}{\theGender}{%
        \theString~%
        \breakforeach}{%
        %invalid gender input %\texttt{\slash}
        }%
    }\@author%
}
\makeatother
\begin{document}
This document was written by \getName.

\gender{female}
\author{Jane Doe}

This document was written by \getName.

\gender{}
\author{Duck}

This document was written by \getName.

\gender{boy}
\author{Jimmy Nogood}

This document was written by \getName.

\gender{girl}
\author{Lily Johnson}

This document was written by \getName.
\end{document}

A: Do the check by comparing with "male" and "female":
\documentclass{article}

\makeatletter
\newcommand{\Handed}{%
  \par
  Handed in by \Apply@Gender\@Author\space on \@Handindate
  \par
}

\newcommand{\@Gender}{Unknown}
\newcommand{\@Author}{Unknown}
\newcommand{\@Handindate}{Unknown}

\newcommand{\Gender}[1]{\renewcommand{\@Gender}{#1}}
\newcommand{\Author}[1]{\renewcommand{\@Author}{#1}}
\newcommand{\Handindate}[1]{\renewcommand{\@Handindate}{#1}}

\newcommand{\Apply@Gender}{%
  \begingroup
  \long\def\@male{male}\long\def\@female{female}%
  \ifx\@Gender\@male
    Mr.~%
  \else
    \ifx\@Gender\@female
      Mrs.~%
    \fi
  \fi
  \endgroup
}
\makeatother

\begin{document}

\Gender{male}
\Author{G. Byron}
\Handindate{2016-06-21}

\Handed

\bigskip

\Gender{female}
\Author{M. Wollstonecraft}
\Handindate{2016-06-22}

\Handed

\bigskip

\Gender{whatever}
\Author{The Creature}
\Handindate{2016-06-23}

\Handed

\end{document}


text:
Q: Why is this recursive function returning undefined values? I am trying to make a calculator in Vanilla js that can evaluate BODMAS expressions. Here is the code:
index.js

document.addEventListener('DOMContentLoaded', function() {
    displayInput();
    displayResult();
})

function displayInput() {
    let valueButtons = document.querySelectorAll('.calculator-button');
    valueButtons.forEach(valueButton => {
        let value = valueButton.innerHTML;
        valueButton.onclick = function() {
            document.querySelector('#calculator-input').value += value;
        }
    })
}

function isOperator(opr) {
    if (opr === '+' || opr === '-' || opr === 'x' || opr === '/') {
        return true;
    }
    return false;
}

function displayResult() {
    let expression = '', result = '';
    document.querySelector('#calculator-calculate').onclick = function(e) {
        e.preventDefault();
        expression = document.querySelector('#calculator-input').value;
        result = getResult(expression);
        document.querySelector('.calculator-result').innerHTML = result;
    }
}

function updateExpression(index, expr) {
    let o1 = '', o2 = '';
    let start = 0, end = expr.length-1, flag = 0;
    for (let i = index-1; i > -1; i--) {
        if (!isOperator(expr[i])) {
            o1 += expr[i];
        }
        else {
            start = i+1;
            break;
        }
    }

    for (let i = index+1; i < expr.length; i++) {
        if (!isOperator(expr[i])) {
            o2 += expr[i];
        }
        else {
            end = i-1;
            break;
        }
    }

    let opr1 = parseInt(o1.split('').reverse().join('')), opr2 = parseInt(o2), result = 0;
    if (expr[index] === '+') {
        result = opr1+opr2;
    }
    if (expr[index] === '-') {
        result = opr1-opr2;
    }
    if (expr[index] === 'x') {
        result = opr1*opr2;
    }
    if (expr[index] === '/') {
        result = opr1/opr2;
    }

    if (start == 0) {
        if (end == expr.length-1) {
            return `${result}`;
        }
        else {
            return `${result}`+expr.substr(end+1,);
        }
    }
    else {
        if (end == expr.length-1) {
            return expr.substr(0, start)+`${result}`;
        }
        else {

            //alert(expr.substr(end+1,));
            return expr.substr(0, start)+`${result}`+expr.substr(end+1,);
        }
    }
}

function getResult(expr) {
    let first = expr.lastIndexOf('('), last = expr.indexOf(')'), flag = 0;
    alert("first = "+first+", last = "+last+", expr = "+expr);
    if (first == -1 || last == -1) {
        return evaluate(expr);
    }
    for (let i = first+1; i < last; i++) {
        if (isOperator(expr[i])) {
            flag = 1;
            break;
        }
    }
    if (flag == 1) {
        expr = expr.substr(0, first)+`${evaluate(`${expr.substr(first+1, last)}`)}`+expr.substr(last+1,);
    }
    getResult(expr);
}

function evaluate(expr) {
    while (expr.search('/') != -1) {
        expr = updateExpression(expr.search('/'), expr);
    }
    while (expr.search('x') != -1) {
        expr = updateExpression(expr.search('x'), expr);
    }
    while (expr.indexOf('+') != -1) {
        expr = updateExpression(expr.indexOf('+'), expr);
    }
    while (expr.search('-') != -1) {
        expr = updateExpression(expr.search('-'), expr);
    }
    return expr;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScipt Calculator</title>
    <link rel="stylesheet" href="file:///A:/js%20projects/calculator/index.css">

        <input type="text" placeholder="Enter expression" id="calculator-input">

            <button class="calculator-button">1</button>
            <button class="calculator-button">2</button>
            <button class="calculator-button">3</button>
            <button class="calculator-button">+</button>
            <button class="calculator-button">-</button>

            <button class="calculator-button">4</button>
            <button class="calculator-button">5</button>
            <button class="calculator-button">6</button>
            <button class="calculator-button">x</button>
            <button class="calculator-button">/</button>

            <button class="calculator-button">7</button>
            <button class="calculator-button">8</button>
            <button class="calculator-button">9</button>
            <button class="calculator-button" id="delete-char">⌫</button>

            <button class="calculator-button">0</button>
            <button type="submit" id="calculator-calculate">=</button>

            No result yet!

When I input ((12+3)+7), I can see that the correct calculation is being done through alerts. But the actual result is undefined:
First alert

Second alert. Problem starts from here: expRem should be 12+3 instead of 12+3)+.

Third alert

........
Last alert

What is wrong here?


text:
Q: Create my first Window 8 phone app I have a 64 bit I3 Laptop with Windows 7 installed on it. I am an ASP.NET MVC developer and have solid understanding of C#.
I have Visual Studio 2010 installed on my machine.
I wanted to try and develop windows 8 phone apps (just for fun).
My question is :
With the current configuration can I create a Windows 8 phone app ? I do not want to upgrade my laptop to Windows 8 (as it is an office laptop).
Please share your thoughts on this.

A: In order to develop for Windows Phone 8 you need Windows 8 64-bits and Visual Studio 2012. So yes, you need to upgrade or do it on a VM and an actual pone.


text:
Q: Is there a specific library type called a Help Library in SharePoint 2013? I'm working on making custom help files for my SharePoint site and found an article that works through the process; however the first thing is to create a Help Library and I am not finding anything that states there is a specific type of library called Help Library. Before I create a generic library labeled help I just wanted to see if there was a specific library for this or if it's just a generic library used for the purpose.

A: The help library is created by a site collection feature.
For SharePoint to create a Site Collection Help Library, you must first turn on the Custom Site Collection Help feature on the Site Collection Features page.
To turn on the Custom Site Collection Help feature:
1.On the Site Actions menu, click Site Settings.
2.Under Site Collection Administration, click Site Collection Features. The Site Collection Features page opens.
3.For the Custom Site Collection Help option, click Activate.
When you turn on Custom Site Collection Help, SharePoint creates a new library in the top-level site of the site collection. The new library is called Site Collection Help.
Hope this helps. Reference Link


text:
Q: ¿Como llenar ArrayList antes de mostrar la vista? o algo similar En mi aplicación tengo lo siguiente

*

*Un RecyclerView que se llenara con CardView

*Un Fragment que contiene el RecyclerView

*Un ArrayList<> que se llena con datos obtenidos desde Firebase
En el onCreateView realizo la instancia a Firebease y obtengo los datos desde la base de datos.
    myRef = FirebaseDatabase.getInstance().getReference();
    myRef.child("Paciente").addValueEventListener(this);

obtengo los datos en el siguiente método
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    if (dataSnapshot.exists()) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            Paciente paciente = new Paciente();
            paciente.setContraseña(ds.child("contraseña").getValue().toString());
            paciente.setExpediente(ds.child("expediente").getValue().toString());
            paciente.setNombreCompleto(ds.child("nombreCompleto").getValue().toString());
            paciente.setTelefono(ds.child("telefono").getValue().toString());
            paciente.setDomicilio(ds.child("domicilio").getValue().toString());
            paciente.setFechaNacimiento(ds.child("fechaNacimiento").getValue().toString());
            paciente.setSexo(ds.child("sexo").getValue().toString());
            paciente.setKey(ds.getKey());
            arrayPacientes.add(paciente);
        }
    }
}

Para llenar mi RecyclerView tengo las siguientes lineas dentro del metodo onCreateView
Adapter_recycler_pacientes adapter_recycler_pacientes = new Adapter_recycler_pacientes(arrayPacientes);
recyclerViewPacientes.setAdapter(adapter_recycler_pacientes);

Mi Adapter es el siguiente
public class Adapter_recycler_pacientes extends RecyclerView.Adapter<Adapter_recycler_pacientes.MyViewHolder> {
private ArrayList<Paciente> arrayListPacientes;

public Adapter_recycler_pacientes(ArrayList<Paciente>arrayListPacientes){
    this.arrayListPacientes = arrayListPacientes;
}

@NonNull
@Override
public Adapter_recycler_pacientes.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View  view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_paciente,null,false);
    return new Adapter_recycler_pacientes.MyViewHolder(view) ;
}

@Override
public void onBindViewHolder(@NonNull Adapter_recycler_pacientes.MyViewHolder myViewHolder, int i) {
    myViewHolder.textViewNombre.setText(arrayListPacientes.get(i).getNombreCompleto());
    myViewHolder.textViewDomicilio.setText(arrayListPacientes.get(i).getNombreCompleto());
    myViewHolder.textViewPhone.setText(arrayListPacientes.get(i).getNombreCompleto());
    myViewHolder.textViewFechaNacimiento.setText(arrayListPacientes.get(i).getNombreCompleto());
    myViewHolder.textViewExpediente.setText(arrayListPacientes.get(i).getNombreCompleto());
    myViewHolder.textViewKey.setText(arrayListPacientes.get(i).getKey());
}

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView textViewNombre;
    TextView textViewFechaNacimiento;
    TextView textViewPhone;
    TextView textViewDomicilio;
    TextView textViewExpediente;
    TextView textViewKey;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        textViewNombre = itemView.findViewById(R.id.text_nombre);
        textViewFechaNacimiento = itemView.findViewById(R.id.TextViewFecha_nacimiento);
        textViewPhone = itemView.findViewById(R.id.TextViewPhone);
        textViewDomicilio = itemView.findViewById(R.id.TextViewDomicilio);
        textViewExpediente = itemView.findViewById(R.id.TextViewNumExpediente);
        textViewKey = itemView.findViewById(R.id.textViewKey);
    }

}

}
Mi problema es
Que al momento de entrar al Fragment no me muestra ningún CardView

*

*Probé primero el método donde se llena el ArrayList a lo cual logro ver que si tiene datos.

*Lo segundo fue ver si antes de llegar al Adapter el ArrayList lleva datos, y descubro que no tiene ningún dato, al parecer tarda en llenarse o no se como funcione del todo.

Por lo tanto creo que la razón por la que no se muestran los datos es por que el ArrayList tarda en llenarse.. a si que como podria llenarlo antes para poder mostrarlos en el Fragment

A: Llama a notifyDataSetChanged despúes del for
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    if (dataSnapshot.exists()) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            Paciente paciente = new Paciente();
            paciente.setContraseña(ds.child("contraseña").getValue().toString());
            paciente.setExpediente(ds.child("expediente").getValue().toString());
            paciente.setNombreCompleto(ds.child("nombreCompleto").getValue().toString());
            paciente.setTelefono(ds.child("telefono").getValue().toString());
            paciente.setDomicilio(ds.child("domicilio").getValue().toString());
            paciente.setFechaNacimiento(ds.child("fechaNacimiento").getValue().toString());
            paciente.setSexo(ds.child("sexo").getValue().toString());
            paciente.setKey(ds.getKey());
            arrayPacientes.add(paciente);
        }
        adapter_recycler_pacientes.notifyDataSetChanged();
    }
}

No olvides declarar adapter_recycler_pacientes private y fuera de onCreateView


text:
Q: SonarQube 6 - Code Coverage with separate Jenkins Test Job Ist it possible to handle code coverage separate from other SonarQube analyses with Jenkins 2.73 and Sonar 6.7?
We have the following structure:

*

*Jenkins job A: Maven project A (nightly, SonarScanner)

*Jenkins job B: Maven project B (nightly, SonarScanner)

*Jenkins job T: Maven project with test / coverage of A + B (continuously)

Job A and B are special Sonar jobs running at night. Job T ist running all over the day for tests and coverage. We use the maven sonar scanner in job A and B but also would like to provide coverage by job T. Ist this possible?
As a workaround we save the coverage of continuously running job T at master for Job T and copy the jacoco.exec to the build client at runtime of nightly job A and B.
Ist there a better way to do this?


text:
Q: Swift 3 / Alamofire : I am not able to fetch the data on UITableView I am using Alamofire and trying to fetch data on my tableview, however I am not able to get the data. When I use the cmd Print, its showing me the data but not able to fetch the data. How can I fetch the data on my tableview?
Please find the code below:-
import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate {
//let myarray = ["item1", "item2", "item3"]
var tableData = Array<Group>()

var arrRes = [[String:AnyObject]]() //Array of dictionary

var group = [Group]()

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    loadGroups()
}

func loadGroups(){

    let testhappyhour:Group = Group(tempName: "TEST", tempID: "TESST", icons: "TEST", tempgbcount: "TEST")
    self.group.append(testhappyhour)

    //let groupQuery:String = "http://jsonplaceholder.typicode.com/users"
    Alamofire.request("http://jsonplaceholder.typicode.com/users").responseJSON
        { response in switch response.result {
        case .success(let JSON):
            let response = JSON as! NSArray
            for item in response { // loop through data items
                let obj = item as! NSDictionary
                let happyhour = Group(tempName:obj["NAME"] as! String, tempID:obj["id"] as! String, icons:obj["icon"] as! String, tempgbcount:obj["TOTAL"] as! String)
                self.group.append(happyhour)
            }
            self.tableview.reloadData()

        case .failure(let error):
            print("Request failed with error: \(error)")
            }
    }
}

func convertToArray(text: String) -> [Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tableview.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //return myarray.count
    return arrRes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
   // cell.textLabel?.text = myarray[indexPath.item]
    let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "groupCell")!
    var dict = arrRes[indexPath.row]
    cell.textLabel?.text = dict["NAME"] as? String
    cell.detailTextLabel?.text = dict["TOTAL"] as? String
    return cell
}

}

Thank you!!

A: Need to change loadGroups function like this
func loadGroups(){

    let testhappyhour:Group = Group(tempName: "TEST", tempID: "TESST", icons: "TEST", tempgbcount: "TEST")
    self.group.append(testhappyhour)

    Alamofire.request("http://jsonplaceholder.typicode.com/users").responseJSON
        { response in switch response.result {
        case .success(let JSON):
            let response = JSON as! NSArray
            for item in response { // loop through data items
                let obj = item as! NSDictionary
                let happyhour = Group(tempName:obj["NAME"] as! String, tempID:obj["id"] as! String, icons:obj["icon"] as! String, tempgbcount:obj["TOTAL"] as! String)
                self.group.append(happyhour)
                self.arrRes.append(obj) // ADD THIS LINE
            }
            self.tableview.reloadData()

        case .failure(let error):
            print("Request failed with error: \(error)")
            }
    }
}

A: Array 'group' is appended with the Alamofire responses, but Array 'arrRes' is used as the table view data source. If you use self.group instead of arrRes in the data source methods, the table should update with the new groups received in the Alamofire response.


text:
Q: Extracting dates out of python array of string using regex I'm trying to extract dates out of a string using python. The date is in the format mm-dd-yyyy. So I know the regex should be something like /d{2}-/d{2}-/d{4}. However when I try and iterate over the array below I am not able to extract the dates out of the string.
import re
logs = ["First entry to journal logs. (01-01-2015)", "Last entry to journal logs 07-01-2016"]
for i in logs:
    m = re.match("/d{2}-/d{2}-/d{4}",i)
    print m.group(0)

I haven't work with re before so not sure if I'm using it properly.

A: This should do the trick:
import re

s = ["First entry to journal logs. (01-01-2015)", "Last entry to journal logs 07-01-2016"]

print([re.findall(r'\d{2}\-\d{2}\-\d{4}', i) for i in s])

Yields:
[['01-01-2015'], ['07-01-2016']]

A: You can't use match to search inside a text, If you use match you need to match from Initial position to Final position, to search inside a text use search:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import re
logs = ["First entry to journal logs. (01-01-2015)", "Last entry to journal logs 07-01-2016"]
for i in logs:
    m = re.search("[0-9]{2}\-[0-9]{2}\-[0-9]{4}",i)
    if m:
        print m.group(0)

Output:
01-01-2015
07-01-2016


text:
Q: ffmpeg reducing the qualitu of photos I am using ffmpeg to convert photos to video and i am pretty successfull so far.
However I am facing quality issue.
    $command1="ffmpeg -r 1/1 -pattern_type glob -i 'pics/*.jpg' -vf \"pad=ceil(iw/2)*2:ceil(ih/2)*2\" finalPics/video.mp4";
    exec($command1);

What is wrong with the command as video quality is really reducing the quality of images

A: Try using
ffmpeg -r 1/1 -framerate 25 -pattern_type glob -i 'pics/*.jpg' -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p pics/video.mp4


text:
Q: Undefined key NSException in UIPickerView iOS7.1 I'm getting an exception in the iOS 7.1 simulator that doesn't appear in 7.0. It appears to be handled somewhere in the core because it only triggers an exception raise breakpoint. It doesn't log to the console or crash. This occurs while scrolling through options in a UIPickerView. There is no meaningful backtrace available (right from UIApplicationMain into objc_exception_throw), but examining the exception during throw in the debugger shows:
[<UIPickerView 0xb9a6700> valueForUndefinedKey:]: this class is not key value coding-compliant for the key _mode.
I searched in my project for mode, setMode:, mode = but I don't think I'm the one setting this. Anyone else run into this? I guess it's okay if it's not crashing the app but it gave me a scare, and I'd rather take action to prevent it from being thrown. If I have some more time I'll try to isolate this in a test project and follow up.
Edit: Better backtrace:
         thread #1: tid = 0x10975c, 0x02590909 libc++abi.dylib`__cxa_throw, queue = 'com.apple.main-thread, stop reason = breakpoint 1.2
     frame #0: 0x02590909 libc++abi.dylib`__cxa_throw
     frame #1: 0x01b1d9fc libobjc.A.dylib`objc_exception_throw + 323
     frame #2: 0x020e1fe1 CoreFoundation`-[NSException raise] + 17
     frame #3: 0x017ddc7a Foundation`-[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 282
     frame #4: 0x0174adfd Foundation`_NSGetUsingKeyValueGetter + 81
     frame #5: 0x0174a437 Foundation`-[NSObject(NSKeyValueCoding) valueForKey:] + 260
     frame #6: 0x0d615dff AccessibilityUtilities`-[NSObject(UIAccessibilitySafeCategory) safeValueForKey:] + 43
     frame #7: 0x1151c1f6 UIKit`-[UIAccessibilityPickerComponent accessibilityTraits] + 398
     frame #8: 0x0d716021 UIAccessibility`-[NSObject(AXPrivCategory) accessibilityAttributeValue:] + 1865
     frame #9: 0x0d70a7d7 UIAccessibility`_copyMultipleAttributeValuesCallback + 409
     frame #10: 0x0d76c537 AXRuntime`_AXXMIGCopyMultipleAttributeValues + 202
     frame #11: 0x0d767e78 AXRuntime`_XCopyMultipleAttributeValues + 473
     frame #12: 0x0d7726b4 AXRuntime`mshMIGPerform + 256
     frame #13: 0x01fcdca5 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
     frame #14: 0x01fcd9db CoreFoundation`__CFRunLoopDoSource1 + 523
     frame #15: 0x01ff868c CoreFoundation`__CFRunLoopRun + 2156
     frame #16: 0x01ff79d3 CoreFoundation`CFRunLoopRunSpecific + 467
     frame #17: 0x01ff77eb CoreFoundation`CFRunLoopRunInMode + 123
     frame #18: 0x03fea5ee GraphicsServices`GSEventRunModal + 192
     frame #19: 0x03fea42b GraphicsServices`GSEventRun + 104
     frame #20: 0x007ddf9b UIKit`UIApplicationMain + 1225
     frame #21: 0x0004863d [redacted]`main(argc=1, argv=0xbfffef50) + 141 at main.m:16

A: In my case, on Xcode 6.2 and iOS 8.2, only simulator crashes (but can safely continue). Since _mode is nowhere within our code, it's probably safe to assume there is a simulator bug or misconfiguration.
For now, I am using a category on the offending UIPickerView to get rid of the annoyance:
#import "UIPickerView+FixCrash.h"

@implementation UIPickerView (FixCrash)

#if TARGET_IPHONE_SIMULATOR
- (id)valueForUndefinedKey:(NSString *)key
{
    return nil;
}
#endif

@end


text:
Q: What different between Task.Run(Foo) and FooAsync()? In fact, I'm asking about What the different between Use a thread run a block method AND Direct run a unblock/asynchronous method?
Such as GetResponse / GetResponseAsync, ExecuteReader / BeginExecuteReader etc.
On the surface, neither blockades the program, but what's the difference in principle? I think this actually involves a real understanding of multithreading and asynchrony.
Thanks.

A: The short answer: Task.Run will assign the method to a pool thread whereas an async method just has to return a Task, but apart from that it does whatever it wants.
A bit detailed answer:
Without any specific example it is impossible to tell what will happen in an async method. It may or may not use a thread inside or it can 'cheat' and block the caller the same way as a regular method returning something by Task.FromResult(myResult) in the end.
Actually Task.Run has overloads with Func<Task> and Func<Task<TResult>> parameters as well so if you know that an async method cheats (or though it doesn't use a thread you want to force it for some well-founded reason), then you can wrap even already async methods in Task.Run calls.
As for the concrete examples:

*

*Task.Run(() => GetResponse(...)) returns immediately an uncompleted Task and schedules GetResponse to be executed on a pool thread. Once the thread finishes, the task will be completed.

*GetResponseAsync(...) returns immediately an uncompleted task that will be completed once the response is received on the underlying socket. No pool threads this time.

*Task.Run(() => ExecuteReader(...)): same as for the first point

*BeginExecuteReader: Now this is an interesting one. As this uses the .NET 1.0 IAsyncResult solution we may think it just calls a Delegate.BeginInvoke for ExecuteReader, which would be the trivial solution and would also end up using a pool thread. But if you investigate BeginExecuteReaderInternal you can see that it also uses tasks internally. It must have been refactored since tasks were introduced in .NET 4.0.

Btw, you can await also IAsyncResult methods by TaskFactory:
await Task.Factory.FromAsync(BeginExecuteReader(...));

This will not create any additional threads (on top of the ones created by the Begin... method, if any) just turns the IAsyncResult into an awaitable Task in a  convenient way.


text:
Q: Trying to get or pass Button in/to Custom SurfaceView from the same Layout I am creating a small game I have an activity:
GameActivity.java:
public class GameActivity extends Activity {

    public static Button btnPause;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // requesting to turn the title OFF
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // making it full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.game_layout);
        btnPause = (Button) findViewById(R.id.buttonPause);

    }

    @Override
    public void onBackPressed() {
        Toast.makeText(this,
                "No effect, use the `||` button at top left of screen!",
                Toast.LENGTH_SHORT).show();
    }

}

The layout for above
game_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.spaceinvaders.game.GameSurfaceView
        android:id="@+id/surfaceView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/buttonPause"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/button_pause"
                android:textAppearance="?android:attr/textAppearanceLarge" >
            </Button>

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="right|center_vertical"
                android:layout_weight="1"
                android:gravity="right"
                android:text="@string/health"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <ProgressBar
                style="@android:style/Widget.ProgressBar.Horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right|center_vertical"
                android:layout_marginRight="5dp"
                android:minWidth="175dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="right|center_vertical"
                android:layout_weight="1"
                android:gravity="right"
                android:text="@string/ammo"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <ProgressBar
                style="@android:style/Widget.ProgressBar.Horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginRight="5dp"
                android:minWidth="175dp" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom" >

        <com.spaceinvaders.joystick.JoystickView
            android:id="@+id/joystickView"
            android:layout_width="100dp"
            android:layout_height="100dp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:layout_weight="1" />

        <Button
            android:id="@+id/buttonShoot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:text="X"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

</FrameLayout>

And as you might have noticed there is a custom component/SurfaceView, GameSurfaceView, which looks similar too:
GameSurfaceView.java:
public class GameSurfaceView extends SurfaceView implements
        SurfaceHolder.Callback {

    private GameLoop gameLoop;

    private Bitmap background;
    private Button btnPause;

    public GameSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GameSurfaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs);
        init();
    }

    public GameSurfaceView(Context context) {
        super(context);
        init();
    }

    private void init() {

        btnPause = GameActivity.btnPause;
            //causes NPE
        btnPause.setOnClickListener(new OnClickListener() {

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

        // adding the callback (this) to the surface holder to intercept events
        getHolder().addCallback(this);

        // create the game loop thread
        gameLoop = new GameLoop(getHolder(), this);

        // make the GamePanel focusable so it can handle events
        setFocusable(true);
    }
}

Basically I am trying to pass the button buttonPause from the game_layout.xml to my custom SurfaceView GameSurfaceView and add a OnClickListener; using a static variable However I  keep getting a NullPointerException.
I can easily do this in the GameActivity class but that becomes a problem for buttons like shoot etc...
So basically my question is how do I pass an Button/component from my GameActivity/game_layout to a GameSurfaceView which is contained on game_layout.xml class within that activities layout.
I have tried also tried using findViewById(R.id.buttonPause) in my GameSurfaceView and than adding the OnClickListener which produces the same result (NPE).
Thanks in advance

A: Instead of putting the GameSurfaceView in the xml, add the view dynamically. This way you can have a constructor in GameSurfaceView that have a Button parameter.

A: He can't find the Button in findViewById(), because it's called your SurfaceView.
Not quite sure if it works, but try to get the Button in the SurfaceView with:
Button btnPause = (Button) getParent().findViewById(R.id.buttonPause);

Edit:
Oh Sorry, you get a ViewParent on getParent()..
It will compile like this:
View v = (View) getParent();
Button btnPause = (Button) v.findViewById(R.id.buttonPause);


text:
Q: What happens when converting between tuple/list? How does python internally make the conversion when converting a tuple to a list or the other way around.
Does it "switch a flag" (now you're immutable, now you're not!) or does it iterate through the items and convert them?

A: Tuples and lists are entirely separate types; so when converting a list to a tuple or vice versa a new object is created and element references are copied across.
Python does optimise this by reaching into the internal structure of the other object; for example, list(tupleobj) is essentially the same thing as list().extend(tupleobj), where the listextend function then uses the Python C API function to simply copy across the references from the C array of the tuple:
if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
    PyObject **src, **dest;
    b = PySequence_Fast(b, "argument must be iterable");
    if (!b)
        return NULL;
    n = PySequence_Fast_GET_SIZE(b);
    if (n == 0) {
        /* short circuit when b is empty */
        Py_DECREF(b);
        Py_RETURN_NONE;
    }
    m = Py_SIZE(self);
    if (list_resize(self, m + n) == -1) {
        Py_DECREF(b);
        return NULL;
    }
    /* note that we may still have self == b here for the
     * situation a.extend(a), but the following code works
     * in that case too.  Just make sure to resize self
     * before calling PySequence_Fast_ITEMS.
     */
    /* populate the end of self with b's items */
    src = PySequence_Fast_ITEMS(b);
    dest = self->ob_item + m;
    for (i = 0; i < n; i++) {
        PyObject *o = src[i];
        Py_INCREF(o);
        dest[i] = o;
    }
    Py_DECREF(b);
    Py_RETURN_NONE;
}

PySequence_Fast_ITEMS is a macro to access the ob_item array in the C struct for the tuple, and the for loop copies the items from that array straight over to the self->ob_item array (starting at offset m).


text:
Q: How to transfer photos from my iPad to Mac One of the great benefits of the iPad will be putting a ton of my photos in one, great place to show friends and family (rather than bringing them over to my computer). But I have several thousand photos, all organized on my iPad in folders by year and subject.I would like to transfer them to my mac? How can I do this?
Thanks.

A: How to upload pictures previously stored on a iPad but cannot use iTunes or windows explorer to extract them back to the PC for some reason? As long as you can see them on the iPad, you can get them back onto the PC. Here is how:
It will take time depending on how many pictures you need to transfer, but if you are like me, time is worth the wait.

*

*Sign up with an internet photo album website like Picasa

*Download the app Picasa web album to the iPad

*Start uploading your pics thru the app to the web

*Once you have uploaded a few or all of your pictures to the web, log in to your account on the PC / computer

*Download the pictures from the web directly onto your hard drive.

A: 1- If your iPad is jailbroken, you can either ssh into it from a local computer and copy all the files. Or you can get a utility to view the filsystem of the iPad and transfer the folder manually.
2- If your iPad isn't jailbroken, you could purchase the ssh app and do the same as above. You could also buy something like GoodReader which will allow you to share files and photos. Another option is Apple's photo connector kit for iPad http://store.apple.com/us/product/MC531ZM/A

A: You may want to check out "iMacsoft iPad to Mac Transfer".  Never used it personally, and it's not free, but may be worth the $25 to you.

When you lost the iTunes music or when you want to backup your iPad collection on Mac in case files are damaged or crashed, you need a iPad to Mac transfer to copy iPad to Mac, backup iPad to Mac. iMacsoft iPad to Mac Transfer makes you transfer Music, Movie, Photo, ePub, PDF, Audiobook, Camera Roll, Podcast and TV Show from iPad to Mac. Moreover, you can freely copy iPad files to iTunes library, add Mac files to iPad.


text:
Q: CSV file has an error or it's not an SYLYK File when adding ID header So I created a node.js script to convert the object of an array to CSV format, then I used objects-to-csv from NPM libraries. First, is want to iterate the array by adding an ID. The script was successfully created the CSV file. but when I open it to the WPS and Microsoft Office, there was a warning that either a file has an error or it's not an SYLYK File. please see the code below.

const ObjectsToCsv = require("objects-to-csv");

// Sample data - two columns, three rows:
const data = [
  { code: "CA", name: "California" },
  { code: "TX", name: "Texas" },
  { code: "NY", name: "New York" },
];

// If you use "await", code must be inside an asynchronous function:
(async () => {
  const iterateWithID = data.map((x, i) => {
    return {
      ID: i + 1,
      code: x.code,
      name: x.name,
    };
  });

  const csv = new ObjectsToCsv(iterateWithID);

  // Save to file:
  await csv.toDisk("./output.csv");

  // Return the CSV file as string:
  console.log(await csv.toString());
})();

here is the screenshot of the warning when I open it to the WPS

I tried to remove the iteration of the array, and I didn't encounter any problem when opening the CSV file.
What I really want to fix this warning when I open the CSV file.

A: If you make the first letters ID of a text file, Excel incorrectly assumes you are trying to open an SYLK file. I updated your code to have Id instead of ID.

const ObjectsToCsv = require("objects-to-csv");

// Sample data - two columns, three rows:
const data = [
  { code: "CA", name: "California" },
  { code: "TX", name: "Texas" },
  { code: "NY", name: "New York" },
];

// If you use "await", code must be inside an asynchronous function:
(async () => {
  const iterateWithID = data.map((x, i) => {
    return {
      Id: i + 1,
      code: x.code,
      name: x.name,
    };
  });

  const csv = new ObjectsToCsv(iterateWithID);

  // Save to file:
  await csv.toDisk("./output.csv");

  // Return the CSV file as string:
  console.log(await csv.toString());
})();


text:
Q: 2x2 unequal image placement, Subcaption. First two image are stacked horizontally. second two vertically, why? I have 4 images of various sizes (attached herewith). I want to place them in a 2 x 2 grid. Their widths should be the same, roughly 0.5/textwidth. I have done the following:
'''
\documentclass[12pt,onehalfspacing,headsepline,oneside,openright,a4paper]{article}
\usepackage{subcaption}
\usepackage{graphicx}
\begin{document}
\begin{figure}
    \centering
    \begin{subfigure}[t]{0.5\textwidth}
    \centering
        \raisebox{-\height}{\includegraphics[width=.8\linewidth]{images/image1.jpg}}
        \caption{Step 1: Creating a new Project}
        \vspace{1.7cm}
        \label{fig:newproj}
    \end{subfigure}%
    \begin{subfigure}[t]{0.5\textwidth}
    \centering
    \raisebox{-\height}{\includegraphics[width=.8\linewidth]{images/image2.jpg}}
        \caption{Step 3: Creating a new Model}
        \label{fig:newmod}
    \end{subfigure}
    \newline
    \begin{subfigure}{0.5\textwidth}
    \centering
        \includegraphics[width=0.8\linewidth]{images/image3.jpg}
        %\vspace{0.7cm}
        \caption{Step 5: Choosing model subsystem structure}
        \label{fig:smsc_structure}
    \end{subfigure}
    \begin{subfigure}{0.5\textwidth}
    \centering
        \includegraphics[width=0.8\linewidth]{images/image4.jpg}
        %\vspace{0.7cm}
        \caption{Step 7: Editing new Model}
        \label{fig:smsc_structure}
    \end{subfigure}
    \caption{How to make a model in OPAL-RT}
    \label{fig:scratch}
\end{figure}

\end{document}

'''
The output looks like this:

But what I want is :

To explain in words, I want the top margin and bottom margins of the figures to be flush with each other horizontally. I should be able to do the fine-tuning by using space to add space between sub-figures and captions.
Any insights about what I am doing wrong would be greatly appreciated.
Note: I am new to this forum and I am trying my best to adhere to the guidelines. Kindly give me a chance to rectify any mistakes made before downvoting.

UPDATE:
With the suggestion from @David Carlisle. I have added '%' a comment after the \end{subfigure}. And Adding [t], makes the second row flush to the bottom.
This is how the result looks like:

However, as pointed out, the numbering is now jumbled up (I need c and b to be interchanged). How do I fix that? Updated code is as follows:
'''
\documentclass[12pt,onehalfspacing,headsepline,oneside,openright,a4paper]{article}
\usepackage{subcaption}
\usepackage{graphicx}
\begin{document}
\begin{figure}
    \centering
    \begin{subfigure}[t]{0.5\textwidth}
    \centering
        \raisebox{-\height}{\includegraphics[width=.8\linewidth]{images/image1.jpg}}
        \caption{Step 1: Creating a new Project}
        %\vspace{1.7cm}
        \label{fig:newproj}
    \end{subfigure}%
    \begin{subfigure}[t]{0.5\textwidth}
    \centering
        \raisebox{-\height}{\includegraphics[width=.8\linewidth]{images/image3.jpg}}
    %\includegraphics[width=.8\linewidth]{images/image2.jpg}
        \caption{Step 5: Creating a new Model}
        \label{fig:newmod}
    \end{subfigure}
    \newline
    \begin{subfigure}[t]{0.5\textwidth}
    \centering
        \includegraphics[width=0.8\linewidth]{images/image2.jpg}
        %\vspace{0.7cm}
        \caption{Step 3: Choosing model subsystem structure}
        \label{fig:smsc_structure}
    \end{subfigure}%
    \begin{subfigure}[t]{0.5\textwidth}
    \centering
        \includegraphics[width=0.8\linewidth]{images/image4.jpg}
        %\vspace{0.7cm}
        \caption{Step 7: Editing new Model}
        \label{fig:smsc_structure}
    \end{subfigure}
    \caption{How to make a model in OPAL-RT}
    \label{fig:scratch}
\end{figure}
\end{document}

'''

A: A subfigure is positioned by the same logic as a letter you have
WX
\newline
Y Z

where each of the "letters" is half of the text width.
So on the first line you get two just fitting but on the second line the word-space between them would make them not fit so you get an automatic line break at the space.
In your case the word space comes from the end of line after \end{subfigure} in the case that it is not commented out.

A: I am posting my answer from inputs received from David Carlisle and How to vertically label the subfigures?. I shall not accept my answer as right unless the community agrees. If not I shall choose David's answer as the right one, even though it did not exactly provide a solution.
'''
\documentclass[12pt,onehalfspacing,headsepline,oneside,openright,a4paper]{article}
\usepackage{subcaption}
\usepackage{graphicx}
\begin{document}
\begin{figure}
\begin{subfigure}[t]{0.5\textwidth}
%   \includegraphics[width=0.9\linewidth]{images/image1.jpg}
  \raisebox{-\height}{\includegraphics[width=.9\linewidth]{images/image1.jpg}}
  \vspace{0.25cm}
  \caption{First subfigure} \label{fig:1a}
  \vspace{0.25cm}
  \par\medskip % if more vertical separation needed, use \bigskip
  \includegraphics[width=0.9\linewidth]{images/image2.jpg}
  \caption{Second subfigure} \label{fig:1b}
\end{subfigure}
\hspace*{\fill}
\begin{subfigure}[t]{0.5\textwidth}
    \raisebox{-\height}{\includegraphics[width=.9\linewidth]{images/image3.jpg}}
  %\includegraphics[width=0.9\linewidth]{images/image3.jpg}
  \caption{Third subfigure} \label{fig:1c}
  \par\medskip % if more vertical separation needed, use \bigskip
  \includegraphics[width=0.9\linewidth]{images/image4.jpg}
  \caption{Fourth subfigure} \label{fig:1d}
\end{subfigure}
\caption{This is a figure with six subfigures}\label{fig:1}
\end{figure}

\end{document}

'''
The outcome is as expected


text:
Q: How to export jshint config file from WebStorm I used to work alone on a project. I used to use WebStorm's JSHint plugin for code quality testing.
Now couple of friends joined me so I thought to create a .jshintrc file for all of us to use. But it is quite boring to do it manually and I'm perfectly happy with my current settings.
Is there a way to export my project-wide settings in order to share it with co-worker?

A: JSHint configuration from Settings(Preferences) | Languages & Frameworks | JavaScript | Code Quality Tools | JSHint is stored in <project_dir>\.idea\jsLinters\jshint.xml. You can share this file with your co-workers


text:
Q: ¿La función glm genera y almacena los ODD ratio del modelo estimado? Cuando ejecutas un modelo lineal generalizado con la función glm(*), esta te devuelve un objeto con varios valores importantes sobre el modelo. Sin embargo, no encuentro los valores de los ODD ratio de cada variable necesarios para poder interpretar el modelo. He mirado en la documentación pero no he encontrado estos valores y me extraña muchísimo que no se incluya en el objeto glm. Entonces, ¿Debo generar yo mismo una columna con los ODD ratio o están en el objeto que se genera al ejecutar glm()?
Dejo un link con la documentación que estoy consultando:
documentación glm()

A: Supongo que si te interesan los odd ratios o razones de momio estás trabajando con un modelo logit. En ese caso los OR son los coeficientes exponenciados y los puedes ver con exp(coefficients(modelo)).
R reporta (correctamente) como coeficientes al logaritmo de las razones de probabilidad, de ese modo es más directa la interpretación de la pendiente (el signo del coeficiente). Claro, es más difícil de interpretar en términos de magnitud de la variación y para eso en necesario exponenciarlos.

A: En un modelo econometrico, no es necesario exponenciarlos, pero hay que tener muy en cuenta que cambia la interpretación de los coeficientes.
El modelo Nivel-Nivel representa las variables en su forma original (regresión en forma lineal). Es decir, un cambio de una unidad en X, afecta en β1 unidades a Y.
El modelo Nivel-Log se interpreta como un incremento del 1% de cambio en X es asociado a un cambio en Y de 0,01· β1.
El modelo Log-Nivel es el menor frecuentemente utilizado y se conoce como la semielasticidad de Y respecto a X. Se interpreta como un incremento de 1 unidad en X es asociado a un cambio en Y de (100·β1 )%.
El modelo Log-Log es atribuye a β1 la elasticidad de Y, respecto a X. Se interpreta como un incremento del 1% en X es asociado a un cambio en Y de B1%.


text:
Q: Optimize SQL SELECT for 4000 searches, into Excel by VBA How could this be optimized for speed by batching or other techniques?  Its a 20MB Access2003 Database I am searching from Excel 2003 VBA.
I have my Access Table Keyed (autonumber) so I though this would provide intelligent non-linear searching like binary searches.  Currently searching for 4000 values from a table of 147k records is taking 4.2 minutes.
I found this in a search:

The problem with a straight SELECT on the SQL Server side is that the DB will do a linear search through the table unless the column you're working with has an index on it; then the DB can be smarter.StackOverflow SQL C# Binary Search Question

Is this true and does it also apply to Access2003 DB?
VBA Code, Example:
    Dim cnn As ADODB.Connection
    Dim rst As ADODB.Recordset
    Set cnn = New ADODB.Connection 'open the connection
    With cnn
      .Provider = "Microsoft.Jet.OLEDB.4.0"
      .Open "PNdb2003.mdb"
    End With

    'define the record set
    Set rst = New ADODB.Recordset
    rst.CursorLocation = adUseClient   'for smaller datasets that fit into RAM

    For Each myVariant In Selection.Cells
        strSearchText = myVariant

        Dim sSQL As String
        sSQL = "SELECT Key FROM [MasterTable] WHERE PN=""" & strSearchText & """"

        rst.Open Source:=sSQL, ActiveConnection:=cnn, CursorType:=adOpenStatic, LockType:=adLockOptimistic

        Cells(myVariant.Row, 7).CopyFromRecordset rst

        rst.Close
    Next myVariant

cnn.Close

A: When you state "Access Table Keyed" is this the same field as the PN field?   If not, and I suspect it isn't then yes, creating an index on the PN field will greatly improve performance.  You should also do this for any other fields on which you do any searching.   Even indexing a boolean field can make a significant difference in searching but do a before and after comparision.

A: Yes, unless your select contains an indexed field, preferrably a primary key (or clustered index) searches will in general be performed linearly since any query optimization cannot be done to determine the data order or layout.

A: What about creating a SQL JOIN between the table in your Excel workbook and the table in your Access database, fetch the resultset once and and, most crucially, in the same order as your workbook then using CopyFromRecordset once to populate all rows in the workbook in one go. I imagine this would be orders of magnitude faster than opening a recordset four thousand times.
Update

Can you provide the SQL for how you
  join an Excel spreadsheet and an
  Access table

Something like this:
SELECT A1.customer_number
  FROM [MS Access;Database=C:\Tempo\New_Jet_DB.mdb;].Customers AS A1
       LEFT OUTER JOIN
          [Excel 8.0;HDR=YES;IMEX=1;Database=C:\db.xls;].[Sheet1$] AS E1
          ON A1.customer_number = E1.col1;

A: The optimization tips that seem most obvious based on your code sample are these:
1) Make sure you have an index on MasterTable.PN. This will be absolutely necessary to maximize performance and minimize table scans.
2) Experiment with combining the parameters and running them in a single query instead of 4000 separate queries. Perhaps with an IN statement that concatenates all the values you are interested in. This isn't 100% guaranteed to be faster, but in my experience there tends to be a ton of overhead running multiple queries in a loop like this.
Important: Don't take these a certain optimizations, test run each version several times to confirm that they really are faster in your specific situation. Your mileage may vary.


text:
Q: View is compressing from left and right edge on modal presentation SwiftUI form view is behaving strange when a presentation was started.
Edge layout's for left and right is breaking
Any idea to avoid this problem ?
struct FormActionTest: View {
@State var isShow : Bool = false
var body: some View {
    Form{
        HStack{
                Text("TEST")
                Spacer()
                Text("TEST")
            }
        HStack{
            Button(action: {
                self.isShow.toggle()
            }) {
                Text("Alert")
            }
        }
    }.actionSheet(isPresented: $isShow, content: {
        ActionSheet(title: Text("TEST"))
    })
}

Using Xcode Version 11.2 beta 2 (11B44) tried in simulator and real devices.

A: This is a pretty common visual bug with List and Form, still present in Xcode 11.2. Just report it and wait for a fix, unfortunately.


text:
Q: Math puzzle - Help with degenerate cases? Here is the original problem:
Given the following equalities and the values for $v,x,y\in \mathbb{R}$:
$$\begin{matrix}v^2 = w(w-2x)(w-2y)(w-2z) & (1) \\ w=x+y+z & (2)\end{matrix}$$
Find all values for $z\in \mathbb{R}$.
I will put my solution in spoiler tags in case you find this problem interesting and want to solve it on your own.

 I noticed that this is a modification on Heron's formula. If I had a triangle with sides of lengths $x,y,z$ and area $\dfrac{v}{4}$, it would satisfy Heron's formula with perimeter $w$ and semi-perimeter $\dfrac{w}{2}$.  Therefore, I started with the assumption that I had a valid triangle. Thus, if the angle between the sides of length $x$ and $y$ were $\gamma$, then $\dfrac{v}{4} = \dfrac{1}{2}xy\sin \gamma$. Similarly, by the Law of Cosines, I have $z^2 = x^2+y^2-2xy\cos \gamma$. Since $\sin \gamma = \dfrac{v}{2xy} = \dfrac{\text{opp}}{\text{hyp}}$, then $\cos \gamma = \dfrac{\text{adj}}{\text{hyp}} = \dfrac{\sqrt{4x^2y^2-v^2}}{2xy}$. Since $\cos \gamma$ will be negative for any $\gamma > \dfrac{\pi}{2}$, but the RHS will always be nonnegative, I need a $\pm$. Plugging in, this gives: $$z^2 = x^2+y^2\pm \sqrt{4x^2y^2-v^2}$$ Of course, then I just take the square root of both sides, and voila, I have up to four solutions for $z$. The degenerate cases I already found are when $x=0$ or $y=0$ as then $\gamma$ does not exist. If $x=y=0$, then (1) becomes $v^2=-z^4$, which is a contradiction if $v\neq 0$. If only one of them is 0, (say $x$), then the the formula becomes: $$\begin{matrix}v^2 = w^2(w-2y)(w-2z) & (3) \\ w = y+z & (4)\end{matrix}$$ which only has solutions $z = \pm y$. (It is easy to check that if $w\neq 0$ and $v\neq 0$, then $z$ has only complex solutions).

Question: Have I found all degenerate cases? How do I prove this?

A: After substitution of $w$ and expansion, the equation is biquadratic in $z^2$.
$$z^4-2(x^2+y^2)z^2+(x^2-y^2)^2+v^2=0.$$
It has real roots in $z^2$ when
$$(x^2+y^2)^2-(x^2-y^2)^2-v^2=4x^2y^2-v^2\ge0.$$
Then
$$x^2+y^2+\sqrt{4x^2y^2-v^2}$$ is always positive, while
$$x^2+y^2-\sqrt{4x^2y^2-v^2}$$ requires
$$(x^2+y^2)^2\ge4x^2y^2-v^2,$$
$$(x^2-y^2)^2\ge-v^2$$  which is always true.
Hence, under the only condition
$$2|xy|\ge|v|,$$
we have four real roots
$$\pm\sqrt{x^2+y^2\pm\sqrt{4x^2y^2-v^2}}.$$

Note that we can reduce the variables so that $v=2$ and the locus of $(x,y)$ is made of the four regions disconnected by the equilateral hyperbolas $xy\ge1$ and $-xy\ge1$.

A: Not an answer, but hints / ideas:
Put $X = w - 2x$, $Y = w - 2y$, $Z = w - 2z$, then you have $z = \frac{X+Y}{2} $ and
$$
v^2 = (X+Y+Z)XYZ
$$
So for given $v \ne 0$ , cases with no solution arise when $X=0$, or $Y=0$, or $Z=0$, or $X+Y+Z = 0$, or when exactly one or exactly three of the 4 factors are negative.
Conversely, for given $v =0$ , it is necessary that at least one of $X=0$, $Y=0$, $Z=0$, $X+Y+Z = 0$ must hold.
Lots of cases to discuss ....


text:
Q: Why does a body has inertia? Today I asked a question on this site regarding inertia, and while reading one of the answers, a question popped up

Why does a body have inertia?

I looked up this site and several others, but could not find any resources.

A: Philosophical aspect
Physics typically cannot answer "why"-questions very well.
Physics observes phenomena in the world, creates descriptions of the behaviour observed there, and postulates rules (physics laws) stating that under specific circumstances this very same behaviour will happen again.
So, the best answer that physics can give go along the line "because of a well-founded record of behaviours observed previously".
Inertia
We always observed that it takes some external effort ("force") to change an object's speed, and we call that concept "inertia". Think of a car. To accelerate, you need engine power, to decelerate, you use the brake. Physics found some formulas describing the numerical aspects of that concept.
Answer
A body has "inertia" because that's the best explanation we found so far to describe the effect that bodies have a tendency to keep their speed.

A: If you google it you can find several explanations for this, but I believe using the classical physics, we can clarify it intuitively and simply.
According to the Newton's first law, bodies tend to keep their velocities unchanged. Inertia typically refers to this phenomenon. You can check it by some experimental tests. Therefore, if you want to change their state of motion (i.e., velocities), you need to change their current state of energy by exerting force on each of its constituting particles. More mass is equivalent to more particles that are supposed to be affected by these changes of the energy state. This is why we see this resistance, i.e., inertia, in objects, especially for those with more mass.

A: @Eisenstein I suspect from some of your replies that @RKleberhoff is closer to the meaning of your question. I think your question is more metaphysical and ontological. The reference of @YKindaichi provides are what I would call descriptive answers of how rather than why. I think we sometimes confuse mathematics with why rather than the how it is. Sometimes people summarize this by saying "the map is not the terrritory".
I think all new physics begins in metaphysics and questions of ontology.
As @AKKassem notes, Einstein was also searching for something more ontological in the beginning in the form of Mach's Principle, but abandoned it eventually. I think physicists like Julian Barbour and Lee Smolin and others are getting closer to Einstein's initial approach, using a relational view of the universe that abandons the concept of a spacetime background. I think Leibniz also contributes to this view,
Einstein starts down this path by tying spacetime to matter. I think if anyone thinks about it for a while what we call space or our concept of volume can't possibly be "real" or "true" in any sense of the word. After all the ultimate paradox in a sense is the idea of a "big bang" "inflation" etc that demands some kind of expansion, but expanding into what? There is something and nothing, and you can't really expand into nothing. Volume and spacetime are probably some kind of relational perspective that just keeps changing of an initial something, but it can't possibly be getting bigger (increasing volume)  in any real sense of the word.
Lack of or presence of inertia, in this sense would be the manifestation of a preferred relational perspective, meaning easier to view things along one perspective and harder from another.

A: When no forces are acting on an object, it is either completely still or moving at a constant velocity at the same direction in a straight line. It is easy to think keeping an object at a constant velocity requires forces acting on it, but that is because we don't live in a vacuum


text:
Q: Is there a way to add comments in md5 file? I have a library of files. Each file has each own *.md5 file (created by Total Commander) with md5 hash and additional *.txt file with some comments.
Is there any way to move these comments from *.txt file to *.md5 file (and delete *.txt file) in a form of some internal block of comments (like using "rem" in Windows batch files or "<! --" and "-- >" in HTML) so I could still use *.md5 files to check the hashes?

A: Use # as a comment character.
The accepted answers suggesting ; works with Total Commander in Windows, but gives an error with GNU's md5sum, and probably also with other tools:

md5sum: WARNING: 1 line is improperly formatted

But both Total Commander and the standard md5sum accept the usual Unix comment character # instead. So use that.

Additional notes:
While Windows has traditionally been using ; as a comment character, particularly in it's older .ini files, Unix mostly uses # in it's shells and most scripting environments. (and Windows too now, in Powershell).
Since (arguably) most uses of md5 are on Unix machines where tools like md5 on Macs or md5sum on Linux come with the OS, the traditional # seems a bit safer.
Note also that TC on Windows accepts .md5 files with Unix "LF" line endings (or "/" as path separator), but the Unix tools cannot check md5 files using Windows "CRLF" line endings (or "\" in paths).
However, there is nothing about comments in the original RFC 1321, and there doesn't seem to be any official mention of using comments in .md5 files...

A: Any line beginning with ; in .md5 files is a comment.


text:
Q: Generator returning same value So I have this code:
def odds():
    number = 1

    while True:
        yield number
        number += 2

nums = odds()

for _ in range(100):
    print(next(nums))

and this one:
def odds():
    number = 1

    while True:
        yield number
        number += 2

for _ in range(100):
    print(next(odds()))

The first part, when run, returns 1, 3, 5 ..., but the second one: 1, 1, 1, 1..., just 1's. Why is that?
Note that the difference is that , in the second part, I didn't type nums = odds().


text:
Q: No keyboard output on terminal after running a script using read and whiptail I've written a bash function that accepts a command as an argument, runs it in the background, and allows the user to kill the command by pressing any key. This part works fine.
However, when I pipe it to a whiptail dialog gauge, the whiptail runs as expected, but after it returns, the terminal will no longer display keypresses. I can still run commands, I just don't see what I'm typing printed to the screen. The output is also formatted weirdly, where stdout appears after $.
I'm pretty sure the read command is responsible for this behavior, but I don't understand why. Can anyone offer any insight?
#!/bin/bash
function killOnKeypress() {
    local runcommand="${1}"
    local args=(${@:2})

    # Run the command in the background
    "${runcommand}" ${args[@]} &

    # Get the process id of $runcommand
    local pid=$!

    # Monitor $runcommand and listen for keypress in foreground
    while kill -0 "${pid}" >/dev/null 2>&1; do
        # If key pressed, kill $runcommand and return with code 1
        read -sr -n 1 -t 1 && kill "${pid}" && return 1
    done

    # Set $? to return code of $runcommand
    wait $pid

    # Return $runcommand's exit code
    return $?
}

function count100() {
    for ((i = 0; i < 100; i++)); do
        echo $i
        sleep .02
    done
}

killOnKeypress "count100" | whiptail \
    --gauge "Counting to 100" \
    16 56 \
    0

A: While this doesn't answer OP question, it can be useful for someone else landed here, looking for the fix/workaround.
As NickD in his comment pointed out, whiptail sets -echo (in my environment not just  echo).
To fix your script you can put
stty echo

at the end of it.
What your script (whiptail) changes you can see with 'stty -a' before and after your script is run.
Of course you can save the outputs to files and make it easier to spot the differences:
stty -a > good_terminal

run your script - your terminal is messed, reset it with 'reset' or 'tset' or 'stty sane' and run again 'stty' command, and diff after it:
stty -a > bad_terminal
diff good_terminal bad_terminal

A: It may be that whiptail leaves the terminal in a weird state. Try stty sane as the command  (you'll have to type it blind, so be careful). If that fixes the terminal, then that's probably the problem.


text:
Q: SQL - Converting data to DateTime intervals I'm looking for some elegant SQL code that will read this

and create this

when given a parameter of @interval (minutes integer), in this case 30 minute intervals.
The amount of time logged in, based on the first table needs to be calculated and put into the second table for each 30 minute interval.
RDMBS is MS SQL Server.
Thank you very much in advance.

A: In general, to assign a particular datetime value to a partition, it's simple date arithmetic:
declare @moment_in_time           datetime = current_timestamp
declare @today                    datetime = convert(date,@moment_in_time)
declare @bucket_length_in_seconds int      = 30 * 60
declare @buckets_per_day          int      = 24*60*60 / @bucket_length_in_seconds
declare @bucket_number            int      = datediff(second,@today,@moment_in_time)
                                           / @bucket_length_in_seconds
declare @bucket_start_time        datetime = dateadd(second,
                                               @bucket_length_in_seconds
                                               * ( datediff(second,@today,@moment_in_time)
                                                   /
                                                   @bucket_length_in_seconds
                                                 ) ,
                                               @today
                                               )

select moment_in_time    = @moment_in_time ,
       today             = @today ,
       buckets_per_day   = @buckets_per_day ,
       bucket_number     = @bucket_number ,
       bucket_start_time = @bucket_start_time

Exploding your source table into a row per bucket it covers is up to you. A hint: a sequence table consisting of a continuous sequence of integers ranging from, say, -1,000,000 to +1,000,000 comes in mighty useful sometimes.

A: Assuming that the input data is stored in a table called dbo.inputData then the following T-SQL will give you what you want (and could easily be improved upon!)
create table dbo.outputData
(
    StartDateTime datetime not null,
    EndDateTime datetime not null
);

-- Seed the table
declare @maxDate as datetime =  dateadd(hour, 1, (select max(LoggedOutDateTime) from inputData));
with myCte as
(
    -- Truncate the smallest date to the hour
    select dateadd(hour, datediff(hour,0, min(LoginDateTime)),0) as StartDateTime
    from dbo.inputData
    union all
    select dateadd(minute, 30, StartDateTime)
    from myCte
    where StartDateTime <= @maxDate
)

insert into dbo.outputData(StartDateTime,EndDateTime)
select StartDateTime, dateadd(minute,30,StartDateTime)
from myCte;

-- Now do the actual calculations stuff
with myCte2 as
(
select o.StartDateTime, o.EndDateTime, i.LoginDateTime, i.LoggedOutDateTime,
    case when i.LoggedOutDateTime > o.EndDateTime then o.EndDateTime else i.LoggedOutDateTime end as rangeEnd,
    case when i.LoginDateTime > o.StartDateTime then i.LoginDateTime else o.StartDateTime end as rangeStart
from dbo.outputData as o
inner join dbo.inputData as i
    on i.LoggedOutDateTime > o.StartDateTime and
        i.LoginDateTime < o.EndDateTime
)

select m.StartDateTime, m.EndDateTime, sum(DATEDIFF(SECOND,m.rangeStart, m.rangeEnd)) as secs
from myCte2 as m
group by m.StartDateTime, m.EndDateTime

A: (Date1 - date2)*24*60= your interval in minutes