text:
Q: C : Runtime Error Verdict (Help debugging) I am working on a problem on an Online Judge ( link here ), and I keep getting a runtime error verdict each time I submit my solution. I have been looking at it for a while now, I still can't figure out what's wrong with it. I have also looked up the typical reasons behind a runtime error (arrays out of bonds, memory limit exceeded, logical errors ... ect). I can't find any of them in the code posted below :
#include<stdio.h>

int Hall[110][110];

int isValid(int x, int y){
int i,j,cnt=0;

for(i=x-1; i<=x+1; i++)
    for(j=y-1; j<=y+1; j++)
            if(Hall[x][y]==Hall[i][j])
                cnt++;
if(cnt>1)
    return 0;
else
    return 1;
}

int notChecked(int N,int* checked,int size){
  int i;

  for(i=0; i<size; i++)
     if(checked[i] == N)
        return 0;

  return 1;
}

int main (void){
  int T,R,C,checked[110],i,j,k,size;

  scanf("%d",&T);
  for(i=0; i<T; i++){
    scanf("%d %d",&R,&C);
    //initialize
    size=0;
    for(j=0; j<R*C; j++)    checked[j] = -1;
    for(j=0; j<=C+1; j++){
            Hall[0][j] = -1;
            Hall[R+1][j] = -1;
    }
    for(j=0; j<=R+1; j++){
            Hall[j][0] = -1;
            Hall[j][C+1] = -1;
    }
    //read input
    for(j=1; j<=R; j++)
        for(k=1; k<=C; k++)
            scanf("%d",&Hall[j][k]);

    //algo:
    for(j=1; j<=R; j++)
        for(k=1; k<=C; k++)
            if(Hall[j][k]>=0){
                if(notChecked(Hall[j][k],checked,size)){
                    if(isValid(j,k)==0){
                        checked[size] = Hall[j][k];
                        size++;
                    }
                }
            }

    printf("%d\n",size);
}

return 0;}

Any help is much appreciated !

A: You need to do bounds checking on your input.
According to the site T needs to be between 1 and 100 inclusive, so you need to check for that.  Then for each R and C (N and M on the site), they also need to be between 1 and 100 inclusive.
For each set of R by C entries, you need to make sure you actually read in R rows and C columns.  You also need to ensure that you read in T total sets of entries.

A: Problem Solved !
The code contained an array out of bonds problem, in the following line:
for(j=0; j<R*C; j++)    checked[j] = -1;

Knowing that checked had a size of 110 and R and C a max size of 100 each. I changed the size of checked to 10100 and it worked.
Thanks @chux for the help !


text:
Q: python tkinter Entry widget Dynamic Name anyone can guide me of the following:
I want to dynamically create the Entry widget and assigned hierarchical name (i.e. e1, e2, e3...etc), so that in next step easily reference back to collect the information.
see my draft code below, its not working
bowList = pd.DataFrame(np.empty([12,2]),columns=[['F','S']])

main2 = tki.Tk()
main2.minsize(800,500)

mb1 = tki.Menu(main2)

fm = tki.Menubutton(mb1)

l1 = tki.Label(main2, text="Fore Name")
l1.place(x=50,y=5,width=70)

l2 = tki.Label(main2, text="Surname")
l2.place(x=300,y=5,width=70)

h=1
for i in np.arange(1,12):
    h = i * 30
    tki.Label(main2, text=i).place(x=10,y=h,width=15)
    e1 = tki.StringVar(main2)
    e1 ="e1%i" %(i)
    e2 = "e2%i" %(i)
    print(e1), print(e2)
    e1 = tki.Entry(main2, width=25, textvariable=e1)
    e1.place(x=50,y=h)
    e1.insert(i,i)

    e2 = tki.Entry(main2, width=25)
    e2.place(x=250,y=h)

def BowSave():
    for i in np.arange(1,12):
           #bowList.iloc[i,0] = (e11.get())
           #bowList.iloc[i,1] = (e21.get())
           #np.where(i == 10, print(bowList))
           #print(main2.children.values())
           #print(e11.get())

b1 = tki.Button(main2, text="Save", command=BowSave, height=2, width=5)
b1.place(x=500,y=5)

print(main2.winfo_name)
main2.mainloop()

Thanks,
KP

A: This snippet might get you started.
....
entry_text = ['e1', 'e2', 'e3']

....
    # add text entries
    for x, text in enumerate(entry_text):
        e = ttk.Entry(mFrame, width=80, name=text)
        e.grid(column=1, row=x, sticky='WE', padx=5, pady=5)
        e.insert(0, text)

....
    e1Text = master.children['mFrame'].children['e1'].get()
    e2Text = master.children['mFrame'].children['e2'].get()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I change the header color in html without using CSS? I'm making a website without using anything other than html and headers can't be seen on the screen because of the background. So, I wanted to make them white instead of black. Can I do it without using anything besides html?

A: To change the colour  without using CSS just use the color and background-color of style attribute in html .I have attached an sample code for your reference.
Refer the link to understand more on styles.
https://www.w3schools.com/html/html_styles.asp

Header

content

A: Is this what you are trying to achieve?

Header

content


text:
Q: R curve() on expression involving vector I'd like to plot a function of x, where x is applied to a vector. Anyway, easiest to give a trivial example:
var <- c(1,2,3)
curve(mean(var)+x)
curve(mean(var+x))

While the first one works, the second one gives errors:
'expr' did not evaluate to an object of length 'n' and
In var + x : longer object length is not a multiple of shorter object length
Basically I want to find the minimum of such a function: e.g.
optimize(function(x) mean(var+x), interval=c(0,1))

And then be able to visualise the result. While the optimize function works, I can't figure out how to get the curve() to work as well.. Thanks!

A: The function needs to be vectorized. That means, if it evaluates a vector it has to return a vector of the same length. If you pass any vector to mean the result is always a vector of length 1. Thus, mean is not vectorized. You can use Vectorize:
f <- Vectorize(function(x) mean(var+x))
curve(f,from=0, to=10)

A: This can be done in the general case using sapply:
curve(sapply(x, function(e) mean(var + e)))

In the specific example you give, mean(var) + x, is of course arithmetically equivalent to what you're looking for. Similar shortcuts might exist for whatever more complicated function you're working with.


text:
Q: When i am trying to run this code i am getting the following error I am trying to connect mongodb database by this code but when running this code I get the error(error at the bottom of the code).
One of the error was in the 7th line where it was resolved by adding
{ useNewUrlParser: true } but still it has more errors. I am using MongoDB version 4.0.1. Do anybody know how to resolve this error.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();

app.use(express.static('public'));
app.set('view engine','ejs');

mongoose.connect('mongod://localhost/students', { useNewUrlParser: true });
var studentSchema = new mongoose.Schema({
    name: String,
    age:Number,
    country:String
});

var Student = mongoose.model("Student", studentSchema);
var shashank = new Student({
    name:"Shashank",
    age:"21",
    country:"India"
});

shashank.save((err,student) => {
    if(err){
        console.log('Something went wrong!');
    }
    else {
        console.log("You added: " + student);
    }
});

app.listen(3000,() => {
    console.log('Server Listening!');
});

Error while running this code!
D:\HARDWORK\YelpCamp-Course>node app.js
Server Listening!
                                                                                (node:14060) UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string
    at parseConnectionString (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb-core\lib\uri_parser.js:216:21)
    at connect (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\operations\mongo_client_ops.js:179:3)
    at connectOp (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\operations\mongo_client_ops.js:283:3)
    at executeOperation (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\utils.js:420:24)
    at MongoClient.connect (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\mongo_client.js:168:10)
    at Promise (D:\HARDWORK\YelpCamp-Course\node_modules\mongoose\lib\connection.js:499:12)
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:\HARDWORK\YelpCamp-Course\node_modules\mongoose\lib\connection.js:496:19)
    at Mongoose.connect (D:\HARDWORK\YelpCamp-Course\node_modules\mongoose\lib\index.js:229:15)
    at Object.<anonymous> (D:\HARDWORK\YelpCamp-Course\app.js:9:10)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
(node:14060) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)                                                                                (node:14060) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

A: mongoose.connect('mongod://localhost/students', { useNewUrlParser: true });

It should start with mongodb://..., And  When you use { useNewUrlParser: true } you should always specify the port number in connection string mongoose reference like given below.
mongoose.connect('mongodb://localhost:27017/students', { useNewUrlParser: true });

here port number 27017 is the default port for MongoDB database.

A: The host you write is not correct, and it should be. m
mongoose.connect('mongodb://localhost:27017/students', { useNewUrlParser: true });

A: use this two set before connect to moongose more clean and stable for version 5.7
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);

A: I have faced the same issue, I just started the mongo in the terminal by command
1) sudo service mongod start
2) mongo
worked for me.


text:
Q: Python time.clock() - reset clock value with threads I see time.clock() on Windows 'starts' a timer when called for the first time, and returns elasped time since the first call for calls after that. I read that the only way to restart the clock is to start a new process.
Is starting and killing threads supposed to restart the time.clock() as well? It doesn't seem to be working right now. If not, is the only solution to re-launch the entire executable?

A: A thread is not a process, so, no. (As a minor point, you can't kill a thread in Python, you can only ask it to exit. Killing threads through other means, where such means even exist, is likely to leave Python in a bad state.)
The question is why you want to reset the timer, and also why you are using time.clock(). If you care about the elapsed time between two points at such a high granularity that time.time() is not suitable, you'll just have to subtract the first point from the second point. No resetting required. I would recommend just using time.time() unless you really care about that tiny bit of difference in granularity, as time.time() works the same way on all platforms, contrary to time.clock().

A: Leaving threads apart if you want a clock you can reset with the precision of time.clock() which is higer than the one of time.time() just because the float of the second one is bigger (almost imperceptible difference), for measuring the lapse of time past while running some code you can try this:
t0 = time.clock()
... do something
print('Running time:', time.clock()-t0)

Yo can also try a function decoration for this:
def duration(code):
    def f(*args):
        t0 = time.clock()
        bar = code(*args)
        print('Running time:', time.clock()-t0)
        return bar
    return f

After this you can define your function with the decorator:
@duration
def myFun(*args):
    ... do something

Or just call the function with the decorator:
duration(myFun)(*args)


text:
Q: Inserting HTML into database I am inserting data into a table which contains some basic html tags, double quotes and single quotes.
I am using the following line to handle the data:
htmlentities(($_POST[content]), ENT_QUOTES);

The problem with this is that when I select this data to bring it back onto the screen, displays the actual html tags instead of rendering the html, i.e. if I use the <b>bold</b> tag, is displays it as text instead of making the text within that tag bold.  If I don't use the above line, i.e.
htmlentities(($_POST[content]), ENT_QUOTES);

Then I can't insert the data into the database because the data can contain single quotes and double quotes.
How do I deal with this issue?
So basically, I should be able to insert the data into the database where single or double quotes should not cause a problem.  When when rendering the data back onto the screen, it should render html tabs as they should get rendered into the browser and the quotes should be displayed as quotes in the text being rended back onto the screen.

A: You are inserting data into a database, not into an HTML document. Don't use htmlentities. Use whatever methods your database provides for escaping content. This should be something that uses bound parameters. Bobby-tables explains a number of different methods

A: $html = mysql_real_escape_string($html);

http://php.net/manual/en/function.mysql-real-escape-string.php
Make sure you have made a proper mysql connection mysql_connect before using this function.

A: you have to use strip_tags($str);
if you want remove only html tags.. single quote or double quote will remain...
but the problem in your case is ...you are putting lots of white space with your strings so you can perfectly use use strip_tags($str);

A: Putting so much HTML codes into the mysql table seems an ugly method to me, it is needed if you are adding a post but if you are saving a page which you may repopulate you may consider another way.
this is my method doing this:

*

*Clear any html code

*Put useful data into array (serialize array)

*Save array into database

*Repopulate array when the page is called  (unserialize array)

This saved me to put <1kb data instead of 125kb
This is a good way if you are using templating like systems.


text:
Q: Find the highest completed stage
I have above data which lists the stages and their order and the avg completion. I would like to get the stage beyond which there are no uncompleted stages. For example, from the above data the highest stage that is completed is STAGEID -12 as STAGEID - 14 is not 100% complete which disqualifies the stages beyond it to be not considered as completed as well. If all of the stages are 100% complete then get the highest stage that is completed. Any thoughts on how to query for it would be really helpful.

A: select MAX(STAGEID)
from [Your-table]
where average=100;

A: Let's assume table name is 'stages':
select min(s.stageid)
    from stages s1
       where 1 = (select count(*)
                      from stages s2
                         where s1.stageid <s2.stageid and s2.average <> 100 and s1.average=100 and s2.stageorder = s.stageorder+1);


text:
Q: Make image look correct in browser and print? I dynamically create an invoice off my commerce site. At the top left of the invoice is my company logo. I need that logo to display correctly on the web, but also print sharp (I print directly off loaded page). Currently because the image is web native at 72 ppi, it does not print sharp.
How can I print the logo sharp while also displaying it correctly on the web page?

A: Try making the logo 4 times bigger.  Say the logo is 72x72 pixels.  Make the logo 288x288 and include it in your invoice html as
<img src="logo.gif" style="width:72px;height:72px;"/>

It should be downsized by the browser and printed a bit better.  If it works, and you need higher resolution, just make the logo as large as you need.


text:
Q: ElasticSearch / OpenSearch term search with logical OR I have been scratching my head for a while looking at OpenSearch documentation and stackoverflow questions. How can I do something like this:
Select documents WHERE studentId in [1234, 5678] OR applicationId in [2468, 1357].
As long as studentId exactly matches one of the supplied values, or applicationId exactly matches one of the supplied values, then that document should be included in the response.
When I want to search for multiple values for a single field and get an exact match the following works:
{
    "must":[
        {
            "terms": {
                "studentId":["1234", "5678"]
            }
        }
    ]
}

This will find me exact matches on studentId in [1234, 5678].
If I try to add the condition to also look for (logical or) applicationId in [2468, 1357] then the following will not work:
{
    "must":[
        {
            "terms": {
                "studentId":["1234", "5678"]
            }
        },
        {
            "terms": {
                "applicationId":["2468", "1357"]
            }
        }
    ]
}

because this will do a logical and on the two queries. I want logical or.
I cannot use should because this returns irrelevant results. The following does not work for me:
{
    "should":[
        {
            "terms": {
                "studentId":["1234", "5678"]
            }
        },
        {
            "terms": {
                "applicationId":["2468", "1357"]
            }
        }
    ]
}

This seems to return all results, ranked by relevance. I find that the returned results do not actually match, despite the fact that this is a terms search.

A: Can you try with following query..
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "terms": {
                  "studentId":["1234", "5678"]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "terms": {
                  "applicationId":["2468", "1357"]
                }
              }
            ]
          }
        }
      ]
    }
  }
}


text:
Q: How do we type in Telugu in android? Is it supported? Can we have Telugu typing in android? If so, how?
Does android support Telugu fonts directly?
Or do we use bitmap fonts?

A: Try this.
Indic version of Samsung phone supports most Indian language.

A: You need to add custom font to include telgu font, see the following guide to add support for custom font in your application:
Add custom font for complete android application

A: One can easily type in Telugu using multiling app and its Telugu plugin.
It works in almost all applications. Prior to Jelly bean, Android did not support Telugu fonts.
But now, they do support it.


text:
Q: Can I output only the first instance of a value from a datatable? Is it possible to output only the first instance of a value stored in a data table?
My example is this = I have a datatable wherein each row contains the name of a month. The table is ordered by month, in ascending order. I want to output the name of the month only on its first occurence in the table - if there are five entries with the month January, the text 'January' only needs be output once.
I'm using a repeater - code below. The value in Month should only change if it is different to the value in the previous row.
<asp:Repeater ID="rptEvents" runat="server">
    <ItemTemplate>

<%#Eval("Month")%>

            <asp:HyperLink ID="hlEvents" runat="server" Text='<%#Eval("Title") %>' NavigateUrl='<%#Eval("QuickLink") %>'></asp:HyperLink>

    <%#Eval("Date") %>

    <%#Eval("Description") %>

    </ItemTemplate>
</asp:Repeater>

A: I'd recommend to have 2 Repeaters. The outer will bind to month list and the inner all entries within the month:
<asp:Repeater ID="MonthList" runat="server" OnItemDataBound="MonthList_ItemDataBound">
    <ItemTemplate>

<%# Container.DataItem %>

        <asp:Repeater ID="ItemList" runat="server">
            <ItemTemplate><%# Eval("Name") %></ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>

For this markup code behind may look like:
public partial class _Default : System.Web.UI.Page
{
    public class Entry
    {
        public string Month {get;set;}
        public string Name {get;set;}
    }

    List<Entry> entries = new List<Entry>()
    {
        new Entry() { Month = "Jan", Name = "name1"},
        new Entry() { Month = "Jan", Name = "name2"},
        new Entry() { Month = "Feb", Name = "name3"},
        new Entry() { Month = "Aug", Name = "name4"},
        new Entry() { Month = "Dec", Name = "name5"},
        new Entry() { Month = "Dec", Name = "name6"}
    };

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            MonthList.DataSource = entries.GroupBy(x => x.Month).Select(x => x.Key);
            MonthList.DataBind();
        }
    }

    protected void MonthList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            var itemList = (Repeater)e.Item.FindControl("ItemList");
            var month = (string)e.Item.DataItem;
            itemList.DataSource = entries.Where(x => x.Month == month);
            itemList.DataBind();
        }
    }
}

I used in-memory collection for the sample and Linq to convert it. First, we group the data source by Month. Then, in MonthList_ItemDataBound, for each month being bound we look for the inner repeater and bind it with a collection filtered by current (DataItem) month. Hope this helps.

A: Well, I'm not sure but how about doing it on the db-side?
    SELECT MIN(DISTNCT Month), Title, QuickLink FROM Title, QuickLink

UPDATE:
Seems like I was misunderstood. How about using a method?

<%#GetMonthName(Eval("Month"))%>

And in code-behind, define a class-scope variable to hold the previous month name and compare it to the current month name in your method:
// this is a private class-scope variable.
private static string prevMonthName = string.Empty;

public string GetMonth(string curMonthName)
{
  if (curMonthName == prevMonthName)
  {
    return string.Empty;
  }
  prevMonthName = curMonthName;
  return curMonthName;
}


text:
Q: Redirecting kafka log messages into a separate log (other than catalina.out) I have a project set up using Spring Boot, where I am using Spring Kafka to consume messages. The application is deployed on an independent Tomcat instance. Spring Kafka is generating a lot of logging messages, and they automatically go to catalina.out. Is there a way for me to redirect these Kafka logging messages into a separate log that I have created for my application (dataRiver log)?
I am using logback for logging.
This is what my logback-spring.xml looks like:

<property name="LOGS" value="${catalina.base}/logs" />

<include resource="org/springframework/boot/logging/logback/base.xml" />

<appender name="DATA-RIVER" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOGS}/DataRiver.log</file>
    <append>true</append>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>%p %d %C{1.} [%t-[%X{threadid}]] %m%n</Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOGS}/archived/DataRiver-%d{yyyy-MM-dd}.log</fileNamePattern>
    </rollingPolicy>
</appender>

<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOGS}/DataRiver-Err.log</file>
    <append>true</append>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>%p %d{ISO8601} [%t-[%X{threadid}]] - %m%n</Pattern>
    </encoder>

    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOGS}/archived/DataRiver-Err-%d{yyyy-MM-dd}.log</fileNamePattern>
    </rollingPolicy>
</appender>

<logger name="dataRiver" level="INFO" additivity="false">
    <appender-ref ref="DATA-RIVER"/>
</logger>

<logger name="error" level="WARN" additivity="false">
    <appender-ref ref="ERROR"/>
</logger>

And here's my logging service:
public class LoggingService {

  public static final Logger LOGGER_DATA_RIVER = LoggerFactory.getLogger("dataRiver");
  public static final Logger LOGGER_ERROR = LoggerFactory.getLogger("error");

}

Here's my consumer config:
@Bean
public ConsumerFactory<String, GenericData.Record> testConsumerFactoryFirst() {
  Map<String, Object> dataRiverProps = setTestDataRiverProps();
  dataRiverProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, env.getProperty("test1.bootstrap.servers"));
  dataRiverProps.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, env.getProperty("test1.schema.registry.url"));
  return new DefaultKafkaConsumerFactory<>(dataRiverProps);
}

private ConcurrentKafkaListenerContainerFactory<String, GenericData.Record> testKafkaListenerContainerFactory(ConsumerFactory<String, GenericData.Record> consumerFactory) {
  ConcurrentKafkaListenerContainerFactory<String, GenericData.Record> factory = new ConcurrentKafkaListenerContainerFactory<>();
  factory.setConsumerFactory(consumerFactory);
  factory.setBatchListener(true);
  return factory;
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, GenericData.Record> testKafkaListenerContainerFactoryFirst() {
  return testKafkaListenerContainerFactory(testConsumerFactoryFirst());
}

Here's the consumer:
@KafkaListener(topics = "#{'${test.kafka.topics}'.split(',')}", containerFactory = "testKafkaListenerContainerFactoryFirst")
public void consumeAvroFirst(List<Message<GenericData.Record>> list) {
  consumeJsonMessageBatch(convertAvroToJsonBatch(list), ""Kafka Consumer test-1");
}

private List<String> convertAvroToJsonBatch(List<Message<GenericData.Record>> list) {
  return list.stream().map(record -> record.getPayload().toString()).collect(Collectors.toList());
}

And here is an excerpt from catalina.out:
2019-04-20 02:16:54.190  WARN 18286 --- [ntainer#1-0-C-1] org.apache.kafka.clients.NetworkClient   : [Consumer clientId=consumer-12, groupId=DataRiver1] 10 partitions have leader brokers without a matching listener, including [test.autoEvents-8, test.autoEvents-2, test.autoEvents-4, test.loginEvaluationEvents-17, test.loginEvaluationEvents-11, test.loginEvaluationEvents-5, test.loginEvaluationEvents-13, test.loginEvaluationEvents-7, test.loginEvaluationEvents-1, test.loginEvaluationEvents-19]
2019-04-20 02:16:54.320  WARN 18286 --- [ntainer#1-0-C-1] org.apache.kafka.clients.NetworkClient   : [Consumer clientId=consumer-12, groupId=DataRiver1] 10 partitions have leader brokers without a matching listener, including [test.autoEvents-8, test.autoEvents-2, test.autoEvents-4, test.loginEvaluationEvents-17, test.loginEvaluationEvents-11, test.loginEvaluationEvents-5, test.loginEvaluationEvents-13, test.loginEvaluationEvents-7, test.loginEvaluationEvents-1, test.loginEvaluationEvents-19]
2019-04-20 02:16:54.320  WARN 18286 --- [ntainer#0-0-C-1] org.apache.kafka.clients.NetworkClient   : [Consumer clientId=consumer-10, groupId=DataRiver1] 10 partitions have leader brokers without a matching listener, including [test.autoEvents-8, test.autoEvents-2, test.autoEvents-4, test.loginEvaluationEvents-17, test.loginEvaluationEvents-11, test.loginEvaluationEvents-5, test.loginEvaluationEvents-13, test.loginEvaluationEvents-7, test.loginEvaluationEvents-1, test.loginEvaluationEvents-19]
2019-04-20 02:16:54.346  WARN 18286 --- [ntainer#2-0-C-1] org.apache.kafka.clients.NetworkClient   : [Consumer clientId=consumer-2, groupId=DataRiver1] 10 partitions have leader brokers without a matching listener, including [test.autoEvents-8, test.autoEvents-2, test.autoEvents-4, test.loginEvaluationEvents-17, test.loginEvaluationEvents-11, test.loginEvaluationEvents-5, test.loginEvaluationEvents-13, test.loginEvaluationEvents-7, test.loginEvaluationEvents-1, test.loginEvaluationEvents-19]

Thanks for your help!

A: Create a new appender in logback-spring.xml.  In the appender add a Filter.  Create a filter class to match on the Kafka logs.  Have the appender output to your desired location.
Appender:
<appender name="foo" class="com.foo.bar.SomeClass">
  <target>bar</target>
  <filter class="com.foo.KafkaFilter" />
   ...
</appender>

Filter class:
public class KafkaFilter extends AbstractMatcherFilter {
    @Override
    public FilterReply decide(Object o) {

        LoggingEvent loggingEvent = (LoggingEvent) o;

        if(loggingEvent.getMessage().contains("org.apache.kafka")) {
            return FilterReply.ACCEPT;
        }
    }
}

I recommend taking a look here at this answer: https://stackoverflow.com/a/5653532/10368579
The LogBack documentation has more information on matchers here:
https://logback.qos.ch/manual/filters.html#matcher


text:
Q: Min, Max Avg from a input text Python making loop generic I am pretty new to Python and is busy with a bootcamp one of the task I have to complete have me a bit stump.  They give as a input txt file that looks like the following:

min:1,2,3,4,5,6
max:1,2,3,4,5,6
avg:1,2,3,4,5,6

The task is that I have to open the txt file in my program and then work out the min, max and the avg of each line.  I can do this a long way of doing .readlines(), but they want it in a generic way such that the lines don't matter.  They want me to read through the lines with a loop statement and check the first word and then make that word start the operations.
I hope that I have put the question through correctly.
Regards

A: While your question wasnt entirely clear with how to use use readlines and not , maybe this is what you were looking for.
f=open("store.txt","r")
for i in f.readlines():
    func,data=i.split(":")
    data=[int(j) for j in data.rstrip('\n').split(",")]
    print(func,end=":")
    if(func=="max"):
        print(max(data))
    elif(func=="min"):
        print(min(data))
    else:
        print(sum(data)/len(data))

Next time please try to show your work and ask specific errors , i.e. not how to solve a problem but rather how to change your solution to fix the problem that you are facing

A: eval() may be useful here.
The name of the math operation to perform is conveniently the first word of each line in the text file, and some are python keywords. So after parsing the file into a math expression I found it tempting to just use python's eval function to perform the operations on the list of numbers.
Note: this is a one-off solution as use of eval is discouraged on unknown data, but safe here as we manage the input data.
avg, is not a built-in operation, so we can define it (and any other operations that are not built-ins) with a lambda.
with open('input.txt', 'r') as f:
    data = f.readlines()

clean = [d.strip('\n').split(':') for d in data]

lines = []

# define operations in input file that are not built-in functions
avg = lambda x:  sum(x)/float(len(x)) # float for accurate calculation result

for i in clean:
    lines.append([i[0], list(map(int, i[1].split(',')))])

for expr in lines:
    info = '{}({})'.format(str(expr[0]), str(expr[1]))
    print('{} = {}'.format(info, eval('{op}({d})'.format(op=expr[0],d=expr[1]))))

output:
min([1, 2, 3, 4, 5, 6]) = 1
max([1, 2, 3, 4, 5, 6]) = 6
avg([1, 2, 3, 4, 5, 6]) = 3.5


text:
Q: CUDA 2D ARRAY - Working with elements I am learning cuda and managed to get a 2D Array in there, and return a 2D array of doubles, with some minor issues. Now, I want , for example, to set all values to 250 of double all values, but I cant seem to get past the first row. I can't get to seem to loop correctly. I am doubting if it is the number of blocks/threads or the code itself . Here is my complete code:
#include <stdio.h>
#include <vector>

using namespace std;

#define THETA 10

// Error checking.
//
#define gpuErrorCheck(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

// Pass 2-dim array to GPU and change it there.
//
__global__
void addArrays(double *twoDimArray, size_t pitch)
{
    printf("\n\nOn GPU array : thread : %d\n", threadIdx.x);

    int tidx = blockIdx.x * blockDim.x + threadIdx.x;  //// tidx = Columns in CUDA
    int tidy = blockIdx.y * blockDim.y + threadIdx.y;  //// tidy = Rows In cuda

    if ((tidx < THETA) && (tidy < THETA))
    {
    double tempval = 0;
        for(int i=0; i < THETA ; i++)
        {
            tempval = 250;
        }
    twoDimArray[tidy * THETA + tidx]=tempval;
    }

}

int main()
{

    //
    // 2-Dimensional Array
    //

    printf("\n*******************\n2-DIMENSIONAL ARRAY\n*******************\n\n");

    // Create 2-dim array on the CPU.
    //
    double arrayOnCpu[THETA][THETA];
    double arrayOnCpu2[THETA][THETA];

    // Initialise the vector of vector on the CPU.
    //
    for (int i = 0; i < THETA; i++) // Aantal buitenste vectoren.
    {
        for (int j = 0; j < THETA; j++) // Aantal binnenste elementen.
        {
            arrayOnCpu2[i][j] = j;
        }
    }

    // Print the vector of vectors.
    //
    for (int i = 0; i < THETA; i++)
    {
        for (int j = 0; j < THETA; j++)
        {
            printf("%2.2f\t", arrayOnCpu2[i][j]);
        }
        printf("\n");
    }

    // Create corresponding double array on the GPU.
    //
    double *pToArrayOnGpu;
    size_t pitch;

    gpuErrorCheck( cudaMallocPitch((void **)&pToArrayOnGpu, &pitch, THETA * sizeof(double), THETA) );

    // Copy CPU data to vector on GPU.
    //
    gpuErrorCheck( cudaMemcpy2D(pToArrayOnGpu, pitch, arrayOnCpu2, pitch, THETA * sizeof(double), THETA, cudaMemcpyHostToDevice) );

    // Launch GPU code with THETA threads, one per vector element.
    //
    addArrays<<<1, THETA>>>(pToArrayOnGpu, pitch);
    gpuErrorCheck( cudaDeviceSynchronize() );

    // Copy array from GPU back to CPU.
    //
    gpuErrorCheck( cudaMemcpy2D(arrayOnCpu2, pitch, pToArrayOnGpu,pitch, THETA * sizeof(double), THETA,  cudaMemcpyDeviceToHost) );

    // Print the vector of vectors.
    //
    for (int i = 0; i < THETA; i++) // Aantal buitenste vectoren.
    {
        for (int j = 0; j < THETA; j++) // Aantal binnenste elementen.
        {
            printf("%2.2f\t", arrayOnCpu2[i][j]);
        }
        printf("\n");
    }
    printf("\n\n");

    // Free up the array on the GPU.
    //
    gpuErrorCheck( cudaFree(pToArrayOnGpu) );

    return 0;

}

A: The main problem with the code is that you confused the pitch concept of 2D arrays on the host side and the device side. Below is a brief introduction.
In host, a[row][column] stored in a+row*width_of_column*sizeof(element)+column*sizeof(element). But in cuda's global memory access, continuous access from 256-byte aligned addresses (addr=0, 256, 512, ...) is the most efficient. Thus, in order to improve the efficiency of memory access, the cudaMallocPitch function is available.
In the memory allocated by the cudaMallocPitch(), address of the first element of each row of the array is aligned. Since data per line is undefined,  row*width_of_column*sizeof(element) is not necessarily a multiple of 256. Therefore, in order to ensure the start address alignment of the first element of each line of the array, cudaMallocPitch() allocates more bytes per line when allocating memory to ensure that width_of_column*sizeof(element)+extra allocated bytes are
Multiples of 256 (aligned). Also,the pitch returned from cudaMallocPitch() Should add extra allocated memory.
The function prototype is as follow:
__host__ cudaError_t cudaMemcpy2D ( void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, cudaMemcpyKind kind )

So, When you use cudaMemcpy2D(), You should give the correct pitch which means the pitch is not the same in the array of hosts and devices. In your case,it should be like:
gpuErrorCheck(cudaMemcpy2D(pToArrayOnGpu, pitch, arrayOnCpu2, THETA * sizeof(double), THETA * sizeof(double), THETA, cudaMemcpyHostToDevice));

The first pitch(dpitch) is returned from cudaMallocPitch()while the last one(spitch) is THETA * sizeof(double).
You can get more info in this link.
I made a brief change to your code, which can run correctly on my machine.
env: Ubuntu 16.04 Tesla P100

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <stdio.h>
#include <vector>
using namespace std;

#define THETA 10
// Error checking.
#define gpuErrorCheck(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort = true)
{
    if (code != cudaSuccess)
    {
        fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
        if (abort) exit(code);
    }
}

// Pass 2-dim array to GPU and change it there.
//
__global__
void addArrays(double *twoDimArray, size_t pitch){
    int tidx = threadIdx.x;
    if ((tidx < THETA) /*&& (tidy < THETA)*/){
        double tempval = 250;
        for (int i = 0; i < THETA; i++){
            double* row = (double*)((char*)twoDimArray + i * pitch);
            row[tidx] *= tempval;
        }
    }
}

int main(){
    double arrayOnCpu2[THETA][THETA];

    // Initialise the vector of vector on the CPU.
    for (int i = 0; i < THETA; i++){ // Aantal buitenste vectoren.
        for (int j = 0; j < THETA; j++) // Aantal binnenste elementen.
            arrayOnCpu2[i][j] = j;
    }
    // Print the vector of vectors.
    printf("Before:\n");
    for (int i = 0; i < THETA; i++){
        for (int j = 0; j < THETA; j++)
            printf("%2.2f\t", arrayOnCpu2[i][j]);
        printf("\n");
    }
    // Create corresponding double array on the GPU.
    double *pToArrayOnGpu;
    size_t pitch;
    gpuErrorCheck(cudaMallocPitch((void **)&pToArrayOnGpu, &pitch, THETA * sizeof(double), THETA));

    // Copy CPU data to vector on GPU.
    gpuErrorCheck(cudaMemcpy2D(pToArrayOnGpu, pitch, arrayOnCpu2, THETA * sizeof(double), THETA * sizeof(double), THETA, cudaMemcpyHostToDevice));

    // Launch GPU code with THETA threads, one per vector element.
    addArrays << <1, THETA >> >(pToArrayOnGpu, pitch);
    gpuErrorCheck(cudaDeviceSynchronize());

    // Copy array from GPU back to CPU.
    gpuErrorCheck(cudaMemcpy2D(arrayOnCpu2, THETA * sizeof(double), pToArrayOnGpu, pitch, THETA * sizeof(double), THETA, cudaMemcpyDeviceToHost));

    // Print the vector of vectors.
    printf("After:\n");
    for (int i = 0; i < THETA; i++){ // Aantal buitenste vectoren.
        for (int j = 0; j < THETA; j++) // Aantal binnenste elementen.
            printf("%2.2f\t", arrayOnCpu2[i][j]);
        printf("\n");
    }
    printf("\n\n");

    // Free up the array on the GPU.
    gpuErrorCheck(cudaFree(pToArrayOnGpu));
    return 0;
}

The output is:
Before:
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00
After:
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00
0.00    250.00  500.00  750.00  1000.00 1250.00 1500.00 1750.00 2000.00 2250.00

A: First of all, you generally want to avoid using double on the GPU if you can. While basically all CUDA-capable consumer GPUs nowadays do support double precision arithmetic in some way, it's usually much much slower than single precision.
Apart from that, there seems to be some confusion concerning what the different pitches are supposed to mean. In general, the pitch of an array is the number of bytes you have to skip from the beginning of one row to get to the beginning of the next row. The driver may choose/need to add padding between the rows of a 2D array to make the allocation meet alignment requirements of the hardware and/or allow for more optimal memory access. That means, for a 2D array on the GPU, the pitch may be larger than just element size * width.
For your CPU array, however, the pitch, is just THETA * sizeof(double). The pitch of your GPU array is returned to you from cudaMallocPitch(). In your call to cudaMemcpy2D(), you pass the pitch of the GPU array as both, the GPU and the CPU pitch. Use the correct pitch for your CPU array. In your device code, you access the GPU array via twoDimArray[tidy * THETA + tidx]. Here, you're effectively using a pitch of THETA * sizeof(double) to access the GPU data. You should have used the actual pitch of the array instead. For example:
double* my_row = reinterpret_cast<double*>(reinterpret_cast<char*>(twoDimArray) + tidy * pitch);
my_row[tidx] = tempval;


text:
Q: How to pass django error status to ajax Using django rest framework with backbone.
Current situation:
Whenever an ajax call fails, django responds through  get_error_response
As soon as get_error_response gets invoked, django raises a error on client side too, as i am not handling this error in django(server) side.
views.py snippet
 def get_error_response(self):
    return Response(
        self.serializer.errors, status=status.HTTP_400_BAD_REQUEST
    )

Requirement:
I want to be able to pass all error statuses to $ajax.fail() promise, and handle it there on client side, thereby enabling me to show the error messages to user.
Note:something like the code given below is what i am expecting. But the problem is, this response would got to $ajax.done promise(), wheras i want it in $ajax.fail() promise
 def get_error_response(self):
    return Response({
        "msg":self.serializer.errors, "error_status":status.HTTP_400_BAD_REQUEST
    })

Do ask if more clarity is required.

A: No matter if you're using a Response from Django Rest Framework or the normal Django HttpResponse you always need to pass the keyworded argument status in order to make the response actually have the correct status code thus invoking the correct handler in your front end code.
What your last example does is only passing a data or content argument which is making the response class default to a 200 status code.
return Response(your_data, status=404)


text:
Q: Unable to build maven project from jenkins Getting error while build the project from jenkin
Below is the error
Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project : Execution default-war of goal org.apache.maven.plugins:maven-war-plugin:2.2:war failed: basedir /root/.jenkins/workspace/projectname does not exist ->

A: Is because of job setup issue. Please create a folder named your_job_name at /root/.jenkins/workspace/
OR also you can Delete Pipeline/Job and recreate new job and try to build again.


text:
Q: create multiple events android map application i'm creating a map app that displays events with a description overlay that pops up on click.
i've currently used 2 tutorials
tutorial 1)
tutorial 22)
currently i can display 1 event by defiining the long+lat,
my question is how do i add several events?
also how can i add events from a csv file which contains the long+lat and description for the event?
any help would be appreciated

A:
my question is how do i add several events?

Put multiple OverlayItems in the ItemizedOverlay.

also how can i add events from a csv file which contains the long+lat and description for the event?

Use Java I/O to read in the file.


text:
Q: Sencha app doesn't start in Windows app package We have a cross platform application based on Cordova (version 6.1.1) and Sencha ExtJS (cmd version 6.1.2 ext version 6.0.2). The application also uses the jQuery (version 2.1.4).
Now we found a very frustrating problem on the Windows platform.
We created the Visual Studio project with cordova (the sencha app is built with testing option before)
When we open the Visual Studio (version 14.0.25123.00 Update 2) and build the project (in release mode) on a device, then everything works as expected.
If we create an app package from the Visual Studio and install it any device manually, then seems like the ExtJS application is not loaded, and the application will hang on splash screen after start. (As I debugged it the script elements are added to the html by the microloader script, but the attached onload listeners on these elements are never fired, therefore the app never started)
And here is coming the most funny part. If you use the Visual Studio function to debug an already installed application, and connect to this application, then everything will works as is should, the ExtJS codes will be loaded.
Anyone found this before, or any similar thing?

A: What you can try is to use Vorlon.JS remote debugger. Vorlon.JS An open source, extensible, platform-agnostic tool for remotely debugging and testing your JavaScript.

A: Could it be Cordova is failing something that works fine during debug, more forgiving environment. But truly fails the app when sideloading and running without debugger.. ?


text:
Q: Alternating Series formula I'm having an issue with the following alternating series.
$\frac{1}{2} - \frac{1}{5} + \frac{1}{10} - \frac{1}{17} \text{ } ...$
Can't for the life of me figure out how to come up with the $bn$ for the series,

A: Are you looking for $$\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n^2+1}$$


text:
Q: Amazon Sns and cloudwatch pricing Im studing aws pricing and I have two doubts about Amazon SNS and Amazon Cloudwatch.
About cloudwatch, Im using it to monitor sns topics and to monitor a dynamodb table. Im reading about cloudwatch pricing and it says that the basic monitoring metrics for amazon ec2, amazon ebs, elastic load balancers and amazon rds are free. So to monitor sns topics and dynamodb its not basic monitoring and we need to pay $0.50 per month for each metric?
About SNS it says that we pay based on the number of notifications we publish, the number of notifications we deliver, and any additional API calls for managing topics and subscriptions.
Im bit confuse about this pricing, we pay for any API call, for example create a new topic, getl all topics, etc, ok this part it is clear, but Im not understanding about the other two, for exmaple in my code I have :
message = "this is a test"
message_subject = "Message test"
publication = sns.publish(topicArn, message, subject=message_subject)

In this case we have the cost about publish, and also in this sns.publish we need to pay relative to API calls? And also we need to  pay when we publish a message, and to this cost it is added the cost of deliver notifications? But its not the same thing? Publish a message or deliver a notification? Or notifications it is that confirmation subscriptions that we receive in email when we subscribe some email in the topic?
subscriptionEmail = sns.subscribe(topicArn, "email", email)

A: yup.
for cloud watch it's 0.5$ per metric. Pretty steep if you have a lot of metrics.
for sns: http://aws.amazon.com/sns/pricing/
you pay for api calls (what's called publishes in that page).
you also pay when SNS delivers messages to subscribers.
you are right that the operation of publishing a notification is different from the operation of sending the notification to subscribers and they fall in 2 different pricing buckets
what really matters is the number of notifications you push and who you push them to (deliveries). All the other numbers are a rounding error even for applications with a moderate amount of traffic.
to give an example.
Assume you have 1 SNS topic with 2 email address subscribed to it.
Assume you sent 5_000_000 notifications to the topic.
You would pay (this assumes you have exhausted the free tier already):
5_000_000 / 1_000_000 * 0.50$ = 2.5$ for publishing to the topic
5_000_000 / 100_000 * 2.00$ * 2 (2 email adresses) = 200 $ for email delivery
for a total of 202.5$


text:
Q: Should I address the imbalance when using CalibratedClassifierCV? Im using RandomForestClassifier and XGBClassifier with an imbalanced dataset, 1:2 ratio more or less, 1 being the most prevalent class.
My procedure is the following:

*

*Use StratifiedKFold to get training and testing subsets.

*Use train_test_split to subdivide the training into a calibration and
training set.

*Use the training set to train my model using the
sample_weight

*Create a CalibratedClassifierCV for my model setting
cv to 'prefit'

*Call fit() on CalibratedClassifierCV

*Predict on training set on both uncalibrated and calibrated models

*Get specificity and recall

*Plot calibration curves

Here is the question, when calling the fit() method on CalibratedClassifierCV, should I use sample_weights or not?
When using them, my recall and specificity are balanced (0.73 - 0.75) but my calibration plot looks similar to the uncalibrated model. When I don't use them, my calibration plot looks close to perfect, by my recall is shot to 0.85 and my specificity to 0.55.
Bonus question: Should I make my predictions on the calibrated model or the uncalibrated model?


text:
Q: Why is there no call stack for "generic events" I did read
Capture callstack and events in Xperf
and other sources, but the most straightforward thing I'd like to do is simply display the "Stack" column in WPA's "Generic events" graph.

Why is it not there? Sure, because stack information is not available, but why? I do know "xperf -help stackwalk" but what's listed is not what I'm looking for. For example,
xperf -on networktrace -stackwalk networktrace

is not possible to get the callstack for network events. Why? I must be missing something. Thanks!

A: Activating stacks for user mode events has this syntax: PROVIDER:KEYWORD:LEVEL:'stack'
You have to activate stacks this way:

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance
  Toolkit\xperf.exe" -start UserLogger -on
  Microsoft-Windows-Kernel-Network:::'stack'+Microsoft-Windows-Networking-Correlation:::'stack'+Microsoft-Windows-TCPIP:::'stack'
  -buffersize 2048 -f User.etl


text:
Q: VBscript - anyone can help to check what wrong with my script below Dim Nagios
Nagios = http://gl-nagios.fciconnect.com/centreon/index.php
set WshShell = WScript.CreateObject("WScript.Shell")
call WshShell.Run(nagios, 1, false)

WScript.Sleep 2000
WshShell.SendKeys ""
WScript.Sleep 1000
WshShell.SendKeys "{TAB}"
WScript.Sleep 1000
WshShell.SendKeys ""
WshShell.SendKeys "{TAB}"
WScript.Sleep 1000
WshShell.SendKeys "{ENTER}"
WScript.Sleep 5000
'Browse to DownHost
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WScript.Sleep 2000
WshShell.SendKeys "{ENTER}"
WScript.Sleep 5000
WshShell.SendKeys "{PRTSC}"
WScript.Sleep 5000
WshShell.AppActivate"C:\AutoScreenCapture\IECapt --url="nagios" --out=C:\AutoScreenCapture\Warning.jpg"
WScript.Quit

I intend to use vbscript to login to website and do screenshot on its active webpage and also using IEcapt freeware to capture its screenshot. Not sure where do I go wrong with the script. Any experts advise.

A: You have several issues, but before I get to them, let me declare that I am unfamiliar with IECapt and how it works.
First, as @bond stated, you need to enclose the Nagios assignment in quotes:-
Nagios = "http://gl-nagios.fciconnect.com/centreon/index.php"

Second, AppActivate simply switches to another already-running application window. It looks like you need to run the application with a command line to export the image from the clipboard (you can't switch to an app and apply arguments). Therefore, I suggest you remove the call to Run from line 4 and change the AppActivate call to the Run method so you can start it up with arguments.  Again, not exactly sure how the app works so this may need review.
Third, you have a problem with your string concatenation to insert the url.  You need to use the concatenation operator &. To maintain good convention, try to use variable names with the same case as you declared them, in this instance, Nagios:
'Start up the screen-capture app and minimise it
WshShell.Run "C:\AutoScreenCapture\IECapt --url=" & Nagios & " --out=C:\AutoScreenCapture\Warning.jpg", 2

Fourth, I always recommend declaring every variable to avoid runtime bugs and errors.  Therefore, you should always make line 1 of your VBScript files this:-
Option Explicit  'Enforce variable declaration

Fifth, you haven't declared a variable for WshShell:
Dim WshShell

Finally, you should always release memory for variables that you Set:
  Set WshShell = Nothing
  Set Nagios = Nothing


text:
Q: Why is a CSS 3D rotation not happening around the center point? I'm building out an aggregation of 3d cubes and trying to rotate the aggregated piece. For some reason it's not rotating along the center point.
When I just have an individual cube, it works as expected. When I join 3 cubes into a column, it works as expected. It's just when I join 3 columns into a "section" that the "section" doesn't rotate along the center point.
When the column and cube had this issue it was because I didn't set a proper height and width on them. Am I setting the wrong height and width for the '.section' element? If so, what should it be? An explanation on why my dimensions are wrong would be appreciated as well.
(Sorry for the astronomical code, but SO won't allow just a codepen and the problem doesn't happen with simplified code.)

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

front

back

right

left

top

bottom

      .scene {
        perspective: 600px;
      }

      .cube {
        width: 100px;
        height: 100px;
        position: relative;
      }

      .cube__face {
        position: absolute;
        width: 100px;
        height: 100px;
        color: white;
        font-size: 1.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .cube__face--front  {
        transform: rotateY(0deg) translateZ(50px);
        background-color: pink;
      }

      .cube__face--right {
        transform: rotateY(90deg) translateZ(50px);
        background-color: yellow;
      }

      .cube__face--back {
        transform: rotateY(180deg) translateZ(50px);
        background-color: green;
      }

      .cube__face--left {
        transform: rotateY(-90deg) translateZ(50px);
        background-color: blue;
      }

      .cube__face--top {
        transform: rotateX(90deg) translateZ(50px);
        background-color: orange;
      }

      .cube__face--bottom {
        transform: rotateX(-90deg) translateZ(50px);
        background-color: magenta;
      }

      .col {
        position: absolute;
        transform-style: preserve-3d;
        width: 100px;
        height: 300px;
      }

      .col .cube {
        position: absolute;
        top: 100px;
      }

      .col .cube:first-child {
        top: 0;
      }

      .col .cube:last-child {
        top: 200px;
      }

      .col-back {
        transform: translateZ(-200px);
      }

      .col-middle {
        transform: translateZ(-100px);
      }

      .section {
        transform-style: preserve-3d;
        backface-visibility: hidden;
        transform: rotateX(0deg);
        transition: all 1s linear;
      }

      .col-section {
        width: 100px;
        height: 100px;
      }

A: Ok, I was swimming in a sea of ignorance as to the fact that transform-origin accepts a 3rd value that corresponds to the z-axis. Basically, the default transform origin was correct for the x and y access, but I needed a custom one for the z-index to push it back a bit.
transform-origin: 50px 150px -100px;


text:
Q: Iterator in template c++ I am trying to understand templates. I am trying to navigate through elements, but I don't know how to get iterator of type T.
template <typename T, typename _Comparator = less<typename T::value_type>>
class MyClass{
  public:
///...
   typename T <typename T::value_type>::iterator i; // not working
///...
}

int main(){
  MyClass <list<string>> a1;
  MyClass <list<string>, CStrComparator> a2 ( list<string>{ "Hello", "world", "test", "this", "foo", "TEsT", "this", "done" }, CStrComparator ( false ) );
}

error:
/home/michal/Desktop/prog/stl2/main.cpp||In member function 'std::set<int> MyClass<_Type, _Comparator>::Search(const T&) const':|
/home/michal/Desktop/prog/stl2/main.cpp|27|error: expected nested-name-specifier before 'T'|
/home/michal/Desktop/prog/stl2/main.cpp|27|error: expected '(' before 'T'|
/home/michal/Desktop/prog/stl2/main.cpp|27|error: expected ';' before 'T'|
/home/michal/Desktop/prog/stl2/main.cpp||In function 'int main()':|
/home/michal/Desktop/prog/stl2/main.cpp|179|error: template argument 1 is invalid|
/home/michal/Desktop/prog/stl2/main.cpp|179|error: template argument 2 is invalid|
/home/michal/Desktop/prog/stl2/main.cpp|180|error: 't6' was not declared in this scope|
/home/michal/Desktop/prog/stl2/main.cpp||In constructor 'MyClass<std::basic_string<char>, _Comparator>::MyClass(const string&, const _Comparator&) [with _Comparator = std::less<char>, std::string = std::basic_string<char>]':|
/home/michal/Desktop/prog/stl2/main.cpp:118|34|instantiated from here|
/home/michal/Desktop/prog/stl2/main.cpp|75|warning: 'MyClass<std::basic_string<char> >::sequence' will be initialized after [-Wreorder]|
/home/michal/Desktop/prog/stl2/main.cpp|74|warning:   'std::less<char> MyClass<std::basic_string<char> >::cmp' [-Wreorder]|
/home/michal/Desktop/prog/stl2/main.cpp|40|warning:   when initialized here [-Wreorder]|
||=== Build finished: 6 errors, 3 warnings ===|

A: You already use the "type of elements of the container T"
typename T::value_type

The same is for iterators:
typename T::iterator i;


text:
Q: curl: when is output file created In case one has requested that the curl output be transferred to output.txt, then when exactly is the output file created.
I ask this because of the following issue that I am facing:
1. I give an rpc call which has a lot of data to be retrieved.
2, After the date is retrieved, i then go and read output.txt to get all the data i need.
3. But some rpc calls take some time for the data to be retrieved (as lot of data), thus I am not sure how long to wait before i go to read output.txt
4. I don't wish to give any random number as it would slow down the code.
5. Now i was thinking if output file is created after all the data is received then it woudl be easy as i just need to check for the existence of output.txt and then go an read.
But i am not sure if this is what happens thus i ask this question?
could someone please help me with this issue?
thanks
sunny

A: You should change your code so that it waits until curl has completed. The exact way depends on what language you use.


text:
Q: In a hypothesis test, what is preventing us from peeking and setting $H_0: \mu = \bar{x}$? In a hypothesis test, it seems that normally we first set the significance level $\alpha$ and then set the null hypothesis value, $H_0: \mu = \mu_0$, find the rejection region, then FINALLY introduce the observed data $X= x$, then see if the observed test statistic $T(x)$ falls into the rejection region.
What is preventing us from first "peeking" at the observed data, $x$, then setting $H_0: \mu = \bar{x}$ and achieving a rejection each time?


text:
Q: Get data using post request in REST API Codeigniter I am working with REST API for the first time in codeigniter.
I have following function in api
 public function cource_topics_post() {
        $username = $this->input->post('username');
        //$value=$this->uri->segment(3);
        $this->response(array('status' => 1, 'username' =>  $username ));
    }

but
$username = $this->input->post('username');

isn't working. need help
My controller is as follows
    <?php

header("Access-Control-Allow-Origin: *");
require(APPPATH . '/libraries/REST_Controller.php');

class Admin extends REST_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('file');
        $this->load->helper(array('form', 'url'));
    }

    public function cource_topics_post() {
        $username = $this->post('username');
        $password = $this->post('password');
        //$value=$this->uri->segment(3);
        $user = "faizan";
        $pass = "faizan";
        if($username == $user && $password == $pass){
            $this->response(array('status' => 1, 'logged in as' =>  $username ));
        }
        else{
            $this->response(array('status' => 0, 'Could not login' => 'incorrect username password'));
        }
    }

}

I am using rest_controller.

A: Make sure you have extended CI_Controller class in your class

A: check Rest config for POST, is activated ?

A: Pass the parameter in the function cource_topics_post
and second correct this
$this->post('username');
to
$this->input->post('username');


text:
Q: How to get HDF5 chunk dimensions in existing file? I'm writing some code to remove parts of an existing HDF5 file (some dimensions, some datasets, etc.) with the C HDF5 API. I'd like the new HDF5 file to come with the same chunk size as my existing HDF5 file, but I can't seem to find anywhere that I can retrieve current chunk dimensions. There is the H5P_GET_CHUNK function, but that retrieves chunk dimensions on dataset creation only. There is also the H5D_GET_CHUNK_STORAGE_SIZE function, which only retrieves total size (not dimensions).
Is there a way to retrieve chunk dimensions (not just total size) from an existing dataset that I'm missing?

A: You may want to have a look at HDFql as it is a (much) simpler way to manipulate HDF5 files, in particular to get the storage dimensions (i.e. chunk size) of a certain dataset. As an example, if you want to get the storage dimensions of a dataset named dset do the following:
SHOW STORAGE DIMENSION dset

Additional information about this operation may be found in section 6.7.15 of the reference manual.


text:
Q: Разрешения файлов и chmod Linux Mint У меня есть файл "filee" владельцем которого я и являюсь, у меня есть права на его чтение и запись, но нет разрешения на запуск.
По этому я решил использовать chmode в абсолютном режиме для изменения прав - sudo chmod 764 filee, никаких ошибок не возникло но права не поменялись.
Помогите разобраться почему эта команда не работает, и в чем я ошибся.
На этом изображении показана последовательность выполнения моих команд:
https://cdn.discordapp.com/attachments/809274410049339452/822746972023947294/2021-03-20_17-21-42.png


text:
Q: Use $\mathbb{P}(\vert \hat{s}_n-s\vert > x)\leq a(n,x)$ and $\mathbb{P}(\vert \hat{s}_n-s_n\vert > x)\leq b(n,x)$ to bound $\vert s_n - s\vert$ Let $s, s_n\in\mathbb{R}$ and $\hat{s}_n$ be a random variable.
I have two concentration inequalities:
$$\mathbb{P}(\vert \hat{s}_n-s\vert > x)\leq a(n,x)$$ for all $n\geq1$ and $x>0$;
and
$$\mathbb{P}(\vert \hat{s}_n-s_n\vert > x)\leq b(n,x)$$ for all $n\geq1$ and $x>0$.
Is there a way to bound $\vert s_n - s\vert$?

A: Assuming that $\hat{s}_n$ is integrable,
\begin{align}
|s_n-s|&\le \mathsf{E}|s_n-\hat{s}_n|+\mathsf{E}|s-\hat{s}_n| \\
&=\int_0^{\infty}\mathsf{P}(|s_n-\hat{s}_n|>x)\,dx+\int_0^{\infty}\mathsf{P}(|s-\hat{s}_n|>x)\,dx \\
&\le \int_0^{\infty}[a(n,x)+b(n,x)]\,dx.
\end{align}


text:
Q: How to set related entity id in one to many relationship Symfony? I am trying to persist two entities that have OneToMany and ManyToOne relationships.
I'm trying to embed a collection of forms inside a form.
I have a many to one related entities and everytime I create a new CurriculumVitae which is related to Candidat the column candidat_id_id is null.
Only the entity CurriculumVitae is successfully created and persisted except the Candidat id in the data datatable.

*

*CurriculumVitae Table

id | titre | candidat_id_id | id_education
candidat_id_id is: null
id_education has this value: Doctrine\Common\Collections\ArrayCollection@000000003d585f990000000052235238

*

*Education Table is empty

id | description | id_curriculum_vitae_id
My problem is with the id_curriculum_vitae_id and the id_education.
CurriculumVitae Entity:
/**
 * CurriculumVitae
 *
 * @ORM\Table(name="curriculum_vitae")
 * @ORM\Entity(repositoryClass="GE\CandidatBundle\Repository\CurriculumVitaeRepository")
 */
class CurriculumVitae
{
    /**
     * @var Candidat
     *
     * @ORM\ManyToOne(targetEntity="GE\CandidatBundle\Entity\Candidat")
     */
    protected $candidatId;

    /**
     * @var Education
     * @ORM\OneToMany(targetEntity="GE\CandidatBundle\Entity\Education", mappedBy="idCurriculumVitae", cascade={"persist", "remove"})
     * @ORM\Column(name="id_education")
     */
    protected $educations;

/**
 * Add education
 *
 * @param \GE\CandidatBundle\Entity\Education $education
 *
 * @return CurriculumVitae
 */
public function addEducation(\GE\CandidatBundle\Entity\Education $education)
{
    $this->educations[] = $education;
    $education->setCurriculumVitae($this);
    return $this;
}

/**
 * Remove education
 *
 * @param \GE\CandidatBundle\Entity\Education $education
 */
public function removeEducation(\GE\CandidatBundle\Entity\Education $education)
{
    $this->educations->removeElement($education);
}
}

Education Entity:
/**
 * Education
 *
 * @ORM\Table(name="education")
 * @ORM\Entity(repositoryClass="GE\CandidatBundle\Repository\EducationRepository")
 */
class Education
{
    ...
    /**
     * @var CurriculumVitae
     * @ORM\ManyToOne(targetEntity="GE\CandidatBundle\Entity\CurriculumVitae")
     */
    private $idCurriculumVitae;
}

CurriculumVitaeController :
class CurriculumVitaeController extends Controller
{
    /**
     * Creates a new curriculumVitae entity.
     *
     * @Route("/candidat/cv/ajouter", name="cv_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $curriculumVitae = new Curriculumvitae();
        $form = $this->createForm('GE\CandidatBundle\Form\CurriculumVitaeType', $curriculumVitae);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($curriculumVitae);
            $em->flush();
            $request->getSession()
                ->getFlashBag()
                ->add('infoCv', 'Votre cv a été bien enregistrée.');

            return $this->redirectToRoute('cv_show', array('id' => $curriculumVitae->getId()));
        }

        return $this->render('curriculumvitae/new.html.twig', array(
            'curriculumVitae' => $curriculumVitae,
            'form' => $form->createView(),
        ));
    }
}

CurriculumVitaeType:
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('candidat', EntityType::class, array(
            'class' => 'GECandidatBundle:Candidat',
            'choice_label' => 'id',
            'multiple'      => false,
            ))
            ->add('educations',
                CollectionType::class, [
                    'entry_type' => EducationType::class,
                    'allow_add' => true,
                    'allow_delete' => true,
                    'prototype' => true,
                    'by_reference' => false,
                    'label' => 'Educations:'
                ]
            )
        ;
    }

A: Try this code and update your database's schema
/**
     * @var CurriculumVitae
     * @ORM\ManyToOne(targetEntity="GE\CandidatBundle\Entity\CurriculumVitae")
     *@ORM\JoinColumn(name="candidatId",referencedColumnName="id",onDelete="SET NULL")
     */
    private $idCurriculumVitae;

A: Sorry, i found my problem.
the id must be defined in the Controller.
$curriculumVitae->setCandidat($candidat);


text:
Q: Custom TextView not visible in 5.0 and higher devices Following is my custom TextView Class:
public class MontTextView extends  android.support.v7.widget.AppCompatTextView{
public MontTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}
public MontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}
public MontTextView(Context context) {
    super(context);
    init();
}
public void init() {
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Montserrat-Regular.ttf");
    setTypeface(tf ,1);
    }
}

And in XML I use it like this:
<com.minimalist.gorakh.customviews.MontTextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="@dimen/_20sdp"
    android:text="Text"
    android:textColor="#fff"
    android:textSize="@dimen/_25ssp"
    app:layout_constraintBottom_toBottomOf="@+id/betaView"
    app:layout_constraintStart_toStartOf="@+id/betaView"
    app:layout_constraintTop_toTopOf="@+id/betaView" />

This is working in pre-lollipop(v-19) like this:

And on a marshmallow emulator:

I copied the custom TextView code from a previous project, but couldn't get what am I doing wrong here.

A: Try this :
import android.widget.*;
import android.util.*;
import android.content.*;
import android.graphics.*;

public class MontTextView extends TextView{

    public MontTextView (Context context) {
        super(context);
        init();
    }

    public MontTextView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MontTextView (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setTypeface(Typeface.createFromAsset(getContext().getAssets(),  "fonts/Montserrat-Regular.ttf"));
    }

}


text:
Q: the grid does not appear in Share Column Configuration What code do we need to enter to make the grid appear in the share?

A: To make it work you have to be Administrator. When you change the column configuration by adding/hiding a column in the Column Configuration) of a grid and save it; then, the modified table will appear as an option when you click share the column configuration option.

A: Thanks for you answer  the grid update will active function.


text:
Q: Simple backend validation error | !preg_match I am trying to create add a very simple name regex test to my backend validation but I keep receiving an error. From my understanding there should be no issue with this and maybe I'm just tired but I could need another set of eyes on it.
The file is connected with use of a fetch call.
$nameRegex = '#/^[A-Za-z]+$/';

if(!preg_match($nameRegex, $_POST['user_first_name'])){
    _res(400, ['Info' => 'Name flaw']);
    exit();
}

Following error received is:

SyntaxError: Unexpected token < in JSON at position 0

so I would assume that it would be a very simple mistake but I can't seem to locate the error.


text:
Q: create xml list with image icons in joomla I desire to create a xml form field of type "list" which also contains images. So, form filed is like:
<field name="mylistvalue" type="list" default="" label="Select an option" description="">
  <option value="0">Option 1 (want icon here) </option>
  <option value="1">Option 2 (want icon here) </option>
</field>

Any help?


text:
Q: Serialize class with array property including index of array elements I have a class
public class clsTest
{
     public string name;

    [XmlArray(ElementName = "values")]
    [XmlArrayItem(ElementName = "value")]
    public float[] values;

    public clsTest()
    {
        name = "name-test";
        values = new float[4];
        values[0] = 0.9F;
        values[1] = 1.1F;
        values[2] = 2.2F;
        values[3] = 3.3F;
    }
}

When I serialize the class I get:
<clsTest>
    <name>name-test</name>

    <values>
          <value>0.9</value>
          <value>1.1</value>
          <value>2.2</value>
          <value>3.3</value>
    </values>

</clsTest>

I want to serialize the class and have array index in the XML output as Attribute. I would like something like this:
<clsTest>
    <name>name-test</name>

    <values>
      <value index="0">0.9</value>
      <value index="1">1.1</value>
      <value index="2">2.2</value>
      <value index="3">3.3</value>
    </values>
</clsTest>

How could I achieve this?

A: There's no magic that will do this for you. The only way you're going to get that output is if you have an object structure that looks like that.  For example:
public class ClsTest
{
    [XmlElement("name")]
    public string Name { get; set; }

    [XmlArray("values")]
    [XmlArrayItem("value")]
    public IndexedFloat[] Values { get; set; }
}

public class IndexedFloat
{
    [XmlAttribute("index")]
    public int Index { get; set; }

    [XmlText]
    public float Value { get; set; }
}

You could add another property allow you to easily get and set the raw float values:
[XmlIgnore]
public IEnumerable<float> ValuesRaw
{
    get { return Values.Select(x => x.Value); }
    set
    {
        Values = value
            .Select((x, i) => new IndexedFloat {Index = i, Value = x})
            .ToArray();
    }
}

You can see in this fiddle that you get the output you want.


text:
Q: Cores diferentes nas células Faço uma consulta e mostro o resultado em uma tabela como mostro na imagem:

Pretendo que a coluna Zona quando aparece Centro de Dia que a célula fique a vermelho, quando for Exterior a branca, quando for Centro a verde, Infância a amarelo, Lar a azul e Paróquia a castanho e também coloque na mesma cor a célula do Nº Registo.
O meu código para mostrar a tabela:
<?php
$result_cursos = "SELECT Id,
       DesTarefa,
       Period,
       Zona,
       Duracao

FROM centrodb.TarPeriodicas;";

    $resultado_cursos = mysqli_query($conn, $result_cursos);

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= 'Nº Registo	';

$tabela1 .= 'Designação da Tarefa	';

$tabela1 .= 'Período	';

$tabela1 .= 'Zona	';

$tabela1 .= 'Duração	';

$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .='
';

    while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {

$tabela1 .= '
';

$tabela1 .= ' '.$rows_cursos['Id'].'	';

$tabela1 .= ''.$rows_cursos['DesTarefa'].'	';

$tabela1 .= ''.$rows_cursos['Period'].'	';

$tabela1 .= ''.$rows_cursos['Zona'].'	';

$tabela1 .= ''.$rows_cursos['Duracao'].'	';

$tabela1 .= '
';
}
$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= '
';

echo $tabela1;

?>

A: Você pode fazer com JavaScript, assim como adicionar direto no PHP.
Com JavaScript você pode utilizar o jQuery ou Vanilla (Js Puro). Em ambos os casos basta filtrar todos os td da tabela e depois ir comparando os valores, caso o valor corresponda a um dos citados, basta utilizar:
/* JavaScript */
$(elemento).css("background", "cor");

/* JavaScript */
document.querySelector("elemento").style.setProperty("background", "cor");

Segue exemplo comentado:

/* Percorre todos os TR do corpo da tabela */
$("table tbody tr").each(function(index, tr) {

  /**
   * Captura o quarto elemento (vai de 0 até n-1).
   * Esse elemento corresponde à zona.
   */
  let td = $(tr).find("td:eq(3)");

  /* Define a cor padrão */
  let color = "while";

  /**
   * Transforma a palavra em minúsculo e verifica
   * Caso a palavra seja uma das que estão em "case",
   * define uma cor à variável.
   */
  switch (td.text().toLowerCase()) {
    case "centro de dia":
      color = "rgba(255,0,0,.4)";
      break;
    case "exterior":
      color = "#FFF"
      break;
    case "centro":
      color = "rgba(0,128,0,.4)"
      break;
    case "infância":
      color = "rgba(255,255,0,.4)"
      break;
    case "lar":
      color = "rgba(0,0,255,.4)"
      break;
    case "paróquia":
      color = "rgba(165,42,42,.4)"
      break;
  }

  /* Define a cor na cédula Zona */
  $(td).css("background", color)

  /* Define a cor na cédula Nº do Registro */
  $(tr).find("td:eq(0)").css("background", color)
});
table thead th {
  color: red;
  font-weight: bold
}

      Nº Registro
      Designação
      Período
      Zona
      Duração

      1
      Compras
      Quinzenal
      Centro de Dia
      1 Dia

      2
      Compras
      Quinzenal
      Exterior
      1 Dia

      3
      Compras
      Quinzenal
      Centro
      1 Dia

      4
      Compras
      Quinzenal
      Infância
      1 Dia

      5
      Compras
      Quinzenal
      Lar
      1 Dia

      6
      Compras
      Quinzenal
      Paróquia
      1 Dia

Como você pode criar um array com as cores e nesse array atribuir um valor CSS com o background e color.
Segue exemplo comentado:
<?php

/* Style com as cores */
$styles = [
    "Centro de Dia" => "background:#FFF;color:#F00",
    "Exterior"      => "background:#F00",
    "Centro"        => "background:#008000;color:#F00",
    "Infância"      => "background:#ffff00;color:#F00",
    "Lar"           => "background:#0000ff;color:#F00",
    "Paróquia"      => "background:#a52a2a;color:#F00",
];

$resultado_cursos = mysqli_query($conn, $result_cursos);
$tabela1 .= '
';
$tabela1 .= '
';
$tabela1 .= '
';
$tabela1 .='
';
$tabela1 .= '
';
$tabela1 .= 'Registro	';
$tabela1 .= 'Designação da Tarefa	';
$tabela1 .= 'Período	';
$tabela1 .= 'Zona	';
$tabela1 .= 'Duração	';
$tabela1 .= '
';
$tabela1 .='
';
$tabela1 .='
';

/* Percorre todos os registros */
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
    $tabela1 .= '
';

    /**
     * Verifica se a variável $styles possui o valor de Zona
     * Caso possua, atribui os valores do índice no atributo style,
     * caso contrário não imprime nada.
     */
    $zona = $rows_cursos['Zona'];
    $corZona = isset( $styles[$zona] ) ? $styles[$zona] : '';

    $tabela1 .= ' '.$rows_cursos['Id'].'	';
    $tabela1 .= ''.$rows_cursos['DesTarefa'].'	';
    $tabela1 .= ''.$rows_cursos['Period'].'	';
    $tabela1 .= ''.$rows_cursos['Zona'].'	';
    $tabela1 .= ''.$rows_cursos['Duracao'].'	';
    $tabela1 .= '
';
}

$tabela1 .='
';
$tabela1 .= '
';
$tabela1 .= '
';


text:
Q: Why special characters like () "" : [] are often removed from data before training translation machine? I see that people often remove special characters like () "" : [] from data before training translation machine. Could you explain for me the benefits of doing so?

A: Date clean-up or pre-processing is performed so that algorithms could focus on important, linguistically meaningful "words" instead of "noise". See "Removing Special Characters":

Special characters, as you know, are non-alphanumeric characters.
These characters are most often found in comments, references,
currency numbers etc. These characters add no value to
text-understanding and induce noise into algorithms.

Whenever this noise finds its way into a model, it can produce output at inference, that contains these unexpected (sequences of) characters, and even affect overall translations. It is a frequent case with brackets in Japanese translations.


text:
Q: SQL Inner Join on 2 conditions where possible I have the following data in a mapping table:
ID1         LOCALID         ID2
Local_-1    BankA_7-9       Local_2647
Local_0     Bank_7-9        Local_2647
Local_2624  BGROMF          NULL
Local_2619  BIS             NULL

ID2 is nullable.
My second table looks like:
ID1        ID2
Local_-1   Local_2674
Local_0    Local_2674
Local_2624 Local_2674
Local_2619 Local_2674

How do I inner join the tables with the following condition? Is it possible to do this without an if statement?
If ID2 in the mapping table is null just join on ID1 otherwise join on ID1 and ID2.
My starting point (which will obviously exclude the null values) is:
SELECT * FROM
    #Table2 C
     INNER JOIN Mapping F
                  ON C.ID1 = F.ID1 AND
                  C.ID2 = F.ID2

A: SELECT * FROM
    #Table2 C
     INNER JOIN Mapping F
                  ON C.ID1 = F.ID1 AND
                  C.ID2 = ISNULL(F.ID2, C.ID2)

A: Use the query
SELECT * FROM
    #Table2 C
     INNER JOIN Mapping F
       ON C.ID1 = F.ID1 AND
       C.ID2 = F.ID2ffgffgf


text:
Q: This pandas series is a view... into what? Consider the following example.
import pandas as pd

df = pd.DataFrame({
    "x": [1, 2, 3],
    "y": [4, 5, 6]
})

x = df["x"]
df.drop(index=[0], inplace=True)

Now we have x._is_view is True, so I would expect x to be a "view" into df. In other words, I would expect x to be identical to df["x"].
However, x still contains the values [1, 2, 3], while df["x"] only contains the values [2, 3].
In what sense is x a view?
P.S. In my head, I have been imagining that df.drop(..., inplace=True) is literally dropping rows of df from memory. Perhaps this is not the case...

A: inplace does not guarantee that the dataframe will be modified in place. In this case, as in many cases, it creates a copy and reassigns it to df. See the discussion of inplace here.
As for x being a view, if you execute x.values.base you will get:
array([[1, 2, 3],
       [4, 5, 6]])

Thus, x is a view of the original dataframe, which is not assigned to df anymore.
Here is another way to verify it:
import pandas as pd
import numpy as np

df = pd.DataFrame({
    "x": [1, 2, 3],
    "y": [4, 5, 6]
})
df_arr = df.values # numpy array underlying df
x = df["x"]
df.drop(index=[0], inplace=True)

Now if you run
np.shares_memory(df_arr, x.values)

the result is True, since x occupies the same space in the memory as df originally did. On the other hand
np.shares_memory(df_arr, df.values)

returns False, because values of df now reside somewhere else.

A: As mentioned in the previous answer.  inplace does not guarantee it won't be copied.  You can inspect the unique id of each object to proof it out.
import pandas as pd

df = pd.DataFrame({
    "x": [1, 2, 3],
    "y": [4, 5, 6]
})

x = df

print(f'Original: {id(df)}')
print(f'View:     {id(x)}')
print(f'Copy:     {id(df.drop(index=[0], inplace=True))}')

Out[1]
Original: 2570551559120
View:     2570551559120
Copy:     140708949432448


text:
Q: PySpark remove special chars in all col names for all special chars - error cannot resolve given column I'm trying to remove special characters from names in a dataframe created from a csv.  There are 100's of columns some with long names. I've tried a number of approaches all returning an error on at least one of the columns?
df = spark.read.format("com.databricks.spark.csv") \
  .option("mode", "DROPMALFORMED") \
  .option("header", "true") \
  .option("inferschema", "true") \
  .option("delimiter", ",").load(getArgument('sourceCSVpath') + getArgument('sourceCSV'))

df = df.select([F.col(col).alias(re.sub("[^0-9a-zA-Z$]+","",col)) for col in df.columns])

temp_df1 = df.select([F.col(col).alias(col.replace('- ', '')) for col in df.columns])

ERROR
cannot resolve 'Organization - No. Of Employees - Employee Figures Date' given input columns
Domestic Ultimate Employee Information Scope Code,NACE Revision 2 Description - Priority 4,NACE Revision 2 Description - Priority 5,NACE Revision 2 Description - Priority 6,Organization - No. Of Employees - Employee Figures Date,Number of Employees Scope Text,Organization Founded Date,NACE Revision 2 Description - Priority 1
9067,,,,,Headquarters Only (Employs Here),1997,Hospital activities
9067,,,,,Headquarters Only (Employs Here),1997,Hospital activities
9067,,,,,Headquarters Only (Employs Here),1997,Hospital activities
9067,,,,,Headquarters Only (Employs Here),1997,Hospital activities
9067,,,,,Headquarters Only (Employs Here),1997,Hospital activities

A: To remove dots (or any other unwanted characters) from the column names you can use DataFrame.toDF:
temp_df1 = df.toDF(*[re.sub("\.", "", col) for col in df.columns])

toDF only takes the order of the columns into account. The original names of the columns which could cause troubles in a select statement are not used.


text:
Q: Are there any patterns in GoF? I'm currently learning for a Design Patterns exam (which will take place tomorrow...). In one of the "test exams" I found the following question:

Jim Coplien said during the invited lecture that there is not even one
  design pattern in the GoF book. What is your opinion about this?

Because I wasn't in this particular lecture (it was last semester ;) I have no clue what he could have meant. And I have no evidence that Jim Coplien said it, but I think that doesn't matter.
What do you think could he meant with this statement?
(I'm not sure if the question is appropriate for this forum, however, I wanted to ask.)

A: Patterns: The Notion is Grounded in Alexander's Work
The GoF claims to take its pattern inspiration from Christopher Alexander (as they say in the front matter of the book), who popularized the term in the broader field of design. To Alexander a pattern: is always an element of pattern language; contributes to deep human feeling; and is always geometric in nature. At least some of the GoF patterns fail on at least one of these points, and several fail on all three. Although "pattern" is a neutral English language word, the cultural and historic roots of the GoF work, combined with their invocation of Alexandrian inspiration, leave it subject to judgment by the fundamental criteria of its ancestor, and it comes up lacking. Even though they know, and express that they know, that they diverge some from Alexander, they still choose to use a term that he crafted, researched, and popularized, and I hold them accountable for that. (That said, they are all valued acquaintances; I was close to John Vlissides, whom we lost several years ago, and have had great dialog with Richard Helm and Eric Gamma on the deeper issues behind this. My discussions with Ralph have been less interesting as they stop at the engineering level.)
Historical Roots
Words mean things. The Alexandrian sense of the term "pattern" was not well understood by the GoF (or by the software community as a whole) when they wrote the book, but they built on the vulgar perception of the time, which was grounded in three sources: 1. Erich Gamma's Ph.D thesis; 2. Ralph Johnson's framework work, and 3. the C++ idioms book (you can find this in the GoF book's own explanation of its sources in section 6.3). (Oh, Knuth was also an influence.) I continued to challenge the authors about it but people liked it, and they liked that people liked it, so the momentum continued.
Several years later (2 December 2004) one of the GoF would write to me to describe his "aha" experience of finally understanding what Alexander was trying to convey. It was quite a bit different than what underlies the content of the GoF book:

Finally grok'ed "generative patterns" and piecemeal growth through a long tortuous route....
  Largely through some interesting universal properties of software (scale-free and
  small-worldness)
A bit slow I am sometimes... but got there in the end...

GoF Patterns Address a Problem of Accidental, rather than Essential, Complexity
That people find them useful as they do is, unfortunately, an indictment of modern programming languages. The languages don't have the proper constructs to express the broken symmetry that Alexander holds to be characteristic of patterns, and which are intrinsic to complex design (Nature of Order, p. 187: "...in general, a large symmetry of the simplified neoclassicist type rarely contributes to the life of a thing, because in any complex whole in the world, there are nearly always complex, asymmetrical forces at work—matters of location, and context, and function—which require that symmetry be broken"; op cit., pp. 63-4: "Nature, too, creates beautiful structures which are governed by repeated application of structure-preserving transformations. In this connection, I think it is useful to remark that what I call structure-preserving transformations are very closely related to what has become known as "symmetry breaking" in physics."). Java in particularly bad about this but so is its ancestor Smalltalk. C++ is rich in features to describe local symmetry-breaking but most people don't really know how to use them. Richard Gabriel – who has also worked closely with Alexander, and who has languages like CLOS and Scheme to his credit — says that he simply doesn't understand the GoF patterns because a properly designed language (like CLOS or Scheme) doesn't need them. I am largely in that same camp.
The Design Movement
There's a lot of design theory behind this that goes back to the Design Movement (Thackara ("Design after Modernism", 1989), Naur, Alexander, Cross ("Developments in Design Methodology," 1984) and other authors in the 1980s). It has always amazed me how little programmers know of this body of literature and how wrong-headed much CS thinking is in light of the obvious findings of the work of the Design Movement at this time. Those of us who founded the pattern discipline (the original 7 of The Hillside Group) back in 1993 were familiar with the major themes of this literature. The PLoP conferences evolved a body of literature that devolved radically from these foundations, being more focused on arcane knowledge than the "quality without a name" that Alexander sought.
Origins of Idioms
The reason I introduced idioms for C++ programmers was to allow them to do object-oriented programming when the language got in their way. Now, we have more powerful approaches like DCI that greatly reduce the need for idioms. Patterns still apply at the domain level — which is in line with Alexander's vision. There have been a few good pattern languages written; e.g., by Hanmer (Patterns for Fault-Tolerant Software, 2007); by Eloranta et al. (Designing Distributed Control Systems, 2014), and the Organisational Patterns which Alexander himself noted met the necessary criteria (Coplien and Harrison, 2004).
The Battle Lost, but the Work Continues
Alexander and I (and Richard Gabriel — read his "Patterns of Software" — and others as well) share disappointment in this early redirection of a term that had been well-established in design before being re-defined by GoF. Yes because they call them Design Patterns, they are Design Patterns — in the context of any discussion about the Design Patterns book by the Gang of Four. In the broader scheme of design theory and architecture, they are not: they are only idioms. Even as the authors themselves say, that's how they started out.
There are several efforts afoot to restore Alexander's vision to the software community. The ScrumPLoP® community (http://scrumplop.org) takes all the Alexandrian groundings of patterns very seriously. An old-time Alexandrian colleague, Greg Bryant, who used to do the IT stuff for CES, has reached out to me and told me of his work to get Alexander's vision back into software, and we're about to trade notes. I'm sure that Dick Gabriel always has something in mind as well though he and I haven't chatted for a while. In the mean time I continue to work directly with Alexander's colleague, Hiroshi Nakano, who connects Alexander's ideas (which he expressed directly in terms of the Tao te Ching in Timeless) directly into their parallels in Japanese culture. It's a much better fit than to try to shoehorn it into Western culture. That probably explains some of the frustration in being able to understand my claim — though it's not an excuse for a professional working in the knowledge business.
An Exhoratation to the Grumblers
Of course, all of this grounding is a matter of published dialectic and research and is available to anyone willing to take the time to research it. It is not as casual a matter as can be quickly dismissed as it was here. It took me 20 years — and I had direct access to the sources. I can appreciate that it's difficult for the average programmer to dig into these things, but I would suggest doing a bit more research before dismissing a well-researched position out-of-hand, before doing one's homework. It's a StackOverflow thing.

A: By the GoF's own definition, it's full of design patterns. So by inference, Coplien has a different definition of a design pattern, or Coplien has misunderstood or misreptresents GoF's definition, or he argues that the GoF definition does not match the GoF patterns.
The question invites you to describe the differences between the two definitions, and provide your opinion on which definition you prefer. Probably your REASONED opinion, as in academia your reasons for your opinion (methodology) matter a lot more than the the opinions themselves.


text:
Q: OBIEE remove dimension value based on measure result One of my dimension contains the different divisions of the company. I have one division which doesn't exist anymore but I want to keep this to check the results of previous years and months.
How do I dynamically eliminate this value of the dimension when it doesn't have a measure anymore?
First I was thinking that adding a filter where the measure should be > 0 or 'not null' but this doesn't seem to do the trick. The dimension keeps showing up.
Thanks!

A: To go a bit into more details on Robin's question which is the most pertinent one:
Do you try to remove the "obsolete" dimension member from dimension-only queries - like prompts for example?
This is crucial to know as forcing a normally dimension-only query over a fact and thus continuously forcing the inclusion of the fact table for all queries potentially has quite a performance impact.
a) ">0" and "is not null are two completely different things and if used in a cavalier fashion can also yield absolutely wrong results. What if the measure is at a negative value? That would make it "disappear" as well for you. What if there simply is no measure yet but the dimension member is implicitly actually valid just not filled yet? That would also make it disappear for you.
b) How can you know the point of view a user is standing at? For an analysis run for last year this will be perfectly valid to show?
c) What about time-variant comparisons? What about rolling calculations?
d) What about the point-in-time of the dimension rather than the fact? --v
e) What about cross-org analysis like "What do our numbers look like when we apply last year's org vs this year's vs a planned new one which is already loaded into the data source?
While I understand the idea behind your question you should not forget that we're talking analytics here and always face changing dimensions and attributes so your request which seems valid from a human point of view for that one, specific use case is - for the solution as a whole - to be considered wisely.

A: Although I'm not clear on what you mean by "eliminate this value of the dimension", I think you may be looking for the pivot measure function, called FILTER(Fact USING (Insert your filter here)).
I am assuming that when aggregating using a measure, your problem is that you are unable to exclude the Division that does not exist anymore, and as a result, your measures/aggregations are incorrect.
In this case, you should use the pivot measure as I indicate above.

Your column formula would look like this:
FILTER(Measure1 USING ("SubjectArea1"."Division" <> 'DivisionName'))

Follow these steps to implement this function:

*

*Edit the column formula of your measure.

*Highlight the formula of the column and click the Filter... button at the bottom of the Column Formula text box. An Insert Filter window will appear.

*Select the Division column from the Subject Areas pane. (Either double-click it, or select it then click the OK button).

*You will see a New Filter window. Change the Operator to is not equal to / is not in.

*Select your Division that you want to exclude.

*Click OK to close the New Filter window.

*Click OK again to close the Insert Filter window.

*Click OK again to close the Edit Column Formula window.

*If your syntax is correct, you will see no errors.


text:
Q: ReportScore GameCenter method not found I am trying to upload my scores for my game to Gamecenter, however I cannot write code to do that without getting errors. Also, it says that there is no class method for reportScores:scores. I am not sure how to implement that into the Gamecenter Class.
-(void) reportScore: (int64_t) score forLeaderboardID: @"tap_amateur" identifier

{

    GKScore *scoreReporter = [[GKScore alloc] initWithLeaderboardIdentifier:@"tap_amateur"];

    scoreReporter.value = score;

    scoreReporter.context = 0;

    NSArray *scores = @[scoreReporter];

    [GKLeaderboard reportScores:scores withCompletionHandler:^(NSError *error) {

    }];

}

@end

A: Try changing:
[GKLeaderboard reportScores:scores withCompletionHandler:^(NSError *error) {

}];

to:
[GKLeaderboard reportScoreWithCompletionHandler:
     ^(NSError* error) {

         [self setLastError:error];

         BOOL success = (error == nil);

         if ([_delegate
              respondsToSelector:
              @selector(onScoresSubmitted:)]) {

             [_delegate onScoresSubmitted:success];
         }
     }];


text:
Q: find number of detected devices in tensorflow As the title already says I want to find out the number of devices (cpus or gpus) that tensorflow is able to detect or make use of.
The reason for this question is because I'm running keras with tf backend on a machine with multiple cpus, but it uses only a single CPU at runtime.

A: Look at this bug report regarding CPU scaling ; https://github.com/tensorflow/tensorflow/issues/583
It was supposedly resolved with change ab02c5, issued at the beginning of May 2016. Try building tensorflow from source to get all the latest updates, which are most likely not in the stable version.