text:
Q: Handle Future[Option[T]] when traversing a List   def getCommentIds(
      commentTargetId: Long,
      sortOrder: CommentOrderEnum): Future[Seq[CommentStatsBO]]

def getCommentDetail(commentId: Long): Future[Option[CommentDetailDTO]]

def getCommentListWithDetail(
      targetId: Long,
      sortOrder: CommentOrderEnum,
      page: Int): Future[Seq[CommentDetailDTO]] = {
    commentModel.getCommentIds(targetId, sortOrder).flatMap {
      commentStatsBOSeq =>
        Future.traverse(commentStatsBOSeq) { commentStatsBO =>
// commentDetail is a Future[Option[T]]
          val commentDetail = getCommentDetail(commentStatsBO.iId)
          commentDetail.map(commentOpt =>
            commentOpt
// merge the stat info into the comment detail
              .map(_.copy(replyCount = Some(commentStatsBO.replyCount)))
              .getOrElse(CommentDetailDTO))

        }

    }
  }

case class CommentDetailDTO(
    id: Long,
    author: JsObject,
    detail: CommentDetail,
replyCount: Option[Int] = None
)

Firstly, the function getCommentIds returns a sequence of CommentStatsBO, then traversing it and try to get detail for every comment. Here comes the question, getCommentDetail returns a Future which contains an option since the comment maybe not found, in this case, how to filter those ones whose option is None? I have tried getOrElse , but don't know how to define an empty object just like Json.obj() since case class doesn't support.
Thanks!

A: Don't try to do too many things at the same time, rather build the solution you need step by step.
If you do a simple Future.traverse using just getCommentDetail you will get a Future[Seq[Option[CommentDetailDTO]]]  which then you can map and use collect with the Seq to remove the Option
def getCommentListWithDetail(
  targetId: Long,
  sortOrder: CommentOrderEnum,
  page: Int
): Future[Seq[CommentDetailDTO]] =
  commentModel.getCommentIds(targetId, sortOrder).flatMap { commentStatsBOSeq =>
    Future.traverse(commentStatsBOSeq) { commentStatsBO =>
      getCommentDetail(commentStatsBO.iId)
    } map { commentOptionalDetails =>
      commentOptionalDetails.collect {
        case Some(commentDetail) => commentDetail
      }
    }
  }

Or if you use cats, you can use traverseFilter
import cats.syntax.all._

def getCommentListWithDetail(
  targetId: Long,
  sortOrder: CommentOrderEnum,
  page: Int
): Future[Seq[CommentDetailDTO]] =
  commentModel.getCommentIds(targetId, sortOrder).flatMap { commentStatsBOSeq =>
    commentStatsBOSeq.traverseFilter(getCommentDetail)
  }


text:
Q: Делаю парсер hh ,но мой парсер собирает не все ссылки на странице Делаю парсер hh на Python.На странице hh находится 50 карточек ,я пытаюсь получить все 50 ссылок на них,но при выполнении моей программы я получаю только 20 ссылок из 50.Может новые карточки подгружаются динамически,хотя в коде элемента присутствуют все 50 карточек.Кто может сказать в чем дело?
def pars3():
    url='https://ekaterinburg.hh.ru/search/vacancy?area=3&clusters=true&enable_snippets=true&ored_clusters=true&text=Python&search_period=7&hhtmFrom=vacancy_search_list'
    head={'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'}
    respons=requests.get(url,headers=head)
    src=respons.text

    m=[]

    soup=BeautifulSoup(src,'html.parser')
    zapros=soup.find_all('div',class_='vacancy-serp-item')
    for i in zapros:
        a=i.find_all('a',class_='bloko-link')
        for z in a:
            if z['href'][0]=='h' and z['href']!='https://feedback.hh.ru/article/details/id/5951':
                m.append(z['href'])

    return m

Как сделать так чтобы парсер стянул всю информацию с сайта ??

A: По вопросу не совсем понятно, какую именно информацию Вам нужно вытянуть с сайта. Можно сделать следующим образом:
import requests
from bs4 import BeautifulSoup
from time import sleep

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'}

list = []

for page in range(1, 3):
    url = f'https://ekaterinburg.hh.ru/search/vacancy?area=3&clusters=true&enable_snippets=true&ored_clusters=true&text=Python&search_period=7&page={page}&hhtmFrom=vacancy_search_list'
    r = requests.get(url, headers=headers).text
    soup = BeautifulSoup(r, 'lxml')
    card=soup.find_all('div',class_='vacancy-serp-item')
    for url in card:
        sleep(1)
        card_url = url.find('a', class_='bloko-link').get('href')
        list.append(card_url)

Получаем ссылки на каждую карточку, и записываем их в список. После этого проходимся ещё одним циклом. Но там нужно опять делать запрос, уже на полученные ссылки. И из карточки вытягивайте уже нужную вам информацию.
for data in list:
   sleep(1)
   r1 = requests.get(data, headers=headers).text
   soup = BeautifulSoup(r1, 'lxml')

Ну и, чтобы не нагружать сайт и оптимизировать работу программы, не держать все данные в памяти в процессе обработки, можно сделать функцию-генератор. Примерно как здесь: как правильно сделать код парсера для python

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# UWP Understanding StoreAppLicense IsTrial and ExpirationDate I have a UWP app that I have had on the Windows Store for over a year. Until recently, I never had it configured as a trial. The app was free forever, but the app had limited capability unless the user bought a durable add-on. But now I want to allow all users to try the full capability of the app for 7 days, then if they don't buy it, it reverts to limited capability.
I have now changed it to a 7 day trial in the store because that is the only way I can think of to determine how many days since the user first installed the app. So what I want to do now is, when the app loads:

*

*Check to see if the user purchased the add-on. If so, enable all features

*If they haven't purchased the add on, check to see if the current date is past the expiration date of the trial. If not, enable all features. If it is, limit the features.

But I think I have no way to test this logic. I first got a license for my app over a year ago when it wasn't configured as a trial. So, when I examine the app license in code, I see this:

So, my questions are:
Is the Expiration date so far into the future because my app license didn't expire when I acquired it?
Is the IsTrial property false because of the same reason? When I acquired the license, it was not a trial license?
I really wish I had some way to reset my license so I could test it, instead of just coding it up and hoping it all works for my existing customers and my new customers. I was hoping I could create a local account on my computer  and test it that way, but that doesn't work either because the license is tied to the machine. If anyone can give me some ideas, I would appreciate it.
Thanks,
David


text:
Q: Redirect loop in /wp-admin/ A site I manage has just become inaccessible to the admin today. I just updated apache on the server to enable mod_deflate and also to upgrade PHP from 5.3 to 5.4.
Since doing that every time I attempt to access /wp-admin/ I receive the redirect loop error. I tried all the usual suspects, i.e:

*

*cleared cookies and cache

*tried different browsers

*disabled theme

*disabled cookies

*deleted .htaccess

*checked site_url etc in wp_options

But no luck. I can access wp-login.php fine but not /wp-admin/
Any help would be greatly appreciated as I am totally stumped.

A: Try renaming the plugins folder to e.g. plugins-, so as to make sure it has nothing to do with them. Switch it back if it's not the case. If it was, proceed to do similar steps with each individual plugin folder until you locate the culprit.
The same for themes if you're still out of luck.
Another thing, per the comment, would be if the URLs are wrong. Say, the server wants www. and WP doesn't. Or the server wants SSL admin and WP doesn't. Or vice versa in each case. Those can very much break a site and trigger infinite redirects all over the place, so be sure to check those too. Adjust the WP config as appropriate using the relevant defines if needed: WP_HOME, WP_SITEURL, FORCE_SSL_ADMIN, FORCE_SSL_LOGIN.
If all else fails, the usual approach to debug this kind of stuff to die(__FILE__.':'.__LINE__); your way throughout WP until you nail down what is causing the infinite loop. (It could be a cron job or some odd thing like that.)
By following the script, I mean opening up the wp-admin/index.php file (which in this case is the one getting hit), and inserting die(__FILE__.':'.__LINE__); towards the top — before WP actually does anything. If it's already redirecting there, it means there's a problem with the server configuration.
If not, proceed to move the statement down step by step until the redirect occurs. Move further up, entering the included files and the relevant wp functions as needed, and continue doing the same. At one point, you'll find the exact statement that is causing the issue.

A: Temporary solution in the end was to downgrade PHP version back to 5.3.

A: I had the permissions wrong. 775 instead of 755. Once changed, everything worked.
Check your folder permissions!


text:
Q: How to plot graphs with word strings excluded? I have a data set like below:
368 150 0.31895877
369 150 0.32141133
370 150 0.3190167
371 150 0.33890757
372 150 0.3649395
373 150 0.37585051
374 150 0.37916244
375 150 0.37619812
376 150 0.37287654
377 150 0.37249031
378 150 0.37102263
379 150 0.34839918
380 150 No Data
381 150 No Data
382 150 No Data
383 150 No Data
384 150 No Data
385 150 No Data
386 150 No Data
387 150 No Data
388 150 No Data
389 150 No Data
390 150 No Data
391 150 No Data
392 150 No Data

This data set sometimes contains "No Data" and I want to ListPointPlot3D with this data.
Therefore, I imported this data and plotted it:
data=Import["datafile.txt","Table"];
ListPointPlot3D[data]

As I expected, I got error about the invalid list.
How can I plot the graph with these No Data rows eliminated?

This is a sample file which I want to plot with.
datafile.txt

A: The data gets imported as a single loooong string which needs to be split correctly and partitioned before plotting it. Here is something I came up with:
In[53]:= data = Import["datafile.txt"];

Note that Dimensions gives you { } and Head gives you String
In[54]:= Dimensions[data]

Out[54]= {}

In[55]:= Head[data]

Out[55]= String

Split and partition data correctly
In[56]:= sp = StringSplit[data, {"\n"}];

In[57]:= sp[[1]]

Out[57]= "217 135 No Data"

In[58]:= sp2 = StringReplace[#, "No Data" -> "NoData"] & /@ sp;

sp3 = StringSplit /@ sp2;

In[60]:= Head[sp3[[1, 1]]]

Out[60]= String

Use ToExpression to convert strings looking like numbers to actual numbers.
In[61]:= Map[ToExpression, sp3, {2}];

In[62]:= ListPointPlot3D[%]

A: When I import your sample data with
data = Import[FileNameJoin[{$HomeDirectory, "Desktop", "data.txt"}], "Table"];

I get
data // InputForm

{{368, 150, 0.31895877}, {369, 150, 0.32141133}, {370, 150, 0.3190167},
 {371, 150, 0.33890757}, {372, 150, 0.3649395}, {373, 150, 0.37585051},
 {374, 150, 0.37916244}, {375, 150, 0.37619812}, {376, 150, 0.37287654},
 {377, 150, 0.37249031}, {378, 150, 0.37102263}, {379, 150, 0.34839918},
 {380, 150, "No", "Data"}, {381, 150, "No", "Data"}, {382, 150, "No", "Data"},
 {383, 150, "No", "Data"}, {384, 150, "No", "Data"}, {385, 150, "No", "Data"},
 {386, 150, "No", "Data"}, {387, 150, "No", "Data"}, {388, 150, "No", "Data"},
 {389, 150, "No", "Data"}, {390, 150, "No", "Data"}, {391, 150, "No", "Data"},
 {392, 150, "No", "Data"}}

It is easy to distinguish good points from bad. Good have have three elements; bad points have more. Therefore, I will simply select all data points which have three elements.
goodData = Select[data, Length[#] == 3 &];
ListPointPlot3D[goodData,
  PlotStyle -> PointSize[Large],
  PlotRange -> {Automatic, {149, 151}, {.3, .4}},
  BoxRatios -> {1, .5, 1},
  Ticks -> {Automatic, {150}, Automatic},
  Filling -> Bottom,
  FillingStyle -> Thick]


text:
Q: Prove that if $a$ is a real number and $a^3 > a$ then $a^5 > a$
Suppose that a is a real number. Prove that if $a^3 > a$ then $a^5 > a$.

Let's consider four cases:

*

*$a > 1 $

*$0 < a < 1$

*$-1 < a < 0 $

*$a < -1$
Case 1. $a^3 > a$ and $a^5 > a$
Case 2. $a^3 < a$
Case 3.  $a^3 > a$ and $a^5 > a$
Case 4. $a^3 < a$
In all cases where $a^3 > a$, $a^5 > a$ as well. Therefore, $a^3 > a \implies a^5 > a$

When examining each case, I made assertions without providing any explanation. Because it seems obvious to me, that, for example, if $a>1$ and $n>1$ then $a^n$ will definitely be larger than $a$. However, when writing formal proof, should you make an assumption that it is obvious? Or you need to provide at least some explanation behind the conclusion reached?
And in general, is the proof above correct?

A: This is true, but messier than necessary and lacking justification. Here's an easier way:
Note that $a^2$ is positive, so we can multiply both sides of the inequality $a^3>a$ by it without changing the direction of the $>$, getting that $a^5>a^3>a,$ using the assumption for the last $>$.
On the concept of obviousness: on one hand, sure, it may obvious, given the intuition you likely have from using real numbers for a long time. However, I'd argue that's the point of the exercise (and many simple ones like this).

A: Solution without cases:
Because $$a^5-a=(a^2+1)(a^3-a).$$

A: You approach is correct (and two answers posted are also correct, and they use some "shortcuts"). If one is to stay closer to your approach, one may provide some more details, For example, Case 1 could be explained further using that:
If $a>1$ and $b>0$ then $ab>b$. Indeed $ab-b=(a-1)b>0$.
Using the above, with $b=a^3$ and then with $b=a^4$ we get
$aa^3>a^3$ (i.e. $a^4>a^3)$ and $aa^4>a^4$, thus $a^5>a^4>a^3>1$.
There are different ways to provide a valid proof, but in either case you should be able to provide specific details in place of what is obvious. Sometimes it takes some deliberation what would be the best way to prove something, even if it is obvious. That is, to figure what properties of numbers you are formally using.


text:
Q: Embed a SVG file in a tex source file I would like to generate latex documents containing SVG pictures with a specific document generator. For specific reasons, I would like to embed these pictures directly inside the latex source file to avoid creating and copying additional files.
Is it possible to create latex functions containing the XML code of a SVG pictures and make them usable by the svg package?


text:
Q: play music with html my music is keept on desktop with this name
doli mix - arcax(Mus.Ge).mp3

how to write code to play this music in html?

A: HTML is just a markup language. As such, it can't play music. In fact, it can't even display anything. All the rendering is done by the browser.
So what you want is to make the browser play music, and that can be done using the <embed> tag:
<embed src="yourfile.mp3" autostart=true loop=false volume=100
hidden=true><noembed><bgsound src="yourfile.mp3"></noembed>

I strongly recommend not doing this though, since it's extremely annoying.

A: You can use the HTML 5 audio tag (reference here):
<audio src="yourfile.ogg" controls="controls">

Of course this won't work on older browsers.

A: Even a simple anchor tag mp3 will play this music if you have your browser set up with a plugin like VLC, QuickTime, Windows Media Player, etc. Click the link and it will take you to a new page with the media renderer.

A: The code below would autoplay you music in the html document. All you need to do is put the music in the same folder as the html document. The autoplay loop part would make it automatically play the music and loop it together. You can remove these if you want to. Hope it is helpful.
<audio autoplay loop>
      <source src="doli mix - arcax(Mus.Ge).mp3 " type="audio/mpeg">
</audio>


text:
Q: Internal link wasn't translated to title In my question "your post was converted to a comment" has link to "deleted" page the link to page What does "your post was converted to a comment" mean? wasn't automatically converted to title.
Is it a bug?

A: Links are converted automatically to question titles (one-boxed) if they are

*

*internal to the site you're posting on (and therefore do not reference a post on a different site) OR point to Meta.SE; AND

*to a question, not an answer or a comment.
Meta.SE is different in that it one-boxes in both directions: links on Meta.SE pointing to questions across entire network as well as links on child-metas (not main sites) pointing to Meta.SE.
In your case, however, you linked to a post on http://*.stackoverflow.* that doesn't exist. It may have been a result of the the MSE/MSO split as http://*.stackexchange.* works.

A: The link does not "onebox" because it's wrong.
That question does not exist in Meta Stack Overflow, but rather on Meta Stack Exchange. (This site)
The link you have in that other question of yours is:
http://meta.stackoverflow.com/questions/133593/what-does-your-post-was-converted-to-a-comment-mean

If you put it in a browser, you will be redirected automatically to http://meta.stackexchange.com/questions/133593/what-does-your-post-was-converted-to-a-comment-mean due to a check performed after MSE/MSO split.
So, the code that translates links to title is asking MSO "do you have question with ID of 133593? And it get a "no" as a response. hence no title. Putting correct link will result in correct title.
Question is, where you got that link from? If it was  somewhere on SE you should report and ask to fix. (Or of course edit yourself if from a different post.)


text:
Q: Build.sbt breaks when adding GraphFrames build with scala 2.11 I'm trying to add GraphFrames to my scala spark application, and this was going fine when I added the one based on 2.10. However, as soon as I tried to build it with GraphFrames build with scala 2.11, it breaks.
The problem would be that there are conflicting versions of scala used (2.10 and 2.11). I'm getting the following error:
[error] Modules were resolved with conflicting cross-version suffixes in {file:/E:/Documents/School/LSDE/hadoopcryptoledger/examples/scala-spark-graphx-bitcointransaction/}root:
[error]    org.apache.spark:spark-launcher _2.10, _2.11
[error]    org.json4s:json4s-ast _2.10, _2.11
[error]    org.apache.spark:spark-network-shuffle _2.10, _2.11
[error]    com.twitter:chill _2.10, _2.11
[error]    org.json4s:json4s-jackson _2.10, _2.11
[error]    com.fasterxml.jackson.module:jackson-module-scala _2.10, _2.11
[error]    org.json4s:json4s-core _2.10, _2.11
[error]    org.apache.spark:spark-unsafe _2.10, _2.11
[error]    org.apache.spark:spark-core _2.10, _2.11
[error]    org.apache.spark:spark-network-common _2.10, _2.11

However, I can't troubleshoot what causes this.. This is my full build.sbt:
import sbt._
import Keys._
import scala._

lazy val root = (project in file("."))
.settings(
    name := "example-hcl-spark-scala-graphx-bitcointransaction",
    version := "0.1"
)
 .configs( IntegrationTest )
  .settings( Defaults.itSettings : _*)

scalacOptions += "-target:jvm-1.7"

crossScalaVersions := Seq("2.11.8")

resolvers += Resolver.mavenLocal

fork  := true

jacoco.settings

itJacoco.settings

assemblyJarName in assembly := "example-hcl-spark-scala-graphx-bitcointransaction.jar"

libraryDependencies += "com.github.zuinnote" % "hadoopcryptoledger-fileformat" % "1.0.7" % "compile"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.5.0" % "provided"

libraryDependencies += "org.apache.spark" %% "spark-graphx" % "1.5.0" % "provided"

libraryDependencies += "org.apache.hadoop" % "hadoop-client" % "2.7.0" % "provided"

libraryDependencies += "javax.servlet" % "javax.servlet-api" % "3.0.1" % "it"

libraryDependencies += "org.apache.hadoop" % "hadoop-common" % "2.7.0" % "it" classifier "" classifier "tests"

libraryDependencies += "org.apache.hadoop" % "hadoop-hdfs" % "2.7.0" % "it" classifier "" classifier "tests"

libraryDependencies += "org.apache.hadoop" % "hadoop-minicluster" % "2.7.0" % "it"

libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.2.0" % "provided"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test,it"

libraryDependencies += "graphframes" % "graphframes" % "0.5.0-spark2.1-s_2.11"

Can anyone pinpoint which dependency is based on scala 2.10 causing the build to fail?

A: I found out what the problem was. Apparently, if you use:
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.5.0" % "provided"

It uses the 2.10 version by default. It all worked once I changed the dependencies of spark core and spark graphx to:
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.2.0"

libraryDependencies += "org.apache.spark" % "spark-graphx_2.11" % "2.2.0" % "provided"


text:
Q: Can anyone explain the Zaeed cutscene in Mass Effect 3? I did not make Zaeed loyal in ME2. I played through the Volus Ambassador mission, but have no idea what happened. One minute I am talking to the Volus ambassador on some kind of Plantronics earpiece, then I hear weird shooting noises, then you walk in and Zaeed is bleeding all over the place.
What happened? Did the Volus shoot him? How? Why? What?

A: Shepard's presence on the Volus ambassador's commline convinced Zaeed that it was better to protect him - at least until Shepard can get a chance to speak with the Volus.
Unfortunately, Zaeed's partners want to stick to their original plan of killing the ambassador. Zaeed refuses to let them kill the ambassador, and they wind up getting in a gunfight over the volus, and ultimately wind up killing each other. If your Zaeed is loyal, he'll survive this extrication (as always), otherwise, he gives his life saving the ambassador.


text:
Q: Hypothesis on means of two Pareto distributions I have two independent groups and they seems to form a Pareto distribution when the histograms are looked at. Is there a particular hypothesis test that is specifically made to compare the means of such distributions?
I should also mention that the distributions are highly unbalanced (one group has 1000 instances and the other has 35,000 instances).
I want to check if the mean of one group is greater than the mean of the other group.

A: With such huge sample sizes, you will certainly reject the null; it may be better to focus on measuring the size of the difference than testing for it.
In the case that the lower limit of both Pareto distributions ($x_m$ Wikipedia's parameterization) is the same, the test is straightforward -- it amounts to testing equality of the $\alpha$ parameter.
The mean, when it exists, is $\frac{\alpha x_m}{\alpha-1}$, which increases as $\alpha$ decreases toward 1.
Note that the log of a Pareto random variable is a shifted exponential whose lower limit (shift parameter) is $\log(x_m)$, and $\alpha$ is the rate parameter. So let's proceed this way -- by working with the logs.
In the case that $x_m$ is common to both groups but unknown, you could estimate its log by the smallest observation in either group, subtracting it from all other log-values (and then discarding that observation from whichever sample it occurred in).
You could then compare the means of the resulting exponentials via an F-test, as here (the ratio of the means of the shifted logs $\bar{X}/\bar{Y}$ should be $\sim F_{2n_x,2n_y}$), or you could do a straight likelihood ratio test. They should give very similar results (at considerably smaller sample sizes than yours they can differ more).

A: Pareto might not have a finite mean, so this comparison simply might not be reasonable.
You could make a simulation by bootstrapping from your samples and get a pretty good idea of if one group is larger than the other.


text:
Q: What do $0$ and $1$ mean in a extension (exact sequence) of group? I'm self-studying homological algebra but stuck in a little place. What does $0$ and $1$ mean by the author? (I didn't read the book from start to end.) Does it mean the trivial group? Then why we write in different symbols?

A: My immediate suspicion: $K$ is abelian, written additively, and the trivial (sub)group is $0$. $Q$ is just a group, and is written multiplicatively, making the trivial (quotient) group $1$.

A: Both $0$ and $1$ are generaly used to represent the trivial group. Usually, $0$ is used in an abelian context (where the group operation is written additively and the identity element as $0$) and $1$ is commonly used in a non (necessarily) abelian context (the group operation is written multiplicatively, so the identity element is $1$).
Since $0$ can be identified with a subgroup of $K$ and $K$ is abelian, they write it as $0$. In general, you can use both but is not very common to see the two notations mixed.


text:
Q: Why can't I change the number of elements / buses in the input scope of AU multi channel mixer? UPDATE:
I'm changing my code to illustrate the issue in a more streamlined way. Also I had a little bug which, while not deterring from the problem, did add some confusion.
I'm instantiating a Multi Channel Mixer AU in iOS (kAudioUnitSubType_MultiChannelMixer) and I do the following:
OSStatus status = noErr;

//  Set component type:
AudioComponentDescription cd = {0};
cd.componentType = kAudioUnitType_Mixer;
cd.componentSubType = kAudioUnitSubType_MultiChannelMixer;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;

//  Alloc unit:
AudioComponent defaultOutput = AudioComponentFindNext(NULL, &cd);
AudioUnit mixer;
status = AudioComponentInstanceNew(defaultOutput, &mixer);
NSLog(@"AU init status: %li", status);

//  You can try initializing the unit before or after the attempt to set its input bus count.
//  It doesn't matter; it won't work either way.
AudioUnitInitialize(mixer);

//  Get number of inputs
UInt32 busSize = sizeof(UInt32);
UInt32 busCount = 0;
status = AudioUnitGetProperty(mixer,
                              kAudioUnitProperty_ElementCount,
                              kAudioUnitScope_Input,
                              0,
                              &busCount,
                              &busSize);
NSLog(@"AU get input bus count | status: %li | count: %lu", status, busCount);

//  Try setting number of inputs
busCount = 3;
status = AudioUnitSetProperty(mixer,
                              kAudioUnitProperty_ElementCount,
                              kAudioUnitScope_Input,
                              0,
                              &busCount,
                              busSize);

NSLog(@"AU set input status: %li", status);

//  Get number of inputs
busCount = 0;
status = AudioUnitGetProperty(mixer,
                              kAudioUnitProperty_ElementCount,
                              kAudioUnitScope_Input,
                              0,
                              &busCount,
                              &busSize);

NSLog(@"AU get input bus count | status: %li | count: %lu", status, busCount);

//  Try setting number of inputs
busCount = 10;
status = AudioUnitSetProperty(mixer,
                              kAudioUnitProperty_ElementCount,
                              kAudioUnitScope_Input,
                              0,
                              &busCount,
                              busSize);

NSLog(@"AU set input status: %li", status);

//  Get number of inputs
busCount = 0;
status = AudioUnitGetProperty(mixer,
                              kAudioUnitProperty_ElementCount,
                              kAudioUnitScope_Input,
                              0,
                              &busCount,
                              &busSize);

NSLog(@"AU get input bus count | status: %li | count: %lu", status, busCount);

And I get the following output:
2013-10-11 19:54:32.248 AUMultiChannelRadar[3996:a0b] AU init status: 0
2013-10-11 19:54:32.249 AUMultiChannelRadar[3996:a0b] AU get input bus count | status: 0 | count: 8
2013-10-11 19:54:32.250 AUMultiChannelRadar[3996:a0b] AU set input status: 0
2013-10-11 19:54:32.250 AUMultiChannelRadar[3996:a0b] AU get input bus count | status: 0 | count: 8
2013-10-11 19:54:32.250 AUMultiChannelRadar[3996:a0b] AU set input status: 0
2013-10-11 19:54:32.251 AUMultiChannelRadar[3996:a0b] AU get input bus count | status: 0 | count: 10

I'd expect the bus count to not be 8 by default (since the Audio Unit documentation doesn't say there is a default value on instantiation) and I'd expect to be able to change the number of input elements to both less and more than 8 for that matter (since the docs say it can have "Any" number of inputs). However, from the output, attempting to set the input count to less than 8 does nothing; I can only set it to more than 8.

A: I talked to an Apple engineer who is part of the CoreAudio team and showed him my code and he agreed it is most certainly a bug. He even tried it out himself and got the same results as me: the unit seems to be instantiated with 8 inputs by default and you can only set the number to more than 8 but not less (yes, my code originally showed 2 inputs cause I was messing up and dividing 8/4 -- thanks).
He told me to file a radar so I did. # 15214291.

A: I think there is no need to divide the number of elements on UInt32 size.
UInt32 numElements = 0;
UInt32 size = sizeof(numElements);
AudioUnitGetProperty(_audioUnit, kAudioUnitProperty_ElementCount, kAudioUnitScope_Input, 0, &numElements, &size);

So, numElements will contain number of elements.


text:
Q: Can I dim the rest of the page on hover with only CSS? I'm not very good at explaining, but hopefully I can get my point across with some nifty photoshop.
Currently, when you hover links on my page, it looks like this:
http://i.gyazo.com/086a81e116c55b2660689e3807b201ca.gif
But I want it to dim the whole page on hover besides the link, sort of like:
http://i.gyazo.com/f6523ae998ad826e6ad338c055f5ae3c.gif
Below is the code for the links, and I'm pretty sure there's next to nothing I'm doing right, but maybe it'll help. (I'm hardly past "beginner" in the world of coding. I can usually get my way around CSS, but this stumps me.)
.linkage {
    width: 100%;
    height: 18px;
    z-index:999;
    margin-top: 10px;
    padding-top: 2px;
    background-color: transparent;
    text-align: center;
    font-size: 20px;
    font-family: arial;
}

.linkage a {
    color: #fcfcfc;
}

.linkage a:hover+.dim{
        color: #fff;
        font-size:30px;
    text-shadow: -2px 2px 8px #fff, 1px -1px 8px #fff;
}

.dim {
    width: 100%;
    height: 100%;
    z-index: -6;
    display: none;
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(0,0,0,0.4);
}

Thanks for any help you can offer!

A: I'm guessing, this is what are you looking for.

body {
  background-color: #bbb;
}
.links  {
  height: 3em;
}

.link {
  transition: font-size 500ms ease 0s;
  color: #666;
}
.link:hover {
  font-size: 1.2em;
  color: white;
  text-shadow: 0 0 5px rgba(255,255,255,0.8);
}

/* relevant part */
.link:active {
  z-index: 5;
  text-shadow: 0 0 15px rgba(255,255,255,1);
}
/* adding pseudo element to "dim" the page on click */
.link:active::after {
  z-index: -1;
  content: "";
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,0.4);
}

  Lorem ipsum.
  Ipsam, placeat!
  Dicta, aliquam?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum sequi, vitae, numquam earum molestiae illo, sapiente delectus enim possimus quod incidunt hic ab neque eaque provident, consequatur sint. Nihil neque natus amet eaque dolorum accusantium voluptatem aspernatur! Voluptas pariatur qui possimus incidunt beatae in atque nobis nostrum, vero tempora porro, ipsum, adipisci. Quasi fugit amet facilis, aliquid dolores ab molestiae dolorem obcaecati quo, perferendis ullam quas harum iste! Aperiam sunt quis cumque culpa esse mollitia nam autem animi dolorum sequi, similique delectus laboriosam tenetur vel saepe. Ut enim facilis quia, iusto neque dolores. Similique dolores corporis totam nesciunt et tempora.


text:
Q: odds/probability of single prize raffle this might seem basic but for all my searching i haven't seen it said for single prize.
if the scenario is:
1 prize
100 tickets
player 1: 1 ticket
player 2: 1 ticket
player 3: 5 tickets
player 4: 20 tickets
player 5: 73 tickets
player 1 has 1/100 odds of winning and that's unaffected by player 5 buying 73 tickets.
but wouldn't players buying substantially more tickets change the possible outcome for player 1? regardless of the odds remaining the same?
appreciate any helps thanks!

A: If all tickets are sold, then Player 1 will have a $1\%%$ chance to win the prize. The distribution of the other tickets doesn't matter.
You may have seen a phrase in some sweepstakes stating: "The odds of winning depends on the number of entries received." Therefore, if only $20$ tickets are sold, then Player 1's odds of winning are $1/20$. Or if a thousand tickets are sold, Player 1's odds are $1/1000$, and so forth.


text:
Q: HTML, CSS, JS in separate area not affecting entire website I want to put up tutorials on my website. In order for the user to see some examples I want to output the code (HTML, CSS, JavaScript) plus the result.
So my markup for a the code box, including a little example, looks like the following:

 This is an example

        /* Example CSS code */
        div{
            font-size: 120%;
        }
        div span{
            font-size: 130%;
        }

       /* Example jQuery code */
       $("div").hover(function(){
           $(this).find("span").css("fontSize", "140%");
       }, function(){
           $(this).find("span").css("fontSize", "130%");
       });

Via JavaScript/jQuery I escape necessary characters like "<" that are inside the code tags, so that the actual code is printed as text, and not evaluated as eg HTML.
No problems so far.
My problem arises when it comes to the "result" part, where I actually want the written code to be evaluated as code. So far I got it to work with jQuery:
Unescaping the HTML characters, putting the css stuff inside a  tag, and the JS inside a  tag. The problem now being that the "new" Css and JS will also apply to the rest of the website <-- definitely not what I want. But whats the solution?
I found an article about "scoped css":
Putting your css inside a   tag will make the css apply to only the parent and its children elements. But support is low and this would only help the CSS, not the JS.
Givng my example code an id or class is simple, but not something desirable for each tutorial I wanna put up there, neither for writing nor for reading.
I would need to wrap that tutorial-code in a bubble, separated from my website's code. Kind of like an iframe or such. I would really appreciate any ideas or comments on this.
Thanks in advance.

A: Be more specific with your selections, instead of having $("div") use $("#result div"), also a nice thing you can do with jQuery instead of wraping it, you can use if so: if($("#result div").attr("on") == "on") {//do stuff}

A: You can use textareas to display your code. As for the "results" section, an iframe is probably your best bet.

.code{
    border:0;
    resize: none;
    height:100px;
    width:300px;
    overflow:hidden;
}
<textarea class="code">

 This is an example

</textarea>

<textarea class="code">
        /* Example CSS code */
        div{
            font-size: 120%;
        }
        div span{
            font-size: 130%;
        }
</textarea>

<textarea class="code">
       /* Example jQuery code */
       $("div").hover(function(){
           $(this).find("span").css("fontSize", "140%");
       }, function(){
           $(this).find("span").css("fontSize", "130%");
       });
</textarea>

A: Seems to me you are tryingf to achieve something like this.
var parent = $(".code-box.example-1"),
    parentC = parent.attr("class").match(/example-\d+/),
    htmlSnip = parent.find(".lang-html > pre").text().replace("<", "<").replace(">", ">"),
    cssSnip = parent.find(".lang-css > pre").html().replace(/(\/\*.*\*\/\n)|(^\s*)/gm, "").replace(/^([^{\n]+)(?={$)/gm, "." + parentC + " .lang-result " + "$1"),
    jsSnip = parent.find(".lang-js > pre").html().replace(/(\/\*.*\*\/\n)|(^\s*)/gm, "").replace(/(\$\(")([^"]+)("\))/gm, "$1." + parentC + " .lang-result " + "$2 $3");

parent.find(".lang-result").html(htmlSnip).prepend("" + "


text:
Q: error clearing credentials remotely using PSEXEC cmd /c trying to clear credentials remotely using psexec but receive the following error when runnning elevated
@echo off
echo "Credential Clearer"

set /p asset="Enter IP Address: "

psexec \\%asset% cmd /c for /F "tokens=1,2 delims= " %G in ('cmdkey /list ^| findstr Target') do  cmdkey /delete %H

@echo off
pause

the for loop itself works fine when pasted into the command prompt but when i run it remotely using psexec the output is
H was unexpected at this time
cmd exited on ""ip address" with error code 1


text:
Q: Variable that updates conditional value I have a dataframe with two columns: Tick and Bid. This is tick data for a financial instrument. If the Tick column has a value price has moved up/down. The Bid column holds the current bid price. Here's an example:
Test <- data.frame(Tick=c(NA, NA, NA ,NA, NA , "1", NA, NA, NA,
                          NA, NA, "-1",NA, NA),
                   Bid=c("393.75", "393.75" ,"393.75" ,"394", "394",
                          NA,"394" ,"394","394","394","393.75",
                          NA, "393.75", "393.75"))

I want to create a variable I'll call Best_Bid_Ex that holds the value of the first price after a tick event occurs (is.na(Test$Tick == FALSE)) and resets with the new bid price with the next event.
Test$Best_Bid_Ex <- c("393.75", "393.75" ,"393.75" ,"393.75",
"393.75", NA,"394" ,"394","394","394","394", NA, "393.75", "393.75")

I tried different indexing techniques but I can't get anything to work.

A: In the devel version of 'data.table', there is a convenient function rleid for generating a run-length_type_id column for grouping purpose.
We convert the 'data.frame' to 'data.table' (setDT(Test)).  Apply rleid on the logical index (!is.na(Tick)) to get numeric group for each set of 'TRUE/FALSE/TRUE' groups and then create the 'Best_Bid_Ex' as the first value of 'Bid' column (Bid[1L]) grouped by the numeric grouping from rleid.
library(data.table)#v1.9.5+
setDT(Test)[, Best_Bid_Ex:= Bid[1L], rleid(!is.na(Tick))]
Test
#  Tick    Bid Best_Bid_Ex
# 1:   NA 393.75      393.75
# 2:   NA 393.75      393.75
# 3:   NA 393.75      393.75
# 4:   NA    394      393.75
# 5:   NA    394      393.75
# 6:    1     NA          NA
# 7:   NA    394         394
# 8:   NA    394         394
# 9:   NA    394         394
#10:   NA    394         394
#11:   NA 393.75         394
#12:   -1     NA          NA
#13:   NA 393.75      393.75
#14:   NA 393.75      393.75

Instructions to install the devel version are here


text:
Q: Statements on "if" not followed I´m doing a little programming on C with a dsPIC, I have found a little tiny problem that I don´t know why or how is it happenning.
Compiler C30 for MPLAB
I have this code:
int Function1(){
.
.
.
while(1){
.
.
.
P1 = EPC96_1[18];  //Here the value of P1 = 0xB6
P2 = EPC96_1[19];
CRC_CCITT(EPC96_2, 18);   //in this function CRC_1 is calculated also CRC2
if(P1 != CRC_1){       //In the calculation of CRC_1 it comes always 0xB6
  P1++;                //Both values P1 and CRC1 are the same, stil it
  if(P2 != CRC_2)      //comes here and continues with the break
    break;
  }
}
return 1;
}
//end of my function, return to main code

----Sorry, I didn´t specify, it supose not to come into the if, the != is supose to be like that, because what I want the program to do is when both variables are equal, it should return to the while(1) start.----
I looked up for the variables on the Watch of the MPLAB (8.92) and they are the same. I do not think the problem is in the code before or after or in any other place, but I could be wrong.
Has anybody found the same problem during your experience time?
Thank you for your time.

A: Assuming that P1 and CRC_1 are int variables.
According to the comments in your code, both variables will have value 0xB6.  The if-statement checks for inequality (!=), not equality (==), so it will skip the block.
I suggest inserting printf()-statements to output the values of the two variables before and/or inside the if-statement.  It may be that either one of them holds unexpected values.
printf("P1=%d, CRC_1=%d\n", P1, CRC_1);

A: The data type of variables are unknown.
What datatype of P1, P2, EPC96_1, CRC_1, CRC_2?
Where the variable are defined?
What function CR_CCCITT() is do?


text:
Q: When running two devices in parallel is the amperage always split exactly 50/50? I have a AC to DC adaptor that outputs 12V 3A.
This came with a USB HDD dock which has two slots.
I want to splice a 12V fan into the wire in parallel so they are both powered by the same wall plug.
Will the fan just use however many amps it needs and leave the rest for the USB HDD dock or will it only be possible for each device to get 12V 1.5A now because they are in parralell?

A: The sum of the currents will be limited to 3 A. As with any power supply, it is the user's responsibility to ensure that the total remains below the spec'd limit. Power supplies have a wide range of behaviors when the current limit is exceeded, any of which may disrupt operation of downstream components, so overloading should be avoided.

A:
Will the fan just use however many amps it needs and leave the rest for the USB HDD dock?

Yes.  That's what will happen.  In fact, the USB HDD dock will take what it needs, and very likely leave the total current draw less than 3A (assuming it doesn't need more than 1.5A).

or will it only be possible for each device to get 12V 1.5A now because they are in parallel?

There seems to be some misunderstanding out there about the whole volts & amps things work.  If you have a device that consumes 1A from a 12V supply, then that's what it'll do -- whether the supply is rated at 1A or 100A.  If you put it in parallel with another device that consumes 5A from a 12V supply, then together -- assuming they don't try to pull more current than the supply can, well, supply, the total current will be 6A.
Basically, a device can only "see" the voltage applied -- it can't see any other devices connected to the same power rail.  So it'll always pull the same current for the same voltage.


text:
Q: Wordpress pagination not working past page 1 Working on this site and it's blog posts here:
http://itsuptous.org/team-pages/
The pagination does not work past page 1. Using this as my query:
    $posts = query_posts($query_string.'&orderby=title&order=asc&posts_per_page=4&paged='.$paged);

And this plugin for my pagination: http://wordpress.org/extend/plugins/wp-paginate/faq/
    <?php if(function_exists('wp_paginate')) {
        wp_paginate();
    } ?>

Anyone have any thoughts? Thanks in advance.

A: @Daniel - That solved it! Setting the Reading settings both to 4. Thanks a bunch. Wonder why that disparity caused issues. I thought I could independently set how many posts per page per blog layout. I guess not.


text:
Q: PHPMailer Connects but not sending (Google XOAUTH2) Can anyone interpret the following output from PHPMailer and diagnose the problem? I have successfully tested my code in isolation but after incorporating into an application it fails
2021-08-19 14:25:31 3   Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array()
2021-08-19 14:25:31 3   Connection: opened
2021-08-19 14:25:31 2   SERVER -> CLIENT: 220 smtp.gmail.com ESMTP q184sm1663611qkd.35 - gsmtp

2021-08-19 14:25:31 1   CLIENT -> SERVER: EHLO localhost

2021-08-19 14:25:31 2   SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2607:fea8:e2c0:5dd:6c0a:3ddc:897:57d9]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8

2021-08-19 14:25:31

2021-08-19 14:25:31 1   CLIENT -> SERVER: QUIT

2021-08-19 14:25:32 2   SERVER -> CLIENT: 221 2.0.0 closing connection q184sm1663611qkd.35 - gsmtp

2021-08-19 14:25:32 3   Connection: closed

The code is based on the XOAUTH2 example in the PHPMailer documentation. The essential function is here:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;

class MainController extends Controller
{
    function sendPHPMail($to, $name, $reply, $subject, $body, $attach, $type) {
        // This function sends an HTML email via Google's SMTP server using XOAUTH2

        //Create a new PHPMailer instance
        $mail = new PHPMailer();

        //Tell PHPMailer to use SMTP
        $mail->isSMTP();

        //Enable SMTP debugging
        //SMTP::DEBUG_OFF = off (for production use)
        //SMTP::DEBUG_CLIENT = client messages
        //SMTP::DEBUG_SERVER = client and server messages
        $mail->SMTPDebug = SMTP::DEBUG_CONNECTION;
        $mail->Debugoutput = function($str, $level) {
            file_put_contents('smtp.txt', gmdate('Y-m-d H:i:s'). "\t$level\t$str\n", FILE_APPEND | LOCK_EX);
        };
        //Set the hostname of the mail server
        $mail->Host = $this->f3->get('mailHost');

        //Set the SMTP port number:
        // - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
        // - 587 for SMTP+STARTTLS
        $mail->Port = 465;

        //Set the encryption mechanism to use:
        // - SMTPS (implicit TLS on port 465) or
        // - STARTTLS (explicit TLS on port 587)
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;

        //Set AuthType to use XOAUTH2
        $mail->AuthType = 'XOAUTH2';

        //Fill in authentication details here
        //Either the gmail account owner, or the user that gave consent
        $emailUser = $this->f3->get('mailUser');
        $clientId = $this->f3->get('oauthClientID');
        $clientSecret = $this->f3->get('oauthClientSecret');

        // Refresh Token obtained by configuring and running get_oauth_token.php
        // after setting up an app in Google Developer Console.
        $refreshToken = $this->f3->get('oauthRefreshToken');
        //Create a new OAuth2 provider instance
        $provider = new Google(
            [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
            ]
        );

        //Pass the OAuth provider instance to PHPMailer
        $mail->setOAuth(
            new OAuth(
                [
                    'provider' => $provider,
                    'clientId' => $clientId,
                    'clientSecret' => $clientSecret,
                    'refreshToken' => $refreshToken,
                    'userName' => $emailUser,
                ]
            )
        );

        //Set who the message is to be sent from
        //For gmail, this generally needs to be the same as the user you logged in as
        $mail->setFrom($emailUser, "Mississippi Valley Textile Museum");
        $mail->addReplyTo($reply);

        //Set who the message is to be sent to
        $mail->addAddress($to, $name);

        //Set the subject line
        $mail->Subject = $subject;

        //Set HTML message body, convert referenced images to embedded
        //Specify a basic plain-text alternative body
        $mail->CharSet = PHPMailer::CHARSET_UTF8;
        $mail->msgHTML($body);

        //Replace the plain text body with one created manually
        $mail->AltBody = 'This email is HTML; enable HTML mail if you cannot see it.';

        //Add attachment if specified
        if ($attach) {
            $mail->addStringAttachment($attach, "MVTM{$type}.pdf");        }

        //send the message, catch and log errors
        try {
            return $mail->send();
        } catch (phpmailerException $e) {
            file_put_contents('smtp.txt', gmdate('Y-m-d H:i:s'). "\n$e->errorMessage\n", FILE_APPEND | LOCK_EX);
            //Pretty error messages from PHPMailer
            return false;
        } catch (Exception $e) {
            file_put_contents('smtp.txt', gmdate('Y-m-d H:i:s'). "\n$e->errorMessage\n", FILE_APPEND | LOCK_EX);
            // error messages from anything else
            return false;
        }
    }

It appears to get by the initial connection but not the actual transmission to the smtp server

A: Solved. OK, there is nothing wrong with my code as shown here. The problem was in my app config file which hold the ClientSecret and RefreshToken. I had used single rather than double quotes which caused an escape to be misinterpretted. 3 days wasted but lesson learned.


text:
Q: How to access object method within jQuery event I'm trying my hand in designing an application in JavaScript that is object oriented with help from jQuery. However, I've run into issues when using the jQuery event handlers within my application's class. Here is the offending snippet of code:

The problem is I need to access the filter_songs method of the Library class from the jQuery search_input.keyup event handler. Normally I would use "this" but jQuery uses it for the html object that triggered the event. Am I approaching the design of this application wrong, or is there a way to fix this issue? Thanks for the help.

A: You need a closure. Try this:
var self = this;
this.search_input.keyup(function() {
            var sender = $(this);
            var s = $.trim(sender.val());
            self.filter_songs(s);
        });


text:
Q: How to automatically detect the arguments to pass in Python? So here's one example. I have a module with multiple classes for computing properties, let's say, Density. Then, I have substances, whom I make inherit the properties, so I can call them afterwards:
class Density():

    def __init__(self):
        self.rho_method_1_A = None
        self.rho_method_1_B = None
        self.rho_method_2_A = None
        self.rho_method_2_B = None

   def density_method_1(self,T):
        return self.rho_method_1_A*T + self.rho_method_1_B*T**2

   def density_method_2(self,T,P):
        return P*(self.rho_method_2_A/T + self.rho_method_1_B*log(T))

class Water(Density):

   def __init__(self):
        self.rho_method_1_A = 0.2
        self.rho_method_1_B = 0.0088
        self.rho_method_2_A = 1.9
        self.rho_method_2_B = 10

Water.density_method_1(T=300)

Basically, I want the user to be able to set beforehand the method of choice. The problem is, depending on the model that he/she chose, it will either accept only T, or both T and P (in some other cases, maybe T won't even be accepted). Essentially:
 density_method = density_method_2 # This is chosen by the user in an outer module
 Water.density_method(code magically knows what to put here by detecting the arguments that
                      density_method_2 accepts)

To be clear: The user itself will know which arguments the method accepts, so if he chose method_2, P will be known on the outer module. I suspect **kwargs and/or decorators are part of the solution, but I can't quite figure it out. Any help is appreciated. Thanks and have a great weekend.
Update: It is relevant to notice that density_method will be called inside a temporal loop of tens of thousands of iterations. So, I'm trying to avoid if/else statements by completely defining density_method before starting the temporal loop.

A: Possible solution (tested with Python 3.8):
from math import log

class Density():
  def __init__(self, method=1):
      self.method = method
      self.rho_method_1_A = None
      self.rho_method_1_B = None
      self.rho_method_2_A = None
      self.rho_method_2_B = None

  def density_method_1(self, T):
    return self.rho_method_1_A*T + self.rho_method_1_B*T**2

  def density_method_2(self, T, P):
    return P*(self.rho_method_2_A/T + self.rho_method_1_B*log(T))

  def density_method(self, *args, **kwargs):
    if self.method == 1:
      return self.density_method_1(*args, **kwargs)
    elif self.method == 2:
      return self.density_method_2(*args, **kwargs)
    else:
      raise ValueError("No density method found")

class Water(Density):
  def __init__(self, method):
    super(Water, self).__init__(method=method)
    self.rho_method_1_A = 0.2
    self.rho_method_1_B = 0.0088
    self.rho_method_2_A = 1.9
    self.rho_method_2_B = 10

class Air(Density):
  def __init__(self, method):
    super(Air, self).__init__(method=method)
    self.rho_method_1_A = 0.2
    self.rho_method_1_B = 0.0088
    self.rho_method_2_A = 1.9
    self.rho_method_2_B = 10

water = Water(method=1)
air = Air(method=2)

print(water.density_method(T=1))
print(air.density_method(T=1, P=2))

The solution can be improved but the general idea is to have a "wrapper" method density_method that calls the relevant density_method_* for each sub-class of Density.
Edit (following the comments to my answer):
You should look into python method overloading, like the example here:
https://www.geeksforgeeks.org/python-method-overloading/
from multipledispatch import dispatch

#passing one parameter
@dispatch(int,int)
def product(first,second):
    result = first*second
    print(result);

#passing two parameters
@dispatch(int,int,int)
def product(first,second,third):
    result  = first * second * third
    print(result);

#you can also pass data type of any value as per requirement
@dispatch(float,float,float)
def product(first,second,third):
    result  = first * second * third
    print(result);

#calling product method with 2 arguments
product(2,3,2) #this will give output of 12
product(2.2,3.4,2.3) # this will give output of 17.985999999999997


text:
Q: Munit 2.1 mock a Map response and reference it as file How to mock a Map response in munit2 if I would like to reference a file. For example in db connector. I tried
#[MunitTools::resultOfScript('mockExamples/singleStudentGet.groovy')]

and
#[resultOfScript('mockExamples/singleStudentGet.groovy')]

The later used to work in munit1.2 but is not working in munit2.
Please help.

A: Using resultOfScript() doesn't seem to be supported in MUnit 2.x. As an alternative you could migrate the Groovy script to a DataWeave script. See the docs at https://docs.mulesoft.com/munit/2.2/mock-file-cookbook#mocking-files-using-variables-in-a-dataweave-module for an example of how to use DataWeave scripts in MUnit 2.


text:
Q: foreach inherited (sub-class) object in a super-class list I have a super-class named "ClassA" and two sub-classes "Class1" and "Class2".
I have a list containing objects of "Class1" and "Class2", that list is of type "ClassA".
I want to loop through only the "Class1" objects in the list by doing something like
List<ClassA> AList = new List<ClassA>;
AList.Add(new Class1());
AList.Add(new Class2());

foreach (Class1 c1 in AList)
{
    // Do Something
}

but when I do that, the code throws an exception when it reaches an object that is not of type "Class1".
How can this be done in a simple way without having to check the type of the object in the list and cast it if it's the correct type. like this:
foreach (ClassA cA in AList)
{
    if (cA.GetType() == typeof(Class1))
    {
        // Do Something
    }
}

A: foreach(Class1 c1 in AList.OfType<Class1>())
{
    //do something
}

A: Using LINQ:
foreach (Class1 c1 in AList.OfType<Class1>()) { }

Note that if you want to check for a type in a loop, the as and is operators are meant for this. Like:
foreach (ClassA cA in AList) {
  Class1 c1 = cA as Class1;
  if (c1 != null) {
    // do something
  }
}


text:
Q: Sagemaker memory leak I deployed a deep learning model in the sagemaker and created a endpoint.
Unfortunately, I put it a large size image then the endpoint return  'RuntimeError: CUDA error: out of memory'.
So I would like to re-launch the endpoint, but seems there is not any restart button.
What could I do for restarting it?
Thank you

A: Assuming you meant UpdateEndpoint by "restart", you will not be able to update a SageMaker endpoint if it is already in 'Failed' status. This is documented in SageMaker API references.
If you have already identified the cause of endpoint failure, you can delete the failed endpoint and create a new one with the correct model.


text:
Q: Magento 2.4 header.phtml file issue In my Magento 2.4 platform . I have  my header.phml in below location:/var/www/html/magento/app/design/frontend/MyPackage/MyTheme/templates/html/header.phml . But Magento is not reading the header file I created. It runs fine on localhost. I just want to know from where server is taking the header .phtml file . Same file works in localhost. I have used cache command and all css styles are lost and also the template header is not updated.
Any pointers to this will be much appreciated.


text:
Q: how to make div size fixed? I have a problem in my project, where the size of the div varies, which shouldn't happen. I#ve put an example which shows it.

html, body, .grid-container { height: 100%; margin: 0; }

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  gap: 1px 1px;
}

._ {
  display: grid;
  grid-template-columns: 120px 120px;
  grid-template-rows: 1fr 1fr;
  gap: 1px 1px;
  grid-area: 1 / 2 / 4 / 4;
}

.A { grid-area: 1 / 1 / 3 / 2;
    align-self: flex-end;
    border: 1px solid red;
    position: relative;
    }

.B { grid-area: 1 / 2 / 3 / 3;
    border: 1px solid red;
    position: relative;
    }

.grid-container *:after {
 content:attr(class);
 position: absolute;
 top: 0;
 left: 0;
}

.circle {
  width: 115px;
  height: 115px;
  background: red;
  border-radius: 100px;
}

If you do not pu the circle div in, A & B are the same height. But as soon as you put it into the A div, the size changes to perfectly equal the one of the circle, which I totally do not want to happen.
Since I'm building a Connect 4 game and I use the Border for the "GameField" it has to stay the same size.
I've already tried adding the parameter height: 690; to the A div (every circle is 115px->6 circles = 690)  but then the align end did not work anymore. I also change between align-self: end; and align-self: flex-end; but that didn't change anything...
If what Im searching for isn't possible, I would love to know how else I can achieve a outline of a specificities set of cells in a css grid.
Thank you so much in advance for helping (or at least trying) me. <3

A: I didn't understand literally, but you can try and use this instead of above.
I think you can add the features you want (such as height) to this code I wrote.

.grid-container {
    display: inline-table;
}
._ {
    display: grid;
    grid-template-columns: 120px 120px;
    grid-template-rows: 1fr 1fr;
    gap: 1px 1px;
    grid-area: 1 / 2 / 4 / 4;
}
.grid-container *:not(.circle):after {
    content: attr(class);
    position: absolute;
    top: 0;
    left: 0;
}
._ > div {
    border: 1px solid red;
    align-self: end;
    position: relative;
    display: inline-flex;
}
.circle {
    width: 115px;
    height: 115px;
    background: red;
    border-radius: 100px;
    align-self: end;
}
.B {
    height: 20px;
}
.C {
    height: 30px;
}
.D {
    height: 40px;
}

You don't have to use css for .A and .B, you're able to use like code above. Also I added two div to better understand
If I misunderstood, send me message back, I'll check again


text:
Q: extending a class with a generic T In TypeScript is there a way to extend a class with a generic type? Refer to my "hypothetical scenario" example where I want my class to have property called "breed" (or whatever):
interface dog {
  breed: string;
}

export class animal<T> extends T {
  legs: number;
}

export class main {
  private mydog: animal = new animal<dog>();

  constructor() {
    this.mydog.legs = 4;
    this.mydog.breed = "husky"; //<-- not conventionally possible, but basically want to acheive this
  }
}

A: You can't because classes are defined at compile time, and when the animal class is compiled T is not known.
You can however define a property of type T inside animal.
interface dog {

  breed: string;

}

export class animal < T > {
  actual: T;
  legs: number;
}

export class main {

  private mydog: animal < dog > = new animal < dog > ();

  constructor() {

    this.mydog.legs = 4;
    this.mydog.actual.breed = "husky"; // this will fail because actual is undefined (you must set it too)
  }

}

I guess it depends on why you need the animal class to be generic, but you can also just have dog extend animal.
export class animal {
  legs: number;
}

class dog extends animal {
  breed: string;
}

export class main {

  private mydog: dog = new dog();

  constructor() {

    this.mydog.legs = 4;
    this.mydog.breed = "husky";
  }

}


text:
Q: Find propositional formulas $\phi$ and $\psi$ such that $(\phi \rightarrow (\psi \rightarrow (¬\psi)))$ is a theorem of L. Find propositional formulas $\phi$ and $\psi$ such that $(\phi \rightarrow (\psi \rightarrow (¬\psi)))$ is a theorem of L.
So every axiom is a theorem of L so I thought there would be some way to write $(\phi \rightarrow (\psi \rightarrow (¬\psi)))$ in terms of some variables $p_1, p_\ldots$ so that it is one of the axioms;
(A1) $(\phi \rightarrow ( \psi \rightarrow \phi))$
(A2) $((\phi \rightarrow (\psi \rightarrow \chi))\rightarrow((\phi \rightarrow \psi)\rightarrow(\psi \rightarrow \chi)))$
(A3) $(((¬\phi) \rightarrow (¬\psi)) \rightarrow (\psi \rightarrow \phi))$
But I am not sure how to do that or if it is even the correct approach.
Thanks
By trying to use A3 I have got $((p_1 \rightarrow (p_2 \rightarrow p_3)) \rightarrow ((p_1 \rightarrow p_2) \rightarrow (p_1 \rightarrow p_3)))$ but I expect that is totally wrong.

A: Looking at the first axiom, it's enough to require that $\phi=\left(\neg \psi\right)$, so let $\phi=(\neg p)$ and $\psi =p$.

A: Axioms are frmulated with schematic letters. In :

(A1) $(A→(B→A))$

$A$ and $B$ are variable in the metalanguage which stay for formulae; we may replace them with formulae whatever and we will get always an instance of the axiom.
Thus, if $\varphi$ and $\psi$ are formulae, as suggested by Git Gud, the following are both instances of (A1) :

$\vdash (\varphi → (\psi → \varphi))$

and

$\vdash (\lnot \psi →(\psi → \lnot \psi))$.

The first one has been obtained with the subst of the formula $\varphi$ in place of the schematic letter $A$ and with $\psi$ in place of $B$.
The second one with the subst of the formula $\lnot \psi$ in place of the schematic letter $A$ and with $\psi$ in place of $B$.
The only care we must take is that substitution must be uniform (as per comment of Hunan Rostomyan) i.e. we must replace each occurences of, let say, $A$ with the same formula.

A: Interesting question and I think there are three options:

*

*$ \phi \equiv  (\psi \rightarrow (¬\psi) $ (for example if $ \phi $ is $  \psi \rightarrow  \lnot \psi)$  but simple equality is enough.

*$ \lnot \phi $ is a theorem , then you get impossible antecedent.

*$ \psi \rightarrow \lnot\psi $ is a theorem, what will be the case if  $\lnot\psi $ is a theorem , then you get true concequent.
Each of these three off course stands for an infinite number of formulas so have a pick.

A: What is "(ϕ→(ψ→(¬ψ)))"?  It is a conditional.
What do we know about all conditionals?  They have an antecedent and a consequent.
What is the antecedent of (ϕ→(ψ→(¬ψ))), and what is it's consequent?  The antecedent is ϕ and the consequent is (ψ→(¬ψ).
So, how might we make (ϕ→(ψ→(¬ψ))) into a theorem?  Well, all tautologies are theorems by the completeness theorem.  So, how might we make (ϕ→(ψ→(¬ψ))) into a tautology?
Well, let's suppose we substituted ϕ with (ψ→(¬ψ)).  We would then have the well-formed formula [(ψ→(¬ψ))→(ψ→(¬ψ))].  Thus we might substitute  ϕ with (p→(¬p)) and ψ with p to obtain a formula which is a theorem of L.


text:
Q: Identify $E(X\mid X+Y)$ for $X$ and $Y$ independent and Poisson I am currently trying to understand how does an instance of the EM algorithm is derived when there are "hidden variables" in this old paper: http://www.ncbi.nlm.nih.gov/pubmed/18238264.
I don't really understand how the expectation step is derived, and what bothers me the most, is that I cannot prove the following statement (right before 2.11):
$$
\mathbb{E}[X|X+Y] = \frac{(X+Y)\lambda_X}{\lambda_X+\lambda_Y}
$$
where $X \sim Poisson\{\lambda_X\}$ and $Y \sim Poisson\{\lambda_Y\}$
To begin, I wrote the discrete expectation as follows:
$$
\mathbb{E}[X|X+Y] = \sum_{k=1}^{X+Y} k P(X=k|X+Y)\\
= \sum_{k=0}^{X+Y} k \frac{P(X+Y|X=k)P(x)}{P(X+Y)}
$$
Where I can replace
$$ P(X+Y=k) = \frac{(\lambda_X+\lambda_Y)^ke^{-(\lambda_X+\lambda_Y)}}{k!}$$
$$ P(k=x) = \frac{\lambda_X^xe^{-\lambda_X}}{x!}$$
$$ P(X+Y=k|x) = P(Y=x-k) = \frac{\lambda_Y^{x-k}e^{-\lambda_Y}}{(x-k)!}$$
but I dont really know how to mix that together, because I don't really see what does the event $X+Y$ stands for, and how does it rely on the x in the integral ?
Thank you very much for you help

A: Here is a hint:  Assuming $X$ and $Y$ are Poisson and independent, the conditional distribution of $X$ given that $X+Y = n$ is binomial with parameters $n$ and $p = \lambda_X/(\lambda_X + \lambda_Y)$.

Let us prove the above statement (which is stronger than simply doing the expectation calculation).  Consider the random variable $X + Y = N$.  Then
$$\Pr[X = x \mid N = n] = \frac{\Pr[(X = x) \cap (N = n)]}{\Pr[N = n]}= \frac{\Pr[(X = x) \cap (Y = n-x)]}{\Pr[N = n]}.
$$  The numerator is straightforward.  The denominator is $$\begin{align*} \Pr[N = n] &= \sum_{x=0}^n \Pr[(X = x) \cap (Y = n-x)] \\
&= \sum_{x=0}^n e^{-\lambda_X} \frac{\lambda_X^x}{x!} e^{-\lambda_Y} \frac{\lambda_Y^{n-x}}{(n-x)!} \\
&= \frac{e^{-(\lambda_X+\lambda_Y)}}{n!} \sum_{x=0}^n \binom{n}{x} \lambda_X^x \lambda_Y^{n-x} \\
&= \frac{e^{-(\lambda_X + \lambda_Y)}}{n!} (\lambda_X + \lambda_Y)^n, \end{align*}$$ which of course proves that the sum of independent Poisson variables is Poisson with rate equal to the sum of the individual rates.  Then $$\Pr[X = x \mid N = n] = e^{-\lambda_X} \frac{\lambda_X^x}{x!} e^{-\lambda_Y} \frac{\lambda_Y^{n-x}}{(n-x)!} e^{\lambda_X + \lambda_Y} \frac{n!}{(\lambda_X + \lambda_Y)^n} = \binom{n}{x} \left(\frac{\lambda_X}{\lambda_X + \lambda_Y}\right)^x \left(\frac{\lambda_Y}{\lambda_X + \lambda_Y}\right)^{n-x},$$ which of course is binomial with the claimed parameters.  The distributional properties immediately follow.


text:
Q: How to decode the URL when navigating one route to another roue in angular 5? I want to navigate a page from one route another route with query parameters.
var name = "engine & machinery";

this.router.navigateByUrl('dashboard?isopen='+true+'&name='+name);

From this, route navigate to dashboard page but query parameters not coming properly.
Url comes like,
http://localhost:4200/dashboard?isopen=true&name=engine%20&%20machinery=

Getting query parameters by the following code,
console.log("testt", this.route.snapshot.queryParamMap.get('name'));

its return only the "engine".
So, anyone help me for decoding the url and how to get the parameter value?
Thanks in advance

A: Use encodeURIComponent to encode the URL with special characters like these.
var name = encodeURIComponent("engine & machinery");

while creating the URL.
And in the receiving end, decode it using the decodeURIComponent
Something like this:
const encodedName = this.route.snapshot.queryParamMap.get('name')
const decodedName = decodeURIComponent(encodedName);
// This would yield `engine & machinery`

Here's a Sample StackBlitz for your ref.


text:
Q: Thread pool stack security issue In a naive implementation of a thread pool, can a piece of code that is being executed read the data left by some previous code on the stack (if it was running on the same thread instance)? Also, are there any other inherent security issues connected to thread pools?

A: Because all of the threads are running in the same process already, even if it were possible, it's not a security issue. Security boundaries are at the process level (well, technically, it does depend on your OS, but that's how it works in all the mainstream OSes).


text:
Q: List addAll() method not adding I am trying to make changes to the data source directly and notify the adapter of any changes. But addAll() does not update my list. It seems everything is OK in my code, but not during run. Please help me to correct the code. Thank You in Advance.
    List<String> pgs = myClass.getPgs();
    List<String> tmppgs = pgs;

    /*
    .
     lots of code for string processing which results in >> String content for each i
    .
     */

    for (int i = 0; i < tmppgs.size(); i++) {
    tmppgs.set(i, content);
    }

    Toast.makeText(getActivity(),String.valueOf(tmppgs.size()), Toast.LENGTH_LONG).show();
    // Toast shows desired result which is OK.

    pgs.clear();
    pgs.addAll(tmppgs);
    Toast.makeText(getActivity(),String.valueOf(pgs.size()), Toast.LENGTH_LONG).show();
    //Unexpectedly shows zero

    mAdapter.notifyDataSetChanged();
}

A: pgs and temppgs are the same ArrayList object:
List<String> tmppgs = pgs;

Hence, when you call pgs.clear(), you are emptying that one list. pgs.addAll(tmppgs) will have no effect, because you are attempting to add the contents of an empty list to itself.
It is unclear why you are doing the clear() and addAll() in the first place. If your objective is to wind up with the list modified via the set() calls... you are already modifying that list via the set() calls. Just comment out the clear() and addAll() lines (and, eventually, get rid of tmppgs, since you no longer need it).

A: You can change
List<String> tmppgs = pgs;

to
List<String> tmppgs = myClass.getPgs();;

shall work for you.


text:
Q: converting int to/from System.Numerics.BigInteger in C# I have a property that returns System.Numerics.BigInteger. When I casting the property to int, I got this error.
Cannot convert type 'System.Numerics.BigInteger' to 'int'
How can I convert int to/from System.Numerics.BigInteger in C#?

A: Here are some choices that will convert BigInteger to int
BigInteger bi = someBigInteger;
int i = (int)bi;
int y = Int32.Parse(bi.ToString());

Watch Out though if the BigInteger value is too large it will throw a new exception so maybe do
int x;
bool result = int.TryParse(bi.ToString(), out x);

Or
try
{
    int z = (int)bi;
}
catch (OverflowException ex)
{
    Console.WriteLine(ex);
}

Or
int t = 0;
if (bi > int.MaxValue || bi < int.MinValue)
{
    Console.WriteLine("Oh Noes are ahead");
}
else
{
    t = (int)bi;
}

A: The conversion from BigInteger to Int32 is explicit, so just assigning a BigInteger variable/property to an int variable doesn't work:
BigInteger big = ...

int result = big;           // compiler error:
                            //   "Cannot implicitly convert type
                            //    'System.Numerics.BigInteger' to 'int'.
                            //    An explicit conversion exists (are you
                            //    missing a cast?)"

This works (although it might throw an exception at runtime if the value is too large to fit in the int variable):
BigInteger big = ...

int result = (int)big;      // works

Note that, if the BigInteger value is boxed in an object,  you cannot unbox it and convert it to int at the same time:
BigInteger original = ...;

object obj = original;      // box value

int result = (int)obj;      // runtime error
                            //   "Specified cast is not valid."

This works:
BigInteger original = ...;

object obj = original;            // box value

BigInteger big = (BigInteger)obj; // unbox value

int result = (int)big;            // works

A: Having the int.Parse method only works if the initial BigInteger value would fit anyway.  If not, try this:
int result = (int)(big & 0xFFFFFFFF);

Ugly?  Yes.
Works for any BigInteger value?  Yes, as it throws away the upper bits of whatever is there.

A: By trying to improve the @lee-turpin answer when casting negative numbers, I came with a similar solution, but in this case without the issue with negative numbers. In my case, I was trying to have a 32-bit hash value from a BigInteger object.
var h = (int)(bigInteger % int.MaxValue);

Still ugly, but it works with any BigInteger value. Hope it helps.


text:
Q: Maximo/Oracle SQL statement returning unwanted data from joined tables Pretty sure it's a simple fix, but I'm lost.  Trying to pull data from joined tables where there's a checkbox = 1 (gditwocertflag).  I only want to see the specific row that's checked.  But I'm pulling every labor row from work orders that meet specificed criteria with that block being checked.  I've tried to join different ways with the same result, so I'm pretty sure it's not the join that's the issue. Also tried a nested select that errored on the sub query returning more than 1 row.  Here's where I'm at right now.  Is it how I'm calling it?
select w.wonum, l.laborcode as certifier
from maximo.workorder W, maximo.labtrans L
where w.wonum = l.refwo
and w.status = 'CLOSE'
and w.gditperformingrcc like ('MDKM%')
and w.gditusertype = 'PMEL'
and w.wonum not like ('QA%')
and l.gditwocertflag = '1'
and parent is null
and (w.actfinish >= trunc(add_months(sysdate, -12), 'MM')
and w.actfinish  < trunc(add_months(sysdate, -0), 'MM'))
;

A: Thanks for your help.  Problem solved.  We share a database with two other locations and I didn't filter them out specifically.  I thought the filters I had would have done the trick.  However, it didn't.  And coincidentally they have the some work order numbers that match some of ours, which isn't supposed to happen.  Which is why it appeared I was returning incorrect data.  I've been scratching my head at this for the last two days...

A: If GDITWOCERTFLAG is a YORN field in Maximo you should be using an Integer value to compare:
select w.wonum, l.laborcode as certifier
from maximo.workorder W
join maximo.labtrans L
on w.wonum = l.refwo
and l.gditwocertflag = 1
where w.status = 'CLOSE'
and w.gditperformingrcc like ('MDKM%')
and w.gditusertype = 'PMEL'
and w.wonum not like ('QA%')
and parent is null
and (w.actfinish >= trunc(add_months(sysdate, -12), 'MM')
and w.actfinish  < trunc(add_months(sysdate, -0), 'MM'))
;


text:
Q: MySQL Explain gives different result for same query, query performance changes I've been having some performance issues on my production server. The main issue, I think is the table pricelist_entries, which has approximately 6 million rows. Basically its holds all of the products available. The query below usually takes a second to execute but ever since the table pricelist_entries grew past 3 million rows the execution time has started to increase. The weird thing is that sometimes the same query will take 10 seconds, other times 1 second. First I thought that maybe its the query cache but I disabled that and I still get the same variating result. What I can see from the two explains is that when its fast the query only accesses about 5000 rows while when its slow it seem to do an almost full table scan. I can't figure out why this happens. Any help is appreciated.

A: Thanks for confirming that innodb_buffer_pool_size is OK.
Here are some ideas; I don't know which will be best:
Plan A
pricelist:  INDEX(pCurrent, tagged_to)
materials:  INDEX(companyID, article_nr_lev)

Plan B
SELECT STRAIGHT_JOIN ...
    FROM pricelist ...    -- first
    JOIN pricelist_entries ...
    LEFT JOIN materials

Please provide SHOW CREATE TABLE for each table; there could be some more clues there.
More
materials.article_nr_lev = pricelist_entries.peArtnr -- Whenever JOINing, the datatypes must be the same (or 'close').  Those two value are probably close enough -- same collation (mandatory) and both VARCHAR.  But they are of different lengths; I think that is 'close enough'.  However, do you sometimes need 255 characters, and sometimes need only 50?  For various subtle reasons (having to do with the execution of queries), it is better to keep VARCHAR sizes smaller (yet large enough to be safe).  I suspect the 255 could be changed to 50 without harm.
Also you have a lot of 4-byte INT fields that could probably be turned into smaller fields (eg, 2-byte SMALLINT UNSIGNED).  Shrinking table sizes often leads to improved performance, albeit minor.
category int(11) NOT NULL COMMENT '0 - Inget val 1 - Alkov 2 - ... -- Consider using ENUM.  That would avoid remembering the mapping.  (And take 1 byte instead of 4.)
Be careful about CHARCTER SET -- some columns are dec8, some are utf8.  The may be issues with comparisons, conversions, etc.  (I haven't noticed any problems with the query in question.)


text:
Q: Is it safe to omit "struct" keyword for structures in C header in C++? I know in C++ the struct keyword can be safely omitted for structures, but I'm not sure if the same rule can be safely apply to the structures inherited from C headers. To be more specific, those structures form socket interface, e.g., sockaddr_in, sockaddr_in6...etc
So, can I safely omit struct keyword for all the structures including those from C interfaces when I'm using C++?
I've done some searching on this one, but can't find any clear answer.

*

*Here is a similar question, but did not mention those old C structure
Why does C need "struct" keyword and not C++?

*Another one here
C++ struct keyword usage, but the question did not received a detailed or sure answer.

I did try to take out the struct keyword from one of my C++ source and it compiled without any error. But I would like to know if it's safe in all cases.


text:
Q: How to track pagination information for multi database connection? I have following setup
MySQL server instance1
MySQL server instance2
in both these table I have a single table records which are partitioned. I have to retrieve the data from each instance and show the data in JQGrid.
Here are the consideration to be made:
1) From each database instance only 1000 records needs to be got.
2) Merge these 1000 records and sort in ascending order by a default column.
3) Again from the merged records get only 1000 records to be shown in a Grid.
4) For the next 1000 records we should not show any of the earlier records which have been shown.
The major problem I am having is how to uniquely identify the last row shown from the fetched records.
I thought about doing it this way:
1) Get the rowid for each record from all the connection. But from two instances the rowid would be same then how would I identify which record is from which database?
2) Check for rowid and primary key combination. But if the client sets the primary key's auto-increment value as same on all the instance then we would not get a unique combination.
Am I missing something or is there any other way to do it?
I am using JDBC connection to connect the database.
[SOLVED IT]
Solved the problem by writing a small function which calculates and create a map for the number of records to be fetched from each connection for each iteration.
Sorry can't add the code here as it is clients IP.

A: You usually uniquely identify a row with a POJO class where you override your hashCode() and equals() methods basing on your class fields. You can put your last row into a HashMap and check against it.
A rownumber retrieved from the tables can be achieved by creating one using RANK() and PARTITION BY. Create a temporary or tmp_ table with your merging results then drop it.
hope this helps abit.

A: if the two mysql instance can see each other, how about create a view, UNION the two query results. then in java world, you could do query/pagination on this view?


text:
Q: I want to insert a 200k character data in a column using sqldev. I tried basic insert but it says string too long. may I know how can I insert it? I am using oracle sql developer and I need to insert a 200k data on one cell the data type of the column is already set to clob. However  when I tried to insert the data, it says
SQL Error: ORA-01704 : string literal too long


text:
Q: Composition of images with different dimensions I created a code to make an image composition ...
back=Import["https://i.stack.imgur.com/ouBUD.png"];
img1=Import["https://i.stack.imgur.com/0o8UW.png"];
img2=Import["https://i.stack.imgur.com/uHQWP.png"];
Graphics[{Inset[back,{Center,Center}],Inset[img1,{Left,Bottom}],Inset[img2,{Right,Top}]}]

I tested the dimensions to confirm that this composition is possible:
ImageDimensions[back]
ImageDimensions[img1]
ImageDimensions[img2]

I'm trying to generate the image below:

What is missing from the code so I can get what I want?

A: Need to specify positions for Inset in a specific way.
Graphics[{Inset[back, {Center, Center}, {Center, Center}, ImageDimensions[back]],
  Inset[img1, Scaled[{0, 0}]],
  Inset[img2, Scaled[{1, 1}]]}]

A: Perhaps ImageCompose?
Fold[ImageCompose[#, #2[[1]], #2[[2]], #2[[2]]] &,
  back, {{img1, {Left, Bottom}}, {img2, {Right, Top}}}]

If you wish to have a Graphics object, just wrap with Show:
Show[%, ImageSize -> 600, Frame -> True, PlotRangePadding -> Scaled[.02]]


text:
Q: Change umbraco email regex I want to change my umbraco email regex, because the one that umbraco has as standard is not accepting 'æøå' and uppercase letters. But i have no clue on where i can replace it. One that can help me? Thanks

A: Change following Data Type property, in your Document Type:

Bear in mind that this property might look a little bit different if you are not using Umbraco 7, but the principle is the same: enter the required regex to validate the field.


text:
Q: How can I use MEF to manage interdependent modules? I found this question difficult to express (particularly in title form), so please bear with me.
I have an application that I am continually modifying to do different things. It seems like MEF might be a good way to manage the different pieces of functionality. Broadly speaking, there are three sections of the application that form a pipeline of sorts:

*

*Acquisition

*Transformation

*Expression

In it's simplest form, I can express each of these stages as an interface (IAcquisition etc). The problems start when I want to use acquisition components that provides richer data than standard. I want to design modules that use this richer data, but I can't rely on it being there.
I could, of course, add all of the data to the interface specification. I could deal with poorer data sources by throwing an exception or returning a null value. This seems a long way from ideal.
I'd prefer to do the MEF binding in three stages, such that modules are offered to the user only if they are compatible with those selected previously.
So my question: Can I specify metadata which restricts the set of available imports?
An example:

Acquision1 offers BasicData only
Acquision2 offers BasicData and AdvancedData
Transformation1 requires BasicData
Transformation2 requires BasicData and AdvancedData
Acquisition module is selected first.
If Acquisition1 is selected, don't offer Transformation 2, otherwise offer both.

Is this possible? If so, how?

A: Your question suggests a structure like this:
public class BasicData
{
    public string Basic { get; set; } // example data
}

public class AdvancedData : BasicData
{
    public string Advanced { get; set; } // example data
}

Now you have your acquisition, transformation and expression components. You want to be able to deal with different kinds of data, so they're generic:
public interface IAcquisition<out TDataKind>
{
    TDataKind Acquire();
}

public interface ITransformation<TDataKind>
{
    TDataKind Transform(TDataKind data);
}

public interface IExpression<in TDataKind>
{
    void Express(TDataKind data);
}

And now you want to build a pipeline out of them that looks like this:
IExpression.Express(ITransformation.Transform(IAcquisition.Acquire));

So let's start building a pipeline builder:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Linq.Expressions;

// namespace ...

public static class PipelineBuidler
{
    private static readonly string AcquisitionIdentity =
        AttributedModelServices.GetTypeIdentity(typeof(IAcquisition<>));
    private static readonly string TransformationIdentity =
        AttributedModelServices.GetTypeIdentity(typeof(ITransformation<>));
    private static readonly string ExpressionIdentity =
        AttributedModelServices.GetTypeIdentity(typeof(IExpression<>));

    public static Action BuildPipeline(ComposablePartCatalog catalog,
        Func<IEnumerable<string>, int> acquisitionSelector,
        Func<IEnumerable<string>, int> transformationSelector,
        Func<IEnumerable<string>, int> expressionSelector)
    {
        var container = new CompositionContainer(catalog);

The class holds MEF type identities for your three contract interfaces. We'll need those later to identify the correct exports. Our BuildPipeline method returns an Action. That is going to be the pipeline, so we can just do pipeline(). It takes a ComposablePartCatalog and three Funcs (to select an export). That way, we can keep all the dirty work inside this class. Then we start by creating a CompositionContainer.
Now we have to build ImportDefinitions, first for the acquisition component:
        var aImportDef = new ImportDefinition(def => (def.ContractName == AcquisitionIdentity), null, ImportCardinality.ZeroOrMore, true, false);

This ImportDefinition simply filters out all exports of the IAcquisition<> interface. Now we can give it to the container:
        var aExports = container.GetExports(aImportDef).ToArray();

aExports now holds all IAcquisition<> exports in the catalog. So let's run the selector on this:
        var selectedAExport = aExports[acquisitionSelector(aExports.Select(export => export.Metadata["Name"] as string))];

And there we have our acquisition component:
        var acquisition = selectedAExport.Value;
        var acquisitionDataKind = (Type)selectedAExport.Metadata["DataKind"];

Now we're going to do the same for the transformation and the expression components, but with one slight difference: The ImportDefinition is going to ensure that each component can handle the output of the previous component.
        var tImportDef = new ImportDefinition(def => (def.ContractName == TransformationIdentity) && ((Type)def.Metadata["DataKind"]).IsAssignableFrom(acquisitionDataKind),
            null, ImportCardinality.ZeroOrMore, true, false);
        var tExports = container.GetExports(tImportDef).ToArray();
        var selectedTExport = tExports[transformationSelector(tExports.Select(export => export.Metadata["Name"] as string))];

        var transformation = selectedTExport.Value;
        var transformationDataKind = (Type)selectedTExport.Metadata["DataKind"];

        var eImportDef = new ImportDefinition(def => (def.ContractName == ExpressionIdentity) && ((Type)def.Metadata["DataKind"]).IsAssignableFrom(transformationDataKind),
            null, ImportCardinality.ZeroOrMore, true, false);
        var eExports = container.GetExports(eImportDef).ToArray();
        var selectedEExport = eExports[expressionSelector(eExports.Select(export => export.Metadata["Name"] as string))];

        var expression = selectedEExport.Value;
        var expressionDataKind = (Type)selectedEExport.Metadata["DataKind"];

And now we can wire it all up in an expression tree:
        var acquired = Expression.Call(Expression.Constant(acquisition), typeof(IAcquisition<>).MakeGenericType(acquisitionDataKind).GetMethod("Acquire"));
        var transformed = Expression.Call(Expression.Constant(transformation), typeof(ITransformation<>).MakeGenericType(transformationDataKind).GetMethod("Transform"), acquired);
        var expressed = Expression.Call(Expression.Constant(expression), typeof(IExpression<>).MakeGenericType(expressionDataKind).GetMethod("Express"), transformed);
        return Expression.Lambda<Action>(expressed).Compile();
    }
}

And that's it! A simple example application would look like this:
[Export(typeof(IAcquisition<>))]
[ExportMetadata("DataKind", typeof(BasicData))]
[ExportMetadata("Name", "Basic acquisition")]
public class Acquisition1 : IAcquisition<BasicData>
{
    public BasicData Acquire()
    {
        return new BasicData { Basic = "Acquisition1" };
    }
}

[Export(typeof(IAcquisition<>))]
[ExportMetadata("DataKind", typeof(AdvancedData))]
[ExportMetadata("Name", "Advanced acquisition")]
public class Acquisition2 : IAcquisition<AdvancedData>
{
    public AdvancedData Acquire()
    {
        return new AdvancedData { Advanced = "Acquisition2A", Basic = "Acquisition2B" };
    }
}

[Export(typeof(ITransformation<>))]
[ExportMetadata("DataKind", typeof(BasicData))]
[ExportMetadata("Name", "Basic transformation")]
public class Transformation1 : ITransformation<BasicData>
{
    public BasicData Transform(BasicData data)
    {
        data.Basic += " - Transformed1";
        return data;
    }
}

[Export(typeof(ITransformation<>))]
[ExportMetadata("DataKind", typeof(AdvancedData))]
[ExportMetadata("Name", "Advanced transformation")]
public class Transformation2 : ITransformation<AdvancedData>
{
    public AdvancedData Transform(AdvancedData data)
    {
        data.Basic += " - Transformed2";
        data.Advanced += " - Transformed2";
        return data;
    }
}

[Export(typeof(IExpression<>))]
[ExportMetadata("DataKind", typeof(BasicData))]
[ExportMetadata("Name", "Basic expression")]
public class Expression1 : IExpression<BasicData>
{
    public void Express(BasicData data)
    {
        Console.WriteLine("Expression1: {0}", data.Basic);
    }
}

[Export(typeof(IExpression<>))]
[ExportMetadata("DataKind", typeof(AdvancedData))]
[ExportMetadata("Name", "Advanced expression")]
public class Expression2 : IExpression<AdvancedData>
{
    public void Express(AdvancedData data)
    {
        Console.WriteLine("Expression2: ({0}) - ({1})", data.Basic, data.Advanced);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var pipeline = PipelineBuidler.BuildPipeline(new AssemblyCatalog(typeof(Program).Assembly), StringSelector, StringSelector, StringSelector);
        pipeline();
    }

    static int StringSelector(IEnumerable<string> strings)
    {
        int i = 0;
        foreach (var item in strings)
            Console.WriteLine("[{0}] {1}", i++, item);
        return int.Parse(Console.ReadLine());
    }
}


text:
Q: R : How to filter subset min of minutes in every hour? I'm still new to R. I can query selecting a first row of every hour by partition in SQL server management. I found a very big problem from my program it takes too long time with sqlQuery() function in R and more long on running my shiny web app so much. The one tested way to less take time is query of all data and prepare the data in R much faster.
So here is my example data :
                    Date Val
1    2017-06-11 04:00:02  83
2    2017-06-11 04:01:02  77
3    2017-06-11 04:03:01  78
..
4    2017-05-11 05:00:03  83
5    2017-05-11 05:01:02  95
6    2017-05-11 05:02:02  10
..
7    2017-05-11 06:01:00  29
8    2017-05-11 06:02:02  39
9    2017-05-11 06:03:03  85
10   2017-05-11 06:04:02  71
..
11   2017-05-11 07:05:02  33
12   2017-05-11 07:06:02  14
.. (many rows)
13   2017-05-12 00:01:01  20
14   2017-05-12 00:03:01  45

Sometimes there are missing rows during an hour. My problem is how to filter only a min minute row of every hour.
My example output :
                    Date Val
1    2017-05-11 04:00:02  83
4    2017-05-11 05:00:03  83
7    2017-05-11 06:01:00  29
11   2017-05-11 07:05:02  33
13   2017-05-12 00:01:01  20

Any idea please help. Thank you so much.

A: Here is how I would do. First order by the date. Second group the data by hour (actually first floor Date, then group by the floored Date) and pick up the first row in each group.
library(dplyr)
library(data.table)
library(lubridate)

df <- setDT(df)[order(Date)]
output <- df[, .(Date = Date[1], Val = Val[1]) ,
             by = .(Group = floor_date(Date, "hour"))]
head(output)
##                  Group                Date Val
## 1: 2017-05-11 04:00:00 2017-05-11 04:00:49  99
## 2: 2017-05-11 05:00:00 2017-05-11 05:01:13  45
## 3: 2017-05-11 06:00:00 2017-05-11 06:00:08  45
## 4: 2017-05-11 07:00:00 2017-05-11 07:00:20  64
## 5: 2017-05-11 08:00:00 2017-05-11 08:00:18  99
## 6: 2017-05-11 09:00:00 2017-05-11 09:06:25  40

I tested with this example data
time_origin <- ymd_hms("2017-05-11 04:00:02")
set.seed(123)
df <- data.frame(Date = (sample(100000, size = 1000, TRUE) %>% seconds() %>%
                                  `+`(time_origin)),
                  Val = sample(99, size = 1000, TRUE))

A: You can use lubridate and dplyr to convert the dates, extract the date and hour, then filter for the minimum time within an hour by date. I changed your June 31 to June 30 :)
library(dplyr)
library(lubridate)

dataset %>%
  mutate(Date = ymd_hms(Date), dt = as_date(Date), hr = hour(Date)) %>%
  group_by(dt, hr) %>%
  filter(Date == min(Date)) %>%
  ungroup() %>%
  select(Date, Val)

                 Date   Val
               <dttm> <int>
1 2017-06-30 04:00:02    83
2 2017-05-11 05:00:03    83
3 2017-05-11 06:01:00    29
4 2017-05-11 07:05:02    33
5 2017-05-12 00:01:01    20