text:
Q: Formula/Algorithn for Exponential factoring? Given $s = a^b$ find $a$ and $b$. my first algorithm was the obvious brute force method of checking all $b$ roots or dividing by all possible $a$. But I am wondering if there is a more efficient method. My first optimization was noting that only
Prime $b$ have to be tested but that is still a form of brute force. Can any additional number theory properties be used to generate faster method or algorithm? How dos this problem stack up in terms of difficulty when compared to factoring?

A: This is best. Infinitely quicker than full factoring. Prime $b,$ with
$$ b \leq \frac{\log s}{\log 2}  $$ because $a \geq 2.$ Newton's method for
$$ x^b - s = 0.  $$ It is actually possible to do Newton's method in integers, as long as, when getting near the actual $\lfloor s^{1/b} \rfloor,$ you avoid an infinite loop by switching to just adding or subtracting $1$ as needed. I do this for integer square roots, cube roots, and fifth roots in C++. Oh, if you have a maximum legal integer such as $2^{31}-1,$ it is also necessary, doing this in integers, to check whether $s$ greater than or equal to the biggest legal $a_{\mbox{max}}^b$ that occurs in integers, in which case the value $a_{\mbox{max}}$ is returned. This was surprising at the time, got an infinite loop by asking for the square root (floor thereof) for an integer between $46340^2$ and $2^{31}-1.$
I believe GMP has this fully implemented in integers of arbitrary size.


text:
Q: ng-click change class to selected button i want to change class btn-white to  btn-primary for the selected Button
$scope.SelectedCombination = function (combinationId) {
        $scope.selectedCombination =combinationId;
    };

html
<button ng-repeat="combination in combinations" class="btn btn-white" ng-model="" value="{{combination.combinationId}}" ng-click="SelectedCombination(combination.combinationId)"  type="button">{{combination.name}}</button>

A: use ng-class.don't use any javascript function to set css.
<button ng-repeat="combination in combinations" class="btn btn-white" ng-model="x" value="{{combination.combinationId}}" ng-click="SelectedCombination(combination.combinationId);clicked=true;" ng-class="{btn-primary:clicked}" type="button">{{combination.name}}
</button>

or you can use best approach:
<button ng-repeat="combination in combinations" class="btn btn-white" ng-model="x" value="{{combination.combinationId}}" ng-click="SelectedCombination(combination.combinationId);" ng-class="{'btn-primary':selectedCombination==combination.combinationId}" type="button">{{combination.name}}
</button>

see plunker

A: There is something called Ng-Class. Ng-class,allow you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Online powershell script to get list of site collection admins required? Can anyone provide SharePoint online power-shell to extract list of site collection admins along with all site URL's for entire tenant?

A: You can run the following powershell (this will return all the primary admins of all site collections).
$sites = Get-SPOSite -Limit All
$sites | select url,owner

To get all admins Please try below script.
$spousers = Get-SPOUser -Site https://example.sharepoint.com/sites/training

$spousers | select LoginName, IsSiteAdmin

Read more here: link
Try this one. I dont have any tenant so i cant test it.
 $sites = Get-SPOSite -Limit All
foreach ($site in $sites) {
Get-SPOUser -Site $site.Url | FT LoginName, IsSiteAdmin -AutoSize
}


text:
Q: I need begin a project with react-tabulator With react-tabulator I can use the same options that has Tabulator (javascript)?
I need begin a project with react and not sure how to use react-tabulator

A: Yes, you should be able to use any of the Tabulator options in react-tabulator.  If you find any specific issues, you would be best off creating an issue on the github project.
Here is a link to the example in the documentation.
Here is a simplified example.
import * as React from 'react';
import ReactTabulator from 'react-tabulator'

const columns = [
  { title: 'Name', field: 'name'}
];
const data = [
  { name: 'Oli Bob'},
  { name: 'Mary May' }
];

const TabulatorComponent = <ReactTabulator columns={columns} data={data} />;


text:
Q: How to suppress space between two HTML elements I need to supress the space between $ and amount
Now it is showing $ 23   it should show $23
 $
                                                <%= Html.Encode(String.Format("{0:F}", item.cy_list_price))%>

A: Your markup has a space, so it will render a space. If you don't want it, don't put it there:
$<%= Html.Encode(String.Format("{0:F}", item.cy_list_price))%>

HTML suppresses extra whitespace, but preserves one space.


text:
Q: Mock UIViewController defined in Storyboard I have a UIViewController-class instantiated via Storyboard that contains a constant property. For testing, I want to replace/mock whatever the value of the view controller.
I can actually do this by subclassing and defining a new constant and by overriding the methods that use it. However, I do not know how to instantiate the ViewController, since it's not in the storyboard.
It's important that all views and all other functionality of the original ViewController is still present, of course. How to go about it?

A: If i understand you need to access a property from another ViewController outside your Storyboard without presenting it. Since you're using swift, all you need to do is instantiate the class itself i believe. For example if the ViewController that is not in the storyboard has a class named "SecondController", and the variable inside second controller is called "stringVar" then all you need to do is this:
var secondVC = SecondController()
secondVC.stringVar = "new string value"

Example:
//SecondVC

import UIKit

class SecondViewController: UIViewController {
    var something:String! = "String Value";
}

//Main VC

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        var secondVC = SecondViewController()
        secondVC.something = "Another String Value"
        println(secondVC.something)

    }

 }


text:
Q: javascript to find memory available Let's make it immediately clear: this is not a question about memory leak!
I have a page which allows the user to enter some data and a JavaScript to handle this data and produce a result.
The JavaScript produces incremental outputs on a DIV, something like this:
(function()
{
   var newdiv = document.createElement("div");
   newdiv.innerHTML = produceAnswer();
   result.appendChild(newdiv);
   if (done) {
      return;
   } else {
      setTimeout(arguments.callee, 0);
   }
})();

Under certain circumstances the computation will produce so much data that IE8 will fail
with this message:

not enough storage when dealing with too much data

The question is:
is there way I can work out how much data is too much data?
as I said there is no bug to solve. It's a genuine out of memory because the computation
requires to create too many html elements.
My idea would be to run a function before executing the computation to work out ahead if the browser will succeed. But to do so, in a generic way, I think I need to find the memory available to my browser.
Any suggestion is welcome.

A: Javascript (in the browser) is run in a sandbox, which means that it is fenced-off from accessing things that could cause security issues such as local files, system resources etc - so no, you can't detect memory usage.
As the other answers state, you can make the task easier for the browser by pausing between implementations or using less resource-intensive code, but every browser has its limits.

A: Have a play with this...
document.write(performance.memory.jsHeapSizeLimit+'

');
document.write(performance.memory.usedJSHeapSize+'

');
document.write(performance.memory.totalJSHeapSize);

A: A loop will use less memory than recursion.
   do
   {
     var newdiv = document.createElement("div");
     newdiv.innerHTML = produceAnswer();
     result.appendChild(newdiv);
   } while (!done);

You could also put some upper limit on the number of answers produced.
   var answerCount = 0;
   do
   {
     var newdiv = document.createElement("div");
     newdiv.innerHTML = produceAnswer();
     result.appendChild(newdiv);
   } while (!done && answerCount++ < 1000);

A: I suspect having a 0 timeout delay is the problem - it's trying to re-run instantly.  Try increasing this.


text:
Q: How is Java concurrency implemented for Windows? Does anyone know how is Java concurrency implemented for Windows?  Does it call the native Windows API?  I downloaded the source code from OpenJDK.  So far, I haven't found any file related to concurrency.   Thanks.

A: You're probably referring to the two thread models used throughout the history of the Java Runtime: the green thread model (user-level threads, managed by the JVM) and the non-green thread model (native threads, managed by the OS).
As answered here, green threads aren't used anymore (and haven't been used for a long time) on any of the popular platforms (Windows, Linux, Solaris). So, to answer your question, Java threads are real threads at the implementation level.
The synchronized keyword functions based on the fact that every object is associated with a "hidden" monitor. Therefore, synchronized works by emitting the bytecodes for monitorenter and monitorexit, which are instructions to the JVM to lock and unlock respectively that hidden monitor.


text:
Q: process start failed in activiti There is a bug in my project(Redhat/weblogic12c), god help me!!!
Caused by: java.lang.Throwable: Error parsing XML
    at org.activiti.engine.impl.bpmn.parser.BpmnParse.execute(BpmnParse.java:236)
    at org.activiti.engine.impl.bpmn.deployer.BpmnDeployer.deploy(BpmnDeployer.java:112)
    at org.activiti.engine.impl.persistence.deploy.DeploymentManager.deploy(DeploymentManager.java:50)
    at org.activiti.engine.impl.persistence.deploy.DeploymentManager.resolveProcessDefinition(DeploymentManager.java:121)
    at org.activiti.engine.impl.persistence.deploy.DeploymentManager.findDeployedProcessDefinitionById(DeploymentManager.java:69)
    at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:66)
    at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:36)
    at org.activiti.engine.impl.interceptor.CommandInvoker.execute(CommandInvoker.java:24)
    at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:57)
    at org.activiti.spring.SpringTransactionInterceptor$1.doInTransaction(SpringTransactionInterceptor.java:47)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
    at org.activiti.spring.SpringTransactionInterceptor.execute(SpringTransactionInterceptor.java:45)
    at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:31)
    at org.activiti.engine.impl.cfg.CommandExecutorImpl.execute(CommandExecutorImpl.java:40)
    at org.activiti.engine.impl.cfg.CommandExecutorImpl.execute(CommandExecutorImpl.java:35)
    at org.activiti.engine.impl.RuntimeServiceImpl.startProcessInstanceById(RuntimeServiceImpl.java:107)
    at utry.workflow.engine.service.impl.ActivitiEngineServiceImpl.startFlow(ActivitiEngineServiceImpl.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
    at com.sun.proxy.$Proxy720.startFlow(Unknown Source)
    at utry.workflow.inter.impl.WfBpmServiceImpl.start(WfBpmServiceImpl.java:121)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
    at com.sun.proxy.$Proxy723.start(Unknown Source)
    at utry.workflow.server.service.impl.ProcessInstanceServiceImpl.start(ProcessInstanceServiceImpl.java:59)
    at utry.workflow.server.service.impl.ProcessInstanceServiceImpl.startByXmlId(ProcessInstanceServiceImpl.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
    at com.sun.proxy.$Proxy728.startByXmlId(Unknown Source)
    ... 80 more

Caused by: java.lang.ClassCastException: com.ctc.wstx.stax.WstxInputFactory cannot be cast to javax.xml.stream.XMLInputFactory
        at javax.xml.stream.XMLInputFactory.newInstance(XMLInputFactory.java:136)
        at org.activiti.bpmn.converter.BpmnXMLConverter.convertToBpmnModel(BpmnXMLConverter.java:228)
        at org.activiti.engine.impl.bpmn.parser.BpmnParse.execute(BpmnParse.java:185)
        ... 138 more

A: This is a classloader issue.
How is this deployed? as a war and how is Activiti installed in your JBoss environment?
Thanks,
Greg


text:
Q: How to search in meteor, inside of an array in a collection? I have the following two schemas,
Schema.extraOptions = new SimpleSchema({

name: {
    type: String
},
content: {
    type: String
},
note: {
    type: String
}

});

var wordFields = {
_id: {
    type: String,
    optional: true,
    autoform: {
        omit: true
    }
},
name: {
    type: String,
    label: 'Name'
}
'extraOptions.$': {
    type: Schema.extraOptions,
    optional: true
}
};

How can I search in wordFields for name, extraOptions.name and extraOptions.content?
I tried using easySearch but it is not working as expected.
WordsIndex = new EasySearch.Index({
collection: Words,
fields: ['name', '_id', 'extraOptions' ],
selectorPerField: function (field, searchString) {
    console.log("searchString " + searchString);
    console.log("field " + field);
    if ('extraOptions' === field) {
        // return this selector if the email field is being searched
        console.log("searchString " + searchString);
        console.log("field " + field);
        return {
            extraOptions: {
                $elemMatch: {
                    name: { '$regex' : '.*' + searchString + '.*', '$options' : 'i' },
                    content: { '$regex' : '.*' + searchString + '.*', '$options' : 'i' }
                }
            }
        };
    }
    return this.defaultConfiguration().selectorPerField(field, searchString);
},

engine: new EasySearch.Minimongo()
});

Which way would be the best to search values in this case?

A: Take a look at this Link. Here says that you should access the variables with the keyword this


text:
Q: Get only rows of dataframe where a subset of columns exist in another dataframe I want to get all rows of a dataframe (df2) where the city column value and postcode column value also exist in another dataframe (df1).
Important is here that I want the combination of both columns and not look at the column individually.
My approach was this:
#1. Get all combinations
df_combinations=np.array(df1.select("Ort","Postleitzahl").dropDuplicates().collect())
sc.broadcast(df_combinations)

#2.Define udf
def combination_in_vx(ort,plz):
  for arr_el in dfSpark_combinations:
    if str(arr_el[0]) == ort and int(arr_el[1]) == plz:
      return True
  return False

combination_in_vx = udf(combination_in_vx, BooleanType())

#3.
df_tmp=df_2.withColumn("Combination_Exists", combination_in_vx('city','postcode'))
df_result=df_tmp.filter(df_tmp.Combination_Exists)

Although this should theoretically work it takes forever!
Does anybody know about a better solution here? Thank you very much!

A: You can do a left semi join using the two columns. This will include the rows in df2 where the values in both of the two specified columns exist in df1:
import pyspark.sql.functions as F

df_result = df2.join(df1, ["Ort", "Postleitzahl"], 'left_semi')


text:
Q: Reactjs with fetch for auth and access token, not able to parse response I am pretty new to ReactJS.
I am using Chrome browser.
I am trying to create the sign in page using ReactJS. The page is simple with user id and password. Authentication happens on our SSO server, means I have to post data on the server using fetch call and get access_token as a response.
The problem is as below:
I am not getting response in the console. However, when I look at the Network tab on developer tools, I can see that there is a valid response with all required field including access_token in it.
Now sure how should I parse this.
Is this because fetch is async call?
Here is my entire page code.
P.S: some of the code is not getting formatted.
import React, {Component} from 'react';
import '../App/App.css';
import {FormGroup, FormControl, InputGroup} from 'react-bootstrap';

class Auth extends Component {

    constructor(props) {
        super(props);
        this.state = {
            userid: '',
            password: '',
            accessToken: ''
        }
    }

    submit() {
        console.log('state', this.state);
        const BASE_URL = 'MY SSO URL';
        const params = {
            'grant_type': 'password',
            'username': this.state.userid,
            'password': this.state.password,
            'client_secret': 'secred',
            'client_id': 'client_id',
        };
        const formData = new FormData();
        for (let p in params) {
            formData.append(p, params[p]);
        }
        const headers = {
            'Access-Control-Allow-Origin': '*'
        };
        const request = {
            method: 'POST',
            headers: headers,
            body: formData,
            mode: 'no-cors'
        };

        fetch(BASE_URL, request)
            .then((response) => response.text())
            .then((responseText) => {
                console.log('text',responseText);
            })
            .catch((error) => {
                console.warn(error);
            });
        console.log('all done');
    }

    render() {
        return (

Signin

                <FormGroup>
                    <InputGroup>

                            <FormControl
                                type="text"
                                placeholder="Enter User Id or email"
                                onChange={event => this.setState({userid: event.target.value})}
                                onKeyPress={
                                    event => {
                                        if (event.key === 'Enter') {
                                            this.submit()
                                        }
                                    }}
                            />

                            <FormControl
                                type="password"
                                placeholder="enter password"
                                onChange={event => {
                                    console.log(event.target.value)
                                    this.setState({password: event.target.value})
                                }}
                                onKeyPress={
                                    event => {
                                        if (event.key === 'Enter') {
                                            this.submit()
                                        }
                                    }}
                            />

                        <FormControl
                            type="submit"
                            onClick={() => this.submit()}
                        />
                    </InputGroup>
                </FormGroup>

        )
    }
}
export default Auth;

I tried response.json() this gives error as: Unexpected end of input.

A: As far are your frontend JavaScript code for the fetch(…) request:
mode: 'no-cors'

Remove that. That's the exact reason your code can't access the response.
You never, ever want to do mode: "no-cors". The only thing that actually does is to tell the browser, Never let my frontend JavaScript code access the response from this request.
const headers = {
    'Access-Control-Allow-Origin': '*'
};

Remove those lines too. Access-Control-Allow-Origin is a response header. You never want to send it in a request. The only effect that'll have is to trigger a browser to do a preflight.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
I'm guessing that the reason you're trying mode: 'no-cors' and sending Access-Control-Allow-Origin in the request is that you earlier tried the request without those and you got an error message in the browser console saying that the response lacked Access-Control-Allow-Origin.
If so, there's no way you can get around that by making changes to your frontend JavaScript code—except by changing your code to instead make the request through a proxy, as outlined in the answer at "No 'Access-Control-Allow-Origin' header is present on the requested resource".
Either that or you need to get the owner of the server at your BASE_URL address to configure the server to send the Access-Control-Allow-Origin in its responses.

Here's a longer explanation:
Your browser will only let your frontend JavaScript code access responses from cross-origin requests when the servers you're making the requests to explicitly indicate they're opting in to receiving cross-origin requests, which they do by sending the Access-Control-Allow-Origin response header in their responses.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.
Browsers are the only clients that enforce restrictions on cross-origin requests, and they only enforce them on web applications.
That's why even when you see a No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin … is therefore not allowed access message in your devtools console, you'll still be able to go to the Network tab in devtools and view the response there.
That's because the server has sent the response and the browser has received it, but the browser is just refusing to allow your frontend JavaScript code to access the response due to the fact the server sending the response hasn't opted into to cross-origin requests by sending the Access-Control-Allow-Origin response header.
The reason you can get the response just fine when you make the request from curl, etc., is that no client other than browsers will refuse to allow your code to access the response if it lacks the Access-Control-Allow-Origin response header. But browsers always will.
And note that in none of this is the server doing any blocking or refusing to respond to any requests. The server always continues to just receive requests and send responses. The only difference is in whether the server sends the Access-Control-Allow-Origin header in the response, or not.


text:
Q: How is the quota of Google Maps Places API calculated? I have a list of names for finding out the detail address and coordinates, just like what a user search for on Google Maps app, instead I try to accomplish the task in batch.
I did it in Python with "Requests" package.
I used Google Maps Places API and "textsearch" mode. After sending 100 requests (each contains a string of names of one place), I found in the API console that the free quota (1,000 request / 24h) was exceeded, while the count of "success" was 100.
Why does Google records 1,000 requests while in fact I sent 100?

A: As described in the documentation, text searches are subject to a 10-times multiplier:

Text Search Requests

-- snip --

The Google Places search services share the same usage limits. However, the Text Search service is subject to a 10-times multiplier. That is, each Text Search request that you make will count as 10 requests against your quota. If you've purchased the Google Places API as part of your Google Maps API for Work contract, the multiplier may be different. Please refer to the Google Maps API for Work documentation for details.


text:
Q: Método retorna corre solo 1 vez y retorna solo 1 valor El problema es que el método que hice me retorna solo 1 valor, debo retornar los valores de un vector, pero con forma de String ahora hice el método (lo adjunto a continuación).
public static String toString(Estudiante estudiantes[]){
     String retorno = "";
    for (int i = 0; i < estudiantes.length; i++) {
        retorno = estudiantes[i].toString() + " ";
    } // For
    return retorno;
} // toString

Ese es mi método ahora, el método me retorna solo el valor del último indice ( se sobre escribe) , el resto no me los retorna y no entiendo por qué ya que el for es de 0 al lenght debería ser cambiante el valor de retorno.

A: agregarle el signo '+' dentro del bucle para ir concatenando tu contenido.
public static String toString(Estudiante estudiantes[]){
     String retorno = "";
    for (int i = 0; i < estudiantes.length; i++) {
        retorno += estudiantes[i].toString() + " ";
    } // For
    return retorno;
} // toString


text:
Q: How to centering span How to centering that download button? I tested many times but it's wrong codes.

.col {
  width: 100%;
  height: auto;
  float: left;
}
.download {
  width: auto;
  font-weight: 600;
  font-size: 14px;
  color: #000;
  border: 2px solid #000;
  padding: 17px 37px;
  margin-top: 30px;
  float: left;
}

  Download

A: Just add text-align: center; to .col and replace float:left with display:inline-block; in the button element. jsfiddle

A: *

*Remove float:left; from .download (because it forces the element to be floated to the left).

*Give display:inline-block; (It acts like inline element, it means you can center it by giving text-align:center; to its parent.)
JSFiddle
.col {
    width: 100%;
    height: auto;
    float: left;
    text-align: center;
}
.download {
    font-weight: 600;
    font-size: 14px;
    color: #000;
    border: 2px solid #000;
    padding: 17px 37px;
    margin-top: 30px;
    display: inline-block;
}


text:
Q: How to provide non-admins of Site Collection with Access to Audit Logs I'm working in SharePoint On-Prem 2016, and am curious if you know of a way to grant someone who isn't a site collection admin with access to review the Audit Logs?  (Trying to make it sort of "self-service" so some users can get to the data in the logs of "who opened a file" without having to contact the IT Dept).

A: You can export them on a scheduled basis to a Document library on the same Site Collection. That is the easiest approach.


text:
Q: Why aren't quartz crystals' pin pitch aligned to the inch grid? This is most probably stupid question, but I would love hearing the story. Can not find anything relevant in the net.
The spacing between the pins of HC-49 is 4.88 mm, there're some other variations like 12.3 mm and 3.75 mm, all of them are not exact multiple of 0.1" (or even 0.01").
More to consider - the pitch is even not aligned to the metric grid...
I found it out after drawing the crystal gasket and putting it onto the crystal device on the board, being astonished to see that my assumption about 0.2" pitch being wrong.


text:
Q: Linq to Dictionary. Select keys with values that contain condition string I have a dictionary Dictionary<string, string[]>. How can I select all keys with values that contain string "item1" using Linq?
Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>
{
    {
        "key1",
        new string[] { "item1", "item2", "item3" }
    },
    {
        "key2",
        new string[] { "item1", "item4" }
    }
};

Thanks for the help!

A: Use Where to filter the KeyValuePairs then Select to return the keys.
var result = dictionary
    .Where(kvp => kvp.Value.Contains("item1"))
    .Select(kvp => kvp.Key);


text:
Q: ggplot2: Mark years with geom_ribbon I have a dataset that looks like this:
library(tidyverse)

df  <- tribble(
  ~year, ~value, ~dummy,
  #--|--|----
  2003, 3, 0,
  2004, 4, 0,
  2005, 7, 1,
  2006, 9, 1,
  2007, 15, 1,
  2008, 17, 0,
  2009, 7, 0,
  2010, 8, 0,
  2011, 8, 0,
  2012, 7, 0,
  2013, 2, 0,
  2014, 9, 1,
  2015, 5, 0
)

I'm trying to plot the value series and have gray bars in the background for years that are marked with dummy == 1. (Like this)
I have trouble passing the right years to R. I've tried the following, but it doesn't work:
dummy_years <- df$year[df$dummy == 1]

ggplot(df , aes(x = year)) +
  geom_ribbon(aes(x = dummy_years, ymin = -Inf, ymax = Inf)) +
  geom_line(aes(y = value))

I get: Error: Aesthetics must be either length 1 or the same as the data (13): x, ymin, ymax.

A: We can use geom_rect, filling by dummy, and using a scale_fill_manual:
library(ggplot2)
ggplot(df) +
    geom_line(aes(year, value)) +
    geom_rect(aes(ymax = Inf,
                  ymin = -Inf,
                  xmin = year,
                  xmax = year + 1,
                  fill = factor(dummy)),
              alpha = .5,
              show.legend = FALSE) +
    scale_fill_manual(values = c('transparent', 'grey45')) +
    theme_minimal()


text:
Q: Screen.AllScreens does not change when connecting by RDP I have a desktop PC with a 2560 x 1440 resolution, and a netbook with a 1024 x 600 resolution.
When I RDP-connect with the netbook to the desktop, the screen of the desktop is presented in 1024x600, since the netbook does not allow more. So, there is some re-scaling of the windows, and some kind of 'virtual screen' just changed its size from 2560x1440 to 1024x600.
However, the System.Windows.Forms.Screen.AllScreens property does not reflect this change, its single array item stays at 2560 x 1440.
How can I detect the 'virtual screen size change' in .NET, using WinForms or WPF?
Thank you
Edit:
I forgot to say, the AllScreens property changes its value when I debug in Visual Studio (with the vshost.exe host EXE), but as soon as I run the program without a debugger, the AllScreens property does not reflect the change in screen size.

A: I was able to detect screen resolution changes from both the desktop computer and from a remote laptop connecting through remote desktop as well as having it report the proper resolution numbers by the following technique:
I just created a sample WinForms program that handles this event:
Microsoft.Win32.SystemEvents.DisplaySettingsChanged +=
     SystemEvents_DisplaySettingsChanged;

In my test I had a listbox which displayed the information when the screen changed:
void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
    foreach (var screen in System.Windows.Forms.Screen.AllScreens)
    {
        listBox1.Items.Add("Device Name: " + screen.DeviceName);
        listBox1.Items.Add("Bounds: " +
            screen.Bounds.ToString());
        listBox1.Items.Add("Type: " +
            screen.GetType().ToString());
        listBox1.Items.Add("Working Area: " +
            screen.WorkingArea.ToString());
        listBox1.Items.Add("Primary Screen: " +
            screen.Primary.ToString());
    }
}

I ran the program in release mode outside the debugger on my desktop and then connected from my lower resolution laptop and the numbers changed to reflect the lower resolution.

A: In case anyone wants to do the same in PowerShell, this code does basically the same as Brad Rem's code, only saving results to a TextBox:
[Microsoft.Win32.SystemEvents]::add_DisplaySettingsChanged({
    $AppendText = ''
    foreach ($Screen in [Screen]::AllScreens) {
        $InfoTextBox.Text +=  $AppendText +
            "Device Name: $($Screen.DeviceName)`r`n" +
            "Bounds: $($Screen.Bounds.ToString())`r`n" +
            "Type: $($Screen.GetType().ToString())`r`n" +
            "Working Area: $($Screen.WorkingArea.ToString())`r`n" +
            "Primary Screen: $($Screen.Primary.ToString())`r`n"
        $AppendText = "&`r`n"
    }
    $InfoTextBox.Text += "`r`n"
})

The following results were in a Windows 10 environment for both the remote computer and the local computer.
Results when remoting into a multi-monitor computer that is already logged on, and then braking the RDP-connection by sitting down at the computer and un-locking it:
Device Name: \\.\DISPLAY49
Bounds: {X=0,Y=0,Width=1280,Height=1024}
Type: System.Windows.Forms.Screen
Working Area: {X=0,Y=0,Width=1280,Height=1024}
Primary Screen: True

Device Name: \\.\DISPLAY1
Bounds: {X=0,Y=0,Width=2560,Height=1440}
Type: System.Windows.Forms.Screen
Working Area: {X=0,Y=0,Width=2560,Height=1440}
Primary Screen: True
&
Device Name: \\.\DISPLAY2
Bounds: {X=-1200,Y=0,Width=1200,Height=1920}
Type: System.Windows.Forms.Screen
Working Area: {X=-1200,Y=0,Width=1200,Height=1920}
Primary Screen: False

Results from removing a monitor and plugging it back in:
Device Name: \\.\DISPLAY2
Bounds: {X=0,Y=0,Width=1200,Height=1920}
Type: System.Windows.Forms.Screen
Working Area: {X=0,Y=0,Width=1200,Height=1920}
Primary Screen: True

Device Name: \\.\DISPLAY1
Bounds: {X=0,Y=0,Width=2560,Height=1440}
Type: System.Windows.Forms.Screen
Working Area: {X=0,Y=0,Width=2560,Height=1440}
Primary Screen: True
&
Device Name: \\.\DISPLAY2
Bounds: {X=-1200,Y=0,Width=1200,Height=1920}
Type: System.Windows.Forms.Screen
Working Area: {X=-1200,Y=0,Width=1200,Height=1920}
Primary Screen: False


text: Q: How to get size of file just being created? Problem is that library method _wstat64 returns file size 0 (in st_size member of structure _stat64). After right clicking file in Windows Explorer (or Total Commander) and selecting Properties the size of file is updated also in my program.


text:
Q: Intuition of LLN's condition Let $X_1,X_2,...$ be independent r.v. with finite expectation
If there is a constant $p\in[1,2]$ s.t.
$$\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$$
then $$\frac{1}{n}\sum_{i=1}^n(X_i-EX_i)\rightarrow_p0$$
If there is a constant $p\in[1,2]$ s.t.
$$\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$$
then $$\frac{1}{n}\sum_{i=1}^n(X_i-EX_i)\rightarrow_{a.s.}0$$
My question is that:
1.Does it means that $\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$ implies $\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$? If so, how to prove it?
I think if $p=1$, then we can directly use Kronecker's lemma to prove it, but what if $p\in(1,2]$?

*How to understand these conditions? For example,

If $X_1,X_2,...$ be iid r.v.
then $$\lim_{n\rightarrow\infty}nP(|X_1|>n)=0$$ iff
$$\bar{X}-E(X_1I_{|X_1|\le n})\rightarrow_p 0$$,
so what's the relationship between $\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$ and $\lim_{n\rightarrow\infty}nP(|X_1|>n)=0$? Say if we consider "iid" in the independent WLLN, and let $p=1$
$$\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$$ becomes
$$\lim_{n\rightarrow\infty}\frac{1}{n}\sum_{i=1}^nE|X_i|=0$$
It doesn't make sense, does it means that "iid WLLN" is not the special case of "independent WLLN" ?
3 Similarly, If $X_1,X_2,...$ be iid r.v.
then $$E(|X_1|)<\infty$$ iff
$$\bar{X}-E(X_1)\rightarrow_{a.s.} 0$$
what's the relationship between $E(|X_1|)<\infty$ and $\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$? For example, if we consider "iid" in the independent SLLN and let $p=1$
$$\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$$ implies $$\sum_{i=1}^\infty\frac{E|X_1|}{i}<\infty$$
compare with $$E|X_1|<\infty$$, let $E|X_1|=c<\infty$
$$\sum_{i=1}^\infty\frac{E|X_1|}{i}=\sum_{i=1}^\infty\frac{c}{i}=c\sum_{i=1}^\infty\frac{1}{i}$$ divergence. So $E|X_1|<\infty$ with iid condition does not imply $$\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$$
on the other hand, if we have $$\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$$
can we prove $E|X_1|<\infty$ with iid condition?

A: *

*It cannot be deduced directly that $\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$ implies $\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$ because we do not know a priori whether the results are optimal. For example, the condition $\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$ could be replaced by something much more restrictive. In order words, we can have $P_1\Rightarrow Q_1$, $P_2\Rightarrow Q_2$ and $Q_1\Rightarrow Q_2$ but it does not mean that $P_1\Rightarrow Q_2$.
However, that $\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$ implies $\lim_{n\rightarrow\infty}\frac{1}{n^p}\sum_{i=1}^nE|X_i|^p=0$ follows but some calculus: let $c_i=E|X_i|^p$ and $s_k=\sum_{i=1}^kc_i$. Using Abel's transformation, $\sum_{i=1}^\infty\frac{E|X_i|^p}{i^p}<\infty$ is equivalent to $\sum_k s_k\left(\frac 1{k^p}-\frac 1{(k+1)^p}\right)<\infty$ and we get $\sum_k s_k\frac 1{k^{p+1}}<\infty$. Summing on intervals of the form $[2^n+1,2^{n+1})$ gives $\sum_n s_{2^n}2^{-np}<\infty$ which gives $s_{2^n}2^{-np}\to 0.

*Indeed, if $p=1$ and the $X_i$ have the same distribution, then both conditions fails. They are actually more appropriated in the case $p>1$, where, as you noticed, the conditions take place provided that $\mathbb E\lvert X_1\rvert^p<\infty$. These conditions are also useful in the non-identically distributed case, when the moment of order $p$ of $X_i$ is even allowed to increase with $i$, but of course not too fast.


text:
Q: Forming a connected Island of Xs Given a 2D array of Os and Xs, find the minimum number of Os that need to be flipped into Xs to connect all the Xs connected. An X is connected to another Xs if they are adjacent to each other(Not diagonally).
Sample input:
A =
  [ OOOXOOO

    OOXXOXO

    OXOOOXO ]

Output :
2
The idea I had in my mind was choosing an X and then keep on travelling to the nearest X while flipping the Os in between till we connect all the Xs. Is anything wrong with this or can you suggest a better approach?
Also, is this similar to finding the Minimum Spanning tree using Kruskal's Aglo or Prim's Algo?


text:
Q: WPF TreeView: how to add a trigger for all tree elements The right side of the window contains data, when you drag it to the left, the color of these items turns gray. I have a button that needs to hide gray elements.
Image: The data is highlighted in gray, the hide button is disabled.
Image: The data is highlighted in gray, the hide button is enable, the item is hidden.
But, if I drag the inner treeviewitem, nothing happens
Image: Inner element is dragged, the hide button is disable
Image: Inner element is dragged, the hide button is enable
How can you change the code so that triggers apply to all elements?
TreeView XAML:
 <TreeView
                Grid.Column="2"
                x:Name="RevitCategories">
                <TreeView.ItemContainerStyle>
                    <Style
                        TargetType="TreeViewItem">
                        <EventSetter
                            Event="DragOver"
                            Handler="RevitCategories_OnDragOver" />
                        <EventSetter
                            Event="MouseMove"
                            Handler="RevitCategories_OnMouseMove" />
                        <Style.Triggers>
                            <MultiDataTrigger>
                                <MultiDataTrigger.Conditions>
                                    <Condition
                                        Binding="{Binding Path=ShowUsages, UpdateSourceTrigger=PropertyChanged}"
                                        Value="False" />
                                    <Condition
                                        Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Foreground,
                                        Converter={vm:ColorToHiddenConverter}, UpdateSourceTrigger=PropertyChanged}"
                                        Value="False" />
                                </MultiDataTrigger.Conditions>
                                <Setter
                                    Property="Visibility"
                                    Value="Collapsed" />
                            </MultiDataTrigger>
                        </Style.Triggers>
                    </Style>
                </TreeView.ItemContainerStyle>
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate>
                        <TextBlock
                            FontSize="{DynamicResource MediumFontSize}"
                            FontFamily="{DynamicResource FontFamily}" />
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>

Converter:
public class ColorToHiddenConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var brush = (Brush) value;
        var colorSample = Colors.Gray;
        return brush.Equal(colorSample);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        CultureInfo culture) => null;

    public override object ProvideValue(IServiceProvider serviceProvider) => this;
}

A: Solved: I changed </TreeView.ItemContainerStyle> to <TreeView.Resources> and it worked


text:
Q: MediaEngine is unable to provide next frame with invalidates in the "background" I have an application with two windows -- one is regular WinForms with live plot (which should be constantly updated) and the second window is DirectX/SharpDX with movie playing (MediaEngine).
In order to have live plot I call invalidate every 0.1 second and on paint even I redraw the plot. The problem is that after few seconds MediaEngine reports false for all OnVideoStreamTick calls meaning it does not have next frame to display.
If I comment out the drawing, ME is stuck as before but when I comment out invalidate calls (which as the effect causes redrawing) ME play backs movie with no problem.
What should I do to have live window and movie playing at the same time?
Update, on the first lost frame I check the error and it says DecodeError. Also when I increase the plot update interval from 0.1s to 1s. the playback is OK for longer. Of course I am looking for something more solid than magically increasing the interval.


text:
Q: I can't connect VM on GCP as root I can't connect VM on GCP as root on the browser SSH.
Is there anyone who had the same problem?
the following message is displayed.
You can drastically improve your key transfer times by migration to OS login.
It might be caused to set a password...

A: By default, you will login as the GCP user. Now, to log in as root please run the following command once SSH browser works.

sudo -s

If you cannot login with browser SSH, then I suspect a permission issue with that particular user.
The above is the recommended way of doing things, however if logging in as root is absolutely needed, please follow the steps below:

*

*As root, edit the sshd_config file in /etc/ssh/sshd_config:

nano /etc/ssh/sshd_config

*Make sure PermitRootLogin is set to "yes" and save the /etc/ssh/sshd_config file.

*Restart the SSH server:

service sshd restart

*Change username to root by clicking on the wheel on the top right corner and selecting "Change Linux Username"


text:
Q: How to generate numbers upto 18 digits, sum of whose reciprocals is a whole number I am looking for a way to generate a series of numbers whose sum of reciprocals is a whole number?
For eg - 11  (1/1 + 1/1 = 2 is a whole number), 122 (1/1+1/2+1/2 is a whole number), 236 (1/2 + 1/3 + 1/6 is a whole number)
and likewise.
Also I want to avoid repeat of same combination or permutation of digits. For example, if 122 is printed, I don't want to print 212 and 221.
I want to know how to approach this problem

A: Some thoughts to get you started:

*

*Your number can't contain zeros.

*You can always add ones to a valid number and it will still be valid.

*You don't need to generate numbers. Generate lists of digits instead. If you keep the list in ascending order, you will automatically solve to problem of how to eliminate permutations.

*Each of the true fractions 1/2 to 1/9 can be represented as an expanded  fraction with the common denominator 2520.

So the following approach might work:

*

*Start with an empty array and the sum 0.

*Now call your generating function recursively. In each recursion, check wether the sum is divisible by 2520 without remainder. If so, print that number, and also print all numbers padded with ones at the front until you have 18 digits. So for 236 print 236, 1236, 11236 and so on until 111 111 111 111 111 236.

*If your array has length 18, don't recurse further. Otherwise, call your function after adding each of the digits 2 to 9 to your list, but don't use digits that are smaller than the last digit in the list to keep the list sorted.

*Don't recalculate the sum, but instead keep a running sum: When you recurse, add the corresponding numerator to the sum: 1260 for 2, 840 for 3, 630 for 4 and so on.

This bottom-up approach is a lot faster than examining all possible numbers. The following program will print all 14,137 valid numbers (unordered, i.e. in order of generation) in the fraction of a second:
#include <stdlib.h>
#include <stdio.h>

#define NDIGIT 18

void rec(int set[], int n, int sum)
{
    static int num[10] = {
        0, 2520, 1260, 840, 630, 504, 420, 360, 315, 280
    };

    if (sum % 2520 == 0) {
        for (int j = 0; j < NDIGIT - n + 1; j++) {
            for (int i = 0; i < j; i++) putchar('1');
            for (int i = 0; i < n; i++) putchar(set[i] + '0');
            putchar('\n');
        }
    }

    if (n < NDIGIT) {
        int i0 = n ? set[n - 1] : 2;

        for (int i = i0; i < 10; i++) {
            set[n] = i;
            rec(set, n + 1, sum + num[i]);
        }
    }
}

int main()
{
    int set[NDIGIT];

    rec(set, 0, 0);

    return 0;
}

If you need sorted output, convert the set to a long integer, perhaps uint64_t from <stdint.h> and store it in an array instead of printing them right away. Then sort the array and print the numbers.

A: First, you have nine possible digits (because 0 does not lead to a valid fraction), whose reciprocals have a common divisor 2×2×2×3×3×5×7 = 2520:
1 -> 1/1 = 2520/2520
2 -> 1/2 = 1260/2520
3 -> 1/3 =  840/2520
4 -> 1/4 =  630/2520
5 -> 1/5 =  504/2520
6 -> 1/6 =  420/2520
7 -> 1/7 =  360/2520
8 -> 1/8 =  315/2520
9 -> 1/9 =  280/2520

Therefore, we can use x/2520 to describe the exact value of such sum. The sum is an integer, if and only if x is a multiple of 2520. We can use the modulo operator for this: if x % 2520 == 0, the fraction x/2520 represents an integer.
In practice, we don't need to represent the value of the fraction at all, we only need to remember the numerator modulo 2520, x % 2520!
Let's look at the algorithm that checks whether the sum of the reciprocals of each digits is a whole number, in pseudocode:
Constant Array  per_digit_2520[10] = {
    0,    /* 0 -> 0/1 =    0/2520 */
    2520, /* 1 -> 1/1 = 2520/2520 */
    1260, /* 2 -> 1/2 = 1260/2520 */
    840,  /* 3 -> 1/3 =  840/2520 */
    630,  /* 4 -> 1/4 =  630/2520 */
    504,  /* 5 -> 1/5 =  504/2520 */
    420,  /* 6 -> 1/6 =  420/2520 */
    360,  /* 7 -> 1/7 =  360/2520 */
    315,  /* 8 -> 1/8 =  315/2520 */
    280,  /* 9 -> 1/9 =  280/2520 */
}

Function corresponds_to_whole_fraction(digits):
    Let remain = 0

    For each digit d in digits:
        remain = (remain + per_digit_2520[d]) % 2520
    End For

    If remain == 0:
        Return "Yes, the digits represent a whole fraction"
    Else:
        Return "No, the digits do not represent a whole fraction"
    Fi

End Function

In the loop above, you can also check if digit d is zero, and if so, reject the set of digits.
By writing the above, we can immediately notice that because the order of the fractions in the sum does not change the sum, all combinations of a number yield the exact same sum of reciprocal digit fractions.
In other words, if 236 yields a whole sum (it does, because 1/2 + 1/3 + 1/6 = (1260 + 840 + 420)/2520 = 2520/2520 = 1), then also 326, 362, 623, and 632 yield the same sum. Each number is an unique permutation of the set of digits. To explore permutations further, we need to look at combinatorics.
Fortunately, the corresponds_to_whole_fraction() is simple enough that it is reasonable to generate the desired numbers by generating ordinary numbers, either sequentially or with a random number generator (for numbers with up to 18 digits, I recommend xorshift64star(), since 264 > 1018).
Let's consider the sequential case:
#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>

const unsigned int num_2520[10] = {
    0, 2520, 1260, 840, 630, 504, 420, 360, 315, 280
};

int is_acceptable(uint64_t value)
{
    unsigned int  remain = 0;

    if (!value)
        return 0;

    while (value > 0) {
       const unsigned int  digit = value % 10;

       if (!digit)
           return 0;

       value /= 10;
       remain = (remain + num_2520[digit]) % 2520;
    }

    return (remain == 0);
}

uint64_t next_number(uint64_t previous)
{
    while (++previous)
        if (is_acceptable(previous))
            return previous;

    return 0;
}

int main(void)
{
    uint64_t  value = 0;

    while (1) {
        value = next_number(value);
        if (!value)
            break;

        printf("%" PRIu64 "\n", value);
    }

    /* Never reached */
    return EXIT_SUCCESS;
}

The above program prints all numbers between 1 and 264-1 = 18446744073709551615, inclusive, whose sum of reciprocal digits is a whole number. There are too many of them for anyone to wait long enough for all of them to be printed.
The density is about 0.05% - 0.1% around ten digits, i.e. on average, every one-thousandth (or one two-thousandth) number is acceptable (although there is a lot of variation). So, if you start from a random number, you might wish to check the consecutive numbers starting at that random number, rather than try all new random numbers each time (because random number generators are not very fast in the first place).
If you wanted to limit the above to 18-digit numbers, start with uint64_t value = UINT64_C(99999999999999999); (seventeen nines), and replace the if (!value) with if (value > UINT64_C(999999999999999999)) (eighteen nines).


text:
Q: Plesk API - Response error 1019 You specified incorrect username I  create FTP account  with the Plesk API. Everything works fine until I add the $name variable in  <name>.$name.</name> its showed an error:

Response error 1019 You specified incorrect username.

Can anyone suggest me how to pass variable?
    <?php
require_once('PleskApiClient.php');
 $host = "74.208.10.205";//getenv('REMOTE_HOST');
 $login = getenv('REMOTE_LOGIN') ?: 'root';
 $password = "********";// getenv('REMOTE_PASSWORD');
$client = new PleskApiClient($host);
 $client->setCredentials($login, $password);
$name="finalftp3";
$request = <<<EOF
<packet version="1.6.7.0">
  <ftp-user>
<add>
<name>.$name.</name>
<password>dkfje44Fwe345n</password>
<home>/httpdocs/eie4retailers.com/</home>
<create-non-existent>true</create-non-existent>
<quota>10</quota>
<permissions>
<read>true</read>
<write>true</write>
</permissions>
<webspace-id>1</webspace-id>
</add>
</ftp-user>
</packet>
EOF;
$response = $client->request($request);
echo "Response".$response;`echo "Response".$response;

A: I guess <name>.$name.</name> should be <name>$name</name>. You don't need to concat the variable within a heredoc string.


text:
Q: Controlling the output of a method in the same class I'm testing a method that calls another method within the same class.
Depending on whether this internal method call returns a result I do different things. In this case it's a Cache class and I'm testing my GetOrStore method. I want to test two paths, when Get returns null and when Get returns something.
What's the right approach to controlling the output of Get when called from GetOrStore? It feels like Get should be executed on a mocked instance however I'm unsure how to do that given two methods in the same class.
Update
The only thing I can think to do at this time is to make sure the cache key is removed before running the test:
  HttpRuntime.Cache.Remove("foo"); // Make sure foo isn't in the cache.

  var output = _cache.GetOrStore("foo", () => "Foo", 100);
  Assert.AreEqual(output, "Foo");

This just feels wrong though. I don't actually want the HttpRuntime cache touched during my test.

A: The answer to this is in Moqs CallBase property on mocked instances.
Setting CallBase to true ensures that any methods not explicity setup are called on the real instance of the mocked object.
This then means we can setup the Get method and still have GetOrStore executed correctly:
  var _mockCache = new Mock<Cache>();
  _mockCache.Setup(m => m.Get(It.IsAny<string>())).Returns(null);
  _mockCache.CallBase = true;

  var output = _mockCache.Object.GetOrStore("foo", () => "Foo", 100);
  Assert.AreEqual("Foo", output);

A: The code you posted implies that in the cache class you are testing, the Get method calls static methods on HttpRuntime.Cache. Is this the case?
Mutable static state like this is generally best avoided. You could make a proxy class which wraps HttpRuntime.Cache and have your Cache depend on an instance of that. Then in your tests, you can substitute the proxy with a mocked version which you can easily control.


text:
Q: Cannot connect to gcloud instance via SSH I am getting error while trying to do ssh gcloud instance.
I have removed old ssh key and regenerated new ssh key and tried to connect but still the problem remains as it is.
Please share your suggestions.

A: Check whether the port 22 is open in the firewall for that specific instance. You can follow this document to manage your firewall rules. You can try connecting via serial console instead. The issue you are facing could arise due to many different reasons. It is worth trying different troubleshooting steps for SSH connectivity.
If you created new SSH key properly then check if you added the key to your instance or project-wide metadata. This article is a good read.


text:
Q: Multilevel sorting for array of objects - javascript I'm trying to do multilevel ascending order sorting for below array of objects.

var array = [{id: 1, color: 'red', objname: 'tomato'},
{id: 1, color: 'orange', objname: 'pumpkin'},
{id: 2, color: 'red', objname: 'tomato' },
{id: 1, color: 'red', objname: 'cherry' },
{id: 1, color: 'orange', objname: 'sunset'}];

Expected result Array:

var resultArray =
[{id: 1, color: 'orange', objname: 'pumpkin'},
{id: 1, color: 'orange', objname: 'sunset'},
{id: 1, color: 'red', objname: 'cherry'},
{id: 1, color: 'red', objname: 'tomato'},
{id: 2, color: 'red', objname: 'tomato'}];

From above array of objects, first i want to sort 'id' level and color and finally objname. First level based on id I can able to do but with in that multilevel i dont have idea to sort.
And this is how I'm sorting one level,

sortById(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

With this i can ascending array of objects based on 'id'.
Can any one help me, how can we perform multilevel sorting.

A: You can sort it with multiple OR conditions:

var array = [{id: 1, color: 'red', objname: 'tomato'},{id: 1, color: 'orange', objname: 'pumpkin'},{id: 2, color: 'red', objname: 'tomato' },{id: 1, color: 'red', objname: 'cherry' },{id: 1, color: 'orange', objname: 'sunset'}];

var resultArray = array.sort((a,b)=>{
   return a.id-b.id || a.color.localeCompare(b.color) || a.objname.localeCompare(b.objname)
});

console.log(resultArray);

A: You could take a dynamic approach by collecting the wanted keys and use Array#some with a short circuit for truthy values.

var array = [{ id: 1, color: 'red', objname: 'tomato' }, { id: 1, color: 'orange', objname: 'pumpkin' }, { id: 2, color: 'red', objname: 'tomato' }, { id: 1, color: 'red', objname: 'cherry' }, { id: 1, color: 'orange', objname: 'sunset' }],
    keys = ['id', 'color', 'objname'];

array.sort((a, b) => {
    var result;
    keys.some(k => result = (a[k] > b[k]) - (a[k] < b[k]));
    return result;
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can try something like this.
var array = [{id: 1, color: 'red', objname: 'tomato'},
{id: 1, color: 'orange', objname: 'pumpkin'},
{id: 2, color: 'red', objname: 'tomato' },
{id: 1, color: 'red', objname: 'cherry' },
{id: 1, color: 'orange', objname: 'sunset'}];

array.sort((a, b) => {
      if (a.city === b.city) {
        if(a.color === b.color) {
          return (a.objname).localeCompare(b.objname)
        }
        return (a.color).localeCompare(b.color)
      }
      return a.id - b.id
  }
);

console.log(array);


text:
Q: haml vs haml-rails In order to have rails generators create the views with haml i'm coming across two answers and both seem to work. which is better?
Option1:
declare 'haml' in the gemfile and do
  config.generators do |g|
    g.template_engine :haml
  end

Option2:
just declare 'haml-rails' in the gemfile

A: According to the description on the haml-rails github. It is just an integration of Haml for rails. So if you like easy go with the haml-rails gem
"Haml-rails provides Haml generators for Rails 3. It also enables Haml as the templating engine for you, so you don't have to screw around in your own application.rb when your Gemfile already clearly indicated what templating engine you have installed. Hurrah."

A: Option 2 because Option 1 does not work.  Declaring "haml" in your Gemfile does not give you the ability to set the default template_engine to :haml in your application.rb.
The haml-rails gem includes the generators, so that is the recommended option.


text:
Q: Pressure activated switch for a light up LED straw? Similar to how a vape pen activates with air pressure drop when sucking? I'm looking for a component that I can integrate into an LED straw so that when the user starts sucking on it the light turns on. What should I be looking at? I disassembled a Juul pod and see that there are two leads that connect when you suck on them, although if that is inside of the straw while liquid is moving over it might not be ideal.
Any ideas?

A: My understanding is you're designing a novelty LED straw which lights up when a drink is sucked through it
Back-of-envelope parameters

*

*The length of the straw is 100 mm

*Thus there is a pressure drop of approx 1 kPa (ref)

*Sucking time is about 5 seconds

*Desired response time < 0.1 sec

*The drink is likely to be about 3 °C (Recommended by drinks company)

*Drinks are likely to vary and might be transparent, orange, brown, white and might have particulates or be filtered (water, milk, juice, iced coffee, sodas, cocktails)

*Drinks may be carbonated, acidic, alkaline, salty, sweet

*Drinks might be viscous (milkshake) or not (water)

*Device must be cleanable
I'll assume you have something like this and can put together T-junctions to measure at.

Method 1: Atmospheric Pressure Sensor
Use a device such as MPL3115A2 which is designed for use as an altimeter in drones, with accuracy of approx 1 m in altitude.
Our 1 Kpa drop is equivalent to about 100 metres or altitude, so the range is about right.(ref)

*

*Pro: Small, easy to interface

*Con: Might need some kind of membrane between drink and sensor, physical interface a little tricky

Method 2: General Pressure Sensore
Consider a device such as Honeywell Micropressure Sensor which is for measuring pressures in liquids!

*

*Pro: "compatible with liquids", small, easy physical interface

*Con: Cleaning?

Method 3: Optomechanical
A hole in the straw can be covered with a flexible membrane.  This moves when the internal pressure changes, which is then detected by any photosensing method.  Any flexible tube will move under pressure change, or a pipette or dropper head.

*

*Pro: potentially simple.  Flexible rubber tube might be replacable

Method 4: Optical
Many drinks absorb ultraviolet light.  So a sinple UV LED and photodiode pair might well detect drinks.

*

*Pro: No contact with the drink

*Con: Needs testing

Method 5: Thermal
If the drinks are cold, a thermosensor will detect it.  There are endless, from analogue to digital, but one with direct threshold outputs is the AS6212

*

*Pro: nice and simple, no contact with drink

*Con: response time slow in comparison, perhaps 1 sec

A: I would suggest having two metal plates on both sides. Water has a much higher dielectric constant than air. By using 1 Darlington pair you could most certainly detect this change in capacitance and use it to power an LED.

A: On a non- conducting tube print conducting pads along its length on one side. On the opposite print a solid conducting pad along the entire length. The linear array of capacitors will allow detection the height of water in the straw. LEDs can then be turned on in a sequence driven by the height.

A: The best solution in my opinion is one which does not have moving parts or sensors that depend on what the user does with the straw. Even if they drink room temperature vodka with it, it should work correctly. This rules out temperature, color, pressure, and many other methods. Two thoughts:
Fully encased microphone (Diffifculty: parsing signal)
If the microphone is fully encased in the straw material alongside the electronics, it should be fully washable, and would only really "hear" or focus on conducted sound waves. I imagine that there would be a sound signature for the user's lips touching the tip of the straw, and then sucking would produce a slight vibratio/sound which may be picked up. To try this method, tape the headphones of any earbuds to a straw, connect to your computer and using software like Audacity record and try to analyze any interesting trends in sound. I dont think this problem is fundimentally different to the clap on/off switches, you just need to detect some predefined pattern.
Capacitive (Difficulty: liquid viscocity)
You can get really creative with a capacitive solution. Lets look at two things you can do. 1- Capacitive slider, as seen below (I think geometry one works better for this usecase)

Source: http://ww1.microchip.com/downloads/en/AppNotes/Atmel-42479-Capacitive-Touch-Long-Slider-Design-with-PTC_AT11805_ApplicationNote.pdf

Source: https://www.matrixtsl.com/webshop/capacitive-touch-slider-sensor-module.html
This slider type sensor allows for two things: When the straw is inserted into the drink, some animation can be played. As soon as the liquid level moves up, the capacitance changes (many microcontrollers have ready libraries for this kind of touch sensor which make this easier to implement). Problem: what if the user adds liquid while straw is in the drink? it may be confused with them sucking. If that's something you care about, think about:
2- A capacitive ring on the top of the straw (or both ends if straw is reversible). This allows there to be an "interlock", which only plays the sucking animation if user's lips touch the straw and liquid level rises. Alternatively, a "lossy" approximation of the user sucking is just them placing their lip onto the staw, so you wouldnt need the sliding sensor.
The problem with this method is that the liquid may just stay on the straw's edges after the first use, which may happen for example if they drink a thick milkshake. Even if the resulting layer is thin, I think it will be sufficient for the capacitance sensor to staturate.

What I would probably do is use the microphone alongside with a capacitive sensor for the lips at either end as an interlock. The user will need both capacitive sensors activated before the straw turns on (the bottom one by the drink, the top one by their lips. This allows protection from the straw being needlessly "woken up" by a spoon getting near one sensor while in storage). Even if something like a milkshake keeps the capacitive sensor engaged, the mic will have the final say in turning on the LEDs, and the power expended by keeping the mic for a little while isnt horrible. The capacitive sensor will allow you to keep the straw's MCU in a low power sleep mode, and when activated you can run the mic to process whether the user is sucking.

A: To keep it food-safe a capacitive or inductive sensor might be a good idea.
There are industrial-type I2C connected sensors available if this is a one-off otherwise most modern microcontrollers (esp32 f.i.) support touch input which might be utilizable for this matter.
Also copper plates on both sides could be a method as the capacity will change when the "dielectric" changes from air to liquid.
Temperature change is also an option: Use a sensor that heats up over ambient temp which is thermic coupled to the straw.

A: A barometric pressure sensor could do this. Baro sensors measure absolute pressure, so you could measure the vacuum and  thus estimate the height of the liquid in the straw from it if you wanted to do a fancy animation of some sort.
Related: Low cost barometric pressure sensor
Difficulty: keeping the sensor port clean.


text:
Q: Plural of retail I would like to know what is the plural of retail. Is it ok to just write it as "retails"? It doesn't feel right.
If there isn't a word for the plural of "retail", kindly explain why.

A: A word for a singular retail store is 'retailer', and plural is 'retailers'.


text:
Q: Rails : get json value in hidden_field form (giphy api) I am using the Giphy search API to let my users search for gifs and let them add gif.
Here is simplified part of my code to make it works :
_Form.html.erb
<%= form_for Task.new do |f| %>
<%= f.hidden_field :gif, id: "GifUrl", value: "" %>
<input type="text" name="search" placeholder="Search gif">

<% end %>

Part of my script where I fetch the details of the gif from giphy
  this.displayResult = function(url) {
    const target = document.getElementById('score');
    const img = document.createElement('img');
    img.src = url;

    target.appendChild(img);
  }

What I wanted to do is to scrape the html src value of the gif link returned and pass it in my form through an hidden_field, but it returns : [object Object] as a value, instead of the proper gif link.
 => #<Task id: 285, description: "", user_id: 37, gif: "[object Object]">

Should I use an html parser like nokogiri or am I doing something wrong ?
How can achieve this ?
Thanks !

A: It looks like when using the giphy-api you get a json response. You should look into just using the URL of the image size you would like to store. IE
$("#GifUrl").val(
  giphy_response['data'][SEARCH_RESULT_TO_USE][images][IMAGE_SIZE_TO_USE]['url']
)


text:
Q: Missing partial error that I cannot find in Rails Tutorial I'm currently going through the Rails Tutorial book and Im on the last chapter adding simple views to the Sample App. I'm usually pretty good at finding my errors but in this case I keep getting the following error when trying to render the view of a users followers and people the user follows:
  ActionView::MissingTemplate
(Missing partial users/_user with {:locale=>[:en], :formats=>[:html, :xml], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.

When I look in the terminal log it elaborates the error message as such:
  app/views/users/show_follow.html.erb:25:in `_app_views_users_show_follow_html_erb___427441195944621571_70028589061100'
  app/controllers/users_controller.rb:75:in `followers'

Line 75 corresponds to render 'show_follow' in the followers function below:
  def followers
    @title = "Followers"
    @user = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end

And line 25 to render @users in show_follow.html.erb:
<% provide(:title, @title) %>

      <%= gravatar_for @user %>

<%= @user.name %>

      <%= link_to "view my profile", @user %>
      Microposts:<%= @user.microposts.count %>

      <%= render 'shared/stats' %>
      <% if @users.any? %>

        <% @users.each do |user| %>
          <%= link_to gravatar_for(user, size: 30), user %>
        <% end %>

      <% end %>

<%= @title %>

    <% if @users.any? %>

        <%= render @users %>

      <%= will_paginate %>
    <% end %>

I have spent hours looking for the error, to no avail. Your help would be appreciated!

A: The error is here:
<%= render @users %>

It's trying to find a partial with the same name. To resolve this, you should either create the partial users/_user.erb.html so that it can be loaded. Or you should specifically name the partial to be rendered:
<%= render 'user_index', user_list: @users %>  # As an example

A: I just ran into this same problem as well. I created a new partial in the views/users folder called "_user.html.erb" with this code:

  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
    | <%= link_to 'delete', user, method: :delete,
                                  data: { confirm: 'Are you sure?' } %>
  <% end %>

That worked for me.

A: I had the same problem one time. However, upon a critical look, I realized while naming my file formats I made a mistake and that caused the problem. Check your formats and you are done.


text:
Q: IE11 @media with width For IE11 I'm using the following @media query:
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active){}

Which works fine.
But now I want to also have 3 different ones for mobile, tablet and desktop.  I've tried the following:
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active), only screen and (min-width : 1200px) {
    max-width: 83%;
}

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active), only screen and (min-width : 768px) and (max-width: 1199px) {
    max-width: 90%;
}

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active), only screen and (max-width : 767px) {
    max-width: 100%;
}

But its always landing on the last one with a max-width of 100%.  I've tried putting the width before the -ms-high-contrast but it seems to have the same effect.  Any tips on fixing this?

A: Think you're looking for something more like;
// Extra small devices (portrait phones, less than 576px)
@media screen and (-ms-high-contrast: active),
                  (-ms-high-contrast: none)
              and (max-width: 575.98px) { ... }

// Small devices (landscape phones, 576px and up)
@media screen and (-ms-high-contrast: active),
                  (-ms-high-contrast: none)
              and (min-width: 576px)
              and (max-width: 767.98px) { ... }

// Medium devices (tablets, 768px and up)
@media screen and (-ms-high-contrast: active),
                  (-ms-high-contrast: none)
              and (min-width: 768px)
              and (max-width: 991.98px) { ... }

// Large devices (desktops, 992px and up)
@media screen and (-ms-high-contrast: active),
                  (-ms-high-contrast: none)
              and (min-width: 992px)
              and (max-width: 1199.98px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media screen and (-ms-high-contrast: active),
                  (-ms-high-contrast: none)
              and (min-width: 1200px) { ... }


text:
Q: printing in python terminal is not what I get in text file print(text)
with open("Text file","w") as fin:
     fin.write(text)`

The printing is aligned in fixed width. The written file is not arranged in the same width but in a haphazard way. I need fixed width to convert into excel.
Cant share images since it is not right.
Printing text (on terminal) I get:
Locus     67
pocopine  78

On the file I get:
Lotus  67
pocupine  78

A: You could try using formatting
Example:
print("%-50s %4.f" % ("Test, Exam", 4))

print("%-"Number of spaces"s %"Decimal points if needed".f" % ("Test, Exam", 4))

if you export it to excel and you want the text in different cells you should specify this in question


text:
Q: Failed to install gems via Bundler. remote: ! remote: ! Push rejected, failed to compile Ruby app. remote: remote: ! Push failed I tried all the solution on stack overflow but nothing worked for me.
Here is my problem
Heroku logs -t
 ID 3d636cae-b623-44f8-8aee-7eb12dfcccc0
    -----> Ruby app detected
    -----> Compiling Ruby/Rails
    -----> Using Ruby version: ruby-2.0.0
    -----> Installing dependencies using bundler 1.15.2
           Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
           Fetching gem metadata from https://rubygems.org/........
           Fetching version metadata from https://rubygems.org/..
           Fetching dependency metadata from https://rubygems.org/.
           devise-4.6.1 requires ruby version >= 2.1.0, which is incompatible with the
           current version, ruby 2.0.0p648
           Bundler Output: Fetching gem metadata from https://rubygems.org/........
           Fetching version metadata from https://rubygems.org/..
           Fetching dependency metadata from https://rubygems.org/.
           devise-4.6.1 requires ruby version >= 2.1.0, which is incompatible with the
           current version, ruby 2.0.0p648
     !
     !     Failed to install gems via Bundler.
     !
     !     Push rejected, failed to compile Ruby app.
     !     Push failed

A: devise-4.6.1 requires ruby version >= 2.1.0, which is incompatible with the
           current version, ruby 2.0.0p648

That is pretty clear.
You should probably update your ruby environment on local machine to at least 2.1.0 and update your gemfile also.
or
https://rubygems.org/gems/devise/versions/3.5.10
downgrade to gem 'devise', '~> 3.5', '>= 3.5.10' as it's the last devise using ruby under 2.0.
I would opt for the first option.


text:
Q: Get the current working directory of process with a pid programmatically on OS X Is there a way to get the current working directory of a process using it's PID programmatically on OS X?
Cocoa, Carbon, or AppleScript are all acceptable.
It is not acceptable to send "pwd" to the current terminal window/tab (Do not want to affect the workspace).
The linux command "pwdx" also is also unacceptable (just in case you read over the "Cocoa" part)

A: On 10.5 and later:
lsof -a -p $PID -d cwd -Fn
(Prefix with sudo if the process is owned by root.)

A: The following AppleScript is a partial solution for your problem. Given the UNIX pid in the variable thePID it first gets the name of the process. It then sends the do shell script command to the application process which will result in a child shell process being spawned. The child process inherits the current directory which can then be determined by running the pwd command.
tell application "System Events"
    set theName to name of first process whose unix id is thePID
end tell

tell application theName
    do shell script "/bin/pwd"
end tell

The script does not work for processes that do not link to the AppleEvent framework (e.g., pure POSIX processes).


text:
Q: rocketMQTemplate.asyncSend throws ConcurrentModificationException at MessageDecoder.messageProperties2String I am using rocketmq-spring to send message which version is 2.1.0, sometimes i got ConcurrentModificationException at org.apache.rocketmq.common.message.MessageDecoder.messageProperties2String(MessageDecoder.java:414),the following is a detailed log. Thanks!

#[xx, 10.xx.52] INFO  2022-05-07 15:31:11.043 [XNIO-1 task-74, 29de7f06241a3313, 29de7f06241a3313] com.xx.common.IpProducerService.asyncSendMessage:45 - contentMap{refNo=xx, system=xx, ip=null, platformId=xx, userId=xxx}
#[fp, 10.xx.52] INFO  2022-05-07 15:31:11.043 [XNIO-1 task-74, 29de7f06241a3313, 29de7f06241a3313] com.xx.rocketmq.producer.RocketMqProducer.asyncInfo:19 - -=-=-= [Async Sending Message] -=-=-=
 Topic                = TOPIC_xx_xx
 Tag                   =
 MessageId        = null
 DelayLevel        = 0
 Content            = {"refNo":"xx","system":"xx","platformId":"xx","userId":"xx"}

#[fp, 10.xx.52] ERROR 2022-05-07 15:31:11.044 [AsyncSenderExecutor_3, , ] com.xx.rocketmq.producer.ProduceCallBack.onException:32 - asyncSendMessage caused exception.
java.util.ConcurrentModificationException: null
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
    at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
    at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
    at org.apache.rocketmq.common.message.MessageDecoder.messageProperties2String(MessageDecoder.java:414)
    at org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl.sendKernelImpl(DefaultMQProducerImpl.java:790)
    at org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl.sendDefaultImpl(DefaultMQProducerImpl.java:584)
    at org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl.access$300(DefaultMQProducerImpl.java:97)
    at org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl$4.run(DefaultMQProducerImpl.java:511)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
#[xx, 10.xx.52] INFO  2022-05-07 15:31:11.044 [AsyncSenderExecutor_3, , ] com.xx.common.IpProducerService.handleResult:49 - async produce status is F

A: use different rocketMQTemplates instance to send same message.
asyncSend is doing on ThreadPool in rocketMQTemplates, there are lots of threads there, so you can't send same message(same message use the same propertiy HashMap, not thread-safe) using different rocketMQTemplates.


text:
Q: Team Foundation Serivce (TFS) and running visual studio instance I have created a repo using TFS (cloud) on www.visualstudio.com
I created my repo as on something as myproject.visualstudio.com and when trying to run or click on following link:
Open new instance of Visual Studio it throws an error as

Cannot open file vstfs:///Framework/TeamProject/..... Verify that the
  file still exists and then try again

I searched here on SOV and also on MSDN and found a thread on MSDN forum but it was about some services pack and updates.
Has anybody ever used this service?
Thanks.

A: there is a solution I just found which walks me through IDE.

*

*Run VS2012 Under "Start" in VS 2012 click on "Connect to Team Foundation Server ..."

*It will popup a dialog so then in bottom of dialog/form there is link as "Sign In", click on it

*Enter your user-name and password Now, you are connected to the server and can view
all your Repositories

P.S. don't forget to add your server URL on the list TFS in your IDE provides.

A: I assume that you already created project on yourAccountName.visualstudio.com
Then, if you are using VS2010, install recommended update SP1 VS2010 SP1
After that (it might take a while as long as 30 min), just start VS2010, on start page just click Connect To Team Foundation Server, then on "Select a team Foundation Server" click on "Servers", then "Add", and in "Name or URL of Team Foundation Server" just paste URL of your AccountName such as: "https://yourAccountName.visualstudio.com" (withouth quotes). then you jsut click OK and that's it. Your VS2010 should be now connected with your account at visualstudio.com
This is a bit of a manual method but it works :)
You can find more about it in this MSDN blog Team Foundation Service Preview – Connect Visual Studio 2010 to Your TFS Preview Account


text:
Q: How to find the shortest path from vertex u to v while at least visiting one target for directed graph? I am struggling to perform this in O(|E|log(|V|)) worst-case time complexity where E is the list of edges and V is the vertices in the graph.
So far I tried to use an adjacency list. I first sort the graph from starting vertex u using Kahn's topology algorithm.
I then look for the next target in the sorted topology and push the minimum distance of going from vertex u to v while traversing through the target into a min-heap. I did this by using Dijkstra's algorithm to find the minimum distance from u to the target requiring minimum overall distance. I also find the minimum distance from the target to vertex v.
Edit: Solution for directed graph
I found a solution by creating a copied graph with all the edges in reversee. I run dikjistra from source to destination then from run dikjstra again from destination to source with the graph with all reversed edges. I find overall distancing involving traversing at least one target along the way then I reuse the distance I got from the previous dikjistra executions to find the shortest path.

A: let DistSrc[i] denote the shotest distance of node i from source(here u) and DistDes[i] denote the shotest distance of node i from destination.
Both DistSrc and DistDes can be found by dijkstra algorithm.
iterate over all target nodes (say ti)  and and take the minimum of (DistSrc[ti]+DistDes[ti]) over all ti.


text:
Q: How can I access a date typed field from an ExtJS JSonStore? I've been trying to retrieve a date value and an integer value from the database, using the following code:
var l_alsChampsMois, l_stoDonneesMois;

    try {
        l_alsChampsMois = [
          {name: "date_mois", type: "date", dateFormat: "Y-m-d"},
          {name: "indice", type: "integer"}
        ];

        l_stoDonneesMois = new Ext.data.JsonStore({
            fields: l_alsChampsMois,
            autoLoad: false,
            proxy: {
                type: "ajax",
                url: "/commun/req_sql/req_ind_per_mois.php",
                reader: {
                    type: "json",
                    root: "rows"
                },
                // some configs to use jsFiddle echo service (you will remove them)
                actionMethods: {
                    read: "POST"
                },
               extraParams: {
                    key:"test"
                }
            },
            listeners: {
                load: function(objStore, alsLignes, blnOk, objOptions) {
window.alert("Mois fin : " + objStore.getAt(0).get("date_mois"));
                }
            }
        });

    l_stoDonneesMois.load({params:            {
                                p_idsoc:    l_strIdSociete,
                                p_mois:        l_datDebut.getMonth() + 1,
                                // getMonth renvoie 0 pour janvier, etc.
                                p_annee:    l_datDebut.getFullYear(),
                                p_debut:    1,
                                p_etape:    1
                                }
                            });

with l_strIdSociete and l_datDebut being variables previously assigned and /commun/req_sql/req_ind_per_mois.php the PHP page that retrieves the data and converts it to JSON.
It seems to work fine (indeed, Firebug tells me the load does retrieve a data structure with "date_mois" and "indice" containing the values I expect them to), only the window.alert returns undefined. If I replace "date_mois" with "indice", it returns the expected value for "indice".
I've tried to use objStore.getAt(0).getData()["date_mois"], to no avail.
My only clue about this is that "date_mois" in the data structure shown by Firebug is an Object, but even so it shouldn't be undefined, now should it? I looked up http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Field-cfg-type that wasn't exactly forthcoming with straight answers.
So what did I do wrong there?

A: If you need current time you can use php time function(note: it returns seconds, JS uses milliseconds), in another case you need to convert by mktime function.


text:
Q: BigQuery GCP Regression Model issues I am working on a lab to build a regression model in BigQuery on GCP. I followed the steps almost exactly, but the last query I run fails. Here's what I did.

*

*In BigQuery, I clicked "Create dataset" to create a dataset with the default options.

*I created a table and uploaded a CSV file that I downloaded of tick data of stock prices. The table included the columns: Time (this is just the tick number), Price, and Volume. I kept all the default options, but I checked off the "Auto detect" option.

*I ran the following query and saved it to a data table:
WITH
  raw AS (
  SELECT
    Time,
    Price,
    LAG(Price, 1) OVER(ORDER BY Time) AS min_1_Price,
    LAG(Price, 2) OVER(ORDER BY Time) AS min_2_Price,
    LAG(Price, 3) OVER(ORDER BY Time) AS min_3_Price,
    LAG(Price, 4) OVER(ORDER BY Time) AS min_4_Price
  FROM
    `dataset.table`
  ORDER BY
    Time DESC ),
  raw_plus_trend AS (
  SELECT
    Time,
    Price,
    min_1_Price,
    IF (min_1_Price - min_2_Price > 0, 1, -1) AS min_1_trend,
    IF (min_2_Price - min_3_Price > 0, 1, -1) AS min_2_trend,
    IF (min_3_Price - min_4_Price > 0, 1, -1) AS min_3_trend
  FROM
    raw ),
  ml_data AS (
  SELECT
    Time,
    Price,
    min_1_Price AS day_prev_Price,
    IF (min_1_trend + min_2_trend + min_3_trend > 0, 1, -1) AS trend_3_day
  FROM
    raw_plus_trend )
SELECT
  *
FROM
  ml_data

*I created a regression model by running this query:
CREATE OR REPLACE MODEL `dataset.model`
OPTIONS
  ( model_type='linear_reg',
    input_label_cols=['Price'],
    data_split_method='seq',
    data_split_eval_fraction=0.3,
    data_split_col='Time') AS
SELECT
  Time,
  Price,
  day_prev_Price,
  trend_3_day
FROM
  `dataset.model_data`

*This is where I failed. I ran this query to make the predictions, but it didn't produce anything. I just used 130000 as my time, since the ticks in my table only went up to 124256.
SELECT
  *
FROM
  ml.PREDICT(MODEL `dataset.model`,
    (
    SELECT
      *
    FROM
      `dataset.model_data`
    WHERE
      Time >= 130000) )

What is going wrong here? I also tried the same query at the end with Time >= 124256 and it only produced one row of results, which just turned out to be the same price in the original table.


text:
Q: cinnamon panel icons oversized the panel icon size is too large on cinnamon in my ubuntu 14.04 as you can see in the lower right corner. how to fix this?

A: This issue has been fixed in the latest Cinnamon versions.
You can upgrade Cinnamon using a PPA like sudo add-apt-repository ppa:gwendal-lebihan-dev/cinnamon-nightly
Install the cinnamon with:
sudo apt-get update
sudo apt-get install cinnamon

and then the issue should be fixed...
Oh and BTW: The icon pack is actually missing in that screenshot, if you want a Windows 7 icon pack, add ppa:noobslab/themes and ppa:noobslab/icons to your Software Sources using the method above. Then use the following commands to install the packages:
sudo apt-get update
sudo apt-get install mindows-transformation-themes
sudo apt-get install win-icons

Now you should be able to get an icon pack.
Update:
Do NOT forget to purge the previous cinnamon configuration(s) with sudo apt-get purge cinnamon before you try to install Cinnamon under the new PPA.

A: First purge the PPA and whatever you installed for your old cinnamon. Then use this command to add this letscape PPA:
sudo add-apt-repository ppa:lestcape/cinnamon

Use this to install cinnamon and some beautiful extras:
sudo apt-get -y update
sudo apt-get install cinnamon mint-themes

This works perfect for me, Hope to work for you.


text:
Q: ActionType in action 'Source' is not available in region 'EU_WEST_3' I'm trying to create CodePipeline with TF and I'm running into this error
Error: creating CodePipeline (Pos-CodePipeline-TF): InvalidActionDeclarationException: ActionType (Category: 'Source', Provider: 'GitHubEnterpriseServer', Owner: 'AWS', Version: '2') in action 'Source' is not available in region 'EU_WEST_3'

Here is the tf file
resource "aws_codepipeline" "codepipeline" {
  name     = "Pos-CodePipeline-TF"
  role_arn = "arn:aws:iam::920148820790:role/service-role/AWSCodePipelineServiceRole-eu-west-3-be-pos-connection"

  artifact_store {
    location = aws_s3_bucket.pos_solvee_codepipeline_bucket.bucket
    type     = "S3"
  }

  stage {
    name = "Source"

    action {
      name             = "Source"
      category         = "Source"
      owner            = "AWS"
      provider         = "GitHubEnterpriseServer"
      version          = "2"
      output_artifacts = ["SourceArtifact"]
      namespace        = "SourceVariables"

      configuration = {
        ConnectionArn        = "my-connection-arn"
        FullRepositoryId     = "my repo"
        BranchName           = "main"
        OutputArtifactFormat = "CODE_ZIP"
      }
    }
  }

  stage {
    name = "Build"

    action {
      name             = "Build"
      category         = "Build"
      owner            = "AWS"
      provider         = "CodeBuild"
      namespace        = "BuildVariables"
      input_artifacts  = ["SourceArtifact"]
      output_artifacts = ["BuildArtifact"]
      version          = "1"

      configuration = {
        ProjectName = "pos-solve-build"
      }
    }
  }

  stage {
    name = "Deploy"

    action {
      name            = "Deploy"
      category        = "Deploy"
      owner           = "AWS"
      provider        = "ElasticBeanstalk"
      namespace       = "DeployVariables"
      input_artifacts = ["BuildArtifact"]
      version         = "1"

      configuration = {
        ApplicationName = "pos-system-docker"
        EnvironmentName = "Pos-system-docker-env"
      }
    }
  }
}

resource "aws_s3_bucket" "pos_solvee_codepipeline_bucket" {
  bucket = "pos-solvee-codepipeline-bucket"
}

As I was searching I saw that value for ConnectionArn usually is data terraform_remote_state but I had this configuration created manually so I already have ConnectionArn.
Also tried to have Github instead of GitHubEnterpriseServer but that was causing an error too.
Let me know if there is anything else I need to share.

A: Although I havent tested this particular TF, I see an issue in the source action. For GitHub version 2, GitHub and GitHub Enterprise Cloud, use the CodestarSourceConnection action. So,
Category: Source
Owner: AWS
Provider: CodeStarSourceConnection
Version: 1

Also, from the docs, you must maintain the correct case for the FullRepositoryId value. For example, if your user name is some-user and repo name is My-Repo, the recommended value of FullRepositoryId is some-user/My-Repo.
Hope this helps.
References :

*

*Update a GitHub version 1 source action to a GitHub version 2
source action

*CodeStarSourceConnection for Bitbucket, GitHub, and GitHub
Enterprise Server actions

*Terraform Issue


text:
Q: Problems in Installation of OpenWRT on Dlink DIR-825 I am trying to install OpenWRT on my Dlink router DIR-825 with hardware version B1.
I have Firmware version: 2.06EU.
and I when I try to upgrade Firmware and select the OpenWrt image file openwrt-ar71xx-generic-dir-825-b1-squashfs-factory.bin, I get the error

The uploaded firmware file may not be correct. You may have uploaded a file that is not intended for this Gateway, or the uploaded file may be corrupted.
If the uploaded file is correct, it is possible that the gateway may be too busy to properly receive it right now. In this case, please try the upload again. It is also possible that you are logged in as a "user" instead of an "admin" - only administrators can upload new firmware.
The Gateway will not be reprogrammed.

I really can't figure out what is issue here. I am using router as admin. I am only one using this AP. Please guide me if someone else have gone through some thing like this or have experience dealing with such issues.

A: I found this OpenWRT forum page, by Googling around.
In particular, at the very end a guy with your router states:

Then I booted vista on this notebook and setup the same ip config. I tried the standard d-link firmware upgrade without recovery mode from internet explorer 8 and it still did not work!
  The solution was, to also use the recovery mode (press reset for ~30s until power blinks orange), only then flashing the downloaded image openwrt-ar71xx-dir-825-b1-squashfs-backup-loader.bin did work.
  From there it was easy to sysupgrade to my own image.
Thank you! I hope this helps others that try this.

He took the last words right out of my mouth.

A: You need to flash the image using recovery mode. Read the OpenWRT Wiki page:
http://wiki.openwrt.org/toh/d-link/dir-825#installation

Note: Since original Firmware 2.05WW Build: 05Beta01 it is not possible to flash OpenWrt via the firmware update page. (worked on a B2 revision with Ubuntu's Firefox in 2.05NA and 2.06NA) It looks like Firmware 2.01EU behaves the same way. Please use the firmware recovery mode instead.

Instructions are also on the Wiki page:

*

*Get into the D-Link recovery console with the steps below:
a. While powering up the router, press and hold the reset button until the power LED starts blinking orange (usually takes around 45 (forty-five) seconds )
b. Set a static IP on your PC to 192.168.0.100/24
c. connect to http://192.168.0.1, mind the quirks!

*Click "Browse" and select your OpenWrt image file (openwrt-ar71xx-dir-825-b1-squashfs-factory.bin, this binary image is available in the Backfire 10.03.1rc1 download directory and above)

*Click "Update" and let router flash the image (don't worry if it reboots before it reaches 100%). The page should display "Device is Upgrading the Firmware" in blue letters with the current percentage in red (with an incompatible Browser it doesn't). Look at the screenshot at the end of this section.

*The router's power LED should blink orange during bootup, as soon as it stops flashing, you can connect to it

*Tip! Note that default DHCP will allocate on 192.168.1.x, which is different subnet to the address you allocated above. This is why you can't connect until you change your IP address.

*obtain new IP from the router via DHCP and follow firstlogin


text:
Q: How can I make my javascript run faster and asynchronously I'm trying to make an extension that adds some HTML to a page as it's loaded. Long story short, it gets a list of links in a table, loads those links, and grabs a specific string and adds it to the original page I loaded.
Here is the code: due to the way the webpage was coded, i couldn't get the unique ids because they didn't exist so ignore that part.
var xhr = new XMLHttpRequest();
  for (i = 0; i < length; i++) {
    url = rows[i].getElementsByTagName("td")[0].getElementsByTagName('a')[0].getAttribute('href');
    insert = rows[i].insertCell(-1);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            //var Data = JSON.parse(xhr.responseText);
            var htmlString = xhr.responseText
              , parser = new DOMParser()
              , doc = parser.parseFromString(htmlString,"text/html")
              , test = doc.getElementById('page-wrapper').children[1]
              , ip_address = doc.getElementsByClassName('col-md-5')[0].children[5].children[0].children[0].children[10].innerHTML;
            insert.innerHTML = ip_address;
          }

    };
      xhr.open("GET",url,false);
      xhr.send();
    }

when i call the function, it works fine, however it takes a really long time to load and it all loads at the end rather than updating as each iteration of the for loop completes. I'd like to decrease the time it takes to load but a significant amount, and possibly have ear row update instantly vs at the end. I've tried searching asycn javascript but the bit of code I tried didn't help me much. Any assistance would be appreciated.

A: Using modern Javascript:

rows.forEach(row => {
  fetch(row.querySelector('td:first-of-type a:first-of-type').getAttribute('href'))
  .then(res => res.json())
  .then(data => {
    // do manipulations with DOM
  })
  .catch(console.log)
})