text:
Q: How to find $\int_{0}^{1}\frac{1}{x^{2}+2x+2}\mathrm dx$ with contour integration I want to evaluate the following integral $$\int_{0}^{1}\frac{1}{x^{2}+2x+2}\mathrm dx$$ by contour integration; I have a problem with the choice of the contour/ branch cuts.
Where can I find some some solved integrals like this ?

A: While I certainly wouldn't recommend residue calculus for the integral in question, I couldn't resist doing it anyway.
Let us start by a change of coordinates, mapping $[0,1]$ onto $[0,\infty)$ to get into more familiar territory for residue calculus. We can for example put $t=x/(1-x)$ to get
\begin{align}
\int_0^1 \frac{1}{(x+1)^2 + 1}\,dx &= \int_0^\infty \frac{1}{(\frac{t}{t+1}+1)^2 + 1}\cdot \frac{1}{(t+1)^2}\,dt \\
&= \int_0^\infty \frac{1}{5t^2+6t+2}\,dt, \\
\end{align}
and this can be evaluated by integrating
$$f(z) = \frac{\log z}{5z^2+6z+2}$$
over a keyhole contour, using the natural branch of $\log z$. The function $f$ has poles at $-3/5 \pm i/5$. Omitting lots of details, you end up with
\begin{align}
\int_0^\infty \frac{1}{5t^2+6t+2}\,dt &= -\operatorname{Res}\limits_{z=-3/5+i/5} \frac{\log z}{5z^2+6z+2} - \operatorname{Res}\limits_{z=-3/5-i/5} \frac{\log z}{5z^2+6z+2} \\
&= -\frac{\log(-3/5+i/5)}{2i} + \frac{\log(-3/5-i/5)}{2i} \\
&= \arctan\frac13
\end{align}
which in fact is the same as $\arctan 2- \frac{\pi}{4}$ obtained by Dan (after he fixes his typo).

A: While I can help you with this particular example, if you're just looking for a reference request, I'd recommend either Lars Ahlfors's Complex Analysis or Elias Stein's Complex Analysis No. 2 (part 2 of a great 3 part series). Both contain several examples of how to integrate rational function using different types of contour integrals and try to show general methods of solution. (Although, like most types of integration, it's definitely not an exact science; there are frequently clever manipulations/argument you can do to simplify the process of integrating a particular function.)
Edit: In this particular case, it's worth noting there's a far more direct approach than contour integration: Completing the square yields
\begin{align*}
    \int_0^1 \frac{1}{(x + 1)^2 + 1} \, dx &= \arctan(x+1)\,\big|_{\,0}^{\,1} = \arctan(2) - \frac{\pi}{4}
\end{align*}


text:
Q: An input loop for reading a file I'm a beginner in programming and I need help with this snippet of code presented in my book.
for (My_type var; ist >> var;) { // read until end of file
// maybe check that var is valid
// do something with var

}

if (ist.fail()) {
ist.clear();
char ch;
// the error function is created into the book :
if (!(ist >> ch && ch == '|')) error("Bad termination of input\n");

}
// carry on : we found end of file or terminator

This example is about reading values from  a file. I've tried to use this but I'm having some troubles in understanding how it works :

*

*If I try to test the stream state after the loop I get both eof and fail state, how is that possibile ? How to avoid triggering both fail and eof ?

*When is EOF triggered exactly ? From my test it seems to be triggered when I reach the last value of a sequence, is this definition correct ?
Thank you.

A:
If I try to test the stream state after the loop I get both eof and fail state, how is that possibile ? How to avoid triggering both fail and eof ?

It is possible if there is a character that cannot be converted to My_type, and that character is the last character in the file. Then, failbit and eofbit will be set.

When is EOF triggered exactly ? From my test it seems to be triggered when I reach the last value of a sequence, is this definition correct ?

Yes, eofbit gets set when the last character is read.
Quoting from std::basic_istream:

The extraction stops if one of the following conditions are met:

*

*end-of-file occurs on the input sequence;

*inserting in the output sequence fails (in which case the character to be inserted is not extracted);

*an exception occurs (in which case the exception is caught, and only rethrown if failbit is enabled in exceptions()).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stress in the question: How about you? If I transcribe this question "How about you?" to IPA it looks like: [ haʊ əˈbaʊt yu]. The dictionary shows the word "about" with primary stress on its second syllable but I think in my question it loses the stress:
[context] Hi. How are you? ... I'm fine. How about you?
The way I say it sounds more like this: [ haʊ(w)əbaʊtʃyu ] with some stress on "how" and "you": https://clyp.it/oazaugqw
I would be grateful for your suggestion regarding the stress in my situation.


text:
Q: docker build failed to load cache key: pull access denied, repository does not exist I am trying to build aws/aws-for-fluent-bit and create ECR image. But I download from aws/aws-for-fluent-bit github and build by docker and get docker build error.I don't know how to solve this error.
`=> CANCELED [builder  5/33] RUN yum upgrade -y                                                                                2.0s
=> CANCELED [stage-1  2/18] RUN yum upgrade -y     && yum install -y openssl11-devel           cyrus-sasl-devel           pkgconf  2.0s

FROM docker.io/library/aws-fluent-bit-plugins:latest:

failed to load cache key: pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed`
I download from https://github.com/aws/aws-for-fluent-bit and build docker by image and upload to ECR.I want to add customize conf in fluent bit image.


text:
Q: js jquery slideshow I have been using a jquery slideshow, but when I include a jquery newsticker (text that scrolls to the right) either the slideshow or the menu javascript popup (or both) do not work. For instance, if I put

right above the slideshow script, the slidshow works but something else does not. If I put the code inside the head tag, its the other way around. This is very unusual (and not logical), but Ive been troubled with this stuff for 6 hours. I am sure this is the only link to jquery, besides a prototype.js that works with the menu. However, I am simply editing the website so I do not know how everything works.
Does anyone have an idea about what may be the solution?
The other way I can deal with this is by using a javascript slideshow (but no jquery).
But I cant find an example of what I want, that works without jquery.
What I need is this - php gets all images from a folder, and data (links) from the database. Each image is actually a link, and all images are displayed inside a div.

div id slideshow is what the javascript (again, not jquery) uses to know what to cycle (fade animation). Can someone please help me here?

A: Other libraries like prototype and mootools also share the same "$" alias so when combined in same page they conflict.
You will need to use jQuery.noConflict() to resolve.
In a script tag immediately after jQuery loads call:
 jQuery.noConflict();

Now in order to continue using "$" in your code, wrap code in:
  jQuery(function($){/* $ argument passes use of $ alias for jQuery into function*/

      $(selector).hide() ; /* can use normal jQuery syntax inside this function*/

  });

http://docs.jquery.com/Using_jQuery_with_Other_Libraries


text:
Q: Build path and use in external command How to insert my SCRIPT_PATH Variable into PowerShell script path? Also anyone know any Visual Studio Like tool I can write those? I think Visual Studio uses different .net vbs.
Here is the code:
SCRIPT_PATH = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) - (Len(WScript.ScriptName)))
MsgBox SCRIPT_PATH
Set objShell = CreateObject("WScript.Shell")
objShell.Run "RUNAS  /user:Domain\User ""powershell SCRIPT_PATH & Delete_App_Script.ps1"""
Set objShell = Nothing

How do I do SCRIPT_PATH = SCRIPT_PATH + Delete_App_Script.ps1?
SCRIPT_PATH = SCRIPT_PATH & "Delete_App_Script.ps1" doesn't work.
It gives no errors, so I am not sure what is the problem.
Am I missing some "" or some ,,?
I've seen some .Run ,,, syntax for Admin running and this one, doesn't explain what goes into "".
Not looking forward creating interface for this.
This doesn't work:
Set objShell = CreateObject("WScript.Shell")
SCRIPT_PATH = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) - (Len(WScript.ScriptName)))
SCRIPT_PATH = SCRIPT_PATH & "Delete_App_Script.ps1"
objShell.Run "RUNAS  /user:Dom\adm ""powershell SCRIPT_PATH"""
Set objShell = Nothing

But this works:
Set objShell = CreateObject("WScript.Shell")
objShell.Run "RUNAS  /user:Dom\adm ""powershell C:\Delete_App_Script.ps1"""
Set objShell = Nothing

What am I missing?

A: Use the appropriate FileSystemObject methods when handling paths:
Set fso = CreateObject("Scripting.FileSystemObject")

SCRIPT_PATH = fso.GetParentFolderName(WScript.ScriptFullName)
SCRIPT_PATH = fso.BuildPath(SCRIPT_PATH, "Delete_App_Script.ps1")

For using variables inside strings you need to concatenate the variables to the rest of the string, as @Lankymart pointed out. This is also documented in the language tag info.
objShell.Run "RUNAS /user:Domain\User ""powershell " & SCRIPT_PATH & """"

Note also that you should put the path in double quotes in case it contains spaces:
objShell.Run "RUNAS /user:Domain\User ""powershell \""" & SCRIPT_PATH & "\"""""

and you should use the parameter -File, otherwise PowerShell would interpret the script path as a command string, which wouldn't fail for paths with spaces.
objShell.Run "RUNAS /user:Domain\User ""powershell -File \""" & SCRIPT_PATH & "\"""""


text:
Q: Setup kotlin project with gradle I'm new to kotlin and gradle and tried to set up my very first project:
build.gradle
buildscript {
   ext.kotlin_version = '1.0.1-1'

   repositories {
     mavenCentral()
     jcenter()
   }

   dependencies {
     classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
   }
}

apply plugin: "kotlin"

src\main\kotlin\main.kt
package hello

fun main(args: Array<String>) {
   println("Hello World!")
}

And I get the error message "src\main\kotlin\main.kt: (4, 4): Unresolved reference: println".
The build.gradle file I copied from http://kotlinlang.org/docs/reference/using-gradle.html
I'd expect that the standard libraries are included automatically - or do I need to add something here?
I'm using gradle 2.12, JDK 1.8. (in case this matters)

A: The reference is missing the kotlin-stdlib dependency. It is not added automatically.
kotlin-gradle-plugin buildscript dependency is only Gradle plugin for Kotlin builds, and it doesn't add any dependencies to your project code. In order to use the standard library, one should add it as a dependency.
Append the following to your build.gradle:
repositories {
    jcenter()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

(jcenter() is needed again, these repositories are different from those in buildscript)


text:
Q: Windows 8 offline updates I am trying to update a Windows 8 installation on a machine that is not connected to the internet.
I have been told that standalone installers exist but ultimately the Microsoft sites just direct me to run windows update which isn't an option. Where can I find the standalone installers?

A: You can use WSUS Offline Update to update computers that aren't connected to the internet.  But you'll need a computer that does have access to Windows Update to create the offline install media first.

Then you run the installer on the target computer with the update media targeted:


text:
Q: JSR223 Jmeter. Написание запроса на groovy Добрый день господа форумчане.
Прошу помочь со следующей проблемой
нужно с помощью JRS223 на языке groovy распарсить html(Возможно xml) index(главной страницы любого сайты) и вывести в debug список найденных элементов (среди элементов title и все ссылки).
Регулярка для запросов имеется: <title>(.*?)</title>|<a href="(.*?)"
Структура кейса пока-что выглядит так:

A: Отличный скриншот, Кирилл, но вообще-то это не сервис, где люди пишут для вас вместо вас код
Так что на будущее лучше показывайте что внутри JSR223 PostProcessor и лучше не в виде скриншота, а в виде кода
В виде исключения держите примерную имплементацию:
(prev.getResponseDataAsString() =~ /<title>(.*?)<\/title>|
    log.info(match as String)
}

И результат ее работы

*

*prev - результат выполнения предыдущего Sampler, документация по всем функциям - SampleResult

*log - Log4JLogger
Больше информации на тему всех этих prev, log, ctx, vars, props - Top 8 JMeter Java Classes You Should Be Using with Groovy


text:
Q: JSQMessagesViewController - Make tailless bubble for image message I am trying to create a JSQMessage with MediaItem that is without a tail.
I am creating the message with:
JSQMessage* imageMessage = [JSQMessage messageWithSenderId:fileMessage.sender.userId displayName:senderUser[@"nickname"] media:mediaItem];

however I don't see an option to customise the bubble. Is there a way of doing this?

A: You just need to define your bubble style at the top of your file.
        incomingBubble = JSQMessagesBubbleImageFactory(bubble: UIImage.jsq_bubbleCompactTailless(), capInsets: UIEdgeInsets.zero, layoutDirection: UIApplication.shared.userInterfaceLayoutDirection).incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleBlue())
        outgoingBubble = JSQMessagesBubbleImageFactory(bubble: UIImage.jsq_bubbleCompactTailless(), capInsets: UIEdgeInsets.zero, layoutDirection: UIApplication.shared.userInterfaceLayoutDirection).outgoingMessagesBubbleImage(with: UIColor.lightGray)


text:
Q: Why are bubble canceled in Gell Mann-Low formula ? (I need to check the definition of Bubbles) In Quantum field theory and the standard model from Schwartz, it is written on page 91 that bubbles are "diagram that have connected subgraphs not involving any external point"
And they say that such diagram will not contribute to the Gell-Mann-Low formula because they will simplify with the denominator.
But I don't understand this.
Indeed, if I only have the condition: "diagram with connected subgraph not involving external points", I could end up with a graph that involves 2 subgraphs.

*

*One where the external points are connected to some of the internal ones

*One where there are only internal points

It fullfill the condition as the second graph doesn't involve external points. And if they in fact meant that all the connected subgraphs musn't involve external points, for me it is not possible as I will always have external points involved in the numerator of Gell Mann-Low.
And in such a case because the first subgraph mixes internal & external points it will never be able to cancel with the denominator of Gell Mann Low?
Shouldn't be the definition of bubbles the following:
A graph is a bubble if all the external points are not connected to internal points. And in this case it will be simplified by the denominator of Gell Man Low when we will do the perturbative expansion.
What do I misunderstand?

A: You just need to read the statement on page 91 more carefully. Schwartz says:

To see the cancellation, note that the extra diagrams both include bubbles. That is, they have connected subgraphs not involving any external point. [emphasis present in the original]

He's not saying that diagrams with connected subgraphs that involve no external points are bubbles, he's saying they include bubbles. A bubble is indeed a diagram with no external points. The cancellation comes about by the denominator being the sum over bubble and the numerator factoring into the sum over diagrams with no bubble multiplied by the sum over bubbles, because disconnected diagrams factor into the product of their connected components.


text:
Q: Do static string variables occupy memory space even when null? My requirement is to pass some parameters from a function to another page.
I considered two ways of doing it - 1)sessions , 2) Query strings.
Sessions are known to increase load on the server as apposed to query strings.
This is the way am extracting parameter values from the url(after using query string)
static string para1 ; static string para2;
string[] parts = urlString.Split((new string[] { "?para1=", "&&para2="}), StringSplitOptions.None);

 para1 = parts[1];

 para2= parts[2];

Do these strings results in loading memory if I assign them to null after use? Is using session better than query strings in terms of memory allocation and server performance.

A: Firstly the memory used by these couple of strings is likely to be fairly small in the grand scheme of things, so probably not worth losing a lot of sleep over.
In terms of session vs query string, session variables will stay around for the duration of the user's session.  Also consider whether the hosting environment can support session state.
Also your query string variables will stick around as part of the request object for the duration of the call anyway.

A: I don't think that memory consumption is the main criteria upon which to decide whether to use query string parameters or session variables. In your example, the variables are static anyway so that the memory consumption should not be dependent on the number of users. Please note that static variables can have various unexpected effects in a web application as they are shared between all users.
In general, I'd prefer using query string parameters to transmit data to a certain page. Query string parameters are scoped to the request, so they are available to the requested page only whereas session variables can be accessed from any page.
Also, memory consumed by query string parameters is freed automatically after the request whereas you need to remove session variables if you don't need them anymore if you want to be very efficient as regards memory consumption. Sure, a session will time out if the user is not active anymore, but depending on your configuration this might result in wasting memory for half an hour.
No rule without exceptions: I'd use session variables instead of query string parameters if one of the following conditions is met:

*

*The data is security critical: session variables are stored on the server whereas query string parameters are transmitted to the client and are visible in the browser.

*If a large amount of data is to be transmitted to the other page it is also more efficient to keep the data on the server. In some browsers there is a limit on the length of a query string, so you sometimes cannot use this.

*The data is widely used in the application (widely as in "almost every page") so that the query string parameters had to be repeated over and over again.

A:
Do static string variables occupy memory space even when null?

Technically, yes: all variables have at minimum the pointer size of the machine.  As they are (currently) static, this pointer will remain until your site is shutdown by IIS idle timeout.  But only one pointer per variable, no matter how many requests are made.  Hardly worth the time considering.
If you set them to null after, the memory used by the content should be freed later by the GC, but the pointer will remain.
If you don't use static, then they will be freed as once they go out of scope.
Session always has an extra overhead (not least choosing options for its configuration) and you still need to get the values into session in the first place.  If they're only used for a single request, then there's no need to put them in session (which is ideally used to store values across multiple requests).
Not the topic, but worth noting:
Static variables are shared across all requests, so it's possible (likely?) if two requests are made at the same time then one will be getting the querystring parameters from the other request, more likely the longer processing takes after setting the values.   Best advice is to make these non-static and simply recreate them as required or pass them around if needed in multiple methods.


text:
Q: Maintaining mysql db and server loads I am creating a chart using information from mysql. The problem is, the load on the database is huge and when you have hundreds or more people accessing the chart at the same time, MASSIVE stalling issues arise.
The queries look like the two I have listed below:
$stmt=$db->prepare("SELECT COUNT(*) AS cnt
                    FROM stream_updates
                        INNER JOIN members
                    ON members.username=stream_updates.username
                    WHERE (stream_updates.time between (NOW() - INTERVAL 1 DAY) AND NOW())
                    AND (members.username = :user) OR members.username IN (
                           SELECT friend2 as username FROM list_friends
                           WHERE (friend1 = :user AND friend2 <> :user)
                              UNION
                           SELECT friend1 as username FROM list_friends
                           WHERE (friend2 = :user AND friend1 <> :user)
                    )");
$stmt->bindParam(':user', $username);
$stmt->execute();
$textcnt1 = $stmt->fetchColumn();

$stmt=$db->prepare("SELECT COUNT(*) AS cnt
                    FROM stream_updates
                        INNER JOIN members
                    ON members.username=stream_updates.username
                    WHERE (stream_updates.time between (NOW() - INTERVAL 2 DAY) AND (NOW() - INTERVAL 1 DAY))
                    AND (members.username = :user) OR members.username IN (
                           SELECT friend2 as username FROM list_friends
                           WHERE (friend1 = :user AND friend2 <> :user)
                              UNION
                           SELECT friend1 as username FROM list_friends
                           WHERE (friend2 = :user AND friend1 <> :user)
                    )");
$stmt->bindParam(':user', $username);
$stmt->execute();
$textcnt2 = $stmt->fetchColumn();

So the way it works is simple, 7 queries grab 7 different numbers based on the times they were posted. Each of those 7 queries is run against 5 different databases to make for the total of 35 queries. And this is only for a single chart on the page that is also performing other queries and doing other tasks.
I was thinking perhaps I could store the query values as cookies that expire every 30 minutes so as to lighten the load a touch, but was hoping others with more experience could perhaps offer some insight into how to do this?
The time and username columns are indexed and I am not looking to use stored procedures.
Is there a better way to do this so I don't make 35 separate database queries?
UPDATED WITH AN SQL FIDDLE
http://sqlfiddle.com/#!9/fa369f6/1
The above fiddle only shows one example query. Simply switch to test various queries.
(NOW() - INTERVAL 1 DAY) AND NOW())

to
(NOW() - INTERVAL 2 DAY) AND (NOW() - INTERVAL 1 DAY))

Clarifying the queries
So what these query do is simple. Each does a count for all rows matching a given user on a given table and based on that users friends.
In the sqlfiddle example, the return is 3 because a count of all posts in the "favorites" table matched again both a user and all their friends from table list_friends return 3. If we add another user to the table, but do no include said user in the friends list, those posts would not be counted.
All this works as expected, but 35 queries seems to have a rather large load even when they are indexed columns.
id   |     select_type     |    table     |  type   |  possible_keys  |   key    |  key_len  |        ref         |  rows  |  Extra
-------------------------------------------------------------------------------------------------------------------------------------
1    |       PRIMARY       |  favorites   |   ALL   |      NULL       |   NULL   |  NULL     |         NULL       |    9   |
1    |       PRIMARY       |    members   |  eq_ref |    username     | username |    257    | favorites.username |    1   | Using where; Using index
2    | DEPENDENT SUBQUERY  | list_friends |   ALL   |      NULL       |   NULL   |    NULL   |        NULL        |    3   |    Using where
3    |   DEPENDENT UNION   | list_friends |   ALL   |      NULL       |   NULL   |    NULL   |        NULL        |    3   |    Using where
NULL |    UNION RESULT     |  <union2,3>  |   ALL   |      NULL       |   NULL   |    NULL   |        NULL        |  NULL  |

A: Let's take a look at your explain result, note the possible_keys column.

The possible_keys column indicates which indexes MySQL can choose from
  use to find the rows in this table ...   If this column is NULL (or
  undefined in JSON-formatted output), there are no relevant indexes. In
  this case, you may be able to improve the performance of your query by
  examining the WHERE clause to check whether it refers to some column
  or columns that would be suitable for indexing. If so, create an
  appropriate index and check the query with EXPLAIN again.

It is likely that you will see a big boost in performance if you index friend1,friend2 fields on your list_friends table. Particularly in view of the fact that it's used twice.
ALTER TABLE list_friends ADD INDEX f1f2(friend1,friend2)

You may also benefit from an index on the time field on your favorite table.
These operations will make each of your queries run faster, as for the need to run them 35 times, it's not clear why you are actually running them 7 times and on 5 different databases.

A: How about this:
SELECT datediff(NOW(), `stream_updates`.`time`) AS days, COUNT(*) AS cnt
FROM stream_updates
INNER JOIN members ON members.username = stream_updates.username
WHERE datediff(NOW(), `stream_updates`.`time`) < 3
AND (
  members.username = :user
  OR
  members.username IN (
    SELECT DISTINCT if(friend2 = :user, friend1, friend2)
    FROM list_friends
    WHERE friend1 = :user
    OR friend2 = :user
  )
)
GROUP BY 1

Keywords Distinct might speedup as well
And here is the update to your demo: http://sqlfiddle.com/#!9/fa369f6/7
OR run this, pick up whichever is faster:
SELECT datediff(NOW(), `stream_updates`.`time`) AS days, COUNT(*) AS cnt
FROM stream_updates
INNER JOIN members ON members.username = stream_updates.username
WHERE datediff(NOW(), `stream_updates`.`time`) < 3
AND (
  members.username = :user
  OR EXISTS (
    SELECT 1 FROM list_friends WHERE
    (members.username = friend1 AND friend2 = :user)
    OR
    (members.username = friend2 AND friend1 = :user)
  )
)
GROUP BY 1


text:
Q: Julia storing a partitioned data frame to a dictionary Trying to translate a python script into Julia and Julia seems more than up to it (admittedly I have a very primitive understanding of Julia so I expected some difficulty). In a nutshell, I'm trying to split a data frame by a column vector (that has 32 levels!!) and then write those partitioned data frames to text. In python, I was graciously advised to write something like this to split the data frames and store them in a dict:
injuries = {injury: df[df['Type'] == injury] for injury in df['Type'].unique()}

injuries['BROKEN PELVIS']

Does anyone out there know how to achieve something similar in Julia? I would imagine Julia is syntactically similar but all my efforts thus far have been fruitless. Any input is sincerely appreciated. Thanks.
Chase CB

A: Lets make up some data:
df = DataFrame(val=rand(8), injury = [rep("shoulder",4), rep("leg",4)])

This version does the same as the Python version:
injuries = [injury=>df[df[:injury] .== injury,:] for injury in unique(df[:injury])]

Now injuries is a dictionary of DataFrames, one DataFrame for each injury. You can then just do:
injuries["shoulder"]

and it returns a DataFrame with only the shoulder injuries.


text: Q: Is it possible to upgrade a Windows Server OS that runs ArcGIS Enterprise? Is it possible to do an in-place OS upgrade from Windows Server 2016 to 2019 for a virtual machine (not-cloud) running ArcGIS Enterprise 10.8.1 single machine deployment?


text:
Q: How can my python script check whether there is a new version available on pypi repo? I want to write a python script and make it available on a public pypi repository. Suppose I published version '1.0' and installed it.
Then, having version '1.0' installed, I publish version '1.1' to pypi repo.
When I run my script, I want it to print a warning if a new version exists remotely, no warning if it doesn't, and another warning if the check failed.
What's the best way of doing it?
EDIT: I am aware there are plenty of options for doing it, but when I ask "the best option" I mean whether a canonical interface I can rely on exist, and won't break if the pypi server or user environment changes. The less I depend on the environment, the better.
For instance, some drawbacks of some solutions:

*

*Calling pip using subprocess - my code will break if pip is not in PATH

*Using setuptools as a library - was setuptools meant to be used like that? What if they change the implementation of the library changing the method names? Should I depend on a specific version of setuptools?

*Calling PYPI url directly - if these URLs change, it will break my code

I don't feel there is any good option to do it and I would love to be proven wrong.


text:
Q: How to translate group mongo in pymongo I am trying to retrieve a document from mongo as follows:
{"data":[{
    "results":{
        "user_id":"1234",
        "user_type": "A",
        "user_name": "Brian Johanson",
        "city":"Winnipeg",
        "count":{
            "id": 2,
            "file_id": 14
        }
    }
}]
}

I have a version of this working in the mongo shell, but can't get the same to function in Python, which is where the problem is.
I am very new to mongo, but essentially I am trying to do the mongo equivalent of:
SELECT user_id, max(user_type), max(user_name), MAX(city), count(id), count(file_id), count(*) from userlogs where event_time<1948306176 and event_time> 1048306176 group by user_id

I poked around at doing this manually in mongo using group and aggregate for a while, but ended up using an online translator to generate this:
db.user.group({
"key": {
    "user_id": true
},
"initial": {
    "countid": 0,
    "countfile_id": 0,
    "countstar": 0
},
"reduce": function(obj, prev) {
    prev.maximumvalueuser_type = isNaN(prev.maximumvalueuser_type) ? obj.user_type : Math.max(prev.maximumvalueuser_type, obj.user_type);
    prev.maximumvalueuser_name = isNaN(prev.maximumvalueuser_name) ? obj.user_name : Math.max(prev.maximumvalueuser_name, obj.user_name);
    prev.maximumvaluecity = isNaN(prev.maximumvaluecity) ? obj.city : Math.max(prev.maximumvaluecity, obj.city);
    if (obj.id != null) if (obj.id instanceof Array) prev.countid += obj.id.length;
    else prev.countid++;
    if (obj.file_id != null) if (obj.file_id instanceof Array) prev.countfile_id += obj.file_id.length;
    else prev.countfile_id++;
    if (true != null) if (true instanceof Array) prev.countstar += true.length;
    else prev.countstar++;
},
"cond": {
    "event_time": {
        "$lt": 1948306176,
        "$gt": 1048306176
    }
}

});
Which appears to produce the above document in the mongo shell, however I need this to work in Python.
I tried a couple variants of this:
group_key = """{
    "user_id": true
}"""
group_initial = """{
    "countid": 0,
    "countfile_id": 0,
    "countstar": 0
}"""
group_reduce = """function(obj, prev) {
    prev.maximumvalueuser_type = isNaN(prev.maximumvalueuser_type) ? obj.user_type : Math.max(prev.maximumvalueuser_type, obj.user_type);
    prev.maximumvalueuser_name = isNaN(prev.maximumvalueuser_name) ? obj.user_name : Math.max(prev.maximumvalueuser_name, obj.user_name);
    prev.maximumvaluecity = isNaN(prev.maximumvaluecity) ? obj.city : Math.max(prev.maximumvaluecity, obj.city);
    if (obj.id != null) if (obj.id instanceof Array) prev.countid += obj.id.length;
    else prev.countid++;
    if (obj.file_id != null) if (obj.file_id instanceof Array) prev.countfile_id += obj.file_id.length;
    else prev.countfile_id++;
    if (true != null) if (true instanceof Array) prev.countstar += true.length;
    else prev.countstar++;
}"""
group_cond = """{
    "event_time": {
        "$lt": 1948306176,
        "$gt": 1048306176
    }
}"""
all_events = db["userlogs"].group(key=group_key, initial=group_initial, reduce=group_reduce, condition=group_cond)

However, this yields "failed: initial has to be an object."
How do I produce the above document in Python?


text:
Q: Conditional C/C++ struct definitions I've stumbled across some code that looks like this:
typedef struct SomeStruct
{
    int foo;
    void * bar;
#if defined(__cplusplus)
    SomeStruct();
#endif
} SomeStruct;

It's in a header file that will be included by both .c and .cpp files. That seems to be at least technically a violation of the One-Definition-Rule. The obvious impact I see is that if one of these is ever declared in .c file, the constructor won't run. And unfortunately, someone seems to have used this as a pattern for the correct way to declare structs, and has declared a couple dozen structs just like it.
I'm trying to figure out how serious a problem this is. Beyond the constructor possibly not running, is there any other likely impact? The constructor is implemented in a .cpp file. I see pointers to structs allocted in a .c file (with malloc) that are passed to functions in the .cpp files. They appear to work correctly (compiled with gcc/g++ 4.6.2 for Suse Linux, if that matters), as far as I can tell. Would something break if virtual member functions were also added? Right now, none of these classes have anything in their cplusplus section other than the default constructor, as shown above.

A: It's not exactly a violation of the ODR. Informally, the C compiler see a POD type and the C++ compiler see a class in the global namespace which will become an entity with a mangled name. More importantly, the structure is only declared differently for C and C++ compilers, but it is only defined once in a C++ source file. Most likely there's some allocation and free functions in a C++ source file which expose the constructor/destructor to a C API. For example,
Header file
$ cat some_struct.h
#ifndef SOME_STRUCT_H
#define SOME_STRUCT_H

typedef struct SomeStruct {
    int foo;
    void *var;
#if defined(__cplusplus)
    SomeStruct();
#endif
} SomeStruct;

#if defined(__cplusplus)
extern "C" {
#endif

SomeStruct *some_struct_malloc();
void some_struct_free(SomeStruct **);

#if defined(__cplusplus)
} // extern "C"
#endif

#endif // SOME_STRUCT_H

C++ source file
$ cat some_struct.cpp
#include "some_struct.h"
#include <cstddef>

SomeStruct::SomeStruct()
{
    foo = 10;
    var = NULL;
}

SomeStruct *some_struct_malloc() { return new SomeStruct; }

void some_struct_free(SomeStruct **pp)
{
    if (*pp)
        delete *pp;
    *pp = NULL;
}

C source file:
$ cat main.c
#include "some_struct.h"
#include <stdio.h>

int main()
{
    SomeStruct *p = some_struct_malloc();
    printf("%d\n", p->foo);
}

I would say it is a bad style. But it works as a convenient way to expose a C++ library to a C API


text:
Q: Multiple logical expressions in one if statement in java Hi I have this example:
  (1)
  if(false && false ||true){
            System.out.println("a");
  }

result:
a

and
  (2)
  if(false && false | true){
            System.out.println("a");
  }

result:
(empty)

In case (1) we have short-circuit OR , but in the second we have long-circuit OR. From where comes the difference in the behavior? I know that the expression is evaluated from left to right and AND have bigger priority than OR, so I can't figure out why this happens in case 2?

A: && has priority over || but not over |. See operator precedence list.

A: (1)
if (false && false || true) {
    System.out.println("a");
}

Here && has higher precedence than ||

*

*false && false gets evaluated first resulting false.

*false || true gets evaluated resulting true.

So the result outputs "a".
(2)
if (false && false | true) {
    System.out.println("a");
}

Here | has higher precedence than &&

*

*false | true gets evaluated first resulting true.

*false && true gets evaluated resulting false.

So nothing is output.
Hope it makes sense


text:
Q: Modification of Crazy Function on Set of Measure Zero Still Yields Crazy Function I'm working on the following problem:

Let $f(x) = \frac{1}{x^{1/2}}$ if $x \in 0 <x < 1$ and $0$ otherwise. Let ${r_n}$ be an enumeration of the rationals and set $g(x) = \sum_1^\infty2^{-n}f(x-r_n)$. Show that $g$ is discontinuous at every point and unbounded on every interval. Further this remains so after any modification on a Lebesgue null set.

I'm stuck on the bolded part. I showed unboundedness everywhere and discontinuity everywhere. I "sense" the statement should be correct. I'm not sure what to say about it though.

A: Hint: For any interval, $(a,b)$, and any integer $M$, show that $\{x:g(x)>M\}\cap (a,b)$ has nonzero measure. Removing a null set does not change the measure of this set; in particular it will still be nonempty.
It will help to find rational number $r_n$ which lies in $(a,b)$ and consider the "spike" $2^{-n}f(x-r_n)$. As long as the spike is larger than $M$, than $g$ will be as well. You should be able to find a nontrivial interval where the spike is large.


text:
Q: HttpURLConnection does not work on Android I have a problem and really do not know what is wrong :-/
I have a simple function called after button click
public void clickFunc(View view) {

        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL("http://google.com");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.connect();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                InputStream in = new BufferedInputStream(conn.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;

                while ((line = reader.readLine()) != null) {

                    result.append(line);
                }
                in.close();
                httpTxt.setText(result.toString());

            }
            else {
                httpTxt.setText("false : "+responseCode);
            }
        }
        catch(Exception e){
            httpTxt.setText("Exception: " + e.getMessage());
        }

    }

But after a click my output is Exception: null
In manifest I have <uses-permission android:name="android.permission.INTERNET" />
This code is by my opinion same as all codes mentioned here or at internet :-/
httptxt is my texview for output from the page
Thank you

A: Ok, I did not know I have to do it in the background... it is working now,thank you!
public void clickFunc(View view) {

        new SendPostRequest().execute();
    }
    private class SendPostRequest extends AsyncTask<Void, Void, String> {

    protected String doInBackground (Void... params) {

        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader reader;

        try {
            URL url = new URL("http://stackoverflow.com");

            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.connect();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                InputStream in = new BufferedInputStream(conn.getInputStream());
                reader = new BufferedReader(new InputStreamReader(in));

                String line;

                while ((line = reader.readLine()) != null) {

                    result.append(line);
                }
                in.close();
                return(result.toString());

            }
            else {
                return("false : "+responseCode);
            }
        }
        catch(Exception e){
            return("Exception: " + e.getMessage());
        }
    }
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            httpTxt.setText(s);
        }

    }

I am not an android programmer, so even if its basic I did not know that, sorry guys :)
About my app if you are interested why I wanted it - I read a barcode, go to the php script, look into the database if there is this code and return true or false

A: There are many threads on android, When are you hit an http request this mean it will work with another Thread,So if do you want to hit an http request you have to put  it under async class because it's a long operation, and finally if do you want to change by http response
you have to put your changes inside UI thread which mean it should be under Handler or RunOnUiThread because Async task can't have access to UI thread directly
if you don't want to use Asynctask and runUiThred neither handler
 use  volley it's google's API allowing


text:
Q: Cannot POST Status: 404Not Found in POSTMAN Hello I am using POSTMAN to post and get api calls in JSON to a MONGODB Atlas database which is on a react project. I am getting the above error and I do not know where to start because I am new to using them. I have the drivers db in my localhost created using mongosh not sure if I should have it there as I am trying to connect to the drivers db in Atlas. I am making the call in POSTMAN using http://localhost:5000/drivers/add
//server.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
//app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
const driverRouter = require('./routes/driver');

app.use('/driver', driverRouter);
app.listen(port, () => {
 // perform a database connection when server starts
 dbo.connectToServer(function (err) {
   if (err) console.error(err);

 });
 console.log(`Server is running on port: ${port}`);
});

//route
const router= require('express').Router();
let Driver = require('../models/driver.model');

router.route('/').get((req, res) =>{
    Driver.find()
    .then(driver => res.json(driver))
    .catch(err => res.status(400).json('Error: '+ err));

}
)

router.route('/add').post((req, res) => {
    const name = req.body.name;
    const email = req.body.email;
    const phone = req.body.phone;
    const address = req.body.address;
    const country =req.body.country;
    const newDriver = new Driver({name, email, phone, address, country});

    newDriver.save()
      .then(() => res.json('Driver added!'))
      .catch(err => res.status(400).json('Error: ' + err));
  });

  module.exports = router;

//model
const mongoose = require('mongoose');

const Schema= mongoose.Schema;

const driverSchema= new Schema({
   name:{type: String, required:true},
   email:{type: String, required:true},
   phone:{type: String, required:true},
   address:{type:String, required:true},
   country:{type: String, required:true}
});

const Driver= mongoose.model('Driver', driverSchema);

module.exports =Driver;

A: You are making a request to http://localhost:5000/drivers/add, but your route is /driver, so just remove the s from drivers and make a request to http://localhost:5000/driver/add, then it should work.

A: Change app.use("/driver", driverRouter) to app.use("/drivers", driverRouter)
I added an "s" to driver

A: You are making a request to /drivers, but your route is /driver, so just remove the s from drivers and make a request to http://localhost:5000/driver/add, then it should work.


text:
Q: Upsert issue when updating multiple documents using an array of IDs with $in This query is doing the job fine :
db.collection.update(
    { "_id": oneIdProvided },
    { $inc: { "field": 5 } },{ upsert: true }
)

Now I would like to do the same operation multiple time with different IDs, I thought the good way was to use $in and therefore I tried :
db.collection.update(
    { "_id": { $in: oneArrayOfIds} },
    { $inc: { "field": 5 } },{ upsert: true }
)

Problem is : if one of the provided ID in the array is not existing in the collection, a new document is created (which is what I want) but will be attributed an automatic ID, not using the ID I provided and was looking for.
One solution I see could be to do first an insert query with my array of ID (those already existing would not be modified) and then doing my update query with upsert: false
Do you see a way of doing that in only one query ?

A: We can do this by performing multiple write operations using the bulkWrite() method.
function* range(start, end, step) {
    for (let val=start; val<end; val+=step)
        yield val
}

let oneArrayOfIds; // For example [1, 2, 3, 4]

let bulkOp = oneArrayOfIds.map( id => {
    return {
        "updateOne": {
            "filter": { "_id": id },
            "update": { "$set": { "field": 5 } },
            "upsert": true
        }
    };
});

const limit = 1000;
const len = bulkOp.length;

let chunks = [];
if (len > 1000) {
    for (let index of range(0, len, limit)) {
        db.collection.bulkWrite(bulkOp.slice(index, index+limit));
    }
} else {
    db.collection.bulkWrite(bulkOp);
}


text:
Q: How can I add a Website Project in a solution but it should be excluded from source control? I currently have a solution with a couple of Class Library Projects and Web Application Projects and all of these are bound to a source control (VS Team Services). Now I added an Existing Website Project in the same solution by choosing a Local IIS instance. However, I don't want this Website Project to be in source control.
I have tried File > Source Control > Advanced > Change Source Control ... and then clicked on the website project and then clicked Unbind. By doing this, it seems that the project was unbound. However, as soon as I close the solution it asks me to save the .sln file and seems that it restored the Scc*** info in the file.
I also tried editing the .sln file and set the SccProjectEnlistmentChoice* = 0 (of the website project, under GlobalSection) and then set the ProjectSection of the WebsiteProject to
SccProjectName = ""
SccAuxPath = ""
SccLocalPath = ""
SccProvider = ""

instead of "SAK". This actually worked for me but everytime I open the solution, Visual Studio alerts an error saying "Unspecified error". This is the closest I got into solving this.
Is there a proper way of doing this? I think the proper way should be the "Unbind" method but it seems that it's not working as expected.
I also would like to avoid using .tfignore if possible.
Let me know of other solutions.
I also asked this question at MSDN Social but I think there are more people that may respond here at StackOverflow.

A: Web sites have not been an official thing to do for over 5 years and 3 versions of the product. Thus the support is a little spotty in places.
Because a Web Site does not have a Project file it inherits its source bindings from the Solution. This is as far as the legacy support goes.
I would recommend that you upgrade your Web Site to a Web Application. You can then set binding explicitly for it in the project file.


text:
Q: Stopping Elasticsearch service removes category products in 2.4 I was curious what would happen if I stopped the Elasticsearch service in Magento 2.4. What I found I cant seem to understand.
When the service is stopped it empties all the categories. I would have assumed Elasticsearch was for the mini search/advanced search not the catalog listings.
Can anyone confirm if this is by design or is there a bug in Magento 2.4? Also any ideas on how to fix this?
My setup is Magento 2.4 on Valet (MacOs/PHP 7.3.20). I installed Elasticsearch via Homebrew.
Elasticsearch running

Elasticsearch stopped

A: ElasticSearch is in charge of the entire catalog and search, provisioning the data to Magento 2.4.
ElasticSearch is a requirement in Magento 2.4, as you can see in the page Magento 2.4 technology stack requirements, so it never can be disabled like in Magento 2.3.
I recommend to set the services to auto-restart in a production server, so if ElasticSearch or MySQL service goes down, it will restart automatically. You can do it in Docker using the parameter below.
docker run --restart=always


text:
Q: What can a power set of a countable infinite set contain? So I was wondering if this is complete power set of the power set of natural numbers.

*

*All sets of any finite combinations of natural numbers that can exist. For example, {1, 2, 4}, {4, 2, 5, 6, 7}, {1000, 1 , 78} etc.

*An empty set(Φ) and the set containing all natural numbers(N).

*All sets which contain all natural numbers except a particular finite set of natural numbers. For example N - {1, 2, 4}, N -  {4, 2, 5, 6, 7}, N - {1000, 1 , 78} etc.
This is all I was able to think of. I feel like I am definitely missing something here.

A: You've missed the bi-infinite sets - sets which are infinite and have infinite complement. For example, the set of even numbers is not on your list; neither is the set of prime numbers, the set of perfect cubes, or so on.
In fact, most sets of natural numbers are bi-infinite in the precise sense that the set of non-bi-infinite sets of naturals is countable but the set of bi-infinite sets of naturals is uncountable. The first of these claims is a good exercise; the second is Cantor's diagonal argument.


text:
Q: Cassandra cluster throughput throttled I'm new to Cassandra, and hope to get some help from people who ever met this before.
Currently, I have application severs and Cassandra clusters reside in both east and west Amazon ec2 regions.  And I got such a weird performance test result below, which means when application sever and C* cluster are in same region(I believe they use internal IP), throughput is throttled; while when application sever and C* cluster are across region, throughput is scalable.
West C* and East C* have exactly the same hardware and schema. 2 application servers are identical too.
west app sever -> west C* cluster      throttled
west app sever -> east C* cluster      scalable
east app sever -> east C* cluster      throttled
east app sever -> west C* cluster      scalable

cassandra.yaml.
cluster_name: 'STEAST'
initial_token: -9223372036854775808
hinted_handoff_enabled: true
max_hint_window_in_ms: 10800000 # 3 hours
hinted_handoff_throttle_in_kb: 1024
max_hints_delivery_threads: 2
batchlog_replay_throttle_in_kb: 1024
authenticator: AllowAllAuthenticator
authorizer: AllowAllAuthorizer
permissions_validity_in_ms: 2000
partitioner: org.apache.cassandra.dht.Murmur3Partitioner
data_file_directories:
    - /raid0/cassandra/data

commitlog_directory: /raid0/cassandra/commitlog
disk_failure_policy: stop
commit_failure_policy: stop
key_cache_size_in_mb:
key_cache_save_period: 14400
row_cache_size_in_mb: 0
row_cache_save_period: 0
saved_caches_directory: /raid0/cassandra/saved_caches
commitlog_sync: periodic
commitlog_sync_period_in_ms: 10000
commitlog_segment_size_in_mb: 32

seed_provider:
    - class_name: org.apache.cassandra.locator.SimpleSeedProvider
      parameters:
          - seeds: "10.239.xxx.xxx"

concurrent_reads: 32
concurrent_writes: 32
memtable_flush_queue_size: 4
trickle_fsync: false
trickle_fsync_interval_in_kb: 10240
storage_port: 7000
ssl_storage_port: 7001
listen_address: 10.239.xxx.xxx
start_native_transport: true
native_transport_port: 9042
start_rpc: true
rpc_address: 0.0.0.0
rpc_port: 9160
rpc_keepalive: true
rpc_server_type: sync
thrift_framed_transport_size_in_mb: 15
incremental_backups: false
snapshot_before_compaction: false
auto_snapshot: true
tombstone_warn_threshold: 1000
tombstone_failure_threshold: 100000
column_index_size_in_kb: 64
in_memory_compaction_limit_in_mb: 64
multithreaded_compaction: false
compaction_throughput_mb_per_sec: 16
compaction_preheat_key_cache: true
read_request_timeout_in_ms: 10000
range_request_timeout_in_ms: 10000
write_request_timeout_in_ms: 10000
cas_contention_timeout_in_ms: 1000
truncate_request_timeout_in_ms: 60000
request_timeout_in_ms: 10000
cross_node_timeout: false
phi_convict_threshold: 12
endpoint_snitch: com.datastax.bdp.snitch.DseDelegateSnitch
dynamic_snitch_update_interval_in_ms: 100
dynamic_snitch_reset_interval_in_ms: 600000
dynamic_snitch_badness_threshold: 0.1
request_scheduler: org.apache.cassandra.scheduler.NoScheduler
server_encryption_options:
    internode_encryption: none
    keystore: resources/dse/conf/.keystore
    keystore_password: cassandra
    truststore: resources/dse/conf/.truststore
    truststore_password: cassandra

client_encryption_options:
    enabled: false
    keystore: resources/dse/conf/.keystore
    keystore_password: cassandra
internode_compression: all
inter_dc_tcp_nodelay: false
preheat_kernel_page_cache: false
auto_bootstrap: false

A: Finally, I find there's a lock when compiling prepared statements. I was compiling a new prepared statement whenever a new request come in, after I changed to reuse it I got my app server scale. However, I still don't know why cross-region case can scale.


text:
Q: create expo proguard mapping files for google store over expo.dev The Google Store require the expo proguard mapping files, in old version which creates the native android projects the files where in this files, with latest expo version where everything goes over the cloud service this is not longer possible.
Im currently looking for a way to get this files back to submit the files to the google play console.
help with the config files when its maybe a problem with it


text:
Q: Remove every nth element from the list, if the element is not equal to an element in an other list? I have two lists of strings:
l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']

I need to remove every 2nd element from the l1 if element is not equal to one of the elements from list l2.
so far I have tried:
for e1 in l1:
    i=0
    for e2 in l2:
        if e1!=e2:
            l1.remove(l1[i])
            i=i+1

Expected output:
l1 = ['a1', 'a3', 'a4, 'a5']

How can it be done correctly?

A: You can make a list comprehension to re-create l1:
l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']
l2s = set(l2)

l1 = [item for index,item in enumerate(l1) if (index & 1) == 0 or item in l2s]
print(l1)

Output as requested
I created l2s to make the item in l2s faster if your real l2 is very large.

A: use l1[1::2] to filter the list down to every second value
l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']

for elm in l1[1::2]:
    if elm not in l2:
        l1.remove(elm)

# ['a1', 'a3', 'a4', 'a5']

A: You can try this:
l1 = ['a1', 'a2', 'a3', 'a4','a5', 'a6']
l2 = ['a3', 'a4']
new_l=[j for i,j in enumerate(l1) if i%2==0 or j in l2]
print(new_l)

A: Another simple solution is finding the indexes that are valid for the conditions and then pop the items in reverse order, in order to not mess up indexes.
l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']

idx_lst = []
for i in range(len(l1)):
    if (i + 1) % 2 == 0 and l1[i] not in l2:
        idx_lst.append(i)

for idx in sorted(idx_lst, reverse=True):
    l1.pop(idx)

print(l1)


text:
Q: material menu inside ng-template doesn't work
                Charge: {{ queue.box.batch_number }}

                <ng-template #finishedPart>
                        Fertigteilbox
                        <mat-menu #menu="matMenu">
                        <button mat-menu-item (click)="boxClicked(queue.box)">boxdetail</button>
                        <button mat-menu-item (click)="openBoxes(queue.box.id)">offenebox</button>
                        </mat-menu>
                </ng-template>

here i am trying to open a menu in the else part but i am unable to doso. can someone help me with this.

Thank you

A: The menu is not opened by default. You have to add a menu trigger in order to open the menu. In your case, a better solution would be to just use mat-button in your template.

  Charge: {{ queue.box.batch_number }}

<ng-template #finishedPart>
    Fertigteilbox

        <button mat-button [ngStyle]="{'width':'100%'}" (click)="boxClicked(queue.box)">boxdetail</button>
        <mat-divider></mat-divider>
        <button mat-button [ngStyle]="{'width':'100%'}" (click)="openBoxes(queue.box.id)">offenebox</button>

</ng-template>


text:
Q: Scraping tweet count with rvest I've been using the following code to scrape account's tweet count in R (faster than using API):
library("rvest")
scrape = read_html("https://twitter.com/whitehouse/")
scrape.count = scrape %>%
html_nodes(".js-nav .ProfileNav-value") %>%
html_text() %>%
as.character()
scrape.count = as.numeric(paste(substr(scrape.count,1,1),substr(scrape.count,3,5),sep=""))

It worked perfectly till two days ago. Now it returns an empty value and I have no idea why. I used the SelectorGadget to identify the right selector and it hasn't changed. I also read that rvest may struggle with dynamic websites but until two days ago it had no issues. Any suggestions?


text:
Q: Set the "key" in Spring Redis I am able to store my message using the following command and spring seems to be setting the Key:
org.springframework.data.redis.core.RedisTemplate.boundListOps("myid").rightPush(mymessage);

Is there any way I can generate the Key and pass it while adding the "message" ?

A: RedisTemplate.boundListOps(K key) gives you access to list commands that all get executed against the key used for obtaining the BoundListOperations. You can use RedisTemplate.opsForList() in case you want to get ListOperations which is not bound to a specific key and then call rightPush(K key, V value) there.


text:
Q: python how to catch suds web service soap errors I am trying to use suds (version 0.6) to connect to a web service,
from suds.client import Client
client = Client(SOAP_URL, timeout=10)

now I sometimes get timeout error, so I am wondering how to catch all errors using suds when connecting to a web service, and so then in the catch block I can reconnect the web service.

A: It looks as though all of their errors inherit from Exception so to catch all of the errors, you will need to catch this type of error
Otherwise you can look through their documentation and choose which exceptions you want to handle seperately.
try:
    client = Client(SOAP_URL, timeout=10)
except Exception:
    #enter code to reconnect here
    print("Catch block for creating a client connection")


text:
Q: Trouble implementing password_verify I'm in the process of implementing password_verify as part of a login page.
I've started with plaintext to test everything works, which it did, and then have gone through to hash passwords on registration page with password_hash and then add password_verify on the login page.
Passwords are being successfully hashed, which I've checked through PHPMyAdmin, but I can't get my code to work on the registration page to check them.
Below is the code on the login page relating to pulling the row and testing it:
   if (empty($error))//if the array is empty , it means no error found
{

    $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email') AND Activation IS NULL";

    $result_check_credentials = mysqli_query($dbc, $query_check_credentials);
    if(!$result_check_credentials){//If the QUery Failed
        echo 'Query Failed ';
    }

    if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
    { // A match was made.

        $row = mysqli_fetch_row($query_check_credentials);
        $password = $row[3];

        $verify = password_verify($_POST['Password', $password]);
        if ($verify) {

        $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable

        header("Location: page.php");
        }

    }else
    {

        $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
    }

Column number 4 is the password in the DB and so in the array, password should be value 3 in the array.
I've spent time looking at examples of it being used but having no luck, any help appreciated!
Full PHP code
<?php

include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages

if (empty($_POST['e-mail'])) {//if the email supplied is empty
    $error[] = 'You forgot to enter  your Email ';
} else {

    if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {

        $Email = $_POST['e-mail'];
    } else {
         $error[] = 'Your EMail Address is invalid  ';
    }

}

if (empty($_POST['Password'])) {
    $error[] = 'Please Enter Your Password ';
} else {
    $Password = $_POST['Password'];
}

   if (empty($error))//if the array is empty , it means no error found
{

    $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email') AND Activation IS NULL";

    $result_check_credentials = mysqli_query($dbc, $query_check_credentials);
    if(!$result_check_credentials){//If the QUery Failed
        echo 'Query Failed ';
    }

    if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
    { // A match was made.

        $row = mysqli_fetch_row($query_check_credentials);
        $password = $row[3];

        $verify = password_verify($_POST['Password', $password]);
        if ($verify) {

        $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable

        header("Location: page.php");
        }

    }else
    {

        $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
    }

}  else {

echo '

';
    foreach ($error as $key => $values) {

        echo '
'.$values.'
';

    }
    echo '

';

}

if(isset($msg_error)){

    echo '
'.$msg_error.'
';
}
/// var_dump($error);
mysqli_close($dbc);

} // End of the main Submit conditional.

?>

A: I assume when you say "Row number 4 is the password in the DB" you are in fact referring to a column rather than a row? Why also can you not refer to the actual fieldname in the results rather than a column index? That said, my guess is that the POSTed data has been urlencoded and possibly contains spurious blank spaces so I suggest trimming and url decoding POSTed data prior to the verification test. Try echoing the values to see what data you are actually getting.
<?php
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {

    session_start();
    $error = array();

    if (empty($_POST['e-mail'])) {
        $error[] = 'You forgot to enter  your Email ';
    } else {
        if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
            $Email = $_POST['e-mail'];
        } else {
             $error[] = 'Your EMail Address is invalid  ';
        }
    }

    if (empty($_POST['Password'])) {
        $error[] = 'Please Enter Your Password ';
    } else {
        $Password = $_POST['Password'];
    }

    if ( empty( $error ) ){
        $query_check_credentials = "SELECT * FROM `members` WHERE `Email`='$Email' AND `Activation` IS NULL";

        $result_check_credentials = mysqli_query( $dbc, $query_check_credentials );
        if( !$result_check_credentials ){
            echo 'Query Failed ';
        }

        if (@mysqli_num_rows($result_check_credentials) == 1){

            $row = mysqli_fetch_row( $query_check_credentials );

            /* is $row[3] definitely fetching the correct value from the db? */
            $password = trim( $row[3] );

            /* What does password_verify actually do? I guess it's a simple test using === ? */
            $verify = password_verify( trim( urldecode( $_POST['Password'] ) ), $password );

            /*
                $verify = trim( urldecode( $_POST['Password'] ) ) === $password ? true : false;
            */
            echo 'Do they match?
' . trim( urldecode( $_POST['Password'] ) ) . '
' . $password;

            if ( $verify ) {

                /* ? perhaps a session variable name here ? $_SESSION['dbresults'] */
                $_SESSION = mysqli_fetch_array( $result_check_credentials, MYSQLI_ASSOC );

                header("Location: page.php");
            }
        }else {
            $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
        }

    }  else {

    echo '

';
        foreach ($error as $key => $values) {
            echo '
'.$values.'
';
        }
        echo '

';

    }

    if(isset($msg_error)){
        echo '
'.$msg_error.'
';
    }
    /// var_dump($error);
    mysqli_close($dbc);

} // End of the main Submit conditional.

?>

A: I don't use mySQLi so not sure of the little tips and tricks but the following might be of use. Obviously this does not include all of your original code but you should see some records returned if you create a page with this and run it...
$link = mysqli_connect("localhost", "username", "password", "database");

if ( mysqli_connect_errno() ) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * FROM `members` WHERE `Email`='$Email' AND `Activation` IS NULL";

if ($result = mysqli_query($link, $query)) {
    while ($row = $result->fetch_assoc()) {
        echo $row['password'].' '.trim( urldecode( $_POST['password'] ) ).'
';

        if( $row['password']===trim( urldecode( $_POST['password'] ) ) ){
            echo "--Match!--";
        }

    }
}

mysqli_close( $link );


text:
Q: implementing NSFetchedResultsController I'm having some problems implementing NSFetchedResultsController for something very simple. I'm just trying to learn how it works. All I want to do is display the firstName attribute of Person entities in a table view.
As far as I know I've implemented all the methods required but nothing is showing up in the table view. The method -tableView:cellForRowAtIndexPath: method isn't even being called.
Here is my code:
@implementation MyTableViewController

@synthesize managedObjectContext = _managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;

-(NSFetchedResultsController*) fetchedResultsController
{

    if (!_fetchedResultsController)
    {
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
        NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
        fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    }

    return _fetchedResultsController;

}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
    // Custom initialization
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    NSError *error = nil;

    [self.fetchedResultsController performFetch:&error];

}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    Person *person = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = person.firstName;
    return cell;
}

any help would be hugely appreciated! many thanks, Alex

A: You have to call [NSFetchedResultsController performFetch:] and implement its delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    // The fetch controller is about to start sending change notifications, so prepare the table view for updates.
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {

    UITableView *tableView = self.tableView;

    switch(type) {

        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
           [tableView deleteRowsAtIndexPaths:[NSArray
arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
           [tableView insertRowsAtIndexPaths:[NSArray
arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
           break;
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {

    switch(type) {

        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    // The fetch controller has sent all current change notifications, so tell the table view to process all updates.
    [self.tableView endUpdates];
}

See more at: http://www.raywenderlich.com/999/core-data-tutorial-for-ios-how-to-use-nsfetchedresultscontroller

A: Try getting your NSString from your Person object and via the code here:
NSString *firstName = ((Person *)[personArray objectAtIndex:indexPath.row]).firstName;
Mind you, my suggested line is assuming that you output your NSFetchRequest to a NS(Mutable)Array called personArray.
Hopefully that helps, otherwise let me know.


text:
Q: Update dom without refresh the page in react 16 So, I've been looking for a way to render this img tag on my dom without refresh the screen. But I didn't find a definitive answer on how to do that! I mean, in a natural way, with react library and without change a lot of things.
So, when I click this div, it calls a method

 this.refProjectImageCenter = ref} onClick={(e) => this.selectImage(e, this.refProjectImageCenter)} >

And in this method, I update my state with a new img element (not sure if it's the best way to do it tho)
selectImage(e: any ,  el: HTMLDivElement)
{
        e.preventDefault(); // This is not working
        this.setState({ selected_img:  });
}

And the state will update this part of the DOM

                {this.state.selected_img}

It renders the img indeed, but the page flashes(refresh), and I want to do that asynchronously. It's possible to do that with react? If it's not, how everybody is doing it right now? Thanks a lot.

A: I found the problem Henry and Shubham. I was updating the css class of the main html tag:
this.refMasterDOM.classList.remove("active");

Inside the method componentWillUpdate(). I removed this line and it stopped refreshing the page with sestate command. Although I don't know why.


text:
Q: Deadlock with no user code I'm getting a deadlock in my C++ program, which used std::thread, std::mutex, std::condition_variable, etc.
There's nothing in itself strange about that, until I look at the stacks for each of the threads in my process:
8532    0   Main Thread Main Thread msvcr120.dll!Concurrency::details::ExternalContextBase::Block   Normal
                        ntdll.dll!_ZwWaitForSingleObject@12()
                        KernelBase.dll!_WaitForSingleObjectEx@12()
                        kernel32.dll!_WaitForSingleObjectExImplementation@12()
                        msvcr120.dll!Concurrency::details::ExternalContextBase::Block() Line 145
                        ntdll.dll!_ZwQueryVirtualMemory@24()
                        kernel32.dll!_BasepFillUEFInfo@8()
                        ntdll.dll!_ZwQueryInformationProcess@20()
                        msvcr120.dll!_initterm(void (void) * * pfbegin, void (void) * * pfend) Line 954

-
6484    0   Worker Thread   ntdll.dll!_TppWaiterpThread@4() ntdll.dll!_NtWaitForMultipleObjects@20  Normal
                        ntdll.dll!_NtWaitForMultipleObjects@20()
                        ntdll.dll!_TppWaiterpThread@4()
                        kernel32.dll!@BaseThreadInitThunk@12()
                        ntdll.dll!___RtlUserThreadStart@8()
                        ntdll.dll!__RtlUserThreadStart@8()

-
6296    0   Worker Thread   msvcr120.dll!_threadstartex msvcr120.dll!Concurrency::details::ExternalContextBase::Block   Normal
                        ntdll.dll!_ZwWaitForSingleObject@12()
                        KernelBase.dll!_WaitForSingleObjectEx@12()
                        kernel32.dll!_WaitForSingleObjectExImplementation@12()
                        msvcr120.dll!Concurrency::details::ExternalContextBase::Block() Line 145
                        msvcp120.dll!std::_Thrd_startX(struct _Thrd_imp_t *,unsigned int (*)(void *),void *)
                        msvcr120.dll!_callthreadstartex() Line 376
                        msvcr120.dll!_threadstartex(void * ptd) Line 354
                        kernel32.dll!@BaseThreadInitThunk@12()
                        ntdll.dll!___RtlUserThreadStart@8()
                        ntdll.dll!__RtlUserThreadStart@8()

None of the threads seem to be executing my code, and I know for a fact that we had already entered main, since the program had done some stuff before hanging.
I'm using the following class to communicate with my std::thread, in case I made some mistake there:
template <typename T>
class BlockingQueue
{
public:
    BlockingQueue() : _active(true) {}

    bool Get(T& out)
    {
        std::unique_lock<std::mutex> lock(_mutex);

        _cv.wait(lock, [&](){ return !_queue.empty() || !_active; });

        if (_queue.empty())
        {
            assert(!_active);

            return false;
        }

        out = std::move(_queue.front());
        _queue.pop();

        return true;
    }

    void Put(const T& in)
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);

            _queue.push(in);
        }

        _cv.notify_one();
    }

    void Put(T&& in)
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);

            _queue.push(std::move(in));
        }

        _cv.notify_one();
    }

    void Finish()
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);

            _active = false;
        }

        _cv.notify_all();
    }

private:
    bool _active;
    std::mutex _mutex;
    std::condition_variable _cv;
    std::queue<T> _queue;
};

I have two ideas right now:

*

*Main has already exited for some reason. This is a PoC, so when there's an error we log to stdout and call exit() (Yeah I know, not the greatest, this is being adapted from another C-style program written in C++). I do not see anything being logged to the terminal, but I suppose it's possible that the output was being buffered and hasn't been written out yet?

*The debugger is lying to me in some way. Usually it puts in [frames below may be missing/incorrect] into the stack trace when it does this, but maybe it can happen without that.

A: It turns out I was failing to replace an item in a queue, causing my thread to deadlock on retrieving from the queue, which means that the debugger was lying to me. :(


text:
Q: How to disable line breaking when reindent?

I don't want line breaking when I reindent, I want to keep this code on one line.
I'm using webstorm 11. How to do this?

A: Go to Setting/preferences | Code Style | HTML | Other
Untick Keep line breaks
Set Wrap attributes to Do not wrap
Also disable the following setting so you get a horizontal scrollbar:

*

*For all files (default setting for opened file):
Settings/Preferences | Editor | Use soft wraps in editor

*For currently opened file in editor: Menu | View | Active Editor | Use Soft Wraps


text:
Q: In R can you manually set degrees of freedom for lm() or Anova()? I am replicating SPSS code in R that runs several Type 3 ANOVAs. In SPSS you can specify specific contrasts in an ANOVA (e.g., compare level 2 v level 4 in this 5-level variable). The resulting ANOVA tables return a test where the degrees of freedom are equal to the full sample, rather than the sample that is just concentrated in those two levels.
In R, I use the command below to run an ANOVA comparing those two levels but the resulting Residuals DF is based on the subsample of only those two levels rather than the full sample. Is there a way I can manually set the DF in either the lm() or Anova() function to avoid this issue? Or is there a way to specify contrasts that uses the full sample DF?
Anova(lm(DV ~ FiveLevelFactor, data = data, type = 3, subset = FiveLevelFactor == "2" | FiveLevelFactor == "4"))

A: How about using the linearHypothesis() function from the car package:
library(car)
data(Ornstein)

mod <- lm(interlocks ~ log(assets) + sector + nation, data=Ornstein)
linearHypothesis(mod, "nationUK = nationUS")
# Linear hypothesis test
#
# Hypothesis:
#   nationUK - nationUS = 0
#
# Model 1: restricted model
# Model 2: interlocks ~ log(assets) + sector + nation
#
#   Res.Df   RSS Df Sum of Sq      F Pr(>F)
# 1    235 29829
# 2    234 29690  1    138.36 1.0904 0.2975


text:
Q: Difference in eBPF XDP mode and Socket Filter Mode when parsing a packet header information I was wondering if there's a difference between eBPF XDP and eBPF socket filter mode when parsing a packet header information.
Say I want to retrieve a destination IP address and a source IP address from a packet header using eBPF.
If there's no difference in doing so between XDP and socket filter mode, maybe it's better to implement packet monitoring functionality in XDP instead of implementing it in a socket filter program?
If so, wouldn't it be always better to monitor every incoming packet using XDP instead of using a socket buffer since XDP can offload its operations to a NIC when used with hardware offload mode?
Thanks!

A: If your kernel supports direct packet access for socket filter programs, there is indeed little difference between parsing them with socket filter or XDP programs.
There are however other reasons to prefer tc or socket filter programs to XDP programs. The main reason is likely that XDP has relatively few helpers available, especially compared to tc programs. Then, different program types have access to different information; for example, tc programs have partial access to the skb and socket filter programs can access socket uids and cookies.

A: As a complement to pchaigno's answer: Hardware offload has little to do here. It is supported for both XDP and TC programs, and will bring you the same performance in both cases.
Parsing packets in XDP and socket filters/TC is the same, so if you want performance go for XDP, period. Reasons NOT TO use XDP are the ones stated by pchaigno: more helpers for TC, access to socket buffer. Or lack of XDP support by your driver (in which case generic XDP should bring you performance equivalent to TC). Note that these additional helpers and socket buffer access may not be available to programs offloaded to the hardware (on Netronome NFPs, programs offloaded from XDP and TC all behave the same and have access to the same subset of helpers).
Not relevant to monitoring incoming packet, but another big advantage of TC at the moment is the ability to add filters on the egress side. As of this writing, there is work in progress to support that for XDP, but nothing merged to the kernel.


text:
Q: How do I find factorials of large numbers modulo 1000000007 in C++?
Find the factorial of large number modulo 1000000007

In Python or Java, it's no problem, but in C++ there are overflow constraints.
This is the code I've tried:
#include<iostream>
 #define ull long long int
 #define mod 1000000007
 ull fact(ull n)
 {
           if(n==1 || n==0) return 1;
           return ((n%mod)*(fact(n-1)%mod)%mod);
 }
 int main()
 {
              cout<<fact(50000)<<endl;
              return 0;
 }

But the output is invalid.

A: check this code. There should not be any problem as unsigned long long can easily store any modular value 10^9+7. I mean if you are using modular value instead of actual one then why should you even care about it? (It's known that 10^9+7 can be stored in ull).
 ull ans;
    ull fact(int n)
    {
        if(n<INT_MAX)
        {
        ans=1;
        for(int i=2;i<=n;i++)
         ans=(ans*i)%mod;
         return ans;
        }
    }

This will simply do the factorial.
Here n< INT_MAX condition is used because if we don't use it then if n=INT_MAX the for loop's index increment(i++) may result in inceasing the value of INT_MAX which will make it 0. So the condition will never be false and it will run into infinite loop.
Note: If you want to precisely calculate the factorial in c++ you may take an array of 1000 chars where each of the char represent a digit. then you will multiply gradually to get the result. n*(n-1)*..2*1
Note: If you are making many recursive calls then it may cause overflow in stack memory as each function call results in pushing a frame(that contains it's return points etc).

A: If x!! = 1 * 3 * 5 * 7 * 9 * 11 * ..., then 2x! = 2x!! * 2^x * x!.
This gives us a more efficient factorial algorithm.
template<ull mod>
struct fast_fact {
  ull m( ull a, ull b ) const {
    ull r = (a*b)%mod;
    return r;
  }
  template<class...Ts>
  ull m( ull a, ull b, Ts...ts ) const {
    return m( m( a, b ), ts... );
  }
  // calculates x!!, ie 1*3*5*7*...
  ull double_fact( ull x ) const {
    ull ret = 1;
    for (ull i = 3; i < x; i+=2) {
      ret = m(i,ret);
    }
    return ret;
  }
  // calculate 2^2^n for n=0...bits in ull
  // a pointer to this is stored statically to make calculating
  // 2^k faster:
  ull const* get_pows() const {
    static ull retval[ sizeof(ull)*8 ] = {2%mod};
    for (int i = 1; i < sizeof(ull)*8; ++i) {
      retval[i] = m(retval[i-1],retval[i-1]);
    }
    return retval;
  }
  // calculate 2^x.  We decompose x into bits
  // and multiply together the 2^2^i for each bit i
  // that is set in x:
  ull pow_2( ull x ) const {
    static ull const* pows = get_pows();
    ull retval = 1;
    for (int i = 0; x; ++i, (x=x/2)){
      if (x&1) retval = m(retval, pows[i]);
    }
    return retval;
  }
  // the actual calculation:
  ull operator()( ull x ) const {
    x = x%mod;
    if (x==0) return 1;
    ull result = 1;
     // odd case:
    if (x&1) result = m( (*this)(x-1), x );
    else result = m( double_fact(x), pow_2(x/2), (*this)(x/2) );
    return result;
  }
};
template<ull mod>
ull factorial_mod( ull x ) {
  return fast_fact<mod>()(x);
}

live example
A faster version could reuse results of x!!, as those are repeated quite often.
Caching live example, which is about 2x as fast as the above for large n by caching x!! values reasonably smartly.  Every call to double_factorial(n) creates lg k cache entries, where k is the distance between n and the largest old cache entry.  As k is bounded by n.  This in practice seems to reduce the weighted "cache misses" to nearly zero after the first call: the first calculation of n!! injects enough cached entries that we don't burn significant amounts of time on later calculations of !!.
This optimized version is about 41% faster than a naive iterative implementation (basically all of the time is spent calculating the first n!!).
Further improvements would probably involve making the first x!! calculation faster, with probably marginal improvements from optimizing the cache.  The next question: how do you make x!! faster?


text:
Q: Accordian effect in a UITableView I want to expand a cell in my table view when I select it. Initially it should look like this:

And on expanding, it should give more detail like this:

This is how I'm creating the cell initially:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * MyIdentifier = @"MyIdentifier";
    UITableViewCell * cell = [self.table dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier] autorelease];
        cell.textLabel.frame = CGRectMake(0, 0, cell.textLabel.frame.size.width,
        cell.textLabel.frame.size.height);
 }
 id key = [[articles allKeys] objectAtIndex:indexPath.section];
 cell.textLabel.text =@"TitleTitleTitle";
 cell.detailTextLabel.text=@"DeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatai";
 return cell;
}

A: I published a sample code at github
Your tabelView:cellForRowAtIndexPath: could look like this.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * MyIdentifier = @"MyIdentifier";
    UITableViewCell * cell = [self.table dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier] autorelease];
        cell.textLabel.frame = CGRectMake(0, 0, cell.textLabel.frame.size.width,
                                          cell.textLabel.frame.size.height);
    }
    id key = [[articles allKeys] objectAtIndex:indexPath.section];
    cell.textLabel.text =@"TitleTitleTitle";
    cell.detailTextLabel.text=@"DeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatai";

    //SEE MY NOTE BELOW
    if([indexPath isEqual:selectedIndexPath]){
        cell.textLabel.numberOfLines=0;
        cell.detailTextLabel.numberOfLines=0;

        CGSize constraintSize;
        constraintSize.width = cell.textLabel.frame.size.width;
        constraintSize.height = MAXFLOAT;
        cell.textLabel.frame = [cell.textLabel.text sizeWithFont:cell.textLabel.font constrainedToSize:constraintSize];

        constraintSize.width = cell.detailTextLabel.frame.size.width;
        constraintSize.height = MAXFLOAT;
        cell.detailTextLabel.frame = [cell.detailTextLabel.text sizeWithFont:cell.detailTextLabel.font constrainedToSize:constraintSize];
    } else {
        cell.textLabel.numberOfLines=1;
        cell.detailTextLabel.numberOfLines=1;
    }
    return cell;
}

BUT
You will also need the height of the cell by dynamic in tableView:heightForRowAtIndexPath:, so you should refactor the sizing parts into a helper methods, that writes the sizes of the 2 labels and the height of the cell to ivars, call the method from tableView:heightForRowAtIndexPath:, use the cell height there and the labels sizes in tabelView:cellForRowAtIndexPath:


text:
Q: Iterate list of strings in mithril and create drop down I tried searching a lot of internet but could not find answer to a simple question. I am very new to mithril (do not know why people chose mithril for project :( ). I want to iterate through a list of strings and use its value in drop down with a checkbox.
const DefaultListView = {
    view(ctrl, args) {
    const parentCtrl = args.parentCtrl;
    const attr = args.attr;
    const cssClass = args.cssClass;
    const filterOptions = ['Pending', 'Paid', 'Rejected'];
    // as of now, all are isMultipleSelection filter
    const selectedValue =
    parentCtrl.filterModel.getSelectedFilterValue(attr);

    function isOptionSelected(value) {
      return selectedValue.indexOf(value) > -1;
    }

    return m('.filter-dialog__default-attr-listing', {
      class: cssClass
    }, [
      m('.attributes', {
        onscroll: () => {
          m.redraw(true);
        }
      }, [
        filterOptions.list.map(filter => [
          m('.dropdown-item', {
            onclick() {
              // Todo: Add click metrics.
              // To be done at time of backend integration.
              document.body.click();
            }
          }, [
            m('input.form-check-input', {
              type: 'checkbox',
              checked: isOptionSelected(filter)
            }),
            m('.dropdown-text', 'Pending')
          ])
        ])
      ])
    ]);
  }
};

Not sure. How to do it. This is what I have tried so far but no luck. Can someone help me this?

A: At the beginning of the view function you define an array:
const filterOptions = ['Pending', 'Paid', 'Rejected'];

But later on in the view code where you perform the list iteration, filterOptions is expected to be an object with a list property:
filterOptions.list.map(filter =>

That should be filterOptions.map(filter =>.
There may be other issues with your code but it's impossible to tell without seeing the containing component which passes down the args. You might find it more helpful to ask the Mithril chatroom, where myself and plenty of others are available to discuss & assist with tricky situations.


text:
Q: Site logo and logo link for external users We have enabled sharing on a classic publishing site ( for authorized users) and when they log on the logo is not visible. I figured out that external users do not have access to Site Assets which it where the logo is stored. So after adding the external users with read permissions the logo appeared, however the link is gone for externals, any idea how to reenable it?
Thanks


text:
Q: Conversion. ps-->. pdf: text in gray! When I generate the. Pdf from Ps  with GSview, printing quality is good. However, reading the screen. Pdf texts are gray ..... and makes reading difficult. Nevertheless, everything is ok for figures.
Have you an idea please ?

A: Why do u use PS at all? If you do not have a special reason then I would recommend using pdftex/pdflatex. This way you get directly a pdf file without conversion.
I made a video tutorial for a LaTeX workshop that shows the installation process and shows how to configure Texmaker in order to produce directly a pdf file. Maybe this helps:
http://www.youtube.com/watch?v=RL15I-6NQFQ
As far as I know some  people are still using DVI and PS because they want to include EPS files or because they want to use the very powerful PSTricks package.
But EPS pictures can often easily converted into the PDF format or you produce the pictures as a PDF right away. And I think that you can use PSTricks with pdftex/pdflatex nowadays.


text:
Q: Join PowerBI tables based on "where contains TEXT" I'm not sure this can be done, but the data is all there so I'm hoping so!
In our projects we have a lookup field to select which delivery groups (DGs) are interested in working on the project. There could be 1 DG or 20 interested, its unlimited.
Instead of having a line per DG per project, our database includes them in a field which links them together like 'DG1; DG2; DG3'
PROJECT   DELIVERY GROUPS KEY
A         55171; 55172; 55173
B         55173
C         55170; 55171;
I then have a table to show each distinct delivery group and its key
DG KEY      DG NAME
55170       DG0
55171       DG1
55172       DG2
55173       DG3
So in PowerBI I want to be able to have the Delivery Groups table in a filter so the user can select one or many of them, and then it only shows projects where that delivery group/s is specified
FILTER = 55171
PROJECT   DELIVERY GROUPS KEY  INCLUDE?
A         55171; 55172; 55173  Y
B         55173                N
C         55170; 55171;        Y
But I don't know how to link them in the relationship diagram so its 1:many (1 being the distinct delivery groups table DG key, many being the delivery group key in the project table)
The relationship diagram join would have to be something like "JOIN WHERE 'Project table'[Delivery Group Key] CONTAINS 'Delivery Group table'[Delivery Group Key]
The workaround at the moment is just typing what I'm looking for in the filters using "contain" for the Project delivery groups, but we have other tables which use delivery groups so I'd rather the user just had to click once and everything was filtered
All the tables are SQL based fed into Jaspersoft Studio to create Excel files (we can't connect PowerBI direct to our data yet so has to be extracted as excel, saved to SharePoint and PowerBI runs the data from there) if that helps any solutions at the source instead
Any help greatly appreciated!!

A: You can't create custom relationships in your model like that.
I'd suggest creating a column on your delivery group table that looks up what project it's associated with and then creating a 1-to-many relationship from Projects[Project] to DG[CalculatedCol]. This should be equivalent to what you are wanting assuming a single delivery group isn't associated with multiple projects.


text:
Q: Need help modyfing a file using Sed I am grabbing a  string from style.css and trying use it to replace a string in client_custom.css. The problem is that its only printing the update file on the terminal, but I cant get it to save the updated client_custom.css
Is there anyway I can do this with the following command??
sed -n 73p  style.css | cut -c  30-35 | xargs -I :hex: sed 's/!BGCOLOR!/:hex:/'  client_custom.css

A: The -i option of sed will do an inplace editing of the file provided as argument
sed -n 73p  style.css | cut -c  30-35 | xargs -I :hex: sed -i 's/!BGCOLOR!/:hex:/'  client_custom.css


text:
Q: General method to select first row from every group in DataTable, give a List of grouping column I can use this code to get every first row from each group (group by ID) from DataTable:
dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

But it group only ID and I have to hardcode it myself.
I wonder if there is general method, that put in a list of column name to group.
public DataTable GetFirstFromEachGroupBy(List<string> GroupByColumns)
{
  dt = dt.AsEnumerable().GroupBy(GroupByColumns).Select(g => g.First()).CopyToDataTable();
}

A: You could add a computed column to the table that concatenates the fields, then group by that column:
string newcolExpression = @"' ' + " + string.Join(" + ",GroupByColumns) ; // prepend a space to ensure string concatenation
// e.g. "' ' + ID1 + ID2"

dt.Columns.Add("GroupBy",typeof(string),newcolExpression);

dt = dt.AsEnumerable()
       .GroupBy(r => r["GroupBy"])
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

dt.Columns.Remove("GroupBy");


text:
Q: Using HTML input element (type="submit"), how can we customize the GET field? Using <form method="get"> element including <input type="submit"> element, we can have a way to GET a web page with some fields specified by the <input type="text" name="studentId"> elements, but can I customize those fields?
For example: I always want to add a action=true to the GET url to let the URL be something like this: http://example.com/?studentId=123&action=true?

A: Use <input type="hidden" name="action" value="true" />
inside your form.

A: You can add a hidden form field, though the name action is not a good one, as form has an action attribute and this name can conflict when scripting the form:
<input type="hidden" id="something" name="something" value="somthingelse" />

A:  <div id="gbqffd">
   <input type="hidden" value="en" name="h1">
   <input type="hidden" value="d" name="tbo">
   <input type="hidden" value="search" name="output">
   <input type="hidden" value="psy-ab" name="sclient">
 </div>

Google always has the answer; in this case I never had to do a search just look at the source :)