text:
Q: Probability of Increasing Sequence of Die Rolls Remaining Increasing Context
I was talking with a friend about this simple problem and we couldn't figure it out easily. I spent a little while with paper and pen and googled a bit and checked previous questions but have not been successful finding a solution.  I think I am missing some language/terms.
Problem
Let $D_i$ be the $i$th outcome of a 20-sided die event. That is, $D_i\in[1,20]$. What is the probability that $D_1<D_2<D_3$ for three sequential die events?
Scratch Work
My pen & paper work thus far (I feel like I am abusing notation):
$P(D_1)=1$. $P(D_2>D_1)=\frac{20-D_1}{20}$. $P(D_3>D_2)=\frac{20-D_2}{20}$.
$P(D_1<D_2<D_3)=P(D_1)P(D_2>D_1)P(D_3>D_2)=(1)(\frac{20-D_1}{20})(\frac{20-D_2}{20})=1-\frac{D_1+D_2}{20}+\frac{D_1D_2}{400}$.
$D_1+D_2\in[2,40]$; $D_1D_2\stackrel{?}{\in}[1,400]$.
Closing
I know that I am doing something gravely wrong and I want to know what it is.  All help appreciated, especially generalizations.

A: Note that, if all three rolls are distinct, there is a $\frac{1}{3!}$ chance they come in increasing order (if they are not distinct, there is no chance). The probability of at least two of them matching is $3 \times \dfrac{1}{20} \times \dfrac{19}{20} + 20 \times \dfrac{1}{20^3}$ (splitting into cases where exactly 2 match and all 3 match). The desired probability is then $\dfrac{1}{6} \times \left( 1 - \left( 3 \times \dfrac{1}{20} \times \dfrac{19}{20} + 20 \times \dfrac{1}{20^3} \right) \right) = \boxed{\dfrac{57}{400}}$.

A: Hint: Partition over the middle value:
$$\begin{align}\mathsf P(D_1<D_2<D_3)&=\sum_{t=2}^{19}\mathsf P(D_1<t)\mathsf P(D_2=t)\mathsf P(D_3>t)\\[1ex]&=\sum_{t=2}^{19}\dfrac{(t-1)(20-t)}{20^3}\end{align}$$

A: $$ P(\mbox{Increasing}) = P(\mbox{Increasing}|\mbox{All distinct})P(\mbox{All distinct})$$
$$P(\mbox{All distinct})=\frac{20*19*18}{20*20*20}= \frac{19*9}{200}.$$
As argued above,
$$ P(\mbox{Increasing}|\mbox{All distinct}) = \frac{1}{3!}.$$
Therefore, the answer is $$ \frac{19*9}{200} \times \frac{1}{6} = \frac{57}{400}.$$


text:
Q: Countdown timer in javascript for each row of table in html     var count = Number(sessionStorage.getItem('count')) || 3600;

    var counter = setInterval(timer, 1000); //1000 will  run it every 1 second
    function timer() {
    count = count - 1;
    sessionStorage.setItem('count', count)
    if (count == -1) {
        clearInterval(counter);
        return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    var time_str = hours + ":h " + minutes + ":m " + seconds + ":s";
    //document.cookie = 'time_str = hours + ":h " + minutes + ":m " +     seconds + ":s"; expires=Thu, 26 March 20:47:11 UTC; path=/'

    Array.prototype.forEach.call(document.querySelectorAll('.timer'), function (el ) { el.innerHTML = time_str; });
}

Above is my javascript code for countdown timer. This works fine, but it doesn't stop after   "0h:0m:0s" time. it start counting in negative.

A: Here's a modified version of your code that works for me:
var count = 5;
var counter = setInterval(hockeytimer, 1000);

function hockeytimer() {
  count = count - 1;
  sessionStorage.setItem('count', count);

  if (count == -1) {
    clearInterval(counter);
    return;
  }

  var seconds = count % 60;
  var minutes = Math.floor(count / 60);
  var hours = Math.floor(minutes / 60);
  minutes %= 60;
  hours %= 60;

  if (hours === 0 && minutes === 0  && seconds === 0 ) {
    var table = document.getElementById("hockeyt");
    while (table.rows.length > 0 ) {
      table.deleteRow();
    }
  }

  var time_str = hours + ":h " + minutes + ":m " + seconds + ":s";

  var timerCells = document.querySelectorAll('.hockeytimer');

  for (var i = 0; i < timerCells.length; i++) {
    var timerCell = timerCells[i];
    timerCell.innerHTML = time_str;
  }
}

Demo: http://jsbin.com/ceboqi/1/edit?html,js,output

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xcode 6 constraints on different sizes I'm doing an iPhone app using Xcode 6
My problem here is, I add a constraint to an image, and all is fine, and than I try to add another constraint on a smaller screen and I get the error on the bottom of this message.
Is there any way of adding different constraints according to the size we are at? That is what it feels like on Xcode on the wAny hAny area, but for some reason it just doesn't work.

2014-10-06 17:41:45.059 testapp[2623:26567] Unable to simultaneously
  satisfy constraints.  Probably at least one of the constraints in the
  following list is one you don't want. Try this: (1) look at each
  constraint and try to figure out which you don't expect; (2) find the
  code that added the unwanted constraint or constraints and fix it.
  (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you
  don't understand, refer to the documentation for the UIView property
  translatesAutoresizingMaskIntoConstraints)  (
      "",
      "",
      "",
      "" )
Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints
  to catch this in the debugger. The methods in the
  UIConstraintBasedLayoutDebugging category on UIView listed in
   may also be helpful.

A: When a constraint receives  a negative value or the value that contradicts with other values, it spits an error. For instance:

*

*You have an image, that has height 500 and the constraint attached to it's bottom

*You modify this constraint such a way that the image gets smaller and smaller (constant value)

*Eventually image will have negative value, which is impossible. And the rest of the constraints will also "suffer"

Make sure that the height of the parent view is greater than the height of the image. Hopefully the example above will make you better understand the issue in general.


text:
Q: Got wrong date when converting string date retrieved from the api I'm calling an API to get some dates, but the API returns the date in string format so I'm using new Date() to convert it to date format, the problem is that after the conversion I'm getting a wrong date
For example new Date("2019-04-19") is returning Thu Apr 18 19:00:00 GMT-05:00 2019
this is my code
function HebrewCalAPI(fechas)
{
  var response = UrlFetchApp.fetch("https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3530597&m=50&s=on");

  var data = JSON.parse(response.getContentText());

  var arrayEmpiezan = []

  for(var i in fechas)
  {
    for(var i2 in data.items)
    {
      if(data.items[i2].title == fechas[i])
      {
        arrayEmpiezan.push(new Date(data.items[i2].date));
      }
    }
  }

  return arrayEmpiezan
}

var fiestasEmpiezan = ["Erev Pesach","Pesach VI (CH''M)","Erev Shavuot","Erev Rosh Hashana","Erev Yom Kippur","Erev Sukkot","Sukkot VII (Hoshana Raba)"]
var fiestasAcaban = ["Pesach II", "Pesach VIII","Shavuot II","Rosh Hashana II","Yom Kippur","Sukkot II","Simchat Torah"]

var FiestaEmpieza = date
var FiestaAcaba = date
FiestaEmpieza = HebrewCalAPI(fiestasEmpiezan)
FiestaAcaba = HebrewCalAPI(fiestasAcaban)

Any help please ?


text:
Q: What, how and when to use static formats, formats and format on custom blot? DESCRIPTION
I am trying to create an inline blot for text highlighting. I know this feature is already present in quill. But in my implementation I would like to assign a different value to the html element depending on the type of highlighting that was assigned. Here's what I got:
let Inline = Quill.import('blots/inline');

class TextHighlight extends Inline {
    static create(value) {
        let node = super.create();
        if(!value || value < 1) return node;

        if(value == 5){
            node.style.color = 'rgb(225, 225, 225)';
        }
        else {
            node.style.borderRadius = '2px';
            node.style.padding = '2px';

            if(value == 1){ node.style.background = 'rgb(254, 255, 171)'; }
            if(value == 2){ node.style.background = 'rgb(255, 171, 171)'; }
            if(value == 3){ node.style.background = 'rgb(171, 207, 255)'; }
            if(value == 4){ node.style.background = 'rgb(178, 255, 171)'; }
        }

        node.setAttribute('data-value' , value);
        return node;
    }

    formats() {
        console.log('#formats()');
        let result = this.domNode.getAttribute('data-value');
        return result ? result : 0;
    }
}

TextHighlight.blotName = 'texthighlight';
TextHighlight.tagName = 'span';

My remove/add function:
function highlightSelectedText(value) {
   if (value < 0 || value > 5) return false;

   var range = quill.getSelection();

   if (range && range.length > 0) {
      if (value > 0) {
         quill.formatText(
            range.index,
            range.length,
            'texthighlight',
            value,
            true);
      }
      else {
         quill.formatText(range.index, range.length, 'texthighlight', false, false);
      }
   }
}

And finally the creation of the Quill instance:
var toolbarOptions = {
    container: '#toolbar-container',
    handlers: {
        'texthighlight': function (value) {
            highlightSelectedText(value);
        }
    }
};

var quill = new Quill('#editor', {
    theme: 'bubble',
    modules: {
        toolbar: toolbarOptions
    }
});

The problems

*

*Highlighted text snippets have the following Delta:

...
{
   "attributes": {
      "0": "3"
   },
   "insert": "highlighted text"
},
...

"texthighlight" should appear instead of 0, like:
...
{
   "attributes": {
      "texthighlight": "3"
   },
   "insert": "highlighted text"
},
...

*If I apply formatting more than once, it starts accumulating, putting markup inside markup. For example:

The expected behavior is that only one highlight is present.

*I cannot remove the formatting.

CONCLUSION
There is no doubt that I lack knowledge about how to properly implement this. I was able to create simpler blots in other situations, but now I'm really getting confused about overriding certain blot methods. For example, the following list shows which methods I mean, and what I understand about each:

*

*static formats(node): Returns formats represented by domNode. Called on selection events when index is within formatted range.

*formats(): Returns formats represented by this Blot. It is used for Delta generation. Called on selection events when index is within formatted range.

*format(format , value): Applies formatting to this blot.

In the highlight implementation demonstrated, only formats() and create(value) are being called. I know there is an example of how each of these methods is implemented, but I am not getting the desired behavior. I think it's because I don't know how to exactly implement them. Could someone answer me what they really do, when they are called, and how they should behave (be implemented)?
Can somebody help me, please? :(

A: EDIT (Dec 18, 2019)
So... After hours of research, I was finally able to make the editor a little more correct. In this whole story I ended up creating a blot that is capable of formatting text with different styles depending on the value passed to formatting. You can even remove formatting by providing or omitting a value.
I was finally able to get an answer for item 2 and, as I thought, found it within the toolbar module. Regarding the formats methods and their differences, I think I could better understand it. I still don't understand why formats are called so often. I think I'll find the answer looking at quill core, but... The quill source code is very large as it involves multiple files.
I am putting here a more updated version of the code shown earlier. It is all commented, favoring anyone who wants to learn more about how to:

*

*Define custom blots/formats,

*Define blots that accept values, and behave in different ways
depending on the configured value.

*Define custom toolbar buttons that respond and reflect the state of the
editor content.

I hope that this will enable people to better understand how this tool can be used, and to create greater interest and contribution with it.
Full Example on GitHub
ORIGINAL ANSWER
It seems that I somehow managed to get the desired result. I am putting an answer here, but I do not consider it correct yet, as it is not complete. The desired result is obtained, but I'm still unable to understood how or why things work. Understanding the process becomes something fundamental, especially if and when the code needs to be changed in the future. Below you can check the code of the whole project. To test, just run it.
My remaining questions are:

*

*What are the differences between formats and static formats(domNode)? If you
observe code execution, they are called a few times, and static formats(domNode) are called twice. Is this normal? I do not know, that's why I am asking.

*Within function highlightSelectedText(hl), why does hl appear with
a false value? How does this happen?

*When formatting is applied, the create is used. When
it is removed, format(format, value) is called. There are snippets of code (inside format) that are never reached. Shouldn't applying
and removing formats be a format-only job? Why do I have to change
the DOM element in two different locations?

I think I can find the answer to number 2 by looking at the toolbar module source code. But I'm not quite sure. If I can figure it all out, I'll be back here to edit this answer, okay? I know others may also have the same questions.


text:
Q: Malfuctioning key for Š, Ď, Ň etc. on playonlinux-executed MS Office I am using Ubuntu 15.10 and MS Office installed and executed via playonlinux (problems both on 2007 and 2010 as well).
Everything works OK, the only problem is that the key used mainly for czech punctuation (marked red below) is dead. It has not any changed function, it just does nothing.

Why is that so? Is there any remedy?
The problem does not occur in LibreOffice, Gedit and so on.


text:
Q: Sending email in Java by using database I am currently doing a project where I am required to send an email to the specific address taken from database. However, the column "email" in database does not actually contain emails, but names instead. So in database there are full names in russian language like
"Иванов Александр" which is "Ivanov Alexandr". So when I type this name in the outlook it automatically finds his email: AIvanov@domainname.com. But in my java code when I use name "Иванов Александр" i keep getting error.
Here is my java code
File[] listOfFiles = outDir.listFiles();
    if (outDir.isDirectory()) {
        if (outDir.list().length > 0) {
            for (File file : listOfFiles) {
                    Session session_m = Session.getDefaultInstance(props, null);
                    MimeMessage message = new MimeMessage(session_m);
                    message.setFrom (new InternetAddress("mmm@domainname.com", "mmm@domainname.com"));
                    InternetAddress i = new InternetAddress("\""+email+"\"", false);
                    message.addRecipient(Message.RecipientType.TO, i);
                    message.setSubject("test");
                    message.setText("test");
                    message.setHeader("Content-Type","text/plain;charset=windows-1251");

                    MimeBodyPart mbp1 = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file);
                    mbp1.setDataHandler(new DataHandler(fds));
                    mbp1.setFileName(fds.getName());

                    Multipart mp = new MimeMultipart();
                    mp.addBodyPart(mbp1);

                    System.out.println("[EmailHandler] Attaching the following file to email: " + fds.getName());
                    message.setContent(mp);

                    SMTPTransport t = (SMTPTransport)session_m.getTransport("smtp");
                    t.connect("mail.domainname.com", "main@domainname.com", null);
                    System.out.println("[EmailHandler] Sending email... ");
                    t.sendMessage(message, message.getAllRecipients());
                    file.delete();
                    Thread.sleep(3000);
                }
            } else {
                System.out.println("[EmailHandler] Folder " + outDir.getName() + " is empty... nothing to attach");
            }
        } else {
            System.out.println("Folder not found... Check the path");
        }

In this code the String email is Иванов Александр.
And I kept getting this error
javax.mail.internet.AddressException: Local address contains control or whitespace in string ``Иванов Александр''
So would like to know the ways I can make this string go through.
Thank you.

A: The outlook uses its address book to map a name to one of the email. That is why it is working fine, if you manually try creating a new email and just put the name. Outlook simply do a lookup in the address book and find out the email address.
However, this is not the same with a java program. The program needs exact email address to send an email. Now there could be many ways to find out email address.
The simplest approach is to store the email address in one of the database table.
If the person is associated with the company's SMTP system/active directory; you could use java smtp API / active directory APIs to find out the email or alias (usually be the part of email id before @) and then create email id to be used into the program to send email.

A: You need to provide a valid mail address. If you are using a fixed structure for your mails just convert the name to latin characters and append @domain.com
If you are not using any rules for your mail adress creation then I suggest you to add an email field to the database
Don't know if this resolves your question though
Regards

A: Your program have to

*

*Validate e-mail.
It can be implemented using regular expression: Using a regular expression to validate an email address

*Get email from contact list when field contains only name. There are two library for working with outlook contacts:
Open source java library to read outlook emails, calendar etc


text:
Q: How to bring Firefox icon on the dash in Debian? I have downloaded the latest version of Firefox. Everytime I want to browse the Internet, I have to go to the Firefox folder and double-click on Firefox there. When I search for the browser in Debian, there are no results. How do I put a Firefox icon on the dash?
The desktop environment installed is GNOME 3.


text:
Q: COM interop dictionary used in C# I have a third party DLL i need to call from my C# program.
I have added the dll to the references in my project and VS2010 has generated an COM - interop wrapper dll. The interfaces and classes defined in the DLL are now available in my program and working as they should.
Now the problem are the methods which returns a "dictionary" consisting of a key value pair of an integer and a TSEnt object. In the DLL the return type are defined as VARIANT* and in the wrapper as "object".
The DLL dosn't include any dictionary interface.
The only interface i have found in C#, that I can successfully cast this returnvalue to is a IEnumerable. But fetching values from the returnvalue using a foreach statement only returns a int32, which is the key-part of the underlying key/value pair.
How do i get the value-part of this dictionary ?
I have tried to cast this to IDictionary, IDictionary< int, object >, Hashtable and many more but all with the same result ... cast error.
I guess the DLL is originally written in an early version of Visual Basic.
Please help ... The problem has haunted me for the last 2 weeks ...
Regards
Jesper Sandgaard
From the documentation:
Query(String ObjectType, String PropName, String Pattern)
Queries the repository for Objects of type ObjectType with the property PropName
that have the value Pattern. Returns a Dictionary object containing a list of TSEnt
objects that the repository returns. This list is keyed by the index of the elements
in the list starting from 0. Pattern can contain '*' as wildcard. If the Property
name is a Domained value, use the Display Value in the repository model.

From the DLL (ITypeLib Viewer):
[id(0x00000006), helpstring("method Query")]
HRESULT Query(
[in] BSTR Type,
[in] BSTR PropertyName,
[in] BSTR Pattern,
[out, retval] VARIANT* result);

Definition in VS:
[DispId(6)]
object Query(string Type, string PropertyName, string Pattern);

A: If memory serves me right it is Dictionary object from an old COM runtime scripting library: SCRRUN.dll Import COM-TLB into your project and
cast a variant that you are getting to that type.


text:
Q: Create view that filters by group Is it possible in SharePoint Online to have views based on the group the user is a member of? For example, if I assign user 1 to group A, and user 2 to group B, would it be possible for user 1 to see only tasks from a list that have a column that would match group A.
I tried creating a column that accepts "Person or Group", but I don't know how to filter a view for groups. I know that if we want to filter it for a user, we should put [Me]. Is audience targeting a solution? If so, how would I accomplish it?

A: The default view filter option doesn't allow filtering on [Group]. However, it might be accomplished by using SharePoint Designer.
You can check out this article.
The key is to add the [Where] clause to the View Filter Query (CAML)
<Membership Type="CurrentUserGroups">
    <FieldRef Name="AssignedTo"/>
</Membership>

For audience targeting, you can read here.


text:
Q: Run a task every minute in spring jpa but HikariPool shuts down i'm trying to run a task every minute in spring data jpa. I want to do it with annotations:
JpademoApplication.java
@SpringBootApplication
@EnableScheduling
public class JpademoApplication {

    public static void main(String[] args) {
        try (var context = SpringApplication.run(JpademoApplication.class, args)) {
            var app = context.getBean(RunEveryMinute.class);
            app.run();
        }
    }
}

And my class with the method which i want to run every minute:
@Component
public class RunEveryMinute {

    private static final Logger log = LoggerFactory.getLogger(RunEveryMinute.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 60000)
    public void run() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

pom.xml
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

It is working but the problem is, after that my HikariPool shutting down so it do it only one time instead every minute:
2020-01-31 09:34:47.479  INFO 27966 --- [           main] com.example.jpademo.JpademoApplication   : Starting JpademoApplication on edv-vm with PID 27966 (/home/.../Downloads/jpademo/target/classes started by ...in /home/.../Downloads/jpademo)
2020-01-31 09:34:47.483  INFO 27966 --- [           main] com.example.jpademo.JpademoApplication   : No active profile set, falling back to default profiles: default
2020-01-31 09:34:48.127  INFO 27966 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-01-31 09:34:48.153  INFO 27966 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 16ms. Found 0 JPA repository interfaces.
2020-01-31 09:34:48.679  INFO 27966 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-01-31 09:34:49.144  INFO 27966 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-01-31 09:34:49.280  INFO 27966 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-01-31 09:34:49.374  INFO 27966 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.10.Final}
2020-01-31 09:34:49.604  INFO 27966 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-01-31 09:34:49.742  INFO 27966 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-01-31 09:34:49.975  INFO 27966 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-01-31 09:34:49.984  INFO 27966 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-01-31 09:34:50.083  INFO 27966 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
2020-01-31 09:34:50.107  INFO 27966 --- [   scheduling-1] com.example.jpademo.ScheduledTasks       : The time is now 09:34:50
2020-01-31 09:34:50.112  INFO 27966 --- [           main] com.example.jpademo.JpademoApplication   : Started JpademoApplication in 3.487 seconds (JVM running for 5.109)
2020-01-31 09:34:50.113  INFO 27966 --- [           main] com.example.jpademo.ScheduledTasks       : The time is now 09:34:50
2020-01-31 09:34:50.115  INFO 27966 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'
2020-01-31 09:34:50.116  INFO 27966 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-01-31 09:34:50.116  INFO 27966 --- [           main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-01-31 09:34:50.120  INFO 27966 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-01-31 09:34:50.136  INFO 27966 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0

Can anybody helped out with that ?

A: It seems, that your app is closed immediately after invoking of main method. (So, answer by miiiii is correct).
Do you have a web app?
If yes - then you can add
<dependency>
    <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

dependency. This dependnecy contains servlet container which prevents app to shutdown.
Or use answer from miiiii
Also note, that you don't need to call JpademoApplication.run manually - spring does it automatically.
So, if you add web starter - your main method should like
  public static void main(String[] args) {
        SpringApplication.run(JpademoApplication.class, args));
    }

If your application isn't web application - you need to prevent closing, you can use the following code for that:
public static void main(String[] args) {
        SpringApplication.run(JpademoApplication.class, args));
        Thread.currentThread().join();
    }

A: Your main method is not working as expected. You should change the main method to the following:
@SpringBootApplication
@EnableScheduling
public class JpademoApplication {

    public static void main(String[] args) {
        SpringApplication.run(JpademoApplication.class, args);
    }

}

The spring context will automatically look up all @Component annotated classes and runs the methods which are annotated with @Scheduled. No need for any ohter configuration in your main class.
BTW: All @Scheduled methods run in an own thread. For Database actions you should annotate the methods with @Transactional for an own session.

A: In Application.properties
spring.main.lazy-initialization=true
is stopping the execution of @Scheduled() Methods.
Solution: @Lazy(false)
Example:
@Component
@Lazy(false)
public class RunEveryMinute {

    private static final Logger log = LoggerFactory.getLogger(RunEveryMinute.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 60000)
    public void run() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}


text:
Q: Morphism between quotients of a ring by ideals. Let $I, J$ be ideals of a ring $R$ and $I \subset J$. Is there a homomorphism from $R/I$ to $R/J$? I check that $x + I \mapsto x+J$ satisfies the conditions of a homomorphism. I think that $R/J \to R/I$, $x+J \mapsto x+I$ does not define a homomorphism. Is this correct? Thank you very much.

A: Well, in general there are several such homomorphisms. However, if we let $\eta_I:R\to R/I$ and $\eta_J:R\to R/I$ be the respective quotient morphisms, then there is a unique homomorphism $\kappa:R/I\to R/J$ such that $$\eta_J=\kappa\circ\eta_I$$
In fact we can say something more general. Let $\eta:R\to R/I$ be the quotient map and let $f:R\to S$ be any other morphism such that $I\subseteq \text{ker}(f)$. Then there is a unique lift $\tilde f:R/I\to S$ such that $f=\tilde f\circ\eta$.
To prove this assertion, observe first that $\eta$ is surjective, so for each $q\in R/I$ there is at least one $r\in R$ such that $q=\eta(r)$. So $\tilde f(q)$ must be $f(r)$. It follows that $\tilde f$ is unique where it exists.
It remains to show that there is in fact such $\tilde f$. Let $\chi$ return for each element of $R/I$ an element of $R$ such that $\eta(\chi(q))=q$. Note that $\chi$ is a function of the underlying sets, as opposed to a homomorphism of rings. The existence of such $\chi$ is guaranteed by the surjectivity of $\eta$ and AoC. We claim that $\tilde f:q\mapsto f(\chi(q))$ defines a ring morphism.
Firstly, $\chi(0)\in \text{ker}(\eta)\iff \chi(0)\in I\implies \chi(0)\in \text{ker}(f)$, so $\tilde f$ preserves the additive identity. Likewise, $\chi(1)-1\in \text{ker}(\eta)\implies \chi(1)-1\in \text{ker}(f)$, so $\tilde f$ preserves the multiplicative identity as well. Furthermore, for any two $q_1,q_2\in R/I$, $$\chi(q_1+q_2)-\left(\chi(q_1)+\chi(q_2)\right)\in \text{ker}(\eta)\implies \chi(q_1+q_2)-\left(\chi(q_1)+\chi(q_2)\right)\in \text{ker}(f)$$ And $$\chi(q_1q_2)-\chi(q_1)\chi(q_2)\in \text{ker}(\eta)\implies \chi(q_1q_2)-\left(\chi(q_1)\chi(q_2)\right)\in \text{ker}(f)$$ So $\tilde f$ is additive, multiplicative, and thus a ring homomorphism $\blacksquare$

A: There always is a homomorphism $R/I\to R/J$, when $I\subset J$. Indeed, $I$ is contained in the kernel of the canonical projection $R\to R/J$, so the homomorphism theorems provide a homomorphism $R/I\to R/J$ (which is exactly $x+I\mapsto x+J$).
There can be homomorphisms $R/J\to R/I$.
Example: let $F$ be a field and take

*

*$R=F[x,y]$

*$I=(y)$

*$J=(x,y)$
Then $R/J\cong F$, $R/I\cong F[x]$ and there is a homomorphism $F\to F[x]$ (it is not $x+J\mapsto x+I$, of course).
In other cases this doesn't happen. If $R=\mathbb{Z}$, $I=4\mathbb{Z}$, $J=2\mathbb{Z}$. Then there is no ring homomorphism $R/J\to R/I$.
This happens in more generally in $\mathbb{Z}$: if $I=n\mathbb{Z}$ and $J=m\mathbb{Z}$, then there exists a homomorphism $\mathbb{Z}/m\mathbb{Z}\to\mathbb{Z}/n\mathbb{Z}$ if and only if $n\mid m$.


text:
Q: Sorting CFQuery Results by Month Some Backround:
ColdFusion9
MSAccess Database
I am trying to create a CFChart to compare data in a table labeled closed_tickets. I am comparing this year's data to previous year's data and would like to chart it by month.
I am querying the table and grabbing all data between the dates of 1/1/2012 and 12/31/2013, basically all of this year and last year. Here is that query.

<CFSET previous_year = #CREATEODBCDATETIME("1/1/2012")#>
<CFSET this_year = #CREATEODBCDATETIME("1/1/2013")#>

<cfoutput>
<cfquery name="get_closed_tickets" datasource="#datasource#">
select *
from closed_tickets
where closed_date >= #previous_year#
</cfquery>
</cfoutput>

<cfoutput>
Total Records:#get_closed_tickets.recordcount#

</cfoutput>

Then I perform a query of queries to spit the data into 2 years, this year and previous year:

<cfoutput>
<cfquery name="previous_year" dbtype="query">
select *
from get_closed_tickets
where closed_date >= #previous_year# AND closed_date < #this_year#
</cfquery>
</cfoutput>

<cfoutput>
<cfquery name="this_year" dbtype="query">
select *
from get_closed_tickets
where closed_date >= #this_year#
</cfquery>
</cfoutput>

2012 Records:<cfoutput>#previous_year.recordcount#</cfoutput>

2013 Records:<cfoutput>#this_year.recordcount#</cfoutput>

My question is, I'd like to take this data and chart it using CFChart to compare the data from each year, by month. Ideally I'd like the have a chart that would compare January2012 next to January2013 and so on, for each month of the year.
How can this be done?
Thanks,
Brian

A: Why won't you use SQL "group by"?
It should be something like this:
select count(tickets), closed_date
from   get_closed_tickets
where  closed_date >= #previous_year#
and    closed_date < #this_year#
group by closed_date

Another important thing. You shouldn't use select * in your queries. Always use columns names. It will increase performance if you don't actually need all of the columns in the database table.


text:
Q: How to delete an object from an array in MongoDB trouble with query I have a mongoDB database set up and I am trying to delete an object from an array of objects. Im having a hard time trying to query and successfully delete, any info is appreciated.
The function in my server in Node.js
    let id = req.session.user._id;
    let pokemon = req.body.name;
    let amount = req.body.amount;
    let cost = parseInt(req.body.cost);

    userModel.findOneAndUpdate(
        {
            _id: id,
        },
        {
            $push: {
                cart: {
                    pokemon: pokemon,
                    quantity: amount,
                    price: cost
                },
            },
        },
        (err, data) => {
        }
    );
});

the Hierarchy in my database
database heirarchy


text:
Q: Saving values from recordset I am getting the values by getfieldvalue function from access db. I need to save bunch of those values and then do the calculation with those values. What's the best way ?
Thanks for help. If there is some info missing please let me know. I'll try to provide.
Thank You again
CRecordset rset(&pdatabase);

        if(rset.Open(CRecordset::forwardOnly, selectionStr))
        {
            while(rset.IsBOF()&&rset.IsEOF())
            {
                m_Log->Log("Copying Previous Values from Access DB");
                rset.GetFieldValue((short)0 ,pname_old);
                rset.GetFieldValue((short)1 ,Date_old);
                rset.GetFieldValue((short)2 ,Time_old);
                rset.GetFieldValue((short)3 ,Y_old));
                rset.GetFieldValue((short)4 ,QTime_old);

            }

            rset.MoveNext();
        }

A: You could use a tool from the stl, like std::vector or std::list to handle your datas while getting them, and treat them after your collection.


text:
Q: Running Hyper-V and VMWare together I have two virtualization software on one of my laptops which is dedicated to Windows 8 development.
A VMWare for generic virtualization and the Windows 8 like Hyper-V for the WP8 SDK.
Unfortunately these softwares don't like each other.
Is there a way to get them play along?
The exact problem is that if I install the SDK, VMWare won't even update or run.
There is only one way to make them work. Switch Hyper-V on and off. Which is one restart all the time.

A: Here's how you do it:
Windows Phone 8 SDK on a Virtual Machine with Working Emulator
This assumes that you want to run Hyper-V within VMware. Apparently VMware, using its binary translation thingamajig, can completely virtualise an x86 CPU, although slowly.
I don't think you can run run VMware in a Hyper-V VM (which is what Windows is when Hyper-V is installed and you haven't modified the boot menu).
However, you can modify the boot menu, boot into Windows without Hyper-V and run VMware that way.
Update: Found the site that explains how to do that.

A: From the VMWare Workstation 9 Release notes:

Nested Virtualization
Workstation 9 improves the implementation of virtual Intel VT-x/EPT or
  AMD-V/RVI extensions. This allows users to run ESX as a guest OS and
  run a 64-bit operating system nested in ESX using less system
  resources.
Note: If you enabled the virtualization extensions in a virtual
  machine running on Workstation 8, you might need to disable the
  extensions, upgrade the virtual machine to the latest virtual hardware
  version (compatible with Workstation 9), and then re-enable the
  extensions.
Hyper-V
Hyper-V has been added to the Workstation 9 guest operating system
  list. This enables customers to run Windows 8 with Hyper-V enabled, or
  install Hyper-V Server. This can be used for educational purposes or
  for building prototype Hybrid Clouds. This feature is NOT SUPPORTED
  and probably never will be. Microsoft does not support nesting of
  their hypervisor which makes it extremely difficult - if not
  impossible for VMware to fix issues that may occur in this
  configuration. For this reason, this capability has been implemented
  purely to see if we could do it!
CAUTION: DO NOT ATTEMPT TO RUN HYPER-V ON A VIRTUAL MACHINE IN
  PRODUCTION.

A: VMWare and Hyper-V are both implementations of a software construct known as a hypervisor. Modern computer hardware has special optimization features for hypervisors to support improved performance. These are special circuits built into the cpu and motherboard of your computer.
Modern hypervisor software, such as VMWare and Hyper-V, depend and rely on this special hardware. If one system is using that hardware, the other cannot.
In short, there is no way to use both VMWare and Hyper-V at the same time.


text:
Q: How to select a contact address from Whatsapp using Whatsapp's native contact picker? I'm trying to select the Whatsapp address of a contact from my app, but given the fact that my app is a util for Whatsapp I want users to keep engaged with the native way of selecting a contact, that way
they won't have to get used to a new way of doing things which is annoying for most of us.
I've done some research and I'm aware of links like Send text to specific contact (whatsapp), Sending message through WhatsApp,
and some other questions and answers in the site, but they don't use the Whatsapp's contact picker.
Hope you can help.

A: After playing around for a long while I realized that we can launch the Whatsapp's contact picker activity and receive the results back, but not in the returned uri (the way Android contact picker does) but as an extra.
I've come up with the following solution.
To start the Whatsapp's native contact picker we call the following code from our activity:
Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setPackage("com.whatsapp");
    try{
        startActivityForResult(intent, REQUEST_CODE_PICK_WHATSAPP);
    } catch (Exception e) {
        Toast.makeText(MainActivity.this, R.string.notif_no_whatsapp, Toast.LENGTH_SHORT).show();  //no activity found to handle this intent means whatsapp is not installed
    }

Then, inside activity's onActivityResult(...) method:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    switch (requestCode) {
    case REQUEST_CODE_PICK_WHATSAPP:
        if(resultCode == RESULT_OK){
            if(intent.hasExtra("contact")){
                String address = intent.getStringExtra("contact");
                Log.d(TAG, "The selected Whatsapp address is: "+address);
            }
        }
        break;

    default:
        break;
    }
}

Hope it contributes to make more apps that integrate with Whatsapp seamlessly.


text:
Q: How will migrating from .Net 3.5 to 4.0 affect my WCF components? From your own personal experience, how much of an impact will migrating to .Net 4 have on my existing WCF components?
Is there a big risk that I may need to re-write a lot of code?

A: I was worried about the same thing- we have a large system with about 50 services/contracts across several bindings with some complex config and custom bindings/behaviors. I migrated the whole thing over to 4.0b2 and ran everything with no problems whatsoever. They've done a really good job of preserving backward compatibility where things have changed. I haven't seen a list of breaking changes from 3.5 to 4.0 yet (only between betas), but I'm sure they'll publish one at release.
Good luck!


text:
Q: looping over dataframes...and why this is the wrong approach Let's say I have several dataframes and I want to loop through the rows of each dataframe and do something, like send an SMS message using the httr package. I could create several loops, but I suspect the answer is "don't use loops!".
df1 <- data.frame(A=1:10, B=2:11, C=3:12) # imagine these columns hold words and phone numbers
df2 <- data.frame(A=4:13, B=5:14, C=6:15)

# loop for df1
for (n in 1:nrow(df1)) { # imagine that each row is a person
  # get details for each person (row)
  sms1 <- df1$A[n]
  sms2 <- df1$B[n]
  sms3 <- df1$C[n]
  # create personalized message to send
  sms <- paste(sms1, sms2, sms3, sep=" ")
  # here I would use the POST() function of httr to send a personalized SMS to each person, but that is not important
}

# loop for df2
for (n in 1:nrow(df1)) {
  sms1 <- df2$A[n]
  sms2 <- df2$B[n]
  sms3 <- df2$C[n]
  sms <- paste(sms1, sms2, sms3, sep=" ")
  # here I would use the POST() function of httr to send a personalized SMS, but that is not important
}

But what I really want to do is create an outer loop to loop through each dataframe. Something like:
dfs <- c("df1", "df2")
# loop over dfs
for (d in dfs) {
  for (n in 1:nrow(d)) {
    sms1 <- d$A[n]
    sms2 <- d$B[n]
    sms3 <- d$C[n]
    sms <- paste(sms1, sms2, sms3, sep=" ")
    # here I would use the POST() function of httr to send a personalized SMS, but that is not important
  }
}

But I know this will not work. My d in sms1 <- d$A[n] will not be read as sms1 <- df1$A[n] or sms1 <- df2$A[n].
Is there a way to do this loop? Better yet, what is the correct apply method?
Update:
Here is an example of the POST step I need to do to every row in both dataframes to send a personalized message to every person (row):
# let's say that sms3 in my example is a phone number
# let's also say that I define the following objects once outside of the loop:
  # url, username, password, account, source, network

# when I paste together the following objects, I get string that is formatted for my API gateway.
send <- paste0(url, username, password, account, source, sms3,
                 sms, network)
POST(send)

This would go in the loop as mentioned in comments from my original post:
# remove these paste steps from the loops as recommended in the answers
df1$sms <- paste(df2$A, df2$B)
df2$sms <- paste(df2$A, df2$B)

dfs <- c("df1", "df2")

# loop over dfs
for (d in dfs) {
  for (n in 1:nrow(d)) {
    sms3 <- d$C[n] # to get phone number
    send <- paste0(url, username, password, account, source, sms3, sms, network)
    POST(send)
  }
}

A: You don't need to loop through each row to paste elements together. Instead, you can just call paste once for each data frame:
df1$sms <- paste(df1$A, df1$B, df1$C)

You can then take this and create df1$send by calling paste again, or you can just use one paste, depending on your specific needs.
Now that you have everything you need in df1$send, you can just call POST on each element. POST is not vectorized, so you do have to iterate over the elements somehow. For example:
sapply(df1$send, POST)

You could do this again for df2, but another way would be to create a list of data frames, and loop over that, doing the same paste operation for each data frame. For example:
my.dfs <- list(df1, df2)
for (df in my.dfs) {
  df$sms <- paste(df$A, df$B, df$C)
  ...
  sapply(df$send, POST)
}

(You could also loop over characters strings of names, like you did originally, and then get the actual object corresponding to each string: df <- get(d). But I see no reason here to prefer this.)
An even better way would to be to just combine df1 and df2 into a single data frame. You can create a column to distinguish the two groups. Then you'll only have to paste and POST on one data frame:
comprehensive.df$sms <- paste(comprehensive.df$A, comprehensive.df$B, comprehensive.df$C)
...
sapply(comprehensive.df$send, POST)

How you do this depends on how different your data frames are. If they are only slightly different, you could use rbind.fill from plyr, which handles missing columns. If they have different column names, etc., you could extract the common columns and do some renaming. I just think that if you do cleaning and combining before you get to the meat of the operation, what you're doing will be clearer.
It's okay to use for loops. In fact, if you look at the source for apply, you'll see that it makes use of for loops. The real gain comes not from using apply, but from taking advantage of vectorization by passing whole objects to functions, as is done above with paste. This is more readable (because it's a single, straightforward line) and will probably perform better (because you're only calling the function once).

A: Just rbind your data.frames instead of looping:
df <- rbind(df1, df2)
df$sms <- paste(df$A, df$B, df$C)


text:
Q: How efficient is the derived Eq instance in GHC? Is there a short circuit built in to GHC's (and Haskell's in general) derived Eq instance that will fire when I compare the same instance of a data type?
-- will this fire?
let same = complex == complex

My plan is to read in a lazy datastructure (let's say a tree), change some values and then compare the old and the new version to create a diff that will then be written back to the file.
If there would be a short circuit built in then the compare step would break as soon as it finds that the new structure is referencing old values. At the same time this wouldn't read in more than necessary from the file in the first place.
I know I'm not supposed to worry about references in Haskell but this seems to be a nice way to handle lazy file changes. If there is no shortcircuit builtin, would there be a way to implement this? Suggestions on different schemes welcome.

A: StableNames are specifically designed to solve problems like yours.
Note that StableNames can only be created in the IO monad. So you have two choices: either create your objects in the IO monad, or use unsafePerformIO in your (==) implementation (which is more or less fine in this situation).
But I should stress that it is possible to do this in a totally safe way (without unsafe* functions): only creation of stable names should happen in IO; after that, you may compare them in a totally pure way.
E.g.
data SNWrapper a = SNW !a !(StableName a)

snwrap :: a -> IO (SNWrapper a)
snwrap a = SNW a <$> makeStableName a

instance Eq a => Eq (SNWrapper a) where
  (SNW a sna) (SNW b snb) = sna == snb || a == b

Notice that if stable name comparison says "no", you still need to perform full value comparison to get a definitive answer.
In my experience that worked pretty well when you have lots of sharing and for some reason are not willing to use other methods to indicate sharing.
(Speaking of other methods, you could, for example, replace the IO monad with a State Integer monad and generate unique integers in that monad as an equivalent of "stable names".)
Another trick is, if you have a recursive data structure, make the recursion go through SNWrapper. E.g. instead of
data Tree a = Bin (Tree a) (Tree a) | Leaf a
type WrappedTree a = SNWrapper (Tree a)

use
data Tree a = Bin (WrappedTree a) (WrappedTree a) | Leaf a
type WrappedTree a = SNWrapper (Tree a)

This way, even if short-circuiting doesn't fire at the topmost layer, it might fire somewhere in the middle and still save you some work.

A: There's no short-circuiting when both arguments of (==) are the same object. The derived Eq instance will do a structural comparison, and in the case of equality, of course needs to traverse the entire structure. You can build in a possible shortcut yourself using
GHC.Prim.reallyUnsafePtrEquality# :: a -> a -> GHC.Prim.Int#

but that will in fact fire only rarely:
Prelude GHC.Base> let x = "foo"
Prelude GHC.Base> I# (reallyUnsafePtrEquality# x x)
1
Prelude GHC.Base> I# (reallyUnsafePtrEquality# True True)
1
Prelude GHC.Base> I# (reallyUnsafePtrEquality# 3 3)
0
Prelude GHC.Base> I# (reallyUnsafePtrEquality# (3 :: Int) 3)
0

And if you read a structure from file, it will certainly not find it the same object as one that was already in memory.
You can use rewrite rules to avoid the comparison of lexically identical objects
module Equal where

{-# RULES
"==/same"  forall x. x == x = True
  #-}

main :: IO ()
main = let x = [1 :: Int .. 10] in print (x == x)

which leads to
$ ghc -O -ddump-rule-firings Equal.hs
[1 of 1] Compiling Equal            ( Equal.hs, Equal.o )
Rule fired: Class op enumFromTo
Rule fired: ==/same
Rule fired: Class op show

the rule firing (note: it didn't fire with let x = "foo", but with user-defined types, it should).


text:
Q: Get $.post to Return a View I have a view in ASP.NET MVC 5, on which a user types in some data and I am going to send that data to my controller in C#, and then send the user to the next view. The current code I have is as follows:

Javascript:
function goToNextQuestion(output) {
    $.post("submitUserAnswer", { userOutput: output }, doStuff(), String);
}

function doStuff() {
    alert("doing");
}

C#:
[HttpPost]
public ActionResult submitUserAnswer(String userOutput)
    {
        //store userOutput
        return View("Index");
    }

My alert is popping up, so I assume the $.post is working.....but the view isn't changing to "Index" (yes, "Index" is a valid view). And submitUserAnswer is a valid path I believe, I am not getting a 404 error. Does anyone know 1) what is going wrong and 2) how can I fix what I have or do something differently to get my view to display?

A: TRY DOING THIS
function goToNextQuestion(output) {
doStuff();
var url = '@Url.Content("~/ControllerName/submitUserAnswer?userOutput=")' + output;
window.location.href = url;
}

function doStuff() {
alert("doing");
}

And you dont need [HttpPost] in the controller
public ActionResult submitUserAnswer(String userOutput)
{
    //store userOutput
    return View("Index");
}

A: UseRedirectToAction() method instead of the View() method.


text:
Q: Where to use =like operator? Difference between like and =like? Where to use like and =like operators in openerp. What is the difference between these two?
I want use =like in an openerp method for string matching. Can I do this?

A: If you don't use the = operator, the result will be the given string with [prefixes] and/or [suffixes]. For example:
Domain with like:
[('name', 'like', 'tangaraj')]

This domain will give you records whose name is tangaraj, tangaraja, anyprefixtangarajanysuffix, etc... but it will not give you Tangaraj, because it distinguishes between uppercase and lowercase.
Domain with =like:
[('name', '=like', 'tangaraj')]

This one will give you only records whose name is tangaraj, as the = operator will do.


text:
Q: python datetime does not update on ubuntu I am having the following code on ubuntu as part of a django applicaiton that is deployed using gunicorn.
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
start = now.replace(hour=14,minute=0,second=0,microsecond=0)
end = now.replace(hour=16,minute=0,second=0,microsecond=0)
day1 = datetime.datetime(year, month, day)
day1 = day1.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc)
if day1.weekday() != 0:
    # Make day1 == Weekday 0 == Monday
    day1 = day1 - timedelta(days=day1.weekday())
day2 = day1 + timedelta(days=1)
day3 = day1 + timedelta(days=2)
day4 = day1 + timedelta(days=3)
day5 = day1 + timedelta(days=4)
day6 = day1 + timedelta(days=5)
day7 = day1 + timedelta(days=6)
day8 = day1 + timedelta(days=7)
day9 = day1 + timedelta(days=8)
day10 = day1 + timedelta(days=9)

Meaning that on Monday automatically day1 should be reset to the next week, e.g. from Mo, 21th June to Mo, 28th June. But it is not happening and I always have to restart my server/gunicorn process... any ideas on how to fix this?
Thank you.


text:
Q: How can I select all the data from a table with condition? I am new to android programming and I am having trouble with queries. I tried to search for similar questions but I found nothing :) so, here..
given this patientinfo table
patient_id | name | gender | age
      1    | jen  | female | 20
      2    | jay  |  male  | 19

and records table
patient_id |   date   | description
      1    | 01-01-14 | healthy!
      1    | 02-01-14 | healthy!
      2    | 01-01-14 | needs medication.

I'd like to get all the records of a certain patient.
like for example, if I choose patient1.. all records of patient1 will be displayed.
this is my query..
$query = "SELECT * FROM records INNER JOIN patientinfo ON records.patient_id = patientinfo.patient_id WHERE records.patient_id = $patient_id";

try{
    $stmt = $dbname->prepare($query);
    $result = $stmt->execute();

}catch(PDOException $ex){
        $response["success"] = 0;
        $response["message"] = $ex;

        die(json_encode($response));
    }

but it gives me an error in sql syntax, I think it's in the $patient_id

errorInfo: You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use.

Thank you in advance! hoping for an answer! Thanks :)

A: Try by:
SELECT *
FROM patientinfo, records
WHERE (patientinfo.patient_id = $patient_id) AND (patientinfo.patient_id = records.patient_id);

You may also specifically list the columns to show, and assign them an alias, for instance:
SELECT records.date AS the_date

The WHERE records.patient_id = $patient_id seems ok as long as $patient_id is not an empty string. For that, I'd echo the query prior to executing it and checking whether it's ok.


text:
Q: Web socket disconnect after handshake? after some modification, this is the converstion beween my chrome client and java server:
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:4444
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: Gh/WYxZXrUNZdPc2+LQ/Tg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Sent text to CLIENT_1
-------------Response to handshake------------
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: NmkE36ZEsC5baQaMjLPb5CxHwDM=

the handshake reply is give by:
public static String Key(String thekey) throws NoSuchAlgorithmException {
    String base64;

    thekey = thekey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] digest = md.digest(thekey.getBytes()); // Missing charset
    base64 = Base64.encodeBase64URLSafeString(digest);
    base64=base64.replace("_", "/");
    base64=base64.replace("-", "+");
    return new String(base64);
}
 Send("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + Key(key) +"=\r\n\r\n");

I can then send 10 bytes of data, then the client disconnects.
What can I do?
Thanks in advance!
Smollett.


text:
Q: Как скачать в папку на пк фото из Telegram бота?(Python) Пишу бота с использованием библиотеки pyTelegramBotAPI. Есть задача скачать фото без сжатия(как я понимаю вариант в логе номер 3). Как это сделать в питоне 3?
Такой код не работает:
@bot.message_handler(content_types=['photo'])
        def Zagruzka_informazii(massage):
            file_info = bot.get_file(massage.photo[len(massage.photo) - 1].file_id)

            downloaded_file = bot.download_file(file_info.file_path)
            src = 'C:\Bot\ ' + file_info.file_path;
            with open(src, 'wb') as new_file:
                new_file.write(downloaded_file)
            bot.reply_to(massage, "Фото добавлено")

Ошибка:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Bot\\ photos/file_0.jpg'


text:
Q: Apache pig query to join two schemas For example,
  relation1: {a: chararray, b: chararray}
  (1, abc)
  (2, asd)
  relation2: {a: chararray, c: chararray}
  (1, 2.5)
  (2, 4.0)

The question is:
Is it possible to get a resultant relation with schema as below:
For example: number of tuples in realtion1 is 2 and number of tuples in relation2 is 2. The number of tuples in resultant relation should also be 2 only.
  relation3: {a: chararray, b: chararray, c: chararray}
  (1, abc, 2.5)
  (2, asd, 4.0)

Could any one help to solve this.

A: joined = JOIN relation1 BY a, relation2 BY a;
describe joined;
-- joined: {relation1::a: chararray,relation1::b: chararray,relation2::a: chararray,relation2::c: chararray}
relation3 = FOREACH joined GENERATE relation1::a AS a, b, c;
describe relation3;
-- relation3: {a: chararray, b: chararray, c: chararray}

The '::' is called the disambugate operator and used to deconflict schemas after certain operations (such as a join). After a join all of the values from each alias are still present and you can pull them out using a FOREACH.


text:
Q: I tried to run QGIS using python but I couldn't get any output on screen? uri ="C:/Users/rajagopalv/Desktop/poi_sunnyvale.csvdelimiter=%s&xField=%s&yField=%s" % ("|", "x", "y")

vlayer = QgsVectorLayer(uri, "address_sunny", "delimitedtext")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

This my code as per the http://docs.qgis.org/ but I couldn't get the output layer on the screen.

A: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html
If you looked here, there is "?" between name of file and "delimiter".
Hope it helps.


text:
Q: How to populate a Pandas dataframe with this csv data? Alright, very new to pandas but need to get data from this csv https://www.kaggle.com/datasnaek/mbti-type  into a new Pandas dataframe.
The csv is structured like this:
type                posts

intj "hello world ||| http://linkhere ||| blah blah |||"
entj "hello world ||| http://linkhere ||| blah blah |||"
entj "hello world ||| http://linkhere ||| blah blah |||"
estj "hello world ||| http://linkhere ||| blah blah |||"
intp "hello world ||| http://linkhere ||| blah blah |||"

There are 16 types (type1 - type16) that are repeated for upwards of 8000 entries and each item in posts is a string that, if split at ||| would be an array of 50 strings.
I also need to REMOVE any of these 50 strings per each posts item that contain "http"
What I need is:
target   type    post
1      intj    "hello world shdjd"
2      entp    "hello world fddf"
16     estj   "hello world dsd"
4      esfp    "hello world sfs"
1      intj    "hello world ddfd"

Where each type (because in the csv, types are NOT labeled type1 through type16 but have other names) is matched with its target (an integer identifying it 1-16), and each post that was split after each ||| from each posts item gets its own row.
I have looked at https://www.geeksforgeeks.org/split-a-text-column-into-two-columns-in-pandas-dataframe/ and similar, but am getting very strange results.
How can I make this new dataframe?
EDIT: Ok, now I have each posts item as an array split at the ||| with:
mbtiData.posts.str.split('\|\|\|', expand=True)

but dont know how to put these back in the dataframe.

A: Assume that your input file contains:
type                posts

intj "hello world 1 ||| http://linkhere ||| blah blah 6 |||"
entj "hello world 2 ||| http://linkhere ||| blah blah 7 |||"
entj "hello world 3 ||| http://linkhere ||| blah blah 8 |||"
estj "hello world 4 ||| http://linkhere ||| blah blah 9 |||"
intp "hello world 5 ||| http://linkhere ||| blah blah 10 |||"

As this file is actually space separated, you can read it calling:
df = pd.read_csv('Input.csv', sep=r'\s+')

Then define a filtering function:
def myFilter(tbl):
    return pd.Series([x for x in tbl if len(x) > 0 and 'http' not in x], dtype='O')

which:

*

*filters the source list (table of strings) from empty strings and
strings containing http,

*converts it into a Series.

Explicit dtype specification is needed as of version 1.0, to silence
a DeprecationWarning which otherwise occurs if the output Series was empty.
For your data it doesn't occur, but it could occur if in any row all posts had been filtered out.
Then run:
result = df.set_index('type').posts.str.split(r' *[\|]{3} *').apply(myFilter)\
    .stack().reset_index(level=1, drop=True).reset_index(name='post')

Steps:

*

*Set type column as the index.

*Split posts column by triple "|", possibly surrounded with spaces.
For now each split result contains a plain Pythonic list, with an
empty string at the end and "http-string" if any.

*Apply myFilter to filter out unnecessary strings. The result is now
a DataFrame with columns named with consecutive integers, for each
contained post.

*stack() to convert it into a Series, with a MultiIndex:

*

*top level - the source type,

*second level - source column name (post index within the source row).

*Drop the second index level.

*Convert the only remaining index level to a "regular" column and rename
the column containg posts to post.

The result, for my source data, is:
   type           post
0  intj  hello world 1
1  intj    blah blah 6
2  entj  hello world 2
3  entj    blah blah 7
4  entj  hello world 3
5  entj    blah blah 8
6  estj  hello world 4
7  estj    blah blah 9
8  intp  hello world 5
9  intp   blah blah 10

To generate target column, you should:

*

*define a mapping definition (e.g. a dictionary), something like
types = {'intj': 1, 'entj': 2, 'estj': 3, 'intp': 4} (include all
required type strings and corresponding target values),

*insert target column, calling
result.insert(0, 'target', result.type.apply(lambda tp: types[tp]))
Now the result is:
   target  type           post
0       1  intj  hello world 1
1       1  intj    blah blah 6
2       2  entj  hello world 2
3       2  entj    blah blah 7
4       2  entj  hello world 3
5       2  entj    blah blah 8
6       3  estj  hello world 4
7       3  estj    blah blah 9
8       4  intp  hello world 5
9       4  intp   blah blah 10

Of course, you are free to assing other "type to target" mappings.

A: Maybe not the more pythonic way but the first that came to my mind
import pandas as pd

df = pd.read_csv('mbti_1.csv')

# assing unique id to each type
ids = list(enumerate(df['type'].unique()))
ids = dict((y, x+1) for x, y in ids)

df2 = pd.DataFrame(columns=['target', 'type', 'post'])
for _, row in df.iterrows():
    posts = row['posts'].split('|||')
    for post in posts:
        if 'http' not in post:
            df2.loc[len(df2)] = [ids[row['type']], row['type'], post]

print(df2.sample(10))


text:
Q: How can I display php in javascript? I have some code and basically I want to display it in php. Here is the code:
   <script>
   var useridisplay = GetQueryStringParams('user_id');
   </script>

Basically the code I want to grab to display in php is the useridisplay so I would want to do something like this code:
   <script>
   var useridisplay = GetQueryStringParams('user_id');
   var useridisplay = <? $useridisplay; ?>;
   </script>

So bascially I want to display my code in php here is the code:
   <? echo $useridisplay; ?>

How can I display my code?

A: You can make a simple PHP variable available in Javascript like this:
var useridisplay = "<?php echo $useridisplay; ?>";

Just note that inside your PHP it has the echo statement, and outside the PHP code it has quotes surrounding it.
Note also that you want to sanitize that PHP variable first before just spitting it out, so someone can't inject arbitrary code into your page. In addition to sanitizing server side, it's good practice to use json_encode when echoing to a javascript variable:
var useridisplay = <?php echo json_encode($useridisplay); ?>;


text:
Q: Update to 20.10 failed according to lsb_release -a I tried updating my computer to Ubuntu 20.10, however it seems to have failed.
What I did:
sudo do-release-upgrade

This seemed to have worked, it ran through and the computer restarted with a gorilla welcoming me as new background image. However lsb_release -a tells me I'm still on 20.04:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.1 LTS (fossa-bulbasaur X38)
Release:    20.04
Codename:   focal

Running sudo do-release-upgrade again ends in "aborting"
$ sudo do-release-upgrade
Checking for a new Ubuntu release
Get:1 Upgrade tool signature [819 B]
Get:2 Upgrade tool [1'338 kB]
Fetched 1'339 kB in 0s (0 B/s)
authenticate 'groovy.tar.gz' against 'groovy.tar.gz.gpg'
extracting 'groovy.tar.gz'

Reading cache

Checking package manager
Reading package lists... Done
Building dependency tree
Reading state information... Done
Hit http://archive.ubuntu.com/ubuntu groovy InRelease
Hit http://security.ubuntu.com/ubuntu groovy-security InRelease
Hit http://archive.ubuntu.com/ubuntu groovy-updates InRelease
Get:1 http://archive.ubuntu.com/ubuntu groovy/main Sources [1'300 kB]
Get:2 http://security.ubuntu.com/ubuntu groovy-security/universe i386 Packages [13.8 kB]
Get:3 http://security.ubuntu.com/ubuntu groovy-security/universe amd64 Packages [17.3 kB]

[...]

Fetched 58.9 MB in 6s (9'192 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done

Checking for installed snaps

Calculating snap size requirements

Updating repository information
Hit http://archive.ubuntu.com/ubuntu groovy InRelease
Hit http://security.ubuntu.com/ubuntu groovy-security InRelease
Hit http://archive.ubuntu.com/ubuntu groovy-updates InRelease
Fetched 0 B in 0s (0 B/s)

Checking package manager
Reading package lists... Done
Building dependency tree
Reading state information... Done

Calculating the changes

Calculating the changes

Restoring original system state

Aborting
Reading package lists... Done
Building dependency tree
Reading state information... Done

I don't know in what state my system currently is... The sources all have groovy packets, the background image changed, but the OS clearly still is 20.04.
Would be glad for some help on this...
OS: Ubuntu 20.04, 5.8.0-26-generic /
Hardware: Dell XPS 13 9310

A: I had the same problem (on a Dell Precision 3450 workstation with Ubuntu 20.04 preinstalled) and traced it back to the file /usr/lib/os-release by reading the code of lsb_release (which is a python script).
The file /usr/lib/os-release is part of the package base-files, but is for some reason not updated when a newer version of the package is installed during the release upgrade. That's probably due to customizations by Dell, I have no idea.
In any case, I managed to solve the problem by downloading and unpacking the deb package and overwriting the file /usr/lib/os-release with the new version by hand. When running sudo do-release-upgrade after that, it offered me to upgrade to 21.10 as expected, instead of offering 21.04 again.
After upgrading to 21.10, lsb_release -a was again off and told me that I was still on 21.04. After replacing /usr/lib/os-release with the newest version by hand again, it seems to work now.
I'll report back if it's obviously broken.
Update: It seemed my hack resulted in a broken system, see here.
Update 2: I think I fixed the problem, by removing the packages dca-enabler-packages dca-enabler, see discussion see here. I also installed the package linux-image-generic and changed the boot order to boot it by default since the oem kernel doesnt' get updates through the non LTS releases if i understand correctly.

A: User jos from the comment section is right. If you have the groovy repos in your /etc/apt/sources.list and do
sudo apt update
sudo apt dist-upgrade

you have technically an up-to-date Ubuntu 20.10 installation, regardless of what the text file says in /etc/lsb-release.
I don't know how you ended up with wrong lsb-release info. I would recommend you to cleanly install Ubuntu 20.04, as pointed out in your other question thread, as this gives you gives you a lot more possibilities currently to try things out easily with your Dell XPS 13, since Dell is officially supporting that release for that machine.


text:
Q: How to pull private git repo using chef from gitolite I am new to using chef.
I am able to clone/pull a github repository using the following code on my recipe
git "/var/www/hello_app" do
  repository "git://github.com/MyUser/MyProject.git"
  reference "master"
  action "sync"
  user "gituser"
end

I am trying to pull/clone my files from a private git repository managed my gitolite which means that authentication relies on sshd.
I already have my id_rsa private key installed through a data_bag on gituser's .ssh/id_rsa file , the user who is pulling/cloning the private repo. Pulling/cloning the repository manually works.
The command I execute is
git clone gitoliteuser@myserver:MyProject.gr

How should I modify my recipe so I can pull my private repository ?

A: The important part of the resource is the repository value.  To use your gitolite repo, change the value to the one shown in your question:
git "/var/www/hello_app" do
  repository "gitoliteuser@myserver:MyProject.gr"
  reference "master"
  action "sync"
  user "gituser"
end

More details about using the git resource can be found on the opscode site here : http://docs.opscode.com/resource_git.html


text:
Q: ScalaTest2 cannot run unit-tests when dynamic.classpath is enabled in IntelliJ[12/13] We've ran into a strange problem after upgrading our suite of unit-tests to ScalaTest2.0 (with Scala 2.10)
Now running all our unit-tests is very unreliable: sometimes the process hangs, sometimes we get false failures, and the reporting within IntelliJ is messed up (individual tests are not reported under the proper class name, etc.)
After some investigation, we nailed it down to the IntelliJ property dynamic.classpath. When set to false, the problem disappears and our unit-tests run fine, when set to true (even in a different project) the problem starts to appear.
The problem is that we need dynamic.classpath set to true, else IntelliJ is complaining that the command line is too long, with the following message:
Error running Unit Tests
Command line is too long. In order to reduce its length classpath file can be used.
Would you like to enable classpath file mode for all run configurations of your project?

see problem here: IDEA 10.5 Command line is too long
and What does the dynamic.classpath flag do? (IntelliJ project settings)
Any help appreciated (or maybe a workaround to the "command line too long" without using dynamic classpath?)
IntelliJ v13.0.2 (also happened with 12)
scala plugin v0.30.387
scala v2.10.0
scalatest v2.10-2.0


text:
Q: Copying Data from SAP BW to Azure Data Lake Store using Azure Data Factory I've been trying to copy some data from an on-premises SAP BW to a cloud Azure Data Lake Store. I've already configured the sink as the Data Lake Store but i'm having trouble to configure the source. Already downloaded the netweaver library and put the dlls in my system 32 folder and created the integration runtime which is running on my local machine. Has anyone tried this before?
Thanks

A: I recommend using SAP Open Hub function SAP BW to generate flat file if you do not have any other SAP Data Services or HANA tools in place. Then the files can be loaded into HDFS, which is Azure data lake storage.
The reason for this recommendation:
1. SAP BW Open hub is easy for developer and even for non-SAP-BW person.
2. I do not recommend use netweaver RFC (dll library) approach to integration with SAP BW as this mostly uses MDX to read BW data with significant coding and understanding of BW metadata.
3. This can ensure no violation of SAP data distribution licensing.
Hope this can help.
Lei

A: @lei the nw library Fabricio was mentioning has to be the nwlibrfc32.dll which has to be manually injected by customers such that ADF could work with BW data source. This is the shared framework that PowerBI service accesses BW data source. Technically speaking, it's doable, and Fabricio has to ensure the right DLL is injected (32bit vs. 64bit). Without error log we have to speculate.
However, from solution standpoint, please understand that this is not going to be a performing way due to the bottleneck at the underlying MDX engine and result processor of the BW connector. If the volume is small, then there is nos issue. Otherwise, we need to review other options. Open Hub could be an option, if the user is ok to deal with a set of batch job management in BW and separate set of ADF job management in Azure. From IT agility standpoint, coupling two sets of operational processes is not a best approach.
Another option to consider is to hold off on ADF but opt to SSIS instead. Use SSIS to load SAP data with Azure Feature pack, like we do. But this may not be the best approach either, as there is no ADF any more if Fabricio's team already invested in ADF. Or maybe they favor SSIS. All in all, there has to be some level of tradeoff towards sustainable solution.
Back to the original question, please post the error detail and we can help investigate.


text:
Q: Is there any inbuilt color picker for windows 8 ( javascript) I am developing a windows 8 app(Metro) using html5, JavaScript, CSS, etc . I wanted to add a color picker for my app, so that user can change color of background and text.
Is windows 8 provide any inbuilt color picker or should I use external JavaScript color picker?

A: I found this in the developer docs. I just searched for it.


text:
Q: didUpdateLocations being called repeatedly in Xcode simulator My Xcode swift project seems to be calling the CLLocationManager didUpdateLocations over and over and over in an infinite loop and I can't seem to make it stop. Why is it doing this?! I'm certainly not invoking it programmatically, if that's even possible. Is it something to do with the simulator and the fake location being used? Would it not behave this way if I tested it on a real device? That seems my only potential solution but I can't find anything that will confirm this.

A: In Simulator if you use CLLocationManager then its delegate calling frequently in real device it will work fine.
Try with following Selected Location may be it will be helpful to you.
You can use following option of location in Simulator
Debug -> Location -> City Bicycle Ride OR
Debug -> Location -> City Run


text:
Q: Is a locally linear and invertible map $f: S^n\to S^n$ also globally linear and invertible on $S^n$ Let $f: S^n\to S^n$ be a continuous map such that $f(p)=q$ and there exists neighborhoods of $p$ and $q$ such that $f$ is linear and invertible between these two neighborhoods, I wonder if $f$ is also globally linear and invertible on $S^n$ since intuitively it looks true.
By "locally linear", I mean if we identify $S^n$ with the simplex $\Delta^n$, then the induce map betweem two $\Delta^n$ is locally linear. This notion comes from Hatcher's algebraic topology, page 359, Ex.15, let me know if I interpret it wrong.


text:
Q: OWFS in docker ERROR Segmentation fault (core dumped) I try to run owfs inside a docker container to parse 1-wire temperature values.
When running
owfs -C -uall -m /mnt/1wire --allow_other

inside the container I receive this error
Segmentation fault (core dumped)
On the host system, I can run the same setup & command without problems so far:
I don't know how I to debug it to find the error/solution and would appreciate hints/solutions!
My setup is the following,
Dockerfile:
FROM python:3.8-slim-buster
ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get upgrade -y

COPY ds2490 /etc/modeprobe.d/ds2490
RUN apt-get install owfs -y
RUN apt-get install libtool automake libftdi-dev libusb-dev libusb-1.0.0-dev uthash-dev -y
RUN apt-get install usbutils -y

COPY owfs.conf /etc/owfs.conf
COPY fuse.conf /etc/fuse.conf
RUN mkdir /mnt/1wire

WORKDIR onewire
COPY ./docker_entrypoint.sh ./docker_entrypoint.sh
RUN chmod +x ./docker_entrypoint.sh
COPY ./parse_onewire.py ./parse_onewire.py
RUN chmod +x parse_onewire.py

ENTRYPOINT ./docker_entrypoint.sh

docker-compose.yml:
version: "3"
services:
  onewire_parser:
    container_name: 'onewire'
    build: .
    volumes:
      - /dev/bus/usb:/dev/bus/usb
    privileged: true
    stdin_open: true
    tty: true
    restart: unless-stopped

ds2490:
blacklist ds2490
blacklist ds9490r
blacklist wire

fuse.conf:
#Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#
#mount_max = 1000

# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.
#

user_allow_other

owfs.conf:
######################## SOURCES ########################
# With this setup, any client (but owserver) uses owserver on the
# local machine...
! server: server = localhost:4304
# ...and owserver uses the real hardware, by default fake devices
# This part must be changed on real installation
#server: FAKE = DS18S20,DS2405
# USB device: DS9490
server: usb = all
# Serial port: DS9097
#server: device = /dev/ttyS1
# owserver tcp address
#server: server = 192.168.10.1:3131
# random simulated device
#server: FAKE = DS18S20,DS2405
######################### OWFS ##########################
mountpoint = /mnt/1wire
allow_other
####################### OWHTTPD #########################
http: port = 2121
####################### OWFTPD ##########################
ftp: port = 2120
####################### OWSERVER ########################
server: port = localhost:4304

docker_entrypoint.sh:
#!/bin/bash
owfs -C -uall -m /mnt/1wire --allow_other

A: I'm not quite sure why, but changing the mount direction from /mnt/1wire to /opt/1wire solved the issue. I left everything else as mentioned in the original post.
Maybe someone can explain this?


text:
Q: Migrating data, connection character set (Edit 2: Information has come in, thankfully. It's only accessed via ODBC, where I can set connection charset to match anything I set for the MySQL database. So this whole question is reduced to: If I set connection charset of both ODBC and database to UTF-8, am I done and it will not corrupt the data? (server/database charset is latin1). I will happily accept a simple yes or no with a short explanation why.
--------------- the rest is original background information, not really relevant anymore.--------------
(Edit: to clarify: the data is already imported correctly, this is ONLY a question about connection charset.)
I'm trying to make a decision whether to change the connection character set to that of collation and server for my newly created MySQL database.
The server and collation charsets for it are set to the same as that of the old server running MySQL 4.1 - latin1. Some data is already imported with mysql.exe and is verified as correct.
The connection character set was not changed from the default UTF-8 when the server admin installed MySQL 5.5 and created the new database at one point in time.
The old server reported no variables set for collation or connection character set, so my questions are: (I've assumed the current setting, UTF-8, should be the most correct route)

*

*where to look for what to set it to (hints from experience)

*if I choose to set it to latin1, if scripts writing to the database somewhere could corrupt the data again

*or if it can be switched on and off at will without ever corrupting the data, i.e. if I can postpone the decision.

The database server admin doesn't have the information to give me an answer, and with the information missing from the old database, I would like to make sure but can't.
It's a 1GB .sql file which has required gradual editing in TextPad to import, so it would save time to know if this is a critical setting.
My best plan at the moment is to not change the setting, import the data, and backup - and if a script corrupts data due to incorrectly set connection charset, the backup is restored. Do you see problems with this plan?

A: Oh my, I really should take more time reading your question, yes, the whole point of having a database is for data to persist, if you keep restoring the backup due to incorrect charset issues the data is not persistent, a better plan would be to update your script so that all use the same charset and convert any fields that are not in that charset in the database to the same charset.

A: When migrating data,

*

*set destination data charset+collation to the same as for the ancient MySQL database version. You may have to change Type= to Engine=, timestamp(xx) to timestamp, and some float(xx,xx) to double in the huge sqldump with f.ex. TextEdit before importing it with mysql.exe

*Find out what, if any, connections will write to the tables and if their source charset differs from that of the database. If so, modify the datasource's connection properties so that the connection converts the source data to the database charset.


text:
Q: boost thread code ~uintmax_t(0) bool is_sentinel() const
{
    return milliseconds==~uintmax_t(0);
}

I have found this line of code in thread_data.hpp, I am wondering why is it ~uintmax_t(0) instead of -1 ?
EDIT:
if reason is to avoid compiler warnings, why don't use  :
std::numeric_limits(decltype(milliseconds)>::max()
?

A: One reason for using uintmax_t in the first place is that we don't know what the largest type is. Is it unsigned long or unsigned long long?
My guess is that using ~uintmax_t(0) to produce a large unsigned value simply produces the least number of warnings on the largest number of compilers.
It is common for compilers to warn if you mix signed and unsigned values, or that using a minus on an unsigned value (-1ull) surprisingly(?) gives an unsigned result.

A: ~uintmax_t(0) is the simplest way to produce an all-ones value of type uintmax_t that does not produce compiler warnings.

A: Since milliseconds is unsigned, comparing it to -1 wouldn't make any sense.


text:
Q: Which is first day above and below threshold? I have a dataframe that represents a two year daily time series of temperature for two rivers. For each river and each year, I would like to know what day of year:

*

*temperature is greater than or equal to 15 degrees

*temperature is sustained greater than or equal to 15 degrees (sustained is when there are no more dips below 15 until the autumn)

*temperature is less than or equal to 15 degrees

*temperature is sustained less than or equal to 15 degrees (sustained is when there are are no more peaks above 15 until the following spring)

Example timeseries
library(ggplot2)
library(lubridate)
library(dplyr)
library(dataRetrieval)

siteNumber <- c("01428500","01432805") # United States Geological Survey site numbers
parameterCd <- "00010" # temperature
statCd <- "00003" # mean
startDate <- "2018-01-01"
endDate <- "2019-10-31"

dat <- readNWISdv(siteNumber, parameterCd, startDate, endDate, statCd=statCd) # obtains the timeseries from the USGS
dat <- dat[,c(2:4)]
colnames(dat)[3] <- "temperature"

# To view at the time series
ggplot(data = dat, aes(x = Date, y = temperature)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~site_no)

# Adds a new column for year and day of year (doy; Jan 1 = 1, Dec 31 = 365)
dat <- dat %>%
  mutate(year = year(Date),
         doy = yday(Date))

I have tried using the dplyr filter() function but have had little success
dat %>%
  group_by(site_no,year) %>%
  filter(temperature >= 15 & temperature <= 15)

The ideal output would look something like this:
   site_no year doy_firstabove15 doy_sustainedAbove15 doy_firstbelow15 doy_sustainedBelow15
1 01428500 2018              136                  144              253                  286
2 01428500 2019              140                  146              279                  289
3 01432805 2018              143                  143              272                  276
4 01432805 2019              140                  140              278                  278

A: I like this question. Its specific, tricky, and has a good example. I would go about this by creating a rolling variable that checks for changes in temperature above and below 15. Then you can group by site and year and check for the first instance of the change in group id. Now I make several assumptions here that might be bad. 1) I am grouping by year, but it would likely be better to group by water year. You don't explicitly say that the year is important, but I suspect it is. 2) I also assume that Autumn is defined by the first day of month 9. Maybe you want the sustained to be through the fall instead of the first day. Same assumption for spring.
library(tidyverse)
library(dataRetrieval)

dat |>
  mutate(month = lubridate::month(Date),
         year = lubridate::year(Date)) |>
  group_by(site_no, year) |>
  mutate(gt_15 = temperature > 15,
         lt_15 = temperature < 15,
         chng1 = cumsum(gt_15 != lag(gt_15, def = first(gt_15))),
         chng2 = cumsum(lt_15 != lag(lt_15, def = first(lt_15))),
         )|>
  summarise(first_above_15 = Date[chng1==1][1],
            indx_autum = chng1[month == 9][1],
            first_above_15_sustained = Date[chng1== indx_autum][1],
            first_below_15 = Date[chng2==1][1],
            indx_spring = chng1[month == 3][1],
            first_below_15_sustained = Date[chng2== indx_spring][1],
            .groups = "drop") |>
  select(-contains("indx"))
#> # A tibble: 4 x 6
#>   site_no   year first_above_15 first_above_15_sustained first_belo~1 first_be~2
#>   <chr>    <dbl> <date>         <date>                   <date>       <date>
#> 1 01428500  2018 2018-05-18     2018-05-24               2018-05-16   2018-01-01
#> 2 01428500  2019 2019-05-20     2019-05-26               2019-05-20   2019-01-01
#> 3 01432805  2018 2018-05-23     2018-05-23               2018-05-23   2018-01-01
#> 4 01432805  2019 2019-05-20     2019-05-20               2019-05-20   2019-02-22
#> # ... with abbreviated variable names 1: first_below_15,
#> #   2: first_below_15_sustained

A: This works by splitting the annual time series into times before and after the peak temperature. Then it logically returns the day of year (doy) when temperature is first above 15 before the peak temperature and the first below 15 after the peak temperature.
Similarly, the sustain_above and sustain_beloware determined logically first creating a run-length ID column (run) then extracting the doy where the run is max for the subset of run where the values are TRUE in below_peak or after_peak and get the first element of 'doy'
dat %>%
  mutate(year = year(Date),
         doy = yday(Date)) %>%
  group_by(site_no, year) %>%
  mutate(gt_15 = temperature >= 15,
         lt_15 = temperature <= 15,
         peak_doy = doy[which.max(temperature)],
         below_peak = doy < peak_doy,
         after_peak = doy > peak_doy,
         run = data.table::rleid(lt_15)) %>%
  summarise(first_above = doy[below_peak & gt_15][1],
            sustain_above = first(doy[run == max(run[below_peak])]),
            first_below = doy[after_peak & lt_15][1],
            sustain_below = first(doy[run == max(run[after_peak])]), .groups = 'drop')


text:
Q: PC bluescreened, shut off. No monitor signal, and case was tingling I have a eMachine with windows 7 home premium. I just got done doing a video about my miniature tesla coil (I though that might be important, could induced static cause problems?) And i went to turn on my eMachine.
I was downloading a large file, when randomly the screen blacks, I get a blue screen, and then the pc reboots. After the reboot it froze on the bios splash screen. Any further reboots had  no monitor output.
When I had it off, when I went to unplug the pc to see what was wrong, I noticed the case tingling. I do not thing it is supposed to do that,  so I unplugged the entire power strip.
Is this a power supply problem? Was it caused by my tesla coil being near the pc? Or was it random?


text:
Q: Change jQuery function from hover to slideToggle With help from SOers, I was able to make more efficient a hover and fadein/fadeout function to show text divs under this image layout. But I'd like to work with slideToggle because with hover, the text flickers and the divs bounce. How would I adapt this function to use slideToggle where the toggle requires a click on each image?
jsfiddle: http://jsfiddle.net/Ckrtu/11/
This is an image of what I'm trying to do:

This is the old hover function
$(document).ready(function() {
    $("#imagegallerydiv").delegate("dt[class]", "hover", function(e) {
        if (e.type === "mouseenter") {
            var index = $(this).parent().index();
            $("#wide-text-div-under-all-images div").eq(index).fadeIn('fast');
        }
        if (e.type === "mouseleave") {
            var index = $(this).parent().index();
            $("#wide-text-div-under-all-images div").eq(index).fadeOut('fast');
        }
    });
});

CSS:
#imagegallerydiv {width: 700px; height:200px; margin:5px; text-align: center;}

dl.gallery {width: 97px; text-align: center; float: left;}

.gallery dt {width: 80px; margin-top:2px; font-size: .7em; text-align:center;}

#wide-text-div-under-all-images div {display: none;}

HTML:

Image Title One

Image Title Two

Image Title Three

Image Title Four

Image Title Five

Lorem Ipsum One

Lorem Ipsum Two

Lorem Ipsum Three

Lorem Ipsum Four

Lorem Ipsum Five

A: http://jsfiddle.net/samccone/z83Kx/
I think this example is much simpler to understand and fits the desired outcome better then what you were using before.
Just set the text that you want to show as an attr within the div that is to be clicked

hope that this helps

A: you may want to use this.
$(document).ready(function() {
    var $textUnderImage = $("#wide-text-div-under-all-images div");
    $('dt[class]').toggle(
        // first function fired on first click
        function() {
            var index = $(this).parent().index();
            if($textUnderImage.is(":visible")) {
                $textUnderImage.fadeOut('fast');
            }
            $("#wide-text-div-under-all-images div").eq(index).fadeIn('fast');
        },
        // second function fired on second click
        function() {
            var index = $(this).parent().index();
            $("#wide-text-div-under-all-images div").eq(index).fadeOut('fast');
        }
    );

The first function will show the text on first click, and the second function will hide the text on second click and so on...
toggle method will fire the functions inside it sequentially.  So each time you click the handler, one method after the other is processed once. You can add as much as many function inside a toggle method and each function will be executed on each click sequentially.


text:
Q: watch on store mutations even for same values I use this code to watch mutations, but the CB triggers only if old and new Values would NOT be equal,
VX.store.watch(
    getters => getters.focusedOn,
    ( value, oldValue ) => console.log( oldValue, value )
);

I get results like:
1 0

but I'm looking even for results like:
1 1

How can I get them? (even without using watch)
p.s. and I Don't like to convert my simple "focusedOn" to an object or so.
p.s. The createLogger reports all kind of mutations, so it made me thinking that there should be a way to get all of them.


text:
Q: PHP PDO Postgres database start/stop issue I'm using Yii with postgres database in support library of PDPPDO.
I am facing issue in PDO library to conenct Postgres Database.
I'm using some background process to work so ultimately it will be 24X7 continues task. Now, As per use case it's possible that my Postgres will go OFF/Crash somehow. That time, pg_prepare() function returning me FALSE.. That's tottaly Corrent !!!
Now, after few minutes, if Postgres get start. So ultimately pg_prepare() should give me resource Id. But it's still giving me FALSE !!
I believe that due to restarting postgres server it's not allowing me to use same resource again. In that case I need infinite loop that willy continuously ping over Postgres for new connection.
If need to open connection again then I think following like would help,
    // THOUGH IT'S CHECKING FOR $this->_pdo
    // I need to make it NULL before process...
    Yii:app()->db->open();

Now, Is that right flow? or do you guys have any other idea for this?
Thanks ...

A: After doing plenty of research, found that there isn't any solution for automatically inform Yii that connection is started again. So to maintain this, I am keeping one flag internally to check connection.
In Yii, to reconnect any database you need to delete previous connection using,
    Yii::app()->db->setActive(false);

It will remove all your previous connection and sources and allow you to make connection again using,
    Yii::app()->db->setActive(true);

If still not able to find connection then we can delay our background job for few minutes. Benefit, you don't need to restart your background workers.
Regards


text:
Q: Leaking windows when trying to show a alert dialog I am trying to port an iPhone App to Android, but am having some startup difficulties.
I have the following function to get the data:
    public void onClick(View v) {
        try{
            //Toast.makeText(getApplicationContext(), "Starting update", Toast.LENGTH_SHORT).show();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading...");
            new Thread() {
                public void run() {
                    try{
                        DataManager manager = new DataManager(getApplicationContext());
                        manager.updateData();
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage());

                        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                        alertDialog.setTitle("Error...");
                        alertDialog.setMessage(e.getMessage());
                        alertDialog.show();
                    }
                    progressDialog.dismiss();
                }
            }.start();
        } catch (Exception e) {
            Log.e(TAG, "Problem with getting the data: " + e.getMessage());
            Toast.makeText(getApplicationContext(), "Error during update",
                    Toast.LENGTH_SHORT).show();
        }

    }

But if an exception occurs I get the following error (I initially tried to use an AsyncTask, but ran into the same problem):
08-29 20:23:24.389: ERROR/WindowManager(974): Activity org.idoms.iDomsAndroid.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@412fcc38 that was originally added here
        android.view.WindowLeaked: Activity org.idoms.iDomsAndroid.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@412fcc38 that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
        at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
        at android.view.Window$LocalWindowManager.addView(Window.java:537)
        at android.app.Dialog.show(Dialog.java:278)
        at android.app.ProgressDialog.show(ProgressDialog.java:116)
        at android.app.ProgressDialog.show(ProgressDialog.java:99)
        at android.app.ProgressDialog.show(ProgressDialog.java:94)
        at org.idoms.iDomsAndroid.MainActivity$1.onClick(MainActivity.java:46)
        at android.view.View.performClick(View.java:3511)
        at android.view.View$PerformClick.run(View.java:14105)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

What is the right way to do this?

A: My guess is, threads cannot interact with the main UI thread elements.
progressDialog was created in main Ui thread, other threads cannot interact with it. You can give it a signal in the fields and check its progress, but I would really recommend using Asynctask doing this task.
AsyncTask

A: UI elements (like an AlertDialog) can be manipulated only from the main (UI) Thread. If you try to manipulate them from a background thread (which is what you are doing with new Thread() { ... }), you'll get this Exception.
You could fix this by calling runOnUiThread(new Runnable() { ... }); when accessing AlertDialog or progressDialog, but this is very, very, very dirty.
The better solution is to use AsyncTask (or even better AsyncTaskLoader as it takes care of orientationchanges and some other stuff for you). When using AsyncTask, make sure not to access UI elements in the doInBackground()-method. As the name, saysdoInBackground(...) is executed in a background thread. If you attempt to manipulate UI elements from that method, you'll indeed get the same error as you're experiencing now. If you want to access your UI-elements from your AsyncTask, you can do so in the onPreExecute(...), onProgressUpdate(...) and onPostExecute(...) methods.

A: The reason for the window leaking is due to your alertDialog not being dismissed before the app closes.