text:
Q: Mongodb - updating a collection with >100,000 documents in migration Following migration code seems to be getting stuck while updating this huge collection.
@ChangeSet(order = "010", id = "add_tenant_to_product", author = "pn")
fun addTenantToProduct(mongoTemplate: MongoTemplate) {
    log.info("Adding tenants to products")
    val query = Query()
    val update = Update()
    update.set("tenants", arrayOf("shared"))

    mongoTemplate.updateMulti(query, update, Product::class.java)
}

@ChangeSet(order = "011", id = "add_tenant_to_product_version", author = "pn")
fun addTenantToProductVersion(mongoTemplate: MongoTemplate) {
    log.info("Adding tenants to product-version")
    val query = Query()
    val update = Update()
    ...

The last few lines of the application log indicate the changeset getting invoked but subsequent one not getting invoked.

2021-05-11 08:00:29.385  INFO [product-service,,,] 1 --- [
main] c.a.a.mongock.changelog.Migration        : Adding tenants to
products
2021-05-11 08:00:29.576  INFO [product-service,,,] 1 --- [
main] org.mongodb.driver.connection            : Opened connection

The Spring actuator health probe fails because of this and the container keeps on restarting. Is there a better API to use which will be faster?
Note:

*

*version used: 'com.github.cloudyrock:mongock:1.12'

*below is the configuration

@Profile("!tenant")
@Configuration
class MongockConfig : AbstractMongoConfiguration() {

    @Value("\${spring.data.mongodb.uri}")
    private lateinit var uri: String

    @Value("\${spring.data.mongodb.database}")
    private lateinit var database: String

    override fun mongoClient(): MongoClient {
        return MongoClient(MongoClientURI(uri))
    }

    override fun getDatabaseName(): String {
        return database
    }

    @Bean
    fun mongock(): Mongock {
        return MongockBuilder(mongoClient(), databaseName, "com.somepackage.mongock.changelog")
            .setMongoTemplate(mongoTemplate())
            .setLockQuickConfig()
            .build()
    }
}

Here are the logs

2021-05-10 10:59:33.406  INFO [product-service,,,] 1 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:16, serverValue:26359638}] to dummy-clusterr-39649.servers.mongodirector.com:27017
2021-05-10 10:59:33.525  INFO [product-service,,,] 1 --- [           main] c.github.cloudyrock.mongock.LockChecker  : Mongbee trying to acquire the lock
2021-05-10 10:59:33.574  INFO [product-service,,,] 1 --- [           main] c.github.cloudyrock.mongock.LockChecker  : Lock is taken by other process until: Mon May 10 11:01:03 GMT 2021
2021-05-10 10:59:33.574  INFO [product-service,,,] 1 --- [           main] c.github.cloudyrock.mongock.LockChecker  : Mongock is going to sleep to wait for the lock:  90265 ms(1 minutes)
2021-05-10 11:01:03.839  INFO [product-service,,,] 1 --- [           main] c.github.cloudyrock.mongock.LockChecker  : Mongbee trying to acquire the lock
2021-05-10 11:01:03.844  INFO [product-service,,,] 1 --- [           main] c.github.cloudyrock.mongock.LockChecker  : Mongbee acquired the lock until: Mon May 10 11:04:03 GMT 2021
2021-05-10 11:01:03.844  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : Mongock starting the data migration sequence..
2021-05-10 11:01:03.982  INFO [product-service,,,] 1 --- [           main] org.reflections.Reflections              : Reflections took 60 ms to scan 1 urls, producing 2 keys and 3 values
2021-05-10 11:01:04.038  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@7abd0e71 pass over
2021-05-10 11:01:04.046  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@6635f36 pass over
2021-05-10 11:01:04.047  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@61352a80 pass over
2021-05-10 11:01:04.052  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@7576ed14 pass over
2021-05-10 11:01:04.054  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@b0302179 pass over
2021-05-10 11:01:04.068  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@e6caade0 pass over
2021-05-10 11:01:04.071  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@2688129a pass over
2021-05-10 11:01:04.073  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@e46af677 pass over
2021-05-10 11:01:04.075  INFO [product-service,,,] 1 --- [           main] com.github.cloudyrock.mongock.Mongock    : com.github.cloudyrock.mongock.ChangeEntry@d788b92f pass over
2021-05-10 11:01:04.077  INFO [product-service,,,] 1 --- [           main] c.a.a.mongock.changelog.Migration        : Adding organisations to questions
2021-05-10 11:01:04.158  INFO [product-service,,,] 1 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:17, serverValue:26359725}] to dummy-clusterr-39649.servers.mongodirector.com:27017

A: can you provide a bit more information, such as mongock version you are using, log trace(what you show is not enough fo diagnostic), mongock configuration, etc?
On the other hand, you should use MongockTempalte instead MongoTemplate directly. It's the same API, you wont miss anything. Actually using a MongoTemplate directly should throw an exception.
For more information, please check Mongock's documenation


text:
Q: Object Relations C# I'm not sure how best to objectify and access my various game elements. To simplify my issue I've reduced my game classes into fruit:
Say I have a basket of fruit, comprising an orange, apple and banana. Currently the fruitbasket is a single object, though as I now wish to treat the apple as a separate object, what is the preferred way for the apple to access its now broken references to the variables and methods of the basket?
The basket class contains dozens of constant variables which I reference many times within the apple class - as well as various method calls - and I feel it clumsy to call basket.<var/method> every time, nor do I wish to declare new variables within the apple, referencing the dozens of basket values. Although passing variable values is straight-forward enough the same is not true for methods. How would I best reference the basket methods within the apple, as, once again, these methods are demanded many times within the apple. Should the fruit somehow be derived from the basket?
I'm very eager to treat and manage all of my game elements as harmonious objects, working together and facilitating the coding process of a large project. Any help will be appreciated.
I'm using C# and the MonoGame framework within Visual Studio.

A: You could either:

Derive the apple from the basket
class Apple : Basket { }

Make every variable/method/etc that you want to access static in the basket. Then, you can simply access it from anywhere. e.g.
public class Basket {
    public static List<string> Content = new List<string>();
    public static bool IsEqual(int x, int y) {
        return (x == y);
    }
}

public class Apple {
    Console.Log(Basket.Content.Count.ToString());
    Console.Log(Basket.IsEqual(1, 2).ToString());
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection closed, EOF detected I want to post some json data from ADFS SSO enabled weblogic server to an https url(jetty server) but I am getting the below exception
    java.io.IOException: Connection closed, EOF detected
    at weblogic.socket.JSSEFilterImpl.handleUnwrapResults(JSSEFilterImpl.java:637)
    at weblogic.socket.JSSEFilterImpl.unwrapAndHandleResults(JSSEFilterImpl.java:515)
    at weblogic.socket.JSSEFilterImpl.doHandshake(JSSEFilterImpl.java:96)
    at weblogic.socket.JSSEFilterImpl.doHandshake(JSSEFilterImpl.java:75)
    at weblogic.socket.JSSEFilterImpl.write(JSSEFilterImpl.java:448)
    at weblogic.socket.JSSESocket$JSSEOutputStream.write(JSSESocket.java:93)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
    at weblogic.net.http.HttpURLConnection.writeRequests(HttpURLConnection.java:192)
    at weblogic.net.http.HttpURLConnection.getInputStream(HttpURLConnection.java:433)
    at weblogic.net.http.SOAPHttpsURLConnection.getInputStream(SOAPHttpsURLConnection.java:37)

Below is the snippet
        URL urlObject = new URL(url);
        HttpURLConnection httpConnection = (HttpURLConnection) urlObject.openConnection();
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.addRequestProperty("Content-Type", "application/xml");
        OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream());
        writer.write(paramJSON.toString());
        writer.flush();

        String line;
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        while ((line = reader.readLine()) != null)
        {
            buffer.append(line);
        }

        writer.close();
        reader.close();
        int status = httpConnection.getResponseCode();
        httpConnection.disconnect();

This is working with both http url i.e. without SSL enabled

A: If we are using Weblogic server, we must define:
set JAVA_OPTIONS=%JAVA_OPTIONS% -DUseSunHttpHandler=true

...in the class path inside the Server Domain.
This will tell the weblogic server to use the Sun Http Handlers and not install its own.


text:
Q: Difference between sequentially compact spaces and closed sets in $\mathbb{C}$ According to my notes
$K\subset\mathbb{C}$ sequentially compact $\iff$ Every sequence in K has a subsequence which converges to a Point in K
$A\subseteq\mathbb{C}$ closed set $\iff  ((a_n)_{n\in\mathbb{N}}$ convergent sequence in A $\Rightarrow \lim_{n\rightarrow \infty}a_n\in A$
I am wondering why the definitions, save for $\mathbb{C}$ are not equivalent
If $A\neq\mathbb{C}$ and $A$ closed set, why does $A$  not have to be necessarily compact? Because the opposite is true. If I take a convergent sequence of a sequentially compact subset $K$ then the convergencepoint has to be by Definition in $K$.

A: Take $A=\{z\in\mathbb{C}\,|\,\lvert z\rvert\geqslant1\}$, for instance. It is closed. However, it is not sequentially compact because, for instance, the sequence $1,2,3,\ldots$ has no convergente subsequence. All you can deduce about sequences of elements of $A$ from the fact that $A$ is closed is that if one such sequence converges, then its limit belongs to $A$.


text:
Q: How to stop font size reduction in typesetting fractions and sub- and superscripts When typesetting equations in Mathematica text cell if I press Ctrl+/ the numerator and denominator font is smaller than the base font. Similarly for sub- and superscripts. How do I tell Mathematica notebook to stop changing font size when going into fraction and subscript or superscript mode?

A: This is controlled by the option AllowScriptLevelChange. If it is set to False, the font will not be smaller in the fractions.
There are several ways to do this.
A.  This will only keep the size of the fractions. The easiest is probably the switch off the script level changes that are taking place by selecting the cell bracket and setting
AllowScriptLevelChange -> False

in the options inspector. This is done as follows:

*

*Open Menu/Format/OptionInspector.

*Select the cell in question. It might be good to not only select the right bracket, but also the formula itself.

*In the Option Inspector dialog the field "Show Option Values" should show "Selected". In the lookup text field type AllowScriptLevelChange.

*In the bottom right window uncheck the checkbox at the option AllowScriptLevelChange.
Done.
B. This will control both the size of the fractions and of the exponents. You may adjust ScriptSizeMultipliers directly in the CellBox:

*

*After you have typed the formula select the cell bracket and press Sift+Ctrl+E (Cmnd+Shift+E in Mac).  The cell structure will open.

*Add
ScriptSizeMultipliers -> {1.0}
as the option for the function Cell and again press Sift+Ctrl+E (Cmnd+Shift+E in Mac). This will close the CellBox and return you to the normal view. In this case not only fractions, but also exponents will show 100%.
C.
As the variant of B one can add the option FractionBoxOptions->{AllowScriptLevelChange->False} to the Cell function in the CellBox presentation making all actions described in B.
Have fun!


text:
Q: Always WWW modrewrite php I want to force www in my urls. I'm having problems with writing. I know that this code will do the trick.
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^(.*)$ http://www.example.com/$1

But I want to put all in $_GET['page']
RewriteRule ^(.*)$ /index.php?page=$1 [L]

How should I put this together?

A: You need to add [QSA], which allows you to modify the query string of the URL:
RewriteRule ^(.*)$ /index.php?page=$1 [QSA,L]

A: this should do the job
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^(.*)$ http://www.example.com/$1
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule .* index.php?page=$0 [L]


text:
Q: unable to locate pacakge popcorn time through terminal during installation Hi am a 64bit Linux user.
I've been trying to install Popcorn time using the terminal, after I type
sudo apt-get install popcorn-time-linux64 and that's how it was saved when I downloaded the package from their website, it gives me:
E: Unable to locate package popcorn-time

Any help please?

A: popcorn-time is not available in default ubuntu repositories however you can use webupd ppa and install it from there

sudo add-apt-repository ppa:webupd8team/popcorntime
sudo apt-get update
sudo apt-get install popcorn-time


text:
Q: Prove that a graph on $n$ vertices which not contains $K_4$ as a subgraph has at most $\frac{n^2}{3}$ edges. Prove that a graph on $n$ vertices which not contains $K_4$ as a subgraph has at most $\frac{n^2}{3}$ edges.
I tried prove that with induction. I assume for graph with $n-1$ vertices that has at most $\frac{(n-1)^2}{3}$ edges.
I take graph with $n$ vertices without $K_4$ as subgraph and I remove a vertex and his edges and if I try return him back with his edges it's not goes well.
any idea what is the problem with this way? I guess that I am missing something.

A: Let $G$ be such a (simple) graph on $n$ vertices.  Verify small cases where $n\leq 3$.  Now, suppose that $n>3$.
If $G$ contains no triangles, then it is well known that $G$ has at most $\dfrac{n^2}{4}<\dfrac{n^2}{3}$ edges (this is Mantel's Theorem).  If $G$ contains a triangle, then let $H$ be the induced subgraph obtained from $G$ by removing a triangle.  By induction, $H$ has at most $\dfrac{(n-3)^2}{3}$ vertices.  Now, prove that the number of edges in $G$ that are not in $H$ is at most $3+2(n-3)$. Then, the number of edges of $G$ is at most $$\frac{(n-3)^2}{3}+3+2(n-3)=\frac{n^2}{3}\,.$$
More generally, see Turán's Theorem.

A: You could also use @Batominovski's line of reasoning and not even assume Mantel's Thm:

*

*Verify for $n=1,2,3$. Now assume for general $n$ that if $H$ is a graph on $n-3$ vertices and has no $K_4$, that $H$ has no more than $\frac{(n-3)^2}{3}$ edges.

*Now let $G$ be a graph with at least $\frac{n^3}{2}$ vertices and no $K_4$. Divide into 2 cases, Case 1 $G$ has a triangle $T$, and Case 2 $G$ does not have a triangle.

*For Case 1 [as the answer above] let $H$ be the graph on $n-3$ vertices formed from removing the vertices of $T$ from $G$. Then $H$ has no $K_4$ either and so by induction hypothesis $H$ has fewer than $\frac{(n-3)^2}{2}$ edges. But then $G$ must have fewer than $3+2(n-3)+|E(H)|$ $\le \frac{n^2}{3}$ edges too lest $G$ has a $K_4$ where 3 of the vertices are in $T$ and the fourth is a common neighbour in $G$ to the vertices of $T$.

*For Case 2 ($G$ is triangle-free too), let $u,u_1$ and $u_2$ be vertices in $G$ s.t. $u_1$ and $u_2$ are adjacent, and let $H$ be the graph formed by removing $u,u_1,u_2$ from $G$. As in Case 1 $H$ has no $K_4$ so it has no more than $\frac{(n-3)^2}{3}$ edges by the induction hypthesis. However, $G$ must have fewer than $2+2(n-3)+|E(H)|$ $\le \frac{n^2}{3}$ edges too lest $G$ has a triangle after all ($u_1,u_2$ and a common neighbor in $G$ in $V(H)$). So this is a contradiction too, and the result follows.


text:
Q: Found Zombie Object, but Cannot Find Responsible Caller I am so confused by this problem. I used Instruments to find a Zombie in my code. Usually I would just go through the list of responsible callers and fix it. The only problem is one of the responsible caller methods doesn't exist in my code. I can't find it!

I can't find -[SpriteSheet setImage:]. The setImage: method is nowhere in my code. It sounds crazy to me, but when I do a textual style search of my code, it comes up empty. I looked through the SpriteSheet class, and there are no methods called setImage:.
Please tell me I am missing something here.

A: the setImage method is likely synthezide from a property on the SpriteSheet class:
@property(retain) UIImage *image; => @synthesize image; => there is code because it is autogenerated.
but it seems you release the image in Enemy::dealloc but try to access it again in there. (last 3 lines)


text:
Q: Efficiently or more functionally create an object from an array Is there a more functional way to create an object in JavaScript programatically without assigning each key individually?
For example, given this array (imagine it comes from an outside data source):
let arr = ['a=1', 'b=2', 'c=3'];

What is an easy way to convert this to an object like so?
let expectedResult = { a: '1', b: '2', c: '3'};

It's clunky to assign a new object and loop over the elements with a for or foreach. It would be nice if there were something akin to map that could yield such a final result.
Imagine you could do this:
arr
  .map(item => new KeyValuePair(itemKey, itemValue)) // magically get itemKey/itemValue
  .toObjectFromKeyValuePairs();

That'd be it right there. But of course there's no such function built in.

A: If you're looking for a more functional approach to the code, you could use a library such as Lodash which makes code more succinct.
You could use _.fromPairs to convert pairs of data in arrays to key-value pairs of an object.

const convert = arr => _(arr)
    .map(s => _.split(s, '=', 2))
    .fromPairs()
    .value();
console.log(convert(['a=1', 'b=2', 'c=3']));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

A: You could use reduce, split and slice:
var arr = ['a=1', 'b=2', 'c=3'];

var out = arr.reduce(
  function (output, input) {
    if (typeof input === 'string') {
      var key = input.split('=',1)[0];
      output[key] = input.slice( key.length + 1 );
    }
    return output;
  },
  {}
);

I use the second argument of split to make it stop after the first = found. Then using slice on the input (treating it as an array of characters) allows the value to contain the = separator as in the case of a=b=c.
By using slice, the value will always be a string, even if it is an empty one. If you want to have null values you could change the line to:
output[key || null] = input.slice( key.length + 1 ) || null;

The type check for string is present since split throws error on null and undefined.
If you wanted to parse the current page's query string for example, you could do it using the above technique just like this:
function getQueryStringParams() {
  var reEncodedSpace = /\+/g;
  return location.search.length > 1 // returns false if length is too short
    && location.search.slice( 1 ).split( '&' ).reduce(
      ( output, input ) => {
        if ( input.length ) {
          if ( output === false ) output = {};
          input = input.replace( reEncodedSpace, ' ' ); //transport decode
          let key = input.split( '=', 1 )[ 0 ]; // Get first section as string
          let value = decodeURIComponent( input.slice( key.length + 1) ); // rest is value
          key = decodeURIComponent( key ); // transport decode

          // The standard supports multiple values per key.
          // Using 'hasOwnProperty' to detect if key is pressent in output,
          // and using it from Object.prototype instead of the output object
          // to prevent a key of 'hasOwnProperty' to break the code.
          if ( Object.prototype.hasOwnProperty.call( output, key ) ) {
            if ( Array.isArray( output[ key ] ) ) {
              // Third or more values: add value to array
              output[ key ].push( value );
            } else {
              // Second value of key: convert to array.
              output[ key ] = [ output[ key ], value ];
            }
          } else {
            // First value of key: set value as string.
            output[ key ] = value;
          }
        }
        return output;
      },
      false
    );
}

The function returns false if the search is empty.

A: If you're willing to spare having one additional line for declaration, this could work for you. Although using a library like lodash or underscore, as mentioned in other answers would certainly help:
var arr = ['a=1', 'b=2', 'c=3'];
var expectedResult = {};
arr.map(function(value) {
    var kv = value.split("=");
    expectedResult[kv[0]] = kv[1];
    return value
})

A: Try The Below Code.
let arr = ['a=1', 'b=2', 'c=3'];
let b=arr.toString();
b='{"'+(b.split('=').join('":"').split(',').join('","'))+'"}';
b=$.parseJSON(b);
console.log(b);

You will get the required output.


text:
Q: Integration with a condition of constant values. I know that
$$\frac{1}{e^{\infty}}=0$$
Can I say that integration
$$\int_0^{\infty} \frac{1}{e^{-ax}}dx=-a$$
  where $a\in [0,-\infty)$. The reason is because the values of a is negative.
Is this true or I am wrong in this assumption.

A: $$\int_{0}^\infty \frac{1}{e^{-ax}}dx=\int_{0}^\infty e^{ax}dx$$
Which converges only for negative values of $a$. When it does converge, you have
$$\int_{0}^\infty e^{ax}dx$$
and, since $a$ is negative, by using $u$-sub, we have
$$=\frac{1}{a}\int_{0}^{-\infty} e^{u}du$$
$$=-\frac{1}{a}$$

A: \begin{align}
\int_0^{\infty}e^{ax}\mathrm{d}x=\lim_{n\to \infty} \int_0^n e^{ax}\mathrm{d}x=\frac{1}{a}\lim_{n\to \infty}[e^{ax}+C]_0^n=\lim_{n\to \infty}\frac{e^{na}-1}{a}
\end{align}
which is $\infty$ is $a\ge 0$, and $-1/a$ if $a<0$.


text:
Q: Import Module.bas from http/ftp? I want to import a module via ftp/http.
For example:
ThisWorkbook.VBProject.VBComponents.Import ("http://www.server.de/modul.bas")
I would like to save the code of a module in a central file, but we don't have a shared drive. So I would like to upload my code to some Server and update it from time to time.

A: Expanding on Tim's comment.  Download it to the temp folder and import it from there.  You can download a file using the code below.
Need reference to Microsoft Internet Controls
'Example
'myURL = "http://www.server.de/modul.bas"
'savePath = Environ("temp")
'fileName = "modul.bas"
Sub SaveInternetFile(myURL As String, savePath As String, fileName As String)
    Dim WinHttpReq As Object
    'create XMLHttp object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", myURL, False
    'send request
    WinHttpReq.send
    'check the status to make sure we succeeded
    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.responseBody
        oStream.SaveToFile (savePath & fileName)
        oStream.Close
    'import the new file
    ThisWorkbook.VBProject.VBComponents.Import(savePath & filename)
    End If
End Sub


text:
Q: Adding Varibles to a path? BATCH Okay, so I'm programming a launcher for Minecraft and I'm trying to add logs to it.
echo %TIME% %DATE% Launched > "%DRIVE%\DATA\LOGS\Log Time %TIME% Date %DATE%.txt"

It says it can't find the file specified!
EDIT: Literally a duplicate of my own question.

A: I guess that you want to save a file with name has time and date !
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~8,2%-%ldt:~10,2%_%ldt:~6,2%-%ldt:~4,2%-%ldt:~0,4%.txt
echo %ldt%
echo %TIME% %DATE% Launched > %ldt%
Start "" %ldt%
pause


text:
Q: ASP.NET MVC OpenId Mixed with Ajax I have an MVC app that I'm migrating from a "proprietary" auth mechanism to OpenID Connect
This is the configuration
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = "Cookies",
    CookieName = "AuthCookieName"
});

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    AuthenticationType = "OpenId",
    ClientId = "myClient",
    Authority = "https://mykeycloakinstance...",
    Scope = OpenIdConnectScope.OpenIdProfile,
    ResponseType = "code id_token token",
    TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
    },
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        RedirectToIdentityProvider = async n =>
        {
            n.ProtocolMessage.RedirectUri = n.Request.Uri.AbsoluteUri;
        }
    },
    SaveTokens = true,
    SignInAsAuthenticationType = "Cookies"
});

The app mainly uses the MVC paradigm (i.e. the server pulls info from the database and injects them into a cshtml view file)
But some pages/views also use AJAX (i.e. call endpoints that return JSON data and render the JSON in the client side) and this is where my problem is.
Every 1 minute my access token refreshes (I'm aware that I can change that number but I prefer to leave it relatively low).
The "MVC" part of the application handles it perfectly by quickly redirecting the user to the IDP and back
But pages that perform Ajax request works for the first minute (as long as the access token is valid), and then break and start returning 302 (the AJAX request tries to redirect to the IDP)

Once I refresh the page, the session refreshes and AJAX request start working again (at least for the next minute), but some pages are meant to be "long living" so expecting the user to refresh the page every once in a while is not acceptable.
How can I make AJAX requests work correctly? Should I consider using the implicit flow in my client? If so, what would I do with the "MVC" part?

A: One option is to handle all the tokens in the backend, so the client (browser) does not need to deal with token refresh.
The Implicit flow is deprecated in OAuth 2.1 should no longer be used for new projects.
Two links worth reading are:

*

*https://leastprivilege.com/2020/03/31/spas-are-dead/

*https://leastprivilege.com/2019/01/18/an-alternative-way-to-secure-spas-with-asp-net-core-openid-connect-oauth-2-0-and-proxykit/
If you are using ASP.NET Core, then you can use the IdentityModel library and its built access token management. It can automatically refresh the access tokens using your refresh tokens.
https://identitymodel.readthedocs.io/en/latest/aspnetcore/web.html


text:
Q: "The miss to sales target was caused by" I would like to know if this sentence is written correctly. I'm trying to explain why we missed the sales target.

The miss to sales target was caused by ....

A: I would say that the sentence is not correct, and a corrected version would start with

"The miss of the sales target..."

or

"The miss of our sales target...

or

"The miss of the department's sales target..."

or similar.
However, I think even the corrected version still sounds awkward and long-winded. Instead I would say

"We missed our sales target because..."

or

"We missed our sales target. The miss was caused..."

or

"The department missed its sales target because..."

or perhaps even

"Our sales target miss was caused..."

(That last one is a bit German in style, chaining three nouns in a row into a noun phrase -- I think it's acceptable in English, but I could imagine some people finding it confusing.)


text:
Q: Using the -M to create database migration file on PHPstorn I run the command: composer dump-autoload and then php artisan make:model User -m
I get: Model already exists!
But I can't find it in migration file... Nor anywhere in folder.
How can I find it? Or how can I create database using -M?

A: This command
php artisan make:model User -m

asks laravel to do two commands at once, which is the make:model command, and make:migration command. So it should actually creates

*

*app/User.php, and also

*database\migrations\2018_02_121212_create_users_table.php
But by default, after you initialized a Laravel project, it should have already included one app/User.php, and of course, collision occurs, so error "Model already exist!" emitted.

To create just a migration file, call this instead:
php artisan make:migration create_users_table

To create just a model file, call this:
php artisan make:model User


text:
Q: Use Memory Pool with Custom Allocator for STL Containers I would like to be able to pass to the STL containers (vector, unordered_map, etc) the memory pool from which they need to allocate. I've found this question  but it does not address the specific problem I'm facing.
I already have a working custom allocator that I can specify in the container declaration but could not figure out a way to pass the address for the allocator to use internally (via the placement new operator), from the application. Basically, I would like to go
From:
std::vector<int, myCustomAllocator<int>> myVector;

to:
void* pool = getMemoryPoolAddress();
std::vector<int, myCustomAllocator<int>/*Specify memory pool somehow*/> myVector;

How can I pass pool to my allocator?

A: Standard library allocator is stateless (see CppCon 2015: Andrei Alexandrescu "std::allocator is to Allocation what std::vector is to Vexation" for context). This means that your concrete allocator type can have only one state (monostate) - global one, or static in C++.
So the question you linked contains the answer to your question:
class MyPoolAlloc {
public:
  static MyPool *pMyPool;
  ...
};

MyPool* MyPoolAlloc<T>::pMyPool = NULL;

It's how you can specify your pool for your allocator type.


text:
Q: How to align memory address? Can anyone could tell me how to align a 16-bit memory address to the nearst 2kB address boundry in C?

A: If you want to do it on yourself, or you need it for dynamic allocations/addressings you ca use the following simple computation:
Aligned2kBoundary = (Unaligned + 2047) & ~(2047);

In a more generalized form if bound is your boundary value:
Aligned2kBoundary = (Unaligned + bound -1) & ~(bound-1);

Warning: Works only for boundaries that are powers of 2!
PS for who have not noticed it, this question is for an embedded system and maybe he wants to dynamically adjust the address while running, not while compiling.

A: In C11 you can allocate dynamic memory and specify the alignment with function aligned_alloc. You can also use C11 _Alignas specifier.
Most compilers also have extensions to specify alignment for example gcc has aligned attribute. From documentation:

aligned (alignment)
This attribute specifies a minimum alignment for the variable or structure field, measured in bytes. For example, the declaration:
     int x __attribute__ ((aligned (16))) = 0;

A: You can use aligned_alloc to allocate aligned memory chunk. If you want to align local variables, you can use compiler attributes. In GCC it is aligned
For example:
 int x __attribute__ ((aligned (16))) = 0;

For Visual C++ it is also aligned
For example:
__declspec(align(16)) struct Str1{
   int a, b, c, d, e;
};


text:
Q: Re-sizing an array with a loop I am trying to re-size my array when calling grow() if my current array is to small to continue adding values to the front or back.
void Vector::grow(void)
{
    // Double the capacity
  capacity_ = (capacity_) ? capacity_ * 2 : 1;

  int *temp = new int[capacity_];

  for(unsigned int i = 0; i < size_; i++)
    temp[i] = array_[i];

  array_ = temp;
  ++allocs_;
}

The array_ is part of the private variables in the class .h file
private:
  int *array_;        // The dynamically allocated array
  unsigned size_;     // The number of elements in the array
  unsigned capacity_; // The allocated size of the array
  unsigned allocs_;   // Number of allocations (resizes)

I am getting some problems where I am leaking memory according to Valgrind:
Invalid read of size 4
Address 0x59ff044 is 0 bytes after a block of size 4 alloc'd

A: The problem is you never free the old memory.
for(unsigned int i = 0; i < size_; i++)
   temp[i] = array_[i];

array_ = temp;

should be:
for(unsigned int i = 0; i < size_; i++){
    temp[i] = array_[i];
}

delete[] array_;
array_ = temp;

You could also likely use memcopy instead of the for-loop.

A: If you allocate memory you have to free it, or it will leak.
int *temp = new int[capacity_];

for(unsigned int i = 0; i < size_; i++)
    temp[i] = array_[i];

delete [] array_;  // this leaks if you don't free it.

array_ = temp;
++allocs_;


text:
Q: .Net 6 Code first json collection prop error I'm trying to make a code first application. And I created the entities below. The relationship I want is: A user can have multiple homes and have multiple questions. When trying to add a user, I leave the question and home ICollection properties blank, because I don't have those properties at the moment. But when I leave it blank, it gives validation error. where am i doing wrong
public abstract class BaseEntity
{
    public Guid Id { get; set; }
    public DateTime CreatedTime { get; set; }
    public DateTime ModifiedTime { get; set; }
    public bool IsActive { get; set; }
}

public class User : BaseEntity
{
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime BirthDate { get; set; }
    public bool IsHomeOwner { get; set; }
    public ICollection<Home> Homes { get; set; }
    public ICollection<Question> Questions { get; set; }
}

public class Question : BaseEntity
{
    public string QuestionBody { get; set; }
    public string QuestionAnswer { get; set; }
    public ICollection<User> Users { get; set; }
}

public class Home : BaseEntity
{
    public string Adress { get; set; }
    public Guid UserId { get; set; }
    public Guid HomePropertyId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }
    [ForeignKey("HomePropertyId")]
    public HomeProperty HomeProperties { get; set; }
}

public class HomeProperty : BaseEntity
{
    public string PropertyName { get; set; }
    public bool TV { get; set; }
    public bool Wifi { get; set; }
    public bool Cigarette { get; set; }
    public bool Alcohol { get; set; }
    public bool AllowGuest { get; set; }
    public short PeopleNumber { get; set; }
    public bool HasInvoice { get; set; }
    public short NumberOfRoom { get; set; }
    public Home Home { get; set; }
}

My User request body
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "createdTime": "2022-04-08T13:13:50.470Z",
  "modifiedTime": "2022-04-08T13:13:50.470Z",
  "isActive": true,
  "email": "string",
  "password": "string",
  "birthDate": "2022-04-08T13:13:50.470Z",
  "isHomeOwner": true
}

I got this error
 {
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-d757552c4af46b09997346664a695d46-00b9a78a6116b618-00",
  "errors": {
    "Homes": [
      "The Homes field is required."
    ],
    "Questions": [
      "The Questions field is required."
    ]
  }
}

A: ASP.NET Core treats non-nullable reference types (see nullable reference types ) as required. You can either disable nullable reference types in .csproj:
<Nullable>disable</Nullable>

Though in general I would not recommend it. Or you can mark corresponding properties as nullable:
public class User : BaseEntity
{
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime BirthDate { get; set; }
    public bool IsHomeOwner { get; set; }
    public ICollection<Home>? Homes { get; set; }
    public ICollection<Question>? Questions { get; set; }
}

But I think better approach would be to create a DTO/Model which will not have these properties and use it in your controllers:
public class UserRequest : BaseEntity
{
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime BirthDate { get; set; }
    public bool IsHomeOwner { get; set; }
}

A: Actually your request object should be different object from your entity object. Request object which user sends when making requests is named as DTO and contains only necessity fields for making request. But if you don't want to seperate request objects and entity objects, you can use following:
public class User : BaseEntity
{
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime BirthDate { get; set; }
    public bool IsHomeOwner { get; set; }
    public ICollection<Home?>? Homes { get; set; }
    public ICollection<Question> Questions { get; set; }
}

Making Homes field nullable as nullable object, will solve your error. All nullablefields should be declared nullable as be in Homes example.


text:
Q: how to get xpath - selenium webdriver I testautomated a small part of Outlook Web App. Here I check a test mailbox that our company sends emails to. Within a certain email there are texts I want to check by using Assert. The problem is that I have difficulties finding the right xpath. The HTML looks like this:

        Wij hebben uw bouwdepotdeclaratie verwerkt.

To use driver.findElement(By.xpath(xpath)) I used the following xpath first:
//font[contains(text(),'Wij hebben uw bouwdepotdeclaratie verwerkt')]/br, but that gives me just the
 tag.
Afther that I tried //font[contains(text(),'Wij hebben uw bouwdepotdeclaratie verwerkt')]/text() and that seemed to give me the xpath that I wanted, because in element inspector it highlighted the text Wij hebben uw bouwdepotdeclaratie verwerkt. That is the actual text that I want the selenium webdriver to find and use to store (with .getText()) in a String. But when I used that with driver.findElement(By.xpath(xpath)).getText() it gave me a NoSuchElementException.
What did I do wrong? What would be the right xpath that I can use with the webdriver to get the text?

A: As you were able to figure out the WebElement through the xpath //font[contains(text(),'Wij hebben uw bouwdepotdeclaratie verwerkt')]/text() but through your script you are getting NoSuchElementException you need to induce WebDriverWait for the element to be visible as follows :
String myText = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_of_the_element"))).getText();

Update
As you are getting TimeoutException as an alternative you can induce WebDriverWait for the parent element to be visible and use Java Split method to extract the desired text as follows :
String myText = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//font[contains(text(),'Wij hebben uw bouwdepotdeclaratie verwerkt')]")));
String[] myTextParts = myText.split(Pattern.quote("
"));
String myPart = myTextParts[1];
System.out.println(myPart);

A: let me know did it help you or not,
If the current node is the font element, then something like this:
text()|span

otherwise you have to always combine with | the two complete XPath - the one for text and the one for span, e.g.:
font/text()|font/span

if the current node is just above font - or
//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font/span|//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font/text()

if starting from the root with some complex selection criteria.
If you have complex paths like the last one probably it is better to store a partial one in a variable - e.g. inside an XSLT:
<xsl:variable name="font" select="//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font"/>

. . .

<xsl:for-each select="$font/span|$font/text()">
  . . .
</xsl:for-each>

Another possibility is to do something like this:
//a[text()='View Larger Map']/../../../../div[contains(@class, 'paragraph')][3]/font/node()[name()='span' or name()='']

that works because name() returns an empty string for text() nodes - but I am not 100% sure that it works that way for all XPath processors, and it could match by mistake comment nodes.

A: below xpath should work
//font[contains(.,'Wij hebben uw bouwdepotdeclaratie verwerkt')]
or
//font[contains(text()[2],'Wij hebben uw bouwdepotdeclaratie verwerkt')]

A: The way your HTML is set up and given what you want, you want to get the FONT tag. In your first XPath you are pulling the BR tag, which is why it didn't work. Your second XPath is using text() which, if I remember correctly, isn't supported by Selenium. The easier way is to modify your first XPath to just get the FONT tag (just remove /br).
//font[contains(text(),'Wij hebben uw bouwdepotdeclaratie verwerkt')]

Using this XPath, the code below should work.
String s = driver.findElement(By.xpath(xpath)).getText().trim();

I added trim() to remove the BR spacing and other possible whitespace. You can remove it if it's not needed/wanted.

Based on OP's feedback, I would use the XPath above but I would change the assert to
By locator = By.xpath("//font[contains(text(),'Wij hebben uw bouwdepotdeclaratie verwerkt')]");
List<WebElement> e = driver.findElements(locator);
Assert.assertTrue(e.size() > 0, "Verify text exists in email");


text:
Q: How Get value of JS promptbox then save into Array                       var sav =new Array();
                       sav[] =prompt("Enter value");
                           while(a!="x")
                             {
                     var a =prompt("Enter value");
                             sav[a]=a;
                              }
                            if(a==x)
                            document.write(sav[a]);

How Get value of JS promptbox then save into Array
 help...!

A: Here's a JSFiddle for an example of how to do this with a function so you can reuse the code multiple times.
Here's the code:
var responses = [];

var askAUser = function() {
    var userText = prompt("Enter text:");
    responses.push(userText);
    return responses;
};

// Ask by invoking function
askAUser();

// Shows that the user info has been added to the array.
console.log(responses);

A: Invoke the push() function to add the retrieved value to the array.
sav.push( prompt("Enter value"));
Working Example: http://jsfiddle.net/uz5s2vpL/
If you want to use the value elsewhere within the code, store it within a variable.
  var sav = [];
  var result = prompt("Enter value"));
  sav.push(result);


text:
Q: How to integrate Django API with XMPP server (ejabberd) I'm currently working on a project where I'm using Django rest framework (DRF) for the backend.
I need to implement one to one chat on this application. For this, I'm using XMPP server. I'm using ejabberd as XMPP server.
Now, I need to create users in the ejabberd server using my API built with DRF.
I need to achieve following things with my API:

*

*create new users in the ejabberd server

*create rooms in the ejabberd server

*fetch all the available rooms.

The username will be fetched or retrived from the frontend.
Is there any Python API client or Django API client to do this in the ejabberd server? Like how there is simple-xmpp for node js
I have seen many python packages for this. some of them are,

*

*pyjabberd

*xmppy

*django-xmpp
I'm not sure which one to use and I don't know whether is it possible to implement the above using any of these packages.

A: All those libraries that you mention seem to be to write XMPP clients. In that case, you can write a small XMPP client that will attempt to register account in a xmpp server (being ejabberd or whatever), that joins a MUC room, configures it to be persistent, then requests the lists of rooms...
A completely different approach would be to call API commands that ejabberd provides. As you can see in the API documentation, there are commands to perform precisely what you want, and many more: register,
create_room_with_opts,
muc_online_rooms.
And how to call this API? For playing and checking what those commands do, you can use the ejabberdctl command-line script. Probably you will later want to use ReST (then configure mod_http_api) or XML-RPC (in that case configure ejabberd_xmlrpc). See
Understanding ejabberd commands, and also check the example configuration and example calls using curl.


text:
Q: Converting all underscore connected letters to uppercase in php I have a string like "kp_o_zmq_k" and I need to covert it to "kpOZmqK" where I need to convert all letters connected to the right of the underscore(o,z,k in this case) to uppercase.

A: <?php
function underscore2Camelcase($str) {
  // Split string in words.
  $words = explode('_', strtolower($str));

  $return = '';
  foreach ($words as $word) {
    $return .= ucfirst(trim($word));
  }

  return $return;
}
?>

A: Try with preg_replace_callback function in php.
$ptn = "/_[a-z]?/";
$str = "kp_o_zmq_k";
$result = preg_replace_callback($ptn,"callbackhandler",$str);
// print the result
echo $result;

function callbackhandler($matches) {
    return strtoupper(ltrim($matches[0], "_"));
}


text:
Q: Flag and close vote description still mentions "FAQ" instead of "help center" I may be nit-picking right now, but the description for close and flag reasons still say "see the FAQ" instead of "see the help center". This is network-wide.
Can we please fix this?


text:
Q: Subtracting two datetime values I'm trying to get the length of time a user was logged in for. My code is grabbing the login and logout time but the loginLength field in my DB table isn't updating with this code. Any ideas what's wrong with it?
$logout = "UPDATE Emp
           SET loginStatus = 0,
           LogoutTime = NOW()
           WHERE username = '$_SESSION[username]'";
if (! mysql_query($logout))
        {
        echo "Error" . mysql_error();
        }
$time = "UPDATE Emp
         SET loginLength = DATEDIFF(milliseconds,LoginTime,LogoutTime)
         WHERE username = '$_SESSION[username]'";
         if (! mysql_query($time))
        {
        echo "Error" . mysql_error();
        }

A: I suspect you are using MySQL as your database (the obsolete "mysql_" functions are a hint).  You are then using SQL Server syntax for the date operations.
The MySQL equivalent is:
UPDATE Emp
     SET loginLength = TIMESTAMPDIFF(MICROSECOND, LoginTime, LogoutTime) / 1000
     WHERE username = '$_SESSION[username]';

You can try "MILLISECOND", but it is not documented as working.


text:
Q: Counting the number of occurences for each row in oracle table i have a table with two columns name and disease , and i want to count the number of time each disease is found in the table for example
------------------------
name       | disease   |
------------------------
name1      | a         |
------------------------
name2      | b         |
------------------------
name3      | c         |
------------------------
name4      | a , b , d |
------------------------

i'm looking for a query that would give me a result like this , is it possible? I tried a lot of queries and none of them worked the way i wanted to
------------------------
a          |  2        |
------------------------
b          |  2        |
------------------------
c          |  1        |
------------------------
d          |  1        |
-----------------------

A: WITH TEST_TABE AS (
SELECT 'name1' as name, 'a' AS disease FROM DUAL
UNION
SELECT 'name2' as name, 'b' AS disease FROM DUAL
UNION
SELECT 'name3' as name, 'c' AS disease FROM DUAL
UNION
SELECT 'name4' as name, 'a , b , d' AS disease FROM DUAL
)
SELECT
    SUM(CASE WHEN INSTR(disease, 'a') != 0 THEN 1 END) AS "A",
    SUM(CASE WHEN INSTR(disease, 'b') != 0 THEN 1 END) AS "B",
    SUM(CASE WHEN INSTR(disease, 'c') != 0 THEN 1 END) AS "C",
    SUM(CASE WHEN INSTR(disease, 'd') != 0 THEN 1 END) AS "D"
FROM TEST_TABE;

Results:
A   B   C   D
2   2   1   1

A: Read comments within code:
SQL> with test as
  2    -- sample data
  3   (select 'name1' as name, 'a' as disease from dual union all
  4    select 'name2' as name, 'b' as disease from dual union all
  5    select 'name3' as name, 'c' as disease from dual union all
  6    select 'name4' as name, 'a , b , d' as disease from dual
  7   ),
  8  splt as
  9   -- split the DISEASE column to rows
 10   (select name,
 11      trim(regexp_substr(disease, '[^,]+', 1, column_value)) disease
 12    from test cross
 13    join table(cast(multiset(select level from dual
 14                             connect by level <= regexp_count(disease, ',') + 1
 15                            ) as sys.odcinumberlist))
 16   )
 17  -- finally ...
 18  select disease,
 19         count(*) num
 20  from splt
 21  group by disease
 22  order by disease;

DISEASE           NUM
---------- ----------
a                   2
b                   2
c                   1
d                   1

SQL>


text:
Q: Categories for Article in Liferay I am using Liferay 6.1.0 GA1.
Where I can change Categories that are displayed in
Asset Publisher -> Edit (Article) -> Categorization
where local (defined in group or organization) instead of being global?


text:
Q: TypeScript pass props to children I am quite new at TypeScript and I am trying to send some props to a children, normally I will do it like this, - Maybe this is not the best way.
app.js
import React form 'react'
import Component from './component'

const App = () => {

  const myfunc1 = () => 'some function 1'
  const myfunc2 = () => 'some function 2'
  const myfunc3 = () => 'some function 3'
  const var1 = 'some variable 1'
  const var2 = 'some variable 2'

  return (
    <Component
      myfunc1={myfunc1}
      myfunc2={myfunc2}
      myfunc3={myfunc3}
      var1={var1}
      var2={var2}
    />
  )

}

component.js
import React from 'react'

const Component = ({
  myfunc1,
  myfunc2,
  myfunc3,
  var1,
  var2,
}) => (
   <>
    // Use the props on the component
   </>
)

export default Component

But when doing it with TypeScript, it asks for type declarations on all props on Component.
Is there a better simpler way to pass props so I do not have to declare the type on all props?

A: import { FunctionComponent } from 'react';

type Props = {
  // types...
}

const Component: FunctionComponent<Props> = ({
  myfunc1,
  myfunc2,
  myfunc3,
  var1,
  var2,
}) => (
<>
</>
)


text:
Q: Performance comparison of similar WHERE clauses I want to know that is there any performance difference between the below 2 queries.
Query 1:
Select
         personName
From tbl
Where personName = 'Asif'

Query2:
Select
         personName
From tbl
Where personName = 'Muhammad Asif'

the PersonName field is not on index.
I just want to konw that when we search a string that have spaces then sql engine requires more effort/time to execute the query or it behave the same as without spaces.
Shorty:

*

*If string is like without spaces but short like Asif or alphanumeric Q1234

*if string contain spaces like 'Muhammad Asif'

*if string contain spaces and its bit long like 'My name is Khan'

What will be the impact of sql engine on these search criteria?

A: if you're looking for Muhammad Asif, your first query will not return that record. if you use an equal in your where clause it will only return exact matches.
if you're looking to find records that include the name 'asif', you could use
WHERE personName LIKE '%Asif%' which would return both Asif and Muhammad Asif and any other records that contain Asif. However, LIKE is a fairly resource intensive query


text:
Q: Symfony3 FOSElasticaBundle doc example not working I am trying to set up FOSElasticaBundle.
Composer json entry:
"friendsofsymfony/elastica-bundle": "^3.2"

I was following official docs tutorial, but this line doesn't work:
$finder = $this->container->get('fos_elastica.finder.app.user');

error i get:

You have requested a non-existent service "fos_elastica.index.app.user".

Do you have any idea why ?

Things i checked:

*

*AppKernel.php contains 'new FOS\ElasticaBundle\FOSElasticaBundle(),'

*Profiler under 'Configuration' tab does not show 'FOSElastica' as enabled :(

config.yml:
fos_elastica:
    clients:
        default: { host: localhost, port: 9200 }
    indexes:
        app:
            types:
                user:
                    mappings:
                        email: ~
                    persistence:
                        # the driver can be orm, mongodb, phpcr or propel
                        # listener and finder are not supported by
                        # propel and should be removed
                        driver: orm
                        model: AppBundle\Entity\User
                        provider: ~
                        listener: ~
                        finder: ~

Thanks in advance for any insights, guys :)

A: Turns out bundle didn't install properly.
"minimum-stability": "dev",

in composer.json on fresh installation worked


text:
Q: Densityplot: isolines I'm plotting a densityplot map from interpolated data.
I need to draw lines in which the value of my function is constant (isolines), but to be constant is not the function itself but a manipulation:
I plot z(x,y)=a(x)-b(x,y) the isoline is b(x,y)=costant
plotter[min_, max_, NumberOfTicks_] :=
 DensityPlot[
  If[S*DOS[x] < 1,
   If[δ - λ > 0, δ - λ, 0.1], -1], {x,
   0.02, 0.5}, {S, 0, 1}, PlotPoints -> 100,
  PlotRange -> {Automatic, Automatic, {2.5, 0}},
  ColorFunctionScaling -> False,
  ColorFunction -> (ColorData["DeepSeaColors"][
      LogarithmicScaling[#, min, max]] &),
  PlotLegends ->
   BarLegend[{ColorData["DeepSeaColors"], {0, 2}},
    LegendMarkerSize -> 370,
    Ticks -> ({LogarithmicScaling[#, min, max]} & /@ (min (max/min)^
          Range[0, 2, 1/NumberOfTicks]))],
  ClippingStyle -> {RGBColor["NightBlue"]}, Frame -> True,
  BaseStyle -> {FontWeight -> "Bold", FontSize -> 12},
  FrameLabel -> {"x", "I"}]
plotter[0.1, 3, 2]

A: It sounds to me like you want to put a contour plot of b[x,y] on top of a density plot of a[x]-b[x,y], easy enough to do
a[x_] := Sin[5 x]
b[x_, y_] := Sqrt[2 x^2 + 3 y^2 - 2 x y]
Show[
 DensityPlot[a[x] - b[x, y], {x, -5, 5}, {y, -5, 5}],
 ContourPlot[b[x, y], {x, -5, 5}, {y, -5, 5},
  ContourShading -> False]
 ]


text:
Q: Convert string into mathematical expression I'm trying to convert a text from textbox in a WinForms. I have an application which is drawing charts from linear equation (fe x^2+2x+3) and I need to have output in mathematical expression to make it work.
Main problem I'm facing is I can't find way to convert string "Math.pow(x,2)" to (I don't know if I'm doing this correct) dynamic answer = Math.pow(x,2);
Can you please help me?


text:
Q: Handling Python sockets First off, I've got the following code that... works. Apparently.
while not self.socket_connected:
    try:
        client_socket.connect((self.hostname, self.port))
        self.socket_connected = True
    except:
        sleep(0.5)
        pass

while self.socket_connected:
    message = client_socket.recv(4096)
    if(message == b''):
        client_socket.close()
        self.socket_connected = False
        break

    #...do stuff

I say "apparently" because I'm reading conflicting sources about how one ought to implement sockets in Python.
Firstly, you've got information as here and here that would have you believe an empty buffer is a disconnected socket. That must've been what I read first (the code above is a few months old at this point, and my first serious attempt at sockets in Python).
However, there's also this post that seems a little better informed. That is, if the buffer is empty, it just means you've read everything available for now. Kind of like how I understand TCP to work in the first place. And maybe I missed it, but is that even mentioned in the docs?
Anyway... what I realized about my code is that, every time the buffer is empty, I drop the client-side socket and reconnect to read new information. That's obviously not ideal, and I'd like to change it.
In C, if recv returns zero, the buffer is empty. If it returns <0, something's gone wrong and you can destroy the file descriptor and attempt to reestablish the connection. How is one supposed to do the same in Python?
EDIT: Just as a bit more context - I've got the first five bytes of the messages being received here encoded to the size of the overall message, so I'll be able to test for 'done-ness' internally, provided that I can distinguish between an empty buffer and a dropped socket.
EDIT 2: What I'm asking specifically is how to check Python sockets for both an empty buffer as well as a dropped connection. Both should be handled differently, of course, and I need to make sure I'm getting the full message by possibly doing multiple recv() calls.

A: By default socket.recv is a blocking call, it'll suspend the thread until there is something it has received in the buffer, then it'll return the whole buffer.
When a socket is disconnected the buffer will become b''  not empty, so it returns b''.
Non blocking sockets that have no data when you call .recv will return a socket exception.
So to answer what I believe the question is, by default, socket.recv will return b'' when the client disconnects.
edit: To see if a socket is empty, you could disable blocking, and then catch the exception that would be thrown by calling recv when the buffer is empty.
Alternatively using the select module with sockets to sort your sockets into 3 lists, ready to read, ready to write, and sockets with exceptions.
https://docs.python.org/3/library/select.html#select.select


text:
Q: Windows 10 memory allocation and stack protection I have a piece of C code as follows:
int main() {
    char buf[4] = { 'A', 'B', 'C', 'D' };
    buf[3] = 42;
    return 0;
}

When I compile it in Microsoft Visual Studio Community 2015 (debug mode, no optimisations) and debug it, I would expect the compiler to add an additional 8 bytes of 0xCC above and below my buffer as a sanity check with an instruction like sub esp,Fhor something similar before the rep stos.  Instead, what I'm actually seeing is sub esp,0D0hwhich results in 196 bytes of 0xCC on the stack above the space allocated for the buffer.  I'm just wondering why?  It seems excessive for a canary.  I've included the full disassembly of the function for reference:
 push        ebp
 mov         ebp,esp
 sub         esp,0D0h
 push        ebx
 push        esi
 push        edi
 lea         edi,[ebp-0D0h]
 mov         ecx,34h
 mov         eax,0CCCCCCCCh
 rep stos    dword ptr es:[edi]
 mov         byte ptr [buf],41h
 mov         byte ptr [ebp-0Bh],42h
 mov         byte ptr [ebp-0Ah],43h
 mov         byte ptr [ebp-9],44h
 xor         eax,eax
 mov         dword ptr [ebp-8],eax
 mov         eax,1
 imul        ecx,eax,3
 mov         byte ptr buf[ecx],2Ah
 mov         eax,0B100Dh
 push        edx
 mov         ecx,ebp
 push        eax
 lea         edx,ds:[0F916E0h]
 call        @_RTC_CheckStackVars@8 (0F91244h)
 pop         eax
 pop         edx
 pop         edi
 pop         esi
 pop         ebx
 mov         esp,ebp
 pop         ebp
 ret

Here is a screenshot of the stack (condensed a bit for space).
I've also experimented with just creating a buffer of a single byte, and the compiler allocates 0xCC bytes for this.  For a forty byte buffer it allocates 0xF0.  I'm just trying to make sense of this.  Why is so much space being allocated?
Compiling in 32-bit mode on Windows 10 64, Microsoft Visual Studio Community 2015 Version 14.


text:
Q: only check one radio button using jquery in asp.net I have the following grid view.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="White"
                BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="UserModule_allusers"
                ForeColor="Black" GridLines="Horizontal" OnRowDataBound="grvGroups_RowDataBound"
                Width="324px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:RadioButton ID="selectRow" GroupName="userSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
</asp:GridView>

Here I am using one radio button to select the row. To select the row I am using the following jquery script.
 $('#<%=GridView1.ClientID%>').find('input:radio[id*="selectRow"]').click(function () {
    $('<%=GridView1.ClientID%>').find('input:radio[id*="selectRow"]').attr('checked',false);
                $(this).attr('checked', true);
                var isChecked = $(this).prop("checked");
                var $selectedRow = $(this).parent("td").parent("tr");
                var selectedIndex = $selectedRow[0].rowIndex;
                if (isChecked)
                    $selectedRow.css({
                        "background-color": "DarkSlateBlue",
                        "color": "GhostWhite"
                    });
            });

In this script i am trying to un-checking first for all the radio buttons in the grid and checking the present context radio button. All the radio buttons are unchecking but present radio button is not checked. Where i done the mistake.

A: try this javascript:
$('#<%=GridView1.ClientID%>').find('input:radio[id*="selectRow"]').click(function () {
    $('#<%=GridView1.ClientID%>').find('input:radio[id*="selectRow"]').attr('checked', false).parent("td").parent("tr").css({ "background-color": "white", "color": "black" });
            $(this).attr('checked', true);
            var isChecked = $(this).prop("checked");
            var $selectedRow = $(this).parent("td").parent("tr");
            var selectedIndex = $selectedRow[0].rowIndex;
            if (isChecked)
                $selectedRow.css({
                    "background-color": "DarkSlateBlue",
                    "color": "GhostWhite"
            });
});

You add an error in this line:
$('<%=GridView1.ClientID%>').find('input:radio[id*="selectRow"]').attr('checked',false);

you forgot the # before the gridview ID.
I add code to remove formatting from unselected rows too.


text:
Q: How to attach request parameters to current Android HttpUrlConnection call I am able to send a request from an Android program to a remote server, but it seems the request has no parameters.  How do I attach parameters?
Here is my current code:
    @Override
    protected String doInBackground(String... theParams)
    {

        String myUrl = theParams[0];
        final String myEmail = theParams[1];
        final String myPassword = theParams[2];

        Authenticator.setDefault(new Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication( myEmail, myPassword.toCharArray());
            }
        });

        String response = null;

        try
        {
            final URL url = new URL(myUrl);

            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("login", myEmail);
            conn.setRequestProperty("password", myPassword);

            conn.setUseCaches(false);

            final InputStream is = conn.getInputStream();
            final byte[] buffer = new byte[8196];
            int readCount;
            final StringBuilder builder = new StringBuilder();
            while ((readCount = is.read(buffer)) > -1)
            {
                builder.append(new String(buffer, 0, readCount));
            }

                response = builder.toString();
            Log.d( "After call, response: " , " " + response);
        }
        catch (Exception e)
        {

        }

        return response;
    }

So now I am not sure how to make the Authenticator password/login get attached to the request and get sent to the server. Any idea how I can accomplish that?
Thanks!

A: You simply do this
final URL url = new URL(myUrl+"?login="+myEmail+"&password="+myPassword);

And you do not need the setRequestProperty lines. Those are actually setting your Http Request's properties and not the query params.


text:
Q: surfnorm function more efficient way Matlab After constructing the point cloud I want to get the normal of each point and I used the built-in matlab function surfnorm but its takes a lot of processing time. So if anyone could assist me do this a better and more efficient way.

A: I wonder if the following code would help you. There are three steps here.

*

*Create 500 randomly spaced points (x,y), and compute a corresponding value z (the height of the surface) for which I chose a sinc like function

*Resample the random points using the TriScatteredInterp function - this permits me to obtain points on an evenly sampled grid that "roughly correspond" to the initial surface

*Compute the normal to "some points" on that grid (since there are 480x640 points, computing the normal at every point would just create an impossibly dense "forest of vectors"; by sampling "every 10th point" you can actually see what you are doing

The code I used was as follows:
randomX = rand(1,500);
randomY = rand(1,500);
r = 5*sqrt(randomX.^2 + randomY.^2);
randomZ = sin(r) ./ r;

% resample the data:
[xx yy] = meshgrid(linspace(0,1,640), linspace(0,1,480));
F = TriScatteredInterp(randomX(:), randomY(:), randomZ(:));
zz = F(xx, yy);

%% at each point, the normal is cross product of vectors to neighbors
xyz=reshape([xx yy zz],[size(xx) 3]);
xv = 10:30:479; yv = 10:30:639; % points at which to compute normals
dx = xyz(xv, yv+1, :) - xyz(xv, yv, :);
dy = xyz(xv+1, yv, :) - xyz(xv, yv, :);

normVecs = cross(dx, dy); % here we compute the normals.
normVecs = normVecs ./ repmat(sqrt(sum(normVecs.^2, 3)), [1 1 3]);

figure;
quiver3(xx(xv, yv), yy(xv, yv), zz(xv, yv), ...
    normVecs(:,:,1), normVecs(:,:,2), normVecs(:,:,3));
axis equal
view([56 22]);

And the resulting plot:


text:
Q: Using pandas to concatenate values based on values in other columns I'm very new to using Python and I've been googling around, but nothing seems to exactly fit my problem.
I have a dataset like the following:
  groupID   sentenceID           strings
   A        0                    'abc'
   A        0                    'def'
   A        1                    'ghi'
   B        0                    'abc'
   B        1                    'def'
   B        2                    'ghi'

and I'd like the output to look like:
  groupID   sentenceID           strings
   A        0                    'abc. def'
   A        1                    'ghi'
   B        0                    'abc'
   B        1                    'def'
   B        2                    'ghi'

Written out in plain English, what I'm trying to accomplish is as follows:
For unique group in groupID:
if sentenceID is duplicate, then concatenate strings
if sentenceID is not duplicate, then print string
I'm sure that it's easy to do with pandas, but I'm having trouble getting it right. Can any one help? Thank you in advance.

A: You can use groupbyand a custom aggregating function to do it
df.groupby(['groupID','sentenceID']).\
   aggregate({'strings': (lambda x: '. '.join(x))}).\
   reset_index()

A: Another way with groupby() and apply()
df.groupby(['groupID','sentenceID'])['strings'].apply(lambda x: ', '.join(x)).reset_index()


text:
Q: Convert mimetype to file extension how to convert mimetype to file extension in xcode
for example i have this code
File Extension     MIME Type

aifc                audio/x-aiff
avi                 video/x-msvideo
gz                  application/x-gzip
jpg                 image/jpeg

Xcode
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
        NSString *mime      = [response MIMEType];
        NSString *extension = @"" // how to covert it ?!
}

A: include <MobileCoreServices/MobileCoreServices.h> or <CoreServices/CoreServices.h>
then just following code:
CFStringRef mimeType = (CFStringRef)@"audio/x-aiff";
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);

A: Swift 4:
Import CoreServices
response.mimeType // is Optional<String> - some : "audio/mpeg"

And how to get mp3 is:
guard let mime = response.mimeType,
      let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime as CFString, nil),
      let ext = UTTypeCopyPreferredTagWithClass(uti.takeRetainedValue(), kUTTagClassFilenameExtension) else {
   return
}

ext.takeRetainedValue() // is "mp3"

PD: Consider that Xcode won't get extensions of unknown file like .Storyboard or .cert in this case will exit in the Guard return.


text:
Q: Representing Time in C++ im creating a constructor to set the default time to midnight. My question is how would you represent time as an int because i have other functions that add minutes,hours,etc to it.
Datatype IsMidnight;

DataType SetToMidnight( datatype M){

//set the default time to midnight not sure how to represent midnight as HH:MM
// example datatype= 12:00;

}

A: You are probably looking for C++11's, std::chrono

The chrono library defines three main types (durations, clocks, and
  time points) as well as utility functions and common typedefs.

You can also look for Boost which has a Date/Time library.


text:
Q: updating page title dynamically in angularJS I'm trying to change the page title dynamically using UI-ROUTER.
the page title that will be displayed is the same hat will be used in the URL :courses I know that i had just to bind the retrieved data to the page title but as I'm new to angular and JS I wasn't able to do it.
here is my code:
angular
    .module('myApp.courses', [ 'ui.router', 'ngResource' ])
    .config(
            [
                    '$stateProvider',
                    '$urlRouterProvider',
                    function($stateProvider, $urlRouterProvider) {
                        $stateProvider
                                .state(
                                        "introduction_to",
                                        {
                                            url : "courses/:courses",
                                            views : {
                                                "mainbody" : {
                                                    templateUrl : "resources/html/course_details.html"
                                                },
                                                "derivativebody" : {
                                                    templateUrl : "resources/html/course_chapter.html"
                                                }
                                            },
                                            data : {
                                                pageTitle : "introduction_to",
                                                authenticate : true
                                            }
                                        });}]);

here the page title is not set dynamically, what I'm trying to do is to have the page title like this way: introduction to + 'course name'.
I tried with $stateParams.courses but it's not working, some thing like this
data :{
                pageTitle : "introduction_to" + $stateParams.courses,
                authenticate : true
            }

I'm using this controller to change the title
.controller(
            'AppController',
            function AppController($scope, $location,$state, sessionService) {
                $scope.$on('$stateChangeSuccess', function(event, toState,
                        toParams, fromState, fromParams) {
                    if (angular.isDefined(toState.data.pageTitle)) {
                        $scope.pageTitle = toState.data.pageTitle
                                + '| MyAcademy';
                    }
                    if ((toState.data.authenticate
                            && !sessionService.isLoggedIn())) {
                        $state.go("login");
                        event.preventDefault();
                    }
                });
            });

the title name is received from this ng-href="courses/{{name.name}}"
here is my HTML from where i'm getting the title

{{name.name}}

Write your first code here

                        Start Course


text:
Q: groupBy or partitioning object with multiple keys with lodash I have an array of packets so that each packet has source IP and destination IP.
I want to find the best way to divide the array so that in the end I'll get a dictionary whose keys are IP and their value is all the packets sent from or to that IP.
For example, if this is my array:
let packets = [ {sourceIp:127.0.0.1, destIp:127.0.0.2},
                {sourceIp:127.0.0.2, destIp:127.0.0.3},
                {sourceIp:127.0.0.3, destIp:127.0.0.1},
                {sourceIp:127.0.0.2, destIp:127.0.0.1}]

I'm looking for a way to get-
result = { 127.0.0.1: [{sourceIp:127.0.0.1, destIp:127.0.0.2},{sourceIp:127.0.0.3, destIp:127.0.0.1},
                       {sourceIp:127.0.0.2, destIp:127.0.0.1}],
           127.0.0.2: [{sourceIp:127.0.0.1, destIp:127.0.0.2},{sourceIp:127.0.0.2, destIp:127.0.0.3},
                       {sourceIp:127.0.0.2, destIp:127.0.0.1}],
           127.0.0.3: [{sourceIp:127.0.0.2, destIp:127.0.0.3},{sourceIp:127.0.0.3, destIp:127.0.0.1}]
         }

Thank you:-)

A: First of all json array objects data type should be in string.
Then use lodash in _.groupBy()

const packets = [{
    sourceIp: "127.0 .0 .1",
    destIp: "127.0 .0 .2"
  },
  {
    sourceIp: "127.0 .0 .2",
    destIp: "127.0 .0 .3"
  },
  {
    sourceIp: "127.0 .0 .3",
    destIp: "127.0 .0 .1"
  },
  {
    sourceIp: "127.0 .0 .2",
    destIp: "127.0 .0 .1"
  }
]
const splittedData = _.groupBy(packets, 'sourceIp');
console.clear();
console.log(splittedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

A: Step 1: Create both perspectives
Presuming sourceIp & destinationIp are always different (which seems reasonable), I would first duplicate the array so that you have 1 with source as "key", and 1 with destination as "key":
const packetsBySource = packets.map(({ sourceIp, destIp }) => ({ key: sourceIp, sourceIp, destIp }))
const packetsByDest = packets.map(({ sourceIp, destIp }) => ({ key: destIp, sourceIp, destIp }))

Step 2: Merge & groupBy
Then I would merge these together, and do a groupBy:
import groupBy from 'lodash/groupBy'

const both = [...packetsBySource, ...packetsByDest]
const keyed = groupBy(both, 'key')

Notes

*

*Your objects will still have the extra key property; if this is a problem you will need: const keyedClean = mapValues(keyed, (packets) => packets.map(({ sourceIp, destIp }) => ({ sourceIp, destIp })))

*If you have a really big input array then performance might become important; it might be faster to use groupBy twice on the original array, and then merge the 2 result objects (I don't know off-hand a quick way to merge array properties)


text:
Q: Wordpress session start front end I am trying to create plugin in wordpress.. Plugin data direct to wordpress front end and I want stat wordpress session in front end using the plugin.
I tried using this but this is not working, can someone help me
function register_session()
{
  session_start();
}
add_action('init', 'register_session', 1);

A: Add this to your plugin or themes' functions.php template:
function register_session(){
if( !session_id() ) //checking if session already exists
    session_start();
}
add_action('init','register_session');

Then to set the session data use something like this:
$_SESSION['username'] = 'some data';


text:
Q: Get method name from __objc_selrefs in dyld_shared_cache I am trying to make a dyld extractor similar to dyld_decache and dsc_extractor. But I am having trouble parsing the __objc_selrefs section.
For testing purposes I used libsystem_trace.dylib, and was able to find and parse its mach_header and its segments and sections. But looking at the __DATA.__objc_selrefs section I find pointers like 0x201b8647fc8 and 0x201b860d716, which are way too high and point outside the cache.
In contrast, in a normal Macho file, the pointers in the __objc_selrefs section point to their corresponding string in the __TEXT.__objc_methname section.
I know that dyld slides and rebases sections, but after a lot of tinkering, I still could not fix the pointers. Any guidance would be amazing, especially given how little resources there is out there.

A: These "addresses" don't just point outside the cache, they point outside the maximum range iOS allocates for the userland address space.
The thing is that these aren't raw addresses, they're addresses with some flags mixed into them. I've seen at least 0x20000000000 and 0x40000000000, and they seem to be exclusive to Objective-C code. I have no idea what they mean or what the true bitmask for these flags is, but so far keeping the lower 40 bits (0xffffffffff) of the addresses has done the job for me.
That would turn e.g. your 0x201b8647fc8 value into 0x1b8647fc8, which should be well inside the shared cache boundaries.


text:
Q: How can you pass environment variables to google app engine via app.yaml? I am using Google App Engine to deploy a node app (nextjs, node-12).
To deploy the app, I run:
gcloud app deploy

My app.yaml is as follows (minus variable substitutions):
runtime: nodejs12
env_variables:
  NEXT_PUBLIC_FRONTEND_URL: "A"

In my code is the following line:
const url = `${process.env.NEXT_PUBLIC_FRONTEND_URL}/login/callback`;

When this code runs in app engine, url evaluates to B/login/callback
I don't understand this behavior. The documentation here (https://cloud.google.com/appengine/docs/standard/nodejs/config/appref) seems to indicate to me that this should work, but it does not.
Is there a reason for this? I've unset the variables from my local computer, just in case they were somehow getting passed, and I removed the .env file in case nginx was sourcing it or something like that.

A: What you have done looks correct. Try the following troubleshooting steps

*

*Confirm you are not directly setting the value somewhere in your code e.g. say you call a child process and pass an env to it and you have explicitly set the value there

*Check your deployed versions (you can do this via cloud console, see path below). Do you have multiple versions of the app? Which one are you running?
To check your versions and which one is running
console.cloud.google.com > App Engine > Versions
To view the configuration for each of the deployed versions,
select the version and click on 'View' under the 'config' column . This will display the deployed app.yaml file for that version


text:
Q: Unable to install nvm on macOS 12.3 I want to install nvm on my macOS 12.3.
The command I use to install nvm is curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash.
But the installation doesn't succeed. I got zsh: command not found: nvm error when running nvm command.
I use iTerm as my terminal.
I've read the Troubleshooting on macOS section. And I've confirmed that I hav the following code in my ~/.zshrc file:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

When I run source ~/.zshrc, I got the following error:
/Users/myname/.zshrc:124: condition expected: source

Line 124 of ~/.zshrc is [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm.
I don't understand why the error occurs only when I use source command to execute ~/.zshrc.
If I copy the 3 lines of code and paste them to iTerm, no error would occur. And I can successfully run nvm command after that.
Why does source ~/.zshrc create that error message?

A: The root cause of this problem is that my 122nd line of ~/.zshrc is [[  ]] && source <(kubectl completion zsh).
After changing that line to source <(kubectl completion zsh), the problem is solved.
According to this document, if you want to install zsh auto-completion for kubernetes, adding source <(kubectl completion zsh) is enough.
Adding [[  ]] is redundant and cause errors.


text:
Q: Why we pass value when using an instance of a derived type? let's say Polygon is our base class and Square is our derived class and we want to make  an instance of a derived class like this:
Polygon polygon = new Square(4.5f);

the above example is from a book which says "it is possible to be actually using an instance of a derived type like the Square, but only know that it is a Polygon"
now my questions are :
1- in which cases a derived class could be a base class? I mean in the situation when computer treat derived class as the base class without we know about it or it is not our intention.
2- why we should pass a value like "4.5f " with derived class ?why we can't treat it like when we make an instance of normal class and write:
Polygon polygon = new Square();

A: Starting by the easiest one, number 2:
In that case, you're creating an instance of Square new Square(4.5f) because Square, which could be a Class or Struct defines a constructor signature with a float as parameter.

Square() being a struct (Structs are light-weight objects, also a bit different from classes), all the public fields has to be initialized in its constructor which has parameters, otherwise the compiler will throw a compiler error if you don't initialize the public fields. however, structs has a implicitly parameterless constructor defined which could be used.
The compiler provides a default, parameterless constructor signature if none, only if none constructor is defined (It only applies on classes).

To brief it, if you don't have any other constructor overload, you'll have to instantiate that object passing a float as argument. In that case I assume its a class. If it was a struct, as I said, Structs has a implicitly parameterless constructor defined so the below would be valid.
Polygon polygon = new Square();

Now lets go back to the first question:
This one is related to inheritance and polymorphism.

In C# a class can inherit from a single class and many interfaces, not more and struct can only inherit interfaces.
As C# only allows a class to inherit from a single class, in other hand it allows you to have nested inheritance: class A : B : C : D and so on.
Polymorphism infers that a class can take many forms. It works in the basis that a derived class has all the features it's base class.

In C# the usage of public member are determined statically (compiter time rather at runtime) so when a derived object takes the form of its base object, it only can access the member its base defines. Also in the case of using a base in a method signature as parameter, it could receive different implementations of itself.
I'd suggest you to read this book: C# 6.0 Pocket Reference, by Joseph Albahari & Ben Albahari
Sorry if I complicated the things :)


text:
Q: Front-end development version control for a CMS I'm looking for a best practice methodology for version control for multiple front-end developers working together on CMS based websites.
So we have several CMS based websites in active development. If you are curious, the CMS is DNN.  On our test server we have front-end developers working with CSS, JS, and also adding content to pages which is of course stored on the database.  We also have module developers who have local copies of the source AND database where they develop and promote to the test server.  And we have a TFS server where the module developers can house their repos for version control.
My question is, how do I get front-end developers on version control?  They can't have local versions of the database because all of their content (database) updates would be constantly out of sync with the test server. It's unrealistic for them to build change scripts for their content/page updates for the database (not to mention it is a different skillset and defeats the purpose of the usability of the CMS).  They can't all host local copies of the files and then connect to a shared remote DB because the application uses memory cache..which would be.. you guessed it... out of sync.
I feel like I'm missing something here because other organizations must be accomplishing this somehow.  We absolutely need version control on our JS/CSS resources.
Thanks.

A: You effectively have two sets work work that should be treated separately.
The first is your version of DNN and the customisations that you make. These should be stored in version control and you should create a deployment pipeline to ship the bits from build to servers.
The second is your in application customizations that are done with point'n'click. These are not versionable in the traditional sense and should be considered instance specific. You could, and probably should, script out all of the customisations of data and version that. So you would have a folder for each instance that you ship with the state if the data at the time you shipped.


text:
Q: Java acquire monitor lock of other class Let's say I have this class:
public class Status {
   private int x;

   // monitor lock?
   public Object myLock = new Object();

   public Status(int x) {
      this.x = x;
   }

   public int checkVar() {
      return x;
   }

   public int incrementVar() {
      ++x;
   }
}

Then I have a thread class like this:
public class MyThread implements Runnable {

   public void run() {
        // Is this how to acquire monitor lock of Status class?
        synchronized (statusInstance.myLock) {
          statusInstance.checkVar();
          statusInstance.incrementVar();
        }
   }
}

This is how you acquire the monitor lock of another class right?

A: In Java if you have a reference to any object you can use it as a mutex. But you would be locking on the object and not the class.
The problem is that anyone can mutate that object because it is public and obtain a lock they shouldn't be acquiring.
 statusInstance.myLock = new Object();

Using public mutable objects as mutexes is considered harmful. You can lock on the class given there is only one class in the ClassLoader
 synchronized(Status.class){
    ..
 }

Or making your lock static final
public static final Object MY_LOCK = new Object();

A: Correct. You can also use the object itself as the lock by using:
public class MyThread implements Runnable {

   public void run() {
     // Is this how to acquire monitor lock of Status class?
     synchronized (statusInstance) {
       statusInstance.checkVar();
       statusInstance.incrementVar();
     }
   }
}

which is simpler because you don't need to declare myLock anymore.


text:
Q: Xml:how to parse the xml values in php my xml flie:
<item>
<title geoid="1198">District of Columbia</title>
<description cong_dist="Delegate District (at Large) 98">DC - Delegate District (at Large) 98
 No of Incidents: 1436</description>
<latitude>38.8933115</latitude>
<longitude>-77.0146475</longitude>
<georss:polygon>38.934311 -77.1199 38.939834989364 -77.112868886998 38.94641 -77.1045 38.94891 -77.1007 38.95651 -77.0915 38.960871062931 -77.085827416011 38.967245703105 -77.077535703105 38.971616050926 -77.07185104194 38.98511 -77.054299 38.986557824794 -77.052373393024 38.99511 -77.040999 38.99171 -77.036299 38.98423067065 -77.026499658425 38.977828623846 -76.909395 38.895811472659 -76.913155644266 38.904084963804 -76.923528686655 38.904209815545 -76.923685221832 38.910455906543 -76.931516373827 38.913311 -76.935096 38.918592133391 -76.941928356721 38.930758817183 -76.957668751373 38.93511031877 -76.963298416241 38.946183221387 -76.977623754198 38.951906165093 -76.985027693844 38.95742281319 -76.992164742828 38.961159688178 -76.99699924729 38.96541 -77.002498 38.97011 -77.008298 38.97441 -77.013798 38.97591 -77.015598 38.977828623846 -77.018111761535 38.98423067065 -77.026499658425 38.99171 -77.036299 38.99511 -77.040999 38.986557824794 -77.052373393024 38.98511 -77.054299 38.971616050926 -77.07185104194 38.967245703105 -77.077535703105 38.960871062931 -77.085827416011 38.95651 -77.0915 38.94891 -77.1007 38.94641 -77.1045 38.939834989364 -77.112868886998 38.934311 -77.1199</georss:polygon>
</item>

i stored this values in dc.xmlfile
how to get all the values in a variable.
for example  tag values is stored in $lat variable in php.
how to get this values
i need your kind help...,

A: Try this out
<?php
$string = <<<XML
<?xml version='1.0'?>
<item>
<title geoid="1198">District of Columbia</title>
<description cong_dist="Delegate District (at Large) 98">DC - Delegate District (at Large) 98
 No of Incidents: 1436</description>
<latitude>38.8933115</latitude>
<longitude>-77.0146475</longitude>
<georss:polygon>38.934311 -77.1199 38.939834989364 -77.112868886998 38.94641 -77.1045 38.94891 -77.1007 38.95651 -77.0915 38.960871062931 -77.085827416011 38.967245703105 -77.077535703105 38.971616050926 -77.07185104194 38.98511 -77.054299 38.986557824794 -77.052373393024 38.99511 -77.040999 38.99171 -77.036299 38.98423067065 -77.026499658425 38.977828623846 -76.909395 38.895811472659 -76.913155644266 38.904084963804 -76.923528686655 38.904209815545 -76.923685221832 38.910455906543 -76.931516373827 38.913311 -76.935096 38.918592133391 -76.941928356721 38.930758817183 -76.957668751373 38.93511031877 -76.963298416241 38.946183221387 -76.977623754198 38.951906165093 -76.985027693844 38.95742281319 -76.992164742828 38.961159688178 -76.99699924729 38.96541 -77.002498 38.97011 -77.008298 38.97441 -77.013798 38.97591 -77.015598 38.977828623846 -77.018111761535 38.98423067065 -77.026499658425 38.99171 -77.036299 38.99511 -77.040999 38.986557824794 -77.052373393024 38.98511 -77.054299 38.971616050926 -77.07185104194 38.967245703105 -77.077535703105 38.960871062931 -77.085827416011 38.95651 -77.0915 38.94891 -77.1007 38.94641 -77.1045 38.939834989364 -77.112868886998 38.934311 -77.1199</georss:polygon>
</item>
XML;

$xml = simplexml_load_string($string);
$title = $xml->title;
print_r($title);
?>

A: see this screen shot there is no error at all what you are saying


text:
Q: ListView not showing at all I have setup a custom adapter, and inflating the data in a list view, problem is list view not showing up. In debugging mode the listView is showing that it indeed has an adapter attached to it, but I can't see any thing.
Here is the code to initialize adapter.
 contactAdapter = new ContactAdapter(this, R.layout.contact_layout, contactList);
 master_listView.setAdapter(contactAdapter);

Here the code for ContactAdapter itself
public class ContactAdapter extends BaseAdapter {
Contact contact;
Context context;
LayoutInflater layoutInflater;
List<Contact> listContact;
int resourceID;
public ContactAdapter(Context context, int layoutResourceID, List<Contact> listContact) {
    this.context = context;
    this.listContact = listContact;
    resourceID = layoutResourceID;
}

@Override
public int getCount() {
    return 0;
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

public View getView(int position, View convertView, ViewGroup parent){
    if(convertView==null){
        layoutInflater = ((Activity) context).getLayoutInflater();
        convertView = layoutInflater.inflate(resourceID, parent, false);
    }
    contact = listContact.get(position);
    TextView tv_name = (TextView)convertView.findViewById(R.id.contact_tvName);
    TextView tv_number = (TextView)convertView.findViewById(R.id.contact_tvNumber);
    tv_name.setText(contact.getName());
    tv_number.setText(contact.getNumber());

    return convertView;
}
}

Here is data structure for saving data.
public class Contact {
String number;
String name;

public Contact(String name, String number) {
    super();
    this.name = name;
    this.number = number;
}

public String getNumber() {
    return number;
}

public String getName() {
    return name;
}
}

And finally here is the layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#ffbababa"
tools:context=".MainActivity">

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffffff"
    android:padding="12dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:id="@+id/relativeLayout">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ib_Speak"
        android:background="@drawable/mic_icon"
        android:textColor="#ffffff"
        android:layout_alignTop="@+id/tvSTT"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Speak Something!"
        android:textColor="#ff343134"
        android:textSize="16sp"
        android:id="@+id/tvSTT"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>
<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/relativeLayout" />

</RelativeLayout>

</RelativeLayout>

Is there a problem with my layout, because I am not getting any kind of error, also all the data is correctly setup, as far as I know.
Help would be appreciated.

A: Your getCount() method is returning 0
@Override
public int getCount() {
    return 0;
}

change it to return the size of your list
@Override
public int getCount() {
    return listContact.size();
}


text:
Q: Rails+DelayedJob: How to display a status that the Delayed Job task is running/is done? I am processing a task that needs some time, so I am thinking about assigning this task to Delayed Job. Would be quite user-friendly to display to users an information about status of the currently processed task - like "processing" and "done".
Checking out the official Github page and I see there some success, after, etc methods, but how to use them?
Thank you in advance.

A: Actually I used DelayedJob effectively in my project. The following procedure works fine for me.
Assume we have a module or class like Subscription and I call a method which was defined as an module method using delayed job as follows:

Subscription.delay(:queue =>
  "insertion_order_#{advertiser.advertiser_id}",:priority =>
  1,:record_of =>
  request_tracker.record_of).pull_data(advertiser,date,Insertionorder)

Now if you want to track error,success or any other hooks then you have to define them in the module or the respective class as follows
module Subsciption
  def self.error(job, exception)
    puts "Error occurred"
    sleep(160)
  end
end

Means all those hooks are working on the object which is used for background processing.


text:
Q: How to switch from LESS to SCSS in Meteor / Iron in an existing project I made a small project in Meteor / Iron. There's almost no styling in it yet but a lot of JavaScript already coded. I would like to update the system to handle SCSS instead of LESS since it seems more adapted for this specific project.
I can't find anywhere how to do such thing, do you have any idea ? Do I have to do everything manually ?

A: According to the docs:
$ iron create myApp --css=scss
You could then dump everything but your .scss files into the new project.
Or you can manually swap out packages as mentioned above:
meteor remove less
meteor add fourseven:scss

As far as converting your LESS into SASS, this may help, but I dont think its going to be as automatic as you want.