text:
Q: Normalizing a score based on multiple weighted features I'm trying to define a score for people based on multiple features that each of them have different weights.
The problem I have is that I need to make a formula to normal each score comparing to itself.
Example:
A person with a submitted posts, b published posts, c rejected posts and d reported posts.
Now the person's score is
case when rejected posts > 0  then -x else 0 end + case when reported posts > 0 then -y else 0 end

*

*x, y are weights
As you can see the number of posts a person submitted or published is not in this score which makes it wrong. Because there should be a difference between a person with 10 submitted posts and 10 rejected posts RATHER than a person with 200 submitted posts and 10 rejected posts.
What is the best way to normal this score?

*

*Note : I tried the ((rejected/submitted)*(-x)) too but it doesn't clarify the differences between people very well.


text:
Q: Download music file from server and save in my app I need to download an .mp3 audio file from a server to save in my app and play it without downloading, exactly like the screenshot below, with a progress  bar for the download (I found this in the App Store). Can anyone help me to do this in my app, with source code?
Any help will be appreciated! Thanks in advance!
I used NSURLConnection but it does not really work for me.
Here is the screenshot of what I am trying to do.

A: This questions discusses what you're looking for
Edit:
If you want to download a file THEN play it, what you need to do is:
use an NSURLConnection to download the file to the disk - this link discusses saving large files (i wouldn't keep 2-5mb's in the memory when i don't need them even thought it will probably work).
, than an AVAudioPlayer to play it - check this out.
Edit 2:
For the cancel button, it should practically just call the [NSURLConnection cancel] method and do whatever other finishing up your download class is gonna need...
For the progress bar, in the NSURLConnectionDelegate method didReceiveResponse, you take the NSURLResponse, cast it to a NSHTTPURLResponse, and retrieve the size of the file you're downloading using the expectedContentLength method.
And then in each call to the NSURLConnection:didRecieveData method you count the incoming bytes using [data length] method, divide it by the expectedContentLength from the previous URL response and that's the float the represents your progress that you pass to the progress view's progress property

A: Yes,first one.I wana download the file in my app and show it in table view then play it after download it. – DAVEd Apr 11 '11 at 14:34

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mozilla select option tick icon ugly I am on Mac and noticed that the tick icon of a select option looks like this in Mozilla Firefox:

I'm intended to change the icon to look like in Safari and Google Chrome. Like this:

Anyone knows how to style the select or option element with CSS in order to achieve this?

A: These icons depend on the font that you use.
If you didn't select yours then the default is used.
Not every web browsers has the same configured and that becouse they are different.
Check this answer:
How to draw a checkmark / tick using CSS?
How to change this should be solved right there^.


text:
Q: Send message to user on ConversationUpdate event in Bot Framework In Bot Framework documentation there is a good example where mentioned how to handle ConversationUpdate event which allows to initiate message to user when he connects:
bot.on('conversationUpdate', function (message) {
    if (message.membersAdded && message.membersAdded.length > 0) {
    bot.send(new builder.Message()
        .address(message.address)
        .text('Hello user, good to meet you!'));
    }
});

What if function (message) defined in other .js file module, like this:
var dialog = require("./rootdialog");
bot.on("conversationUpdate", dialog.ConversationUpdate);

How to send message in this case as bot variable is not accessible there?

A: One trick which comes to my mind is implementing a universal function which return a function. Then, pass the bot to an universal function and return the required callback function as its result:
 function ConversationUpdate(bot)
 {
      return (message) => {
          if (message.membersAdded && message.membersAdded.length > 0) {
              bot.send(new builder.Message()
             .address(message.address)
             .text('Hello user, good to meet you!'));
          }
      }
 }

So, you can write what you want as the following:
var dialog = require("./rootdialog");
bot.on("conversationUpdate", dialog.ConversationUpdate(bot));


text:
Q: Orthogonal projection to closed, convex subset in a Hilbert space I don't understand one step in the proof of the following lemma (Projektionssatz):
Let $X$ a Hilbert space with scalar product $(\cdot)_X$ and let $A\subset X$ be convex and closed. Then there is a   unique map $P:X\rightarrow A$ that satisfies: $\|x-P(x)\| = \inf_{y\in A} \|x-      y\|$. This is equivalent to the following statement:
(1) For all $a\in A$ and fixed $x\in X$, $\mbox{Re}\bigl( x-P(x), a-P(x) \bigr)_X \le 0$.
I don't understand the following step in the proof that (1) implies the properties of $P$:
Let $a\in A$. Then
$\|x-P(x)\|^2 + 2\mbox{Re}\bigl( x-P(x), P(x)-a \bigr)_X + \|P(x)-a\|^2 \ge \|x-P(x)\|^2$.
I don't understand the "$\ge$". How do we get rid of the term $\|P(x)-a\|$ on the left hand side?
Thank you very much!

A: It is non-negative! Hence, just drop it.


text:
Q: redirect stdout/stderr to function in C I want to redirect stdout and stderr to a function and write a simple code.
fprintf is ok but when i use printf without \r, stream passed to terminal!
#include <stdio.h>
static ssize_t file_write(void *c, const char *buf, size_t size)
{
  FILE * pFile;
  pFile = fopen ("output.txt","w");
  fprintf(pFile, "%s", buf);
  fclose (pFile);

return size;
}

void redirect()
{
  FILE *stream;
  stream=fopencookie(NULL, "w", (cookie_io_functions_t) {(ssize_t) 0,  file_write, 0, 0});
  setbuf(stdout, NULL);
  stdout = stream;
  setbuf(stderr, NULL);
  stderr = stream;
}

int main()
{
  redirect();
  fprintf(stderr,"1-stderr test\n");
  fprintf(stdout, "2-stdout test\n");
  printf("3-printf with r test\n\r");
  printf("4-printf without r test\n");

return 0;
}

file "output.txt":

1-stderr test
  2-stdout test
  3-printf with r test

Terminal output:

$ ./sample
  4-printf without r test

A: You can't "redirect" standard input from, or standard output to a function in your program.
You can however create a pair of pipes and replace standard input and output with these pipes, and have another function (possibly in another thread or even a child process) use the other end of the pipes to communicate with the function.
You can of course use e.g. setvbuf to change the buffers of stdin and stdout to a pair of buffers you provide, then you can read directly from, or write directly to the buffers like any other memory buffer (i.e. array). Not that I recommend it though, it's frail and prone to errors.
However in this case it seems like what you want is that all writing to stdout should go to the file. In that case (like the use of pipes) there is no standard C way of handling it, but you need to use operating system specific functionality. Then if you're on a POSIX platform (like Linux or OSX) you can tell the operating system to duplicate the underlying file descriptor for your file, and say that STDOUT_FILNO (which is the file descriptor used for stdout) is a duplicate for the file descriptor of the file you opened. Then all writes to stdout will be written to your file. For this you need to use the dup2 system call.


text:
Q: After checking session it is not redirecting to another page Here is my code in which i am checking if session variable is not set then it will redirect to another page:
if (!isset($_SESSION)) {
        session_start();
    }
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
}

Problem: It is not redirecting to another page BUT if i change this line
header("location: http://myweb.com/rel_notes/?page_id=779");

to
die("You aren't allowed to access this page");

then it works. So Kindly tell me why it is not redirecting to another page?
EDIT: This is my whole code of that wordpress page im currently working on:
<?php
ob_start();
session_start();
if (!isset($_SESSION['username']))
 {
 header("location: http://myweb.com/rel_notes/?page_id=779");
 exit();
 }

 if (isset($_POST["cancel"]))
{
 if (!isset($_SESSION)) {
        session_start();
    }
    session_unset();
    session_destroy();
 header("location: http://myweb.com/rel_notes/?page_id=779");
    exit();
  }
 ?>
 <form  method="post" enctype="multipart/form-data">
 <div align="right">
  <input class="btn btn-primary" type="submit" value="Log Out" name="cancel" id="cancel" style=""/>
 </div>
 </form>

A: Try like this. If this is just the code it will work fine.
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
}

If you have any other code after this you may get headers already sent notice.
EDIT :
You can even achieve this using JS. [However , I personally don't recommend]
<?php
session_start();
if (!isset($_SESSION['username']))
{
    //header("location: http://myweb.com/rel_notes/?page_id=779");
    echo "<script>document.location.href='http://myweb.com/rel_notes/?page_id=779'</script>";
    exit;
}

A: Is there any output above this code? header("location: ..."); works only if there was no output yet. If you need it nonetheless, add ob_start(); at the top of your script.


text:
Q: Uncaught TypeError: Cannot call method 'toJSON' of undefined in backbone       var Person = Backbone.Model.extend({
    defaults: {
        name: "John Doe",
        age: 27,
        designation: "worker"
    },
    initialize : function(){
        this.on("invalid",function(model,error){
            alert(error);
        });
    },
    validate: function(attrs){
        if(attrs.age < 0){
         return 'Age must be positive,stupid';
        }
        if( ! attrs.name ){
            return 'Name should not be empty';
        }
    },

    work: function(){
        return this.get('name') + ' is a ' + this.get('designation');
    }
});

var PersonCollection = Backbone.Collection.extend({
    model: Person
});

var peopleView = Backbone.View.extend({
    tagName: 'ul',
    render: function(){
        //filter through all the items in a collections
        //for each, create a new PersonView
        //append it to root element

        this.collection.each(function(person){
            //console.log(person);
            var personView = new PersonView({model:person});
            this.$el.append(personView.render().el);
        },this);
    }
});

// The view for a Person
var PersonView = Backbone.View.extend({
    tagName : 'li',
    className : 'person',
    id : 'person-id',
    template: _.template( $('#personTemplate').html() ),
    initialize : function(){
        _.bindAll(this,'render');
        //console.log(this.model)
        this.render();
    },

    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

var modelperson = new Person;
var viewperson = new PersonView({model : modelperson});

var personCollection = new PersonCollection([
    {
        name: "raghu",
        age:24
    },
    {
        name: "shashank",
        age:23,
        designation: "CTO"
    },
    {
        name : "junaid",
        age : 30,
        designation : "UI"
    },
    {
        name: "vishnu",
        age: 23,
        designation: "content developer"
    }

    ]);

var peopleView = new PersonView({collection: personCollection});

I got the error like call to 'toJSON' undefined, I dont know how to get rid of this.

A: You need to pass model in your view
Change the last line of your code
var peopleView = new PersonView({collection: personCollection});

to
var peopleView = new PersonView({collection: personCollection,model:new Person()});

Demo
Updated, I think its peopleView instead of personView so the last line should be like,
 var pw = new peopleView ({collection: personCollection});
 pw.render();

then you need to change your peopleveiw like,
var peopleView = Backbone.View.extend({
    tagName: 'ul',
    render: function(){
        //filter through all the items in a collections
        //for each, create a new PersonView
        //append it to root element

        this.collection.each(function(person){
            //console.log(person);
            var personView = new PersonView({model:person});
            this.$el.append(personView.render().el);
        },this);
        // apend the element to body if not exists
        $(this.$el).appendTo('body');
    }
});

Updated Demo

A: Here is much cleaner code,which works at my end. Remember I'm using handlebars for templating, however the choice is your to use the templating library which you are comfortable with.
  var Person = Backbone.Model.extend({
      defaults: {
      name: "John Doe",
      age: 27,
      designation: "worker"
      },
      initialize : function(){
      this.on("invalid",function(model,error){
          alert(error);
      });
      },
      validate: function(attrs){
      if(attrs.age < 0){
       return 'Age must be positive,stupid';
      }
      if( ! attrs.name ){
          return 'Name should not be empty';
      }
      },
      work: function(){
      return this.get('name') + ' is a ' + this.get('designation');
      }
  });

  var PersonCollection = Backbone.Collection.extend({
      model: Person
  });

  var PersonView = Backbone.View.extend({
      el : "#list",
      render: function(){
      this.collection.each(function(person){
          var personViewItem = new PersonViewItem({model:person});
          this.$el.append(personViewItem.render().el);
      },this);
      }
  });

  // The view for a Person
  var PersonViewItem = Backbone.View.extend({
      tagName : 'li',
      className : 'person',
      template : Handlebars.compile($('#template').html()),
      initialize : function(){
         _.bindAll(this,'render');
         this.render();
      },
      render: function(){
          this.$el.html(this.template(this.model.toJSON()));
          return this;
      }
  });

  var personCollection = new PersonCollection([{name: "raghu",age:24},{name: "shashank",age:23,designation: "CTO"},{name : "junaid",age : 30,designation : "UI"},{name: "vishnu",age: 23,designation: "content developer"}]);
  var peopleView = new PersonView({collection: personCollection});
  peopleView.render();


text:
Q: Lubuntu sound icon not reopening I am running Ubuntu 12.04.1 with Lubuntu and I am having an issue with the sound icon. When I open it and close it it will not open anymore. Only when I restart my computer will it open again.

A: Try reinstalling indicator-sound
sudo apt-get install indicator-sound


text:
Q: Using checkbox to determine session or cookie - php Right.. So i have this little proglem with my code. I get an all familiar ' Undefined index ' on a checkbox not checked. The thing I want to achieve is as follows: If checked - use cookies, if not - use sessions. Let me post the code fer ye.
HTML:
<input type="checkbox" id="remember_me" name="remember_me"/>Remember me!

PHP:
if ($login_ok == true)
{
    if ($remember_me == "on")
        setcookie('username', $username, time() + 7200);
    else if ($remember_me = "")
        $_SESSION['username'] = $username;

    header('Location: userprofile.php');
    exit();
 }
 else {
     die ('Wrong userrrname / password');
 }

A: Your setting the $remember_me variable in the else if statement
Change this
$remember_me = ""

To this
$remember_me == ""

A: html forms do NOT send values for unchecked checkboxes.
Where you  have:
$remember_me = $_POST['remember_me'];

You will get the undifined index error is remember_me checkbox is unchecked.
Change to
$remember_me = isset($_POST['remember_me'])?$_POST['remember_me']:'';

This sets the variable to an empty string if the checkbox is unchecked, allowing the rest of your code to function.
That aside, sessions use cookies to function


text:
Q: Change css for a new row added in TableView Javafx I'm sorry for mistake I'm french.
So I have a tableView empty. I have a button "Add" when on click added row in a tableView. And when I select an row in my tableView, a new button "Cancel" show.
And when I click on a button "Cancel", the row's css change on my row selected (added a class css ".cancel").
The problem is that I click on button "Cancel", and after I click in the button "Add", the css ".cancel" is applicated at an other row while I don't clicked in the button "Add".
I think that there is a problem in index row.
In my method initialize :
articleTable.setRowFactory(param -> new TableRow<LigneTicket>() {
        @Override
        protected void updateItem(LigneTicket paramT, boolean empty) {
            super.updateItem(paramT, empty);
            if (!isEmpty() && paramT != null && paramT.getArticle().isArticleCanceled()) {
                getStyleClass().add("cancel");
            }
        }
    });

my code on button "Cancel" :
    public void cancelLigneTicket() {
    int indexSelected = articleTable.getSelectionModel().getSelectedIndex();
                     articleTable.getItems().get(indexSelected).getArticle().setArticleAnnuler(true);

articleTable.getSelectionModel().clearSelection();

List<LigneTicket> items = new ArrayList<>(articleTable.getItems());

articleTable.getItems().setAll(items);

buttonAnnulArt.setVisible(false);

Help !!
Thanks.

A: TableRows are used to display the table items. That doesn't mean however, that it will be used with only one item.
This can result in the following sequence of events for a row r:

*

*The item of r is updated to a canceled item and thus the cancel CSS class is added.

*The item of r is updated to a non-canceled item, but the cancel CSS class is not removed.

You need to remove the class again. Furthermore with your code the style class could be added multiple times leading to unnecessary memory consumption.
boolean canceled = !empty && paramT != null && paramT.getArticle().isArticleCanceled());
if (canceled) {
     if (!getStyleClass().contains("cancel"))
          getStyleClass().add("cancel");
} else {
     getStyleClass().remove("cancel");
}

or using PseudoClass:
private static final PseudoClass CANCELED = PseudoClass.getPseudoClass("cancel");

...
pseudoClassStateChanged(CANCELED, !empty && paramT != null && paramT.getArticle().isArticleCanceled());

Furthermore you should prefer the TableView.refresh (available in JavaFX >= 8u60) method to refresh the cell items instead of copying the list and setting the items.


text:
Q: Getting 404 on my app I have a GAE application I'm developing. I've been away for about two weeks and have not used the app. Today I get a 404, not found. How could my app disappear? I can still log in as administrator and the app seems to be set up correctly but even using the links from admin I get a 404.

A: A GAE app doesn't disappear with a 404 error...
You should have another setup issue.
Have a look to the tutorial


text:
Q: Spring kafka Consumer Not Working When deployed in Tomcat I  have a spring kafka consumer that reads  messages from a topic and writes to another topic . I am using spring kafka 2.1.8. When this application is running as spring boot it works fine.When deployed as a war to an external tomcat server (tried pivotal tc server on my workstation as well as an external tomcat server),consumer reads one message ,send to  downstream topic and is stuck. All that I can see is the heart beat message send to the co ordinator. Exact same code process 100's of messages when run as spring boot. I am not sure if this has something to do with spring kafka or my ignorance with spring boot.
@Bean
      public Map<String, Object> consumerConfigs() {
        Map<String, Object> consumerProperties = new HashMap<>();
        consumerProperties.put("bootstrap.servers", kafkaConfigService.getKAFKA_BOOTSTRAP_SERVERS());
        consumerProperties.put("client.id", "rawlogs_client");
        consumerProperties.put("group.id", "rawlogs_etl");
        consumerProperties.put("enable.auto.commit", "false");
        consumerProperties.put("session.timeout.ms", "30000");
        consumerProperties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        consumerProperties.put("value.deserializer", "io.confluent.kafka.serializers.KafkaAvroDeserializer");
        consumerProperties.put("schema.registry.url", kafkaConfigService.getKAFKA_SCHEMA_REGISTRY_URL());
        consumerProperties.put("isolation.level", "read_committed");
        consumerProperties.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
        consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        consumerProperties.put("max.poll.records", "100");
        return consumerProperties;
      }
         @Bean
      public ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
          ConsumerFactory<String, SpecificRecord> kafkaConsumerFactory
         ) {
        ConcurrentKafkaListenerContainerFactory<String, SpecificRecord> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.getContainerProperties().setTransactionManager(kafkaTransactionManager());
        factory.getContainerProperties().setAckMode(AckMode.BATCH);
        factory.getContainerProperties().setIdleEventInterval(60000L);
        factory.getContainerProperties().setAckOnError(false);
        factory.setRetryTemplate(getRetryTemplate());
        factory.getContainerProperties().setConsumerTaskExecutor(threadPoolExecutor());
        return factory;
      }

               @Bean
              public RetryTemplate getRetryTemplate() {
                  RetryTemplate retryTemplate = new RetryTemplate();
                  FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
                  backOffPolicy.setBackOffPeriod(1000);
                  RetryPolicy retryPolicy = new SimpleRetryPolicy();
                  retryTemplate.setBackOffPolicy(backOffPolicy);
                  retryTemplate.setRetryPolicy(retryPolicy);
                  retryTemplate.registerListener(retryListener());
                  return retryTemplate;
              }
    @Bean
     public  ThreadPoolTaskExecutor threadPoolExecutor() {
             ThreadPoolTaskExecutor executor= new ThreadPoolTaskExecutor();
             executor.setMaxPoolSize(3);
             executor.initialize();
             return executor;
         }


text:
Q: Why is atan2 and asin so much faster in JS than in JVM? I have two almost identical pieces of code. One is running Scala on JVM, second is running Javascript. Both perform lots of atan and asin calls (this is extracted from the real application performing quaternion to Euler angles conversion). The Javascript implementations runs an order of magnitude faster.
The JS version takes about 1 000 ms on my machine. The Scala code takes about 10 000 ms when running on JVM, but when compiled using Scala.js it is again running for about 1000 ms (see ScalaFiddle).
What is the reason for such huge performance difference? What changes would I have to implement for the JVM code run this fast?

var size = 100000;
var input = new Array(size);

function fromQuaternion(a, b, c) {
    return Math.asin(a) + Math.atan2(a, b) + Math.atan2(b, c);
}

function convert() {
    var sum = 0;
    for (var i = 0; i < size * 3; i += 3) {
        sum += fromQuaternion(input[i], input[i+1], input[i+2]);
    }
    return sum;
}

for (var i = 0; i < size * 3; i += 3) {
    input[i + 0] = Math.random();
    input[i + 1] = Math.random();
    input[i + 2] = Math.random();
}

var total = 0;
for (var i = 0; i < 10; i++) total += convert();

var start = Date.now();
for (var i = 0; i < 100; i++) total += convert();
var end = Date.now();
console.log("Duration " + (end - start));
console.log("Result " + total);
document.write("Duration " + (end - start));

  val input = Array.fill(100000) {
    val x = util.Random.nextDouble()
    val y = util.Random.nextDouble()
    val z = util.Random.nextDouble()
    (x, y, z)
  }

  def fromQuaternion(a: Double, b: Double, c: Double): Double = {
    Math.asin(a) + Math.atan2(a, b) + Math.atan2(b, c)
  }

  def convert = {
    input.foldLeft(0.0) { (sum, q) =>
      sum + fromQuaternion(q._1, q._2, q._3)
    }
  }

  // warmup
  var sum = 0.0
  for (_ <- 0 until 10) sum += convert

  val start = System.currentTimeMillis()
  for (_ <- 0 until 100) sum += convert
  val end = System.currentTimeMillis()

  println(s"Duration ${end - start} ms")
  println(f"Sum $sum%f")

When I measure asin and atan2 separately (with fromQuaternion containing only a single asin or a single atan2), I get following results:

*

*JS atan2: 453 ms

*JS asin 230 ms

*Java Math atan2 1000 ms

*Java Math asin 3800 ms

*Apache FastMath atan2 1020 ms

*Apache FastMath asin 1400 ms

I have tested Apache FastMath as well. While its asin is a bit faster, its performance is still way behind the one seen in the browser.
My measurements are done with Oracle Java 8 SDK 1.8.0.161 (JVM) and Chrome 78.0.3904.108 (Browser), both running on x64 Windows 10 running Intel Core i7 @ 3.2 GHz with 12 GB RAM.


text:
Q: How to localize the route action/controller in .NET Core Searched but can't find any question specifically about localizing controller/actions rather than just adding the culture itself to URL.
I have a localized .NET Core website, by inserting /es/ into the URL (before controller/action is the way its set up i.e. www.bla.com/es/account/profile).
This uses culture settings and saves the culture in a cookie, and the site uses IStringLocalizer and it all works well.
My problem is, I now need to translate the route itself.
www.bla.com/account/profile

OR
www.bla.com/es/cuenta/perfil

(google translate just for example)
I don't think I am worried about translating any query strings or variable names at the moment, just the action and controller names themselves.

A: To add a middleware to rewrite the url, add this into your Startup.Configure method before UseRouting, UseRoute, or UseMvc depending on what is currently used:
//This definition should be moved as a field or property.
//And the value should be loaded dynamically.
var urlMappings = new Dictionary<string, string>
{
    { "/es/cuenta/perfil", "/account/profile" },
    // others
};

//Rewriting the matched urls.
app.Use(next => http =>
{
    if (urlMappings.TryGetValue(http.Request.Path.Value, out var result))
    {
        http.Request.Path = new PathString(result);
    }
    return next(http);
});

This is just an example on how to implement it, though url mapping rule should be managed within services.


text:
Q: getting problem in transposing an 2D array i have written a code to transpose an aray it works when i took small arrays dimensions like 33 but when i took array size 45 it gives me array out of bound error.i am a beginner.
import java.util.*;
import java.lang.*;
public class Transpose {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("enter rows and cols: ");
        int r = sc.nextInt();
        int c = sc.nextInt();
        long a[][] = new long [r][c];
        long transpose[][] = new long [r][c];

        System.out.print("enter"+" " +r*c+" "+"elements");
        for(int i =0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                a[i][j] = sc.nextInt();
            }
        }

        for(int i =0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                System.out.print(" "+a[i][j] + " ");
            }
            System.out.println();
        }

        for(int i = 0; i < a.length ; i++){
            for(int j = 0; j < a[i].length; j++){
                long temp = a[i][j];
                transpose[i][j] = a[j][i];
                a[i][j] = temp;
            }
        }

        System.out.println();
        for(int i =0; i < transpose.length; i++){
            for(int j = 0; j < transpose[i].length; j++){
                System.out.print(" "+transpose[i][j] + " ");
            }
            System.out.println();
        }
    }
}


text:
Q: What is the proper method of constraining a pseudo-random number to a smaller range? What is the best way to constrain the values of a PRNG to a smaller range? If you use modulus and the old max number is not evenly divisible by the new max number you bias toward the 0 through (old_max - new_max - 1). I assume the best way would be something like this (this is floating point, not integer math)
random_num = PRNG() / max_orginal_range * max_smaller_range

But something in my gut makes me question that method (maybe floating point implementation and representation differences?).
The random number generator will produce consistent results across hardware and software platforms, and the constraint needs to as well.
I was right to doubt the pseudocode above (but not for the reasons I was thinking). MichaelGG's answer got me thinking about the problem in a different way. I can model it using smaller numbers and test every outcome. So, let's assume we have a PRNG that produces a random number between 0 and 31 and you want the smaller range to be 0 to 9. If you use modulus you bias toward 0, 1, 2, and 3. If you use the pseudocode above you bias toward 0, 2, 5, and 7. I don't think there can be a good way to map one set into the other. The best that I have come up with so far is to regenerate the random numbers that are greater than old_max/new_max, but that has deep problems as well (reducing the period, time to generate new numbers until one is in the right range, etc.).
I think I may have naively approached this problem. It may be time to start some serious research into the literature (someone has to have tackled this before).

A: I know this might not be a particularly helpful answer, but I think the best way would be to conceive of a few different methods, then trying them out a few million times, and check the result sets.
When in doubt, try it yourself.
EDIT
It should be noted that many languages (like C#) have built in limiting in their functions
int maximumvalue = 20;
Random rand = new Random();

rand.Next(maximumvalue);

And whenever possible, you should use those rather than any code you would write yourself. Don't Reinvent The Wheel.

A: This problem is akin to rolling a k-sided die given only a p-sided die, without wasting randomness.
In this sense, by Lemma 3 in "Simulating a dice with a dice" by B. Kloeckner, this waste is inevitable unless "every prime number dividing k also divides p". Thus, for example, if p is a power of 2 (and any block of random bits is the same as rolling a die with a power of 2 number of faces) and k has prime factors other than 2, the best you can do is get arbitrarily close to no waste of randomness, such as by batching multiple rolls of the p-sided die until p^n is "close enough" to a power of k.
Let me also go over some of your concerns about regenerating random numbers:

*

*"Reducing the period": Besides batching of bits, this concern can be dealt with in several ways:

*

*Use a PRNG with a bigger "period" (maximum cycle length).

*Add a Bays–Durham shuffle to the PRNG's implementation.

*Use a "true" random number generator; this is not trivial.

*Employ randomness extraction, which is discussed in Devroye and Gravel 2015-2020 and in my Note on Randomness Extraction.  However, randomness extraction is pretty involved.

*Ignore the problem, especially if it isn't a security application or serious simulation.

*"Time to generate new numbers until one is in the right range": If you want unbiased random numbers, then any algorithm that does so will generally have to run forever in the worst case. Again, by Lemma 3, the algorithm will run forever in the worst case unless "every prime number dividing k also divides p", which is not the case if, say, k is 10 and p is 32.

See also the question: How to generate a random integer in the range [0,n] from a stream of random bits without wasting bits?, especially my answer there.

A: If PRNG() is generating uniformly distributed random numbers then the above looks good. In fact (if you want to scale the mean etc.) the above should be fine for all purposes. I guess you need to ask what the error associated with the original PRNG() is, and whether further manipulating will add to that substantially.
If in doubt, generate an appropriately sized sample set, and look at the results in Excel or similar (to check your mean / std.dev etc. for what you'd expect)

A: If you have access to a PRNG function (say, random()) that'll generate numbers in the range 0 <= x < 1, can you not just do:
 random_num = (int) (random() * max_range);

to give you numbers in the range 0 to max_range?

A: Here's how the CLR's Random class works when limited (as per Reflector):
long num = maxValue - minValue;
if (num <= 0x7fffffffL) {
    return (((int) (this.Sample() * num)) + minValue);
}
return (((int) ((long) (this.GetSampleForLargeRange() * num))) + minValue);

Even if you're given a positive int, it's not hard to get it to a double. Just multiply the random int by (1/maxint). Going from a 32-bit int to a double should provide adequate precision. (I haven't actually tested a PRNG like this, so I might be missing something with floats.)

A: Psuedo random number generators are essentially producing a random series of 1s and 0s, which when appended to each other, are an infinitely large number in base two.  each time you consume a bit from you're prng, you are dividing that number by two and keeping the modulus.  You can do this forever without wasting a single bit.
If you need a number in the range [0, N), then you need the same, but instead of base two, you need base N.  It's basically trivial to convert the bases.  Consume the number of bits you need, return the remainder of those bits back to your prng to be used next time a number is needed.


text:
Q: read and execute ruby script script.rb:
puts 'hello'
puts 'foo'

main.rb:
puts `jruby script.rb` # receive the expected result

The question:
How can the same be achieved with reading the "script" before execution?
main.rb:
code=File.open('script.rb', 'r').read.gsub('"', '\"')
# puts `jruby -e '#{code}'` # Does not work for relatively big files;

Windows and unicode are the reasons of this question;
Please note that `jruby script.rb' creates a new process which is essential.

A: Store the modified script in a Tempfile and run that instead of passing the whole contents as an eval argument:
require 'tempfile'

code = IO.read('script.rb').gsub('"', '\"')

begin
  tempfile = Tempfile.new 'mytempfile'
  f.write code
  f.close
  puts `jruby '#{f.path}'`
ensure
  f.close
  f.unlink
end

The reason you're likely getting an error is either a lack of proper escaping or a limit on the maximum argument length in the shell.
Also, beware that in your original implementation you never close the original file. I've fixed that by instead using IO.read.

A: In the command line, using
$ getconf ARG_MAX

will give the upper limit on how many bytes can be used for the command line argument and environment variables.
@Andrew Marshall's answer is better, but suppose you don't want to use a temp file, and assuming we can use fork in JRuby,
require 'ffi'
module Exec
  extend FFI::Library
  ffi_lib FFI::Platform::LIBC
  attach_function :fork, [], :int
end

code = IO.read('script.rb')
pid = Exec.fork
if 0 == pid
  eval code
  exit 0
else
  Process.waitpid pid
end

A: use require
main.rb:
require "script.rb"


text:
Q: Классификация кошек и собак в нейронке Обучил нейронку, кошек и собак на фото правильно классифицирует, но что-либо где их нет не верно относит к одной категории и при этом выдает вероятность соостветствия 90%+
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense

# Каталог с данными для обучения
train_dir = 'C:\Projects\python\dogorcat\cats_vs_dogs/train'
# Каталог с данными для проверки
val_dir = 'C:\Projects\python\dogorcat\cats_vs_dogs/val'
# Каталог с данными для тестирования
test_dir = 'C:\Projects\python\dogorcat\cats_vs_dogs/test'
# Размеры изображения
img_width, img_height = 150, 150
# Размерность тензора на основе изображения для входных данных в нейронную сеть
# backend Tensorflow, channels_last
input_shape = (3, img_width, img_height)
# Количество эпох
epochs = 30
# Размер мини-выборки
batch_size = 16
# Количество изображений для обучения
nb_train_samples = 17500
# Количество изображений для проверки
nb_validation_samples = 3750
# Количество изображений для тестирования
nb_test_samples = 3750

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = datagen.flow_from_directory(
    train_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

val_generator = datagen.flow_from_directory(
    val_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

test_generator = datagen.flow_from_directory(
    test_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=val_generator,
    validation_steps=nb_validation_samples // batch_size)

scores = model.evaluate_generator(test_generator, nb_test_samples // batch_size)

print("Сохраняем сеть")
# Сохраняем сеть для последующего использования
# Генерируем описание модели в формате json
model_json = model.to_json()
json_file = open("cvd_model.json", "w")
# Записываем архитектуру сети в файл
json_file.write(model_json)
json_file.close()
# Записываем данные о весах в файл
model.save_weights("cvd_model.h5")
print("Сохранение сети завершено")

Как заставить фотки без собак и кошек не учитывать?

A: По-моему проще всего будет добавить третью категорию unknown - сложить туда картинки не содержащие ни кошек ни собак и обучить ИНС на наборе данных содержащих три категории.
Кроме того если вы используете loss='categorical_crossentropy', то в качестве функции активации на последнем слое следует использовать activation='softmax', т.к. sigmoid используется для задач бинарной классификации.


text:
Q: How can I change my menu to the toggle menu? My menu opens automatically on mouse hover and it closes the menu when the mouse isn't hovering anymore, But this functionality is not the desired one , I actually want to change my menu code to toggle for menu and all of ul in my menu , how can I do that ?
The below code is my menu code that you can look at it.
The code:

#ABT-Container {
  font-family: 'Roboto', sans-serif;
  background: transparent;
  width: 100%;
  float: right;
}

a {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  color: #333;
}

#nav {
  float: right;
  font-family: 'Roboto', sans-serif;
  padding: 2px 6px 0;
  line-height: 100%;
  border-radius: 1em;
  background: white;
  /* for non-css3 browsers */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#FFFFFF');
  /* for IE */
  background: -webkit-gradient(linear, right top, right bottom, from(#FFFFFF), to(#FFFFFF));
  /* for webkit browsers */
  background: -moz-linear-gradient(top, #FFFFFF, #FFFFFF);
  /* for firefox 3.6+ */
  border: solid 1px white;
}

#nav li {
  font-family: 'Roboto', sans-serif;
  margin: 0 5px;
  padding: 0 0 8px;
  float: right;
  position: relative;
  list-style: none;
}

/* main level link */

#nav a {
  font-family: 'Roboto', sans-serif;
  color: #353535;
  text-decoration: none;
  display: block;
  padding: 8px 20px;
  margin: 0;
  -webkit-border-radius: 0em;
  -moz-border-radius: 0em;
  text-shadow: 0 0px 0px rgba(0, 0, 0, .3);
}

/* sub levels link hover */

#nav ul li:hover a,
#nav li:hover li a {
  font-family: 'Roboto', sans-serif;
  background: none;
  border: none;
  color: #666;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
}

/* level 2 list */

#nav ul {
  font-family: 'Roboto', sans-serif;
  background: #FFFFFF;
  /* for non-css3 browsers */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#FFFFFF');
  /* for IE */
  background: -webkit-gradient(linear, right top, right bottom, from(#fff), to(#FFFFFF));
  /* for webkit browsers */
  background: -moz-linear-gradient(top, #fff, #FFFFFF);
  /* for firefox 3.6+ */
  display: none;
  margin: 0;
  padding: 0;
  width: 185px;
  position: absolute;
  top: 35px;
  right: 0;
  -webkit-border-radius: 1px;
  -moz-border-radius: 1px;
  border-radius: 1px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
  -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
}

/* dropdown */

#nav li:hover>ul {
  font-family: 'Roboto', sans-serif;
  display: block;
}

#nav ul li {
  font-family: 'Roboto', sans-serif;
  float: none;
  margin: 0;
  padding: 0;
}

#nav ul a {
  font-family: 'Roboto', sans-serif;
  font-weight: normal;
  text-shadow: 0 1px 1px rgba(255, 255, 255, .9);
}

/* level 3+ list */

#nav ul ul {
  font-family: 'Roboto', sans-serif;
  right: 181px;
  top: -3px;
}

/* rounded corners for first and last child */

#nav ul li:first-child>a {
  -webkit-border-top-right-radius: 1px;
  -moz-border-radius-topleft: 1px;
  -webkit-border-top-left-radius: 1px;
  -moz-border-radius-topright: 1px;
}

#nav ul li:last-child>a {
  -webkit-border-bottom-right-radius: 1px;
  -moz-border-radius-bottomleft: 1px;
  -webkit-border-bottom-left-radius: 1px;
  -moz-border-radius-bottomright: 1px;
}

/* clearfix */

#nav:after {
  font-family: 'Roboto', sans-serif;
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

#nav {
  font-family: 'Roboto', sans-serif;
  display: inline-block;
}

html[xmlns] #nav {
  font-family: 'Roboto', sans-serif;
  display: block;
}

* html #nav {
  height: 1%;
}

.menu_line {
  width: 25px;
  height: 2px;
  background-color: black;
  color: black;
  margin: 4px 0;
}

About US

Multi-Levels

Sales

Support

Another Link

Department

A: You can also do this without jquery, but personally I'd add something to indicate something has a submenu, as you now have to try to find out.

let hovering = false;

function toggle(element) {
  const nodes = getChildNodes(element.parentElement);
  const parentNodes = getChildNodes(element.parentElement.parentElement);
  if(parentNodes.length > 1) {
    parentNodes.forEach(function(parentNode) {
      const parentChildNodes = getChildNodes(parentNode);
      if(parentChildNodes.length > 1 && parentChildNodes[1].style.display === 'block' && parentChildNodes[1] !== nodes[1])  {
        parentChildNodes[1].style.display = 'none';
      }
    });
  }
  if(nodes[1].style.display === 'block') {
    nodes[1].style.display = 'none';
  } else {
    nodes[1].style.display = 'block';
  }
}

function getChildNodes(node) {
  let children = new Array();
  for(const child in node.childNodes) {
    if(node.childNodes[child].nodeType == 1) {
      children.push(node.childNodes[child]);
    }
  }
  return children;
}

window.onload = function() {
  // For clicks inside the element
  document.getElementById('menuElement').onclick = function(e) {
    // Make sure the event doesn't bubble from your element
    if (e) { e.stopPropagation(); }
    else { window.event.cancelBubble = true; }
    // Place the code for this element here
  };

  // For clicks elsewhere on the page
  document.onclick = function() {
    const uls = document.getElementById('nav').getElementsByTagName('ul');
    for (i = 0; i < uls.length; i++) {
      uls[i].style.display = 'none';
    }
  };
};
#ABT-Container  {
  font-family: 'Roboto', sans-serif;
  background: transparent;
  width:100%; float:right;
}

a {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  color: #333;
}

#nav {
  float: right;
  font-family: 'Roboto', sans-serif;
  padding: 2px 6px 0;
  line-height: 100%;
  border-radius: 1em;
  background: white; /* for non-css3 browsers */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#FFFFFF'); /* for IE */
  background: -webkit-gradient(linear, right top, right bottom, from(#FFFFFF), to(#FFFFFF)); /* for webkit browsers */
  background: -moz-linear-gradient(top,  #FFFFFF,  #FFFFFF); /* for firefox 3.6+ */
  border: solid 1px white;
}

#nav li {
  font-family: 'Roboto', sans-serif;
  margin: 0 5px;
  padding: 0 0 8px;
  float: right;
  position: relative;
  list-style: none;
}

/* main level link */
#nav a {
  font-family: 'Roboto', sans-serif;
  color: #353535;
  text-decoration: none;
  display: block;
  padding:  8px 20px;
  margin: 0;
  -webkit-border-radius: 0em;
  -moz-border-radius: 0em;
  text-shadow: 0 0px 0px rgba(0, 0, 0, .3);
}

/* level 2 list */
#nav ul {
  font-family: 'Roboto', sans-serif;
  background: #FFFFFF; /* for non-css3 browsers */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#FFFFFF'); /* for IE */
  background: -webkit-gradient(linear, right top, right bottom, from(#fff), to(#FFFFFF)); /* for webkit browsers */
  background: -moz-linear-gradient(top,  #fff,  #FFFFFF); /* for firefox 3.6+ */
  display: none;
  margin: 0;
  padding: 0;
  width: 185px;
  position: absolute;
  top: 35px;
  right: 0;
  -webkit-border-radius: 1px;
  -moz-border-radius: 1px;
  border-radius: 1px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
  -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
}

/* dropdown */
#nav ul li {
  font-family: 'Roboto', sans-serif;
  float: none;
  margin: 0;
  padding: 0;
}

#nav ul a {
  font-family: 'Roboto', sans-serif;
  font-weight: normal;
  text-shadow: 0 1px 1px rgba(255, 255, 255, .9);
}

/* level 3+ list */
#nav ul ul {
  font-family: 'Roboto', sans-serif;
  right: 181px;
  top: -3px;
}

/* rounded corners for first and last child */
#nav ul li:first-child > a {
  -webkit-border-top-right-radius: 1px;
  -moz-border-radius-topleft: 1px;
  -webkit-border-top-left-radius: 1px;
  -moz-border-radius-topright: 1px;
}

#nav ul li:last-child > a {
  -webkit-border-bottom-right-radius: 1px;
  -moz-border-radius-bottomleft: 1px;
  -webkit-border-bottom-left-radius: 1px;
  -moz-border-radius-bottomright: 1px;
}

/* clearfix */
#nav:after {
  font-family: 'Roboto', sans-serif;
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

#nav {
  font-family: 'Roboto', sans-serif;
  display: inline-block;
}

html[xmlns] #nav {
  font-family: 'Roboto', sans-serif;
  display: block;
}

* html #nav {
  height: 1%;
}

.menu_line{
  width: 25px;
  height: 2px;
  background-color: black;
  color: black;
  margin: 4px 0;
}

            About US

            Multi-Levels

                Sales

                    Support

                Another Link

                Department

            Multi-Levels2

                Sales2

                    Support2

                Sales3

                    Support3

                Another Link2

                Department2

Edit: Now also closing on clicking somewhere not on the menu.


text:
Q: asp.net mvc forms authentication with no membership I have a following scenario: user logs in using google account and then I call FormsAuthentication.SetAuthCookie(name, true);. In my web.config I have
<authentication mode="Forms">
<forms cookieless="UseCookies"  name=".someName" slidingExpiration="true" timeout="10080"/
</authentication>

And that's it, no membership provider, no dbo.aspnet_* tables. And that would be fine except sometimes (I don't know why) even when user doesn't close browser and sends requests periodically he becomes non-authenticated again. Can anyone explain why?
And what should I do to make authentication persistent? Would be great if solution wouldn't involve sql server as there isn't any.


text:
Q: Запрос из трех таблиц Пытаюсь выполнить вот такой просто запрос
SELECT O.id
FROM accer O
JOIN accer_links I ON I.pid =1
AND I.cid = O.id
JOIN catalog_chains P ON P.pidc !=29
ORDER BY I.sort

Но результат такой, как будто в предпоследней строчке нет != 29 все равно показывает элементы, у которых P.pidc=29, а мне надо P.pidc!=29
Я где-то скобку не закрыл?
CREATE TABLE IF NOT EXISTS `accer` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `hidden` int(1) unsigned NOT NULL DEFAULT '0',
  `name` varchar(255) NOT NULL DEFAULT '',
  `nal1` varchar(255) NOT NULL DEFAULT '',
  `na2` varchar(255) NOT NULL DEFAULT '',
  `nal3` varchar(255) NOT NULL DEFAULT '',
  `nal4` varchar(255) NOT NULL DEFAULT '',
  `nal5` varchar(255) NOT NULL DEFAULT '',
  `kol_vo` varchar(255) NOT NULL DEFAULT '',
  `dop_inf` text NOT NULL,
  `vnimanie` text NOT NULL,
  `recomend` int(1) unsigned NOT NULL DEFAULT '0',
  `gde` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=cp1251 AUTO_INCREMENT=8 ;

INSERT INTO `accer` (`id`, `hidden`, `name`, `nal1`, `na2`, `nal3`, `nal4`, `nal5`, `kol_vo`, `dop_inf`, `vnimanie`, `recomend`, `gde`) VALUES
(3, 1, 'Галстук 11', '1', '1', '1', '1', '1', '1', '1', '1', 0, '1'),
(4, 1, 'ывапн', '', '', '', '', '', '', '', '', 0, ''),
(5, 1, '23141324', '1324', '', '132', '', '4132', '', '41324', '', 0, '4'),
(6, 1, '1', '1', '1', '', '', '', '', '', '', 0, ''),
(7, 1, '123222', '3123', '', '123', '12', '312312', '', '213', '', 0, '');

CREATE TABLE IF NOT EXISTS `accer_links` (
  `pid` int(1) unsigned NOT NULL DEFAULT '0',
  `cid` int(11) unsigned NOT NULL DEFAULT '0',
  `sort` int(11) unsigned NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=cp1251;

--
-- Дамп данных таблицы `accer_links`
--

INSERT INTO `accer_links` (`pid`, `cid`, `sort`) VALUES
(1, 7, 7),
(1, 6, 6),
(2, 5, 5),
(1, 3, 3),
(2, 4, 4);

CREATE TABLE IF NOT EXISTS `catalog_chains` (
  `pidc` int(1) unsigned NOT NULL DEFAULT '0',
  `cidc` int(11) unsigned NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;

--
-- Дамп данных таблицы `catalog_chains`
--

INSERT INTO `catalog_chains` (`pidc`, `cidc`) VALUES
(28, 3),
(29, 6),
(29, 3);


text:
Q: converting XML data design to a SQLite DB design I have a task to convert the data design in XML format to a SQLite DB format. The criteria is to achieve more performance while keeping the same level of data scalability as with XML data.
The problem I face is that the XML data format can be divided based on the independent nodes which can be created as separate tables in the DB. However if the number of child nodes in the independent nodes increases, there will be an increase in the number of columns in the table. I found that there are 500-600 columns on an avg for a table which might seriously impact the query performance.
The data rows need to be frequently updated & queried for reading. Performance is the sole criteria for this change keeping the CPU load to minimum for that process.
Please share an idea to get around this problem. Ideas for converting the XML data to SQLite DB format are most welcome.
Thanks in advance.

A: If all columns are device parameters or similar you can create a table with a ParameterName column and a ParameterValue column.
DeviceId ParameterName ParameterValue
-------------------------------------
1        FrameRate     60
1        Brightness    75
1        BootTime      20
2        FrameRate     30
2        Brightness    100
2        BootTime      10

etc
If your parameter names are the same for many devices you should break out ParameterName to a separate table
ParameterId ParameterName
-------------------------
1           FrameRate
2           BrightNess
3           BootTime

and insert ParameterId in your main table instead of ParameterName.
This will improve performance and reduce storage space.


text:
Q: What's the meaning of the EXC_BREAKPOINT code and subcode? Usually when I set lldb watchpoints, when they're hit, lldb says watchpoint hit old value: new value.  However, I set a watchpoint on an address that seems to be getting written to inside a 3rd party library (libjpeg-turbo) and instead of the usual watchpoint hit, I'm seeing EXC_BREAKPOINT code=258, subcode=0xADDRESS.
In all cases, I can see that the subcode must be the address, as it's always equal to the address or close to the one I set the watchpoint to.  Can anyone confirm this?
If I delete the watchpoint and keep going, lldb won't pause with EXC_BREAKPOINT.  But what does the code mean and where can I find some offical documentation on this?
The exc_types.h doesn't give any detailed information on it.

A: For anyone who is interested in this question there is a nice article about the topic:
Understanding iOS Exception Types

In all cases, I can see that the subcode must be the address, as it's always equal to the address or close to the one I set the watchpoint to. Can anyone confirm this?

There is not much information in exception_types.h headers:
open -t /Applications/Xcode.app//Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/mach/exception_types.h

I can confirm that I always see EXC_BREAKPOINT to have address in subcode.
However other types in the header say that subcode can have different kinds of information:
#define EXC_EMULATION       4   /* Emulation instruction */
  /* Emulation support instruction encountered */
  /* Details in code and subcode fields */

We had to investigate on one Swift crash that produced: EXC_BREAKPOINT. In our case it boiled down to Swift type coercions. Both of the following cause EXC_BREAKPOINT on ARM devices:
func test_crash() {
  let num = Int(DBL_MAX)
}

func test_crash_2() {
  let num = Int(Double(0) / Double(0))
}

In both of these cases EXC_BREAKPOINT has a subcode with an address which is the address of sbrk instruction if you look at the assembly.

A: exc_types.h only has the architecture independent parts of the exception definitions. You need to look in the i386/arm subdirectories to find the architecture specific parts.  If you are on Yosemite, the arm directory won't be in /usr/include/mach, you'll have to look for it in the iPhoneOS SDK inside of Xcode.app.  Anyway, mach/arm/exception.h says:
#define EXC_ARM_DA_DEBUG        0x102   /* Debug (watch/break) Fault */

And as you suspect the subcode is the address of the access.
But lldb doesn't report bare exceptions if it recognizes the exception as implementing some higher level task.  In this case, it should be reporting the stop reason as a watchpoint hit.  For some reason it doesn't recognize this as your watchpoint.  Is the subcode address exactly the same as the one reported by watch list?


text:
Q: Mapbox GL JS How to handle multiple map styles/sprites at the same time in a map? We are using mapbox-gl-js for a mapping web app, we have several custom styles (made with mapbox studio) that we use like layers that we render above our base layers, a base layer can be the mapbox satellite layer, and a custom layer a style that shows information about soils (for example).
I want to know if someone has faced this situation, we've find some workarounds to handle our needs, but isn't really easy and takes time each time we modify a custom style.
Here is a list of issues that we have faced and resolved:

*

*Can't load more that one style per map, so there is no easy way to
load all the custom styles that we have at the same time, and we need to
do it.
In order to show each style in the map, we add each layer in the
style to the map individually, we inspect the layers inside the style
object and iterate over it adding each layer.

*Can't load more than one sprite per map, each style has it's own
sprite, with the resources it needs, for example a svg for a fill
pattern. If we load the sprite for one style, the other styles won't
show correctly, because they also have layers that needs svgs from
their sprites.
To solve this we have a style that contains the svgs of all the other
styles, so we can load the sprite of this style and all the other
styles are displayed correctly. This works, but the sprite has a
limit of 500 icons (more or less depending on the size of your icons), and we will reach that limit eventually, that's
one of our biggest concerns.


text:
Q: Already imported the jar files in netbeans but my source cannot find the library I already imported the jar files in netbeans but my main java file still cannot find the methods. I am using netbeans 7.3.1 on Mac. Does anyone know how make it work?
Thank you,

A: I also had problem with importing classes from imported jar. It was so damn annoying...
There are couple solutions @ web, (clear cache in user's AppData. or make sure to add jar's properly - by using "Add Jar/Folder..." option) but none of them worked for me.
What worked was new project and importing THE SAME (that's sad) jar files into it. So I had 2 project with exactly the same contents, but only one of them was working (compiling).

EDIT:
However, your problem is not related to mine. Root cause of your issue is the jar itself.
It contains class files in default package that is making them impossible to import.
Read here how to import class from default (unnamed) package.

A: hey guyes just keep your .jar files in the "C:\Program Files\Java\jdk1.7.0_45\jre\lib\ext" it will work definitely.I have tried all the other options but i finally copied my .jar files in above path and it worked.


text:
Q: Using semantic UI to create a web app layout with a side nav, fixed header, fixed footer I am trying to create a specific site layout for a web application using semantic ui and can't get it down for some reason.
The layout consists of the following pieces:
Sidebar (Narrow sidebar that has a menu icon at the top for making wider/narrow, additionally icons for the primary sections of site, when menu icon is clicked sidebar gets wider, labels appear near icons and everything to the right gets pushed over).
Main Header (This is basically a semantic ui menu, with a logo as the first item)
Sub Header (this is another horizontal bar that will display text and action icons, guessing I can use menu again)
Content (this is will be where the actual content goes, will be the only thing that is scrollable, rest of page should never scroll).
Footer (this will be fixed at the bottom of page, once again can probably use menu)
Please see image:

I have spent a lot of time trying to build this layout with Semantic UI documentation and can't figure it out. I am tempted to do away with using Semantic UI for the site layout, but I love the sidebar functionality.


text:
Q: Prevent Kubernetes from restarting container when I shut down PostgreSQL I'm maintaining a Kubernetes cluster which includes two PostgreSQL servers in two different pods, a primary and a replica.  The replica is sync'ed from the primary via log shipping.
A glitch caused the log shipping to start failing so the replica is no longer in sync with the primary.
The process for bringing a replica back into sync with the primary requires, amongst other things, stopping the postgres service of the replica.  And this is where I'm having trouble.
It appears that Kubernetes is restarting the container as soon as I shut down the postgres service, which immediately restarts postgres again.  I need the container running with the postgres service inside it stopped, to allow me to perform the next steps in fixing the broken replication.
How can I get Kubernetes to allow me to shut down the postgres service without restarting the container?
Further Details:
To stop the replica I run a shell on the replica pod via kubectl exec -it <pod name> -- /bin/sh, then run pg_ctl stop from the shell.  I get the following response:
server shutting down
command terminated with exit code 137

and I'm kicked out of the shell.
When I run kubectl describe pod I see the following:
Name:         pgset-primary-1
Namespace:    qa
Priority:     0
Node:         aks-nodepool1-95718424-0/10.240.0.4
Start Time:   Fri, 09 Jul 2021 13:48:06 +1200
Labels:       app=pgset-primary
              controller-revision-hash=pgset-primary-6d7d65c8c7
              name=pgset-replica
              statefulset.kubernetes.io/pod-name=pgset-primary-1
Annotations:  <none>
Status:       Running
IP:           10.244.1.42
IPs:
  IP:           10.244.1.42
Controlled By:  StatefulSet/pgset-primary
Containers:
  pgset-primary:
    Container ID:   containerd://bc00b4904ab683d9495ad020328b5033ecb00d19c9e5b12d22de18f828918455
    Image:          *****/crunchy-postgres:centos7-9.6.8-1.6.0
    Image ID:       docker.io/*****/crunchy-postgres@sha256:2850e00f9a619ff4bb6ff889df9bcb2529524ca8110607e4a7d9e36d00879057
    Port:           5432/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sat, 06 Nov 2021 18:29:34 +1300
    Last State:     Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Sat, 06 Nov 2021 18:28:09 +1300
      Finished:     Sat, 06 Nov 2021 18:29:18 +1300
    Ready:          True
    Restart Count:  6
    Limits:
      cpu:     250m
      memory:  512Mi
    Requests:
      cpu:     10m
      memory:  256Mi
    Environment:
      PGHOST:                 /tmp
      PG_PRIMARY_USER:        primaryuser
      PG_MODE:                set
      PG_PRIMARY_HOST:        pgset-primary
      PG_REPLICA_HOST:        pgset-replica
      PG_PRIMARY_PORT:        5432
      [...]
      ARCHIVE_TIMEOUT:        60
      MAX_WAL_KEEP_SEGMENTS:  400
    Mounts:
      /backrestrepo from backrestrepo (rw)
      /pgconf from pgbackrestconf (rw)
      /pgdata from pgdata (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from pgset-sa-token-nh6ng (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  pgdata:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  pgdata-pgset-primary-1
    ReadOnly:   false
  backrestrepo:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  backrestrepo-pgset-primary-1
    ReadOnly:   false
  pgbackrestconf:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      pgbackrest-configmap
    Optional:  false
  pgset-sa-token-nh6ng:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  pgset-sa-token-nh6ng
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/memory-pressure:NoSchedule op=Exists
                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason   Age                 From     Message
  ----     ------   ----                ----     -------
  Warning  BackOff  88m (x3 over 3h1m)  kubelet  Back-off restarting failed container
  Normal   Pulled   88m (x7 over 120d)  kubelet  Container image "*****/crunchy-postgres:centos7-9.6.8-1.6.0" already present on machine
  Normal   Created  88m (x7 over 120d)  kubelet  Created container pgset-primary
  Normal   Started  88m (x7 over 120d)  kubelet  Started container pgset-primary

The events suggest the container was started by Kubernetes.
The pod has no liveness or readiness probes so I don't know what would prompt Kubernetes to restart the container when I shut down the postgres service running within it.

A: This happens due to restartPolicy. Container lifecycle is terminated due to its process being completed. If you do not want a new container to be created you need to change the restart policy for these pods.
If this pod is a part of deployment, look into kubectl explain deployment.spec.template.spec.restartPolicy


text:
Q: Node app doesn't terminate after web request? I'm reading IDs from a text file and making some RESTful requests. It works, but when all IDs have been run, the node app stays running.
main.js:
var fs = require('fs');
var http = require('http');

var ids = fs.readFileSync('test.txt', { encoding: 'utf8' });
ids = ids.split('\n');
var options = {
    hostname: 'internalhost',
    port: 80,
    path: '',
    method: 'DELETE'
};
for (var i = 0; i < ids.length; i++) {
    options.path = '/thing/' + ids[i];
    console.log('Deleting thing ' + ids[i]);

    var req = http.request(options, function(res) {
        console.log('Status: ' + res.statusCode);
    });

    req.on('error', function(e) {
        console.log('Problem with request: ' + e.message);
    });

    req.end();
}

The requests are made successfully but after the last one, the app continues to run. I've tried adding res.end() right after I print the response's status code, but then I get an error that res doesn't have a method end.
What's going on here?

A: It appears you're suffering from a side-effect of HTTP keep-alives.  Node does not exit when there are TCP connections open, and the HTTP Agent leaves TCP connections open for an indefinite amount of time.
You've mentioned that keep-alives will be beneficial for you, so your options are limited.

*

*Simply disabling the Agent will result in keep-alives being disabled, so this isn't really an option.

*You can manually manage and track your requests, and when all have been completed, call process.exit.  I don't like this, however, as it is a rather blunt instrument.  If you have other async operations running (such as DB calls), you may accidentally end your app before those operations complete.

*You can manually manage and track your requests.  When all have been completed, you can loop through the Agent instance's sockets property and close all lingering sockets. (Warning: calling close on an already closed socket throws.)
This is a much safer approach because other outstanding operations will be allowed to finish before the app exits.

*You could upgrade to node ≥ 0.11.4.  (Realistically, you'd probably want to wait until 0.12 stable is released.)  The next node version has a greatly improved Agent implementation that unrefs idle sockets kept in the Agent's connection pool.  In other words, node can exit if the only open TCP connections are those being held for reuse as a keep-alive connection.

*You could also rip out the new Agent implemention from the unstable branch and use it for your app's requests instead of the default Agent provided by your version of node.  (This is probably what I'd do.)

A: node will only terminate if there are no pending events to be handled. In this case I believe the connection is still open, so you can either destroy it manually by calling res.socket.end() or res.destroy() or as @ExplosionPills Suggested, just call process.exit when all requests are done. You can use async module to help you to achieve this.


text:
Q: Swagger for java - the required field prevents execution I am using swagger with the following Maven dependency:
 <dependency>
        <groupId>io.swagger.core.v3</groupId>
        <artifactId>swagger-jaxrs2</artifactId>
        <version>2.0.9</version>
    </dependency>

I wrote an API call as follows:
@Operation(
        method = "GET",
        summary = "Get alerts by Date Range",
        extensions = @Extension(name = "x-rest-api", properties = @ExtensionProperty(name = "public", value = "true")),
        parameters = {
                @Parameter(name = "startDate",
                        in = ParameterIn.QUERY,
                        description = "Get alerts from this date. `startDate` should be in GMT and 24 hour Clock",
                        example = "2020-07-15T15:57:00Z",
                        schema = @Schema(implementation = ZonedDateTime.class),
                        required = true),
                @Parameter(name = "endDate",
                        in = ParameterIn.QUERY,
                        description = "Get alerts to this date. `endDate` should be in GMT and 24 hour Clock",
                        example = "2020-07-20T15:57:00Z",
                        required = true)
        },
        responses = {
                @ApiResponse(
                        responseCode = "200",
                        description = "A list of alerts",
                        content = @Content(schema = @Schema(implementation = AlertObject .class))),
                @ApiResponse(
                        responseCode = "401",
                        description = "Invalid Bearer Token",
                        content = @Content(schema = @Schema(implementation = ApiException.class))
                )
        }
)
@GET
@Path("/old")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public AlertObject alertsByDateRange(@NotNull @Valid @QueryParam("startDate") ZonedDateTime startDate,
                                                 @NotNull @Valid @QueryParam("endDate") ZonedDateTime endDate) { ... }

The above 2 parameters are both supposed to be required parameters. So I set the required = true. However, once I set them to required, I was no longer able to execute this API call through swagger. When I used Postman to call this function it worked perfectly. However, I can no longer use the swagger UI to test. I don't know why that is? I even tried setting the schema field for one of them (I thought that perhaps swagger needed to know how to validate) but that didn't help. So now, when I fill out those fields, swagger highlights them in red and refuses to execute this API call.  When I hover my mouse over the red box, it says "Required field is not provided".
I looked online but I cannot find a good set of examples of how to properly set required parameters in swagger for java, nor could I find an API that describes the nuances of the java version.
So my question is - how do I properly setup required parameters such that they are still executable through the swagger UI?

A: I figured out the issue.
If you notice in the code above, I declare the same parameter in swagger twice. The first time is:
@Parameter(name = "startDate",
                    in = ParameterIn.QUERY,
                    description = "Get alerts from this date. `startDate` should be in GMT and 24 hour Clock",
                    example = "2020-07-15T15:57:00Z",
                    schema = @Schema(implementation = ZonedDateTime.class),
                    required = true),

And the second time is:
@NotNull @Valid @QueryParam("startDate") ZonedDateTime startDate,

When I looked at the yaml, I saw this:
 parameters:
  - name: startDate
    in: query
    description: Get historical alerts from this date. `startDate` should be in
      GMT and 24 hour Clock
    required: true
    schema:
      type: string
      format: date-time
    example: 2020-07-15T15:57:00Z
  ...
  - name: startDate
    in: query
    required: true
    schema:
      type: string
      format: date-time

The parameter appears twice as a result. And you can tell which is which, because the 1st parameter has a description and the second one does not.
(I think the underlying problem is that both are considered required but we are only able to fill out 1 parameter.)
Once I remove the second declaration I was then able to use swagger to test my API calls.


text:
Q: Unexpected Positioning of Paragraphs When Small Capped Letters Do Not Follow the Lettrine Consider the code
\documentclass[foolscap]{octavo} % to get a small image
\usepackage{lettrine,lmodern,xcolor}
\usepackage[tracking=true]{microtype}

\input GoudyIn.fd
\renewcommand{\LettrineFontHook}{\usefont{U}{GoudyIn}{xl}{n}}

\fboxsep=0pt % padding thickness
\fboxrule=0pt % border thickness

\begin{document}
\thispagestyle{empty}
\lettrine[lines=3,loversize=.30,findent=.21em,nindent=2.5pt]{\fcolorbox{black}{blue!35}{T\kern-.04em}}{his} is an example of the use of a lettrine where the letters following the lettrine appear in small caps. All is fine.

\vspace*{7pt}

\lettrine[lines=3,loversize=.30,findent=.21em,nindent=2.5pt]{\fcolorbox{black}{blue!35}{A\kern-.04em}}{} lettrine where there are no letters to be displayed in small caps. Notice the difference in the spacing of the two displays.

\vspace*{7pt}

\lettrine[lines=3,loversize=.30,findent=.21em,nindent=2.5pt]{\fcolorbox{black}{blue!35}{A\kern-.04em}}{} lettrine where there are no letters to be displayed in small caps. Notice the spacing between the lettrine itself and the word "lettrine".

\vspace*{7pt}

\lettrine[lines=3,loversize=.30,findent=.21em,nindent=2.5pt]{\fcolorbox{black}{blue!35}{A\kern-.04em}}{} lettrine where no letters are displayed in small caps. Notice again, that in the previous example, the spacing between the lettrine itself and the word "lettrine" immediately following was off. But now it's fine.

\vspace*{7pt}

\lettrine[lines=3,loversize=.30,findent=.21em,nindent=2.5pt]{\fcolorbox{black}{blue!35}{A\kern-.04em}}{} lettrine where there are no letters to be displayed in small caps. Notice again, that in the previous example, the spacing between the lettrine itself and the word "lettrine" immediately following was off. But now, in this paragraph, all again is \emph{not} fine.
\end{document}

which produces the output

Notice that in the first of the five paragraphs, where there are small-capped letters following the lettrine --- all seems to be fine.
In the second paragraph, the `A' lettrine constitutes a word, and so there are no small-capped letters following it. Compared with the first paragraph, we see that the spacing of the entire paragraph has been slightly increased.
The third paragraph, which is longer than the previous two, has shifted the word "lettrine" farther to the right than before, yet a similar phenomenon does not occur in the lines that follow.
In the fourth paragraph, things seem to be back to normal.
Alas, when we increase the length of the paragraph a little in the fifth example, things seem to revert back to what they were in the third example.
QUESTION: Can anyone point out why these discrepancies might be occurring and how I might prevent such things from happening, so that when I have no small-capped letters following the lettrine, all might be displayed as in the first paragraph?
Thank you.

A: I don't think it's really related to having small caps or not just that any change anywhere in the paragraph, removing a word adding a comma,  ...  can change the line breaking in the whole paragraph.
The difference between
T{his} is
and
A{} lettrine
is that you get a word space after the dropped-cap+ empty argument so in loose lines it is a larger space.
On the word space before lettrine, compare  a normal word space, a fixed unstretched word space or no space

from
}{A\kern-.04em}}{} lettrine
}{A\kern-.04em}}{}\mbox{ }lettrine
}{A\kern-.04em}}{}lettrine

A: If the second mandatory argument to \lettrine you want to use a kern instead of a space and this kern should be the same amount as nindent. Next you want to ignore the possible following spaces.
A kern doesn't participate in justification and its size is fixed. The space following the first word instead does, but of course when the second argument (the first word except for the initial), you don't want it participates in justification.
Now you clearly see the need for a macro doing all the job.
\documentclass[foolscap]{octavo} % to get a small image
\usepackage{lettrine,lmodern,xcolor}
\usepackage[tracking=true]{microtype}

\input{GoudyIn.fd}
\renewcommand{\LettrineFontHook}{\usefont{U}{GoudyIn}{xl}{n}}
\newcommand{\LTR}[2]{%
  \lettrine[
    lines=3,
    loversize=0.3,
    findent=0.21em,
    nindent=2.5pt,
  ]{%
    \setlength{\fboxsep}{0pt}%
    \colorbox{blue!35}{#1\kern-0.04em}%
   }{#2}%
   % now we fix the problem with an empty argument
   \if\relax\detokenize{#2}\relax
     \kern2.5pt\ignorespaces
   \fi
}

\begin{document}

\LTR{T}{his} is an example of the use of a lettrine where the letters
following the lettrine appear in small caps. All is fine.

\vspace*{7pt}

\LTR{A}{} lettrine where there are no letters to be displayed in small
caps. Notice the difference in the spacing of the two displays.

\vspace*{7pt}

\LTR{A}{} lettrine where there are no letters to be displayed in small caps.
Notice the spacing between the lettrine itself and the word ``lettrine''.

\vspace*{7pt}

\LTR{A}{} lettrine where no letters are displayed in small caps.
Notice again, that in the previous example, the spacing between
the lettrine itself and the word "lettrine" immediately following
was off. But now it's fine.

\vspace*{7pt}

\LTR{A}{} lettrine where there are no letters to be displayed in small caps.
Notice again, that in the previous example, the spacing between the lettrine
itself and the word "lettrine" immediately following was off. But now,
in this paragraph, all again is \emph{not} fine.

\end{document}


text:
Q: At what point is session data available? I have the following so far opening a session (php),
session_start() ;

foreach($_SESSION as $key => $value){
    $alert .= '
' . '['.$key.']='.$value ;
}

$alert .= '
$_SERVER[MY_SERVER...]='.$_SERVER['MY_SERVER_GENERATED'] ;

if($_SESSION['MY_SERVER_GENERATED'] !== true ||
    $_SERVER['REMOTE_ADDR'] !== $_SESSION['PREV_REMOTEADDR'] ||
    $_SERVER['HTTP_USER_AGENT'] !== $_SESSION['PREV_USERAGENT']){
        $alert .= 'session destroyed' ;
        session_destroy() ;
}

if(isset($_SESSION['CREATED']) && (strtotime('now') - $_SESSION['CREATED']) > 300){//Delete expired sessions - seconds
    $alert .= '
Your session has expired!
' ;
    $_SESSION = array() ;
}

session_regenerate_id();
$_SESSION['CREATED'] = strtotime('now') ;
$_SESSION['MY_SERVER_GENERATED'] = true ;
$_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT'] ;
$_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR'] ;

echo $alert ;

The problem is the session is being destroyed everytime. $_SESSION is simply empty. At what point is it available to run checks like above?
Oops forgot to specifiy that I have verified the session is holding data but not until the page has been started. So the session is being destroyed because the $_SESSION data is all null and so the conditions are evaluating to false. As an example $alert does not register as having anything stored in it.

A: Your code seems to have a catch 22:
session_start() ;

if(!$_SESSION['MY_SERVER_GENERATED']){ <------- this will always be true
                                                for a fresh session, so
    session_destroy() ;  <--------------------- this will always be executed

your session data never has a chance to populate.


text:
Q: Mysqli object is empty, no connection error I have a very simple piece of code.
$mysqli = new mysqli($host, 'user', 'pass', $dbname);
        if ($mysqli->connect_error) {
           //       ...
        }
 print_r($mysqli);
//  ...

There are 2 servers. One with PHP 5.3 another with 5.2.4
First server works without problems, and print all details about the connection.
The second server doesn't return any error. So it looks like connection succeed.
But the object is empty (while exists)
mysqli Object
(
)

What can be the problem?

A: The answer is found at
New Mysqli Object is Null
Some more tests showed that though the object seems to be empty the properties are not.
And can be accesed directly.
So if I do
print_r($mysqli->host_info);

I get an expected data. While
print_r($mysqli)

shows as empty.
It looks like a bug in PHP 5.2.x
As I mentioned in the question it works normally on the server with PHP 5.3

A: $mysqli = new mysqli($host, 'user', 'pass', $dbname);
if (mysqli_connect_errno()) {
    throw new Exception(mysqli_connect_errno()." ".mysqli_connect_error());
}

will work for any version


text:
Q: Deploying UI in Azure AKS What is the best option to deploy the react UI in Azure ?
The backend is microservices , and planning to use AKS for it .
Confused whether to use the container or any other service to deploy the UI.


text:
Q: Navigation Drawer Toggle not updating current frame This question might have been asked many times, but none of the solutions are working for me.
I have implemented a Navigation Drawer its sliding fine.
Also the items in drawer can listen to clicks.
but the selected item in the NavigationView doesn't get highlighted?
any help would be appreciated.
yes i am doing project that came default with android studio and when i do it manually i am facing this issue.
here is my MainActivity.java
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public static String TAG = "mytag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         //set Action bar
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);       //Fab snackbar
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);          //Drawer parameters
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();                                            //show present view in drawer

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {                                 //inflate the setting menu
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
            Log.i(TAG , "camera clicked....");
            //even if its selected it doesnt reflect in navigation drawer

        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Here is my main activity.xml
<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

Also here is app_bar_main containing coordinator layout.
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.mayurn.sidepanel2.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

A: I solved it..
in the menu xml file mistakenly added android:checkable="false" in each item which i inflated to drawer elements.


text:
Q: ReactJS component HTML5 video I am trying to have have video in my web page using HTML <video> tag using ReactJS and JSX. Right now nothing is playing even though my component has the path to the file
IntroVideo this.props:
{
  introVideo: "assets/media/Cherngloong_website_intro_Uz921bT.mp4",
  muted: "true"
}

Component:
class IntroVideo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    render() {
        return(

                <video className="video-container video-container-overlay" autoPlay="true" loop muted={ this.props.muted }>
                    <source src={ this.props.introVideo } type="video/mp4" />
                </video>

        );
    }
}

Here is what I see in the developer tools:
<video class="video-container video-container-overlay" autoplay="" loop="" muted="" data-reactid=".0.1.0.0">
    <source type="video/mp4" data-reactid=".0.1.0.0.0" src="assets/media/Cherngloong_website_intro_Uz921bT.mp4">
</video>

In the developer tools, if I right click the src value and click on "Open link in new tab", the video would play in the new tab. So I believe it the path to the file is correct.
I am doing the same thing for another Component but it is for an image and it works fine:
About this.props:
{
  aboutImg: "assets/media/The_Lion_Dances_Celebrate_Happy_New_Year_Clipart.jpg"
}

Component:
class About extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    render() {
        return(

                        Message

        );
    }
}

Developer Tools:

Message

A: It looks like a bad path.  The generated html seems to be fine.  I tested it here:
http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video
The video rendered fine, and all I did was change the src.
<video className="video-container video-container-overlay" autoPlay="" loop="" muted="" data-reactid=".0.1.0.0">
  <source type="video/mp4" data-reactid=".0.1.0.0.0" src="mov_bbb.mp4">
</video>

A: Video React
a Component for playing video would be a better option as it has lots of customisation

A: In that case, I add the "?" at the end of the video url and it acts well.
I got the same case with the url by using the video in aws s3 bucket.
So I used the url as "assets/media/Cherngloong_website_intro_Uz921bT.mp4?"

A: put the video in the public/videos folder and write the src as below


text:
Q: Multiple conditions php/mysql I'm working on a multi critera search on php/mysql, this search has 5 entries:
- Type, Price Min - Price Max , Qty Min - Qty Max :
$Type = $_POST['Type'];
$Pmin = $_POST['Pmin'];
$Pmax = $_POST['Pmax'];
$Qtmin = $_POST['Qtmin'];
$Qtmax = $_POST['Qtmax'];
$query = "SELECT * FROM products where type_product='$Type'
and price_min<='$Pmin'
and price_max>='$Pmax'
and qty_min<='$Qtmin'
and qty_max>='$Qtmax' " ;

This works just fine, but the user have to fill all the entries. And my idea is that the user can enter only Type, or Type and Price, or just Qty and so ..
I tried to use the OR clause but I didn't make it work well.

A: Split your query up into parts. It's easier to use a query-assembly class for occasions such as this. And of-course PDO.
$query->select('columns from MyTable')
 ->where('deleted = 0');

if (condition) {
  $query->where('field = ?', $value);
}

if (condition) {
  $query->where('field != ?', $value);
}

$results = $query->execute();

A: where
    (a =  '$a' or '$a' = '')
and (b <= '$b' or '$b' = '')
and (c >= '$c' or '$c' = '')

notice that if a variable is an empty string, its condition is always satisfied.


text:
Q: How to plot trading signals on graph with Python? Can anyone help me please with the following? I am struggling with plotting 'buy' and 'sell' signals on my plot. The logic is following:
I am buying if w is less than 1.804482 - std_err and selling at 1.804482 or if w is less than 1.804482 - std_err*1.5 (stop loss).
I am selling if w is greater than 1.804482 + std_err and buying at 1.804482 or if w is greater than 1.804482 - std_err*1.5 (stop loss).
If anyone also would hint with the way of calculating profits that will be terrific.
fig, ax = plt.subplots(figsize=(10,4),dpi=100)

plt.plot(w,color='black')

plt.axhline(1.804482,c='green',lw=1,ls='--')
plt.axhline(1.804482 + std_err,color='blue',ls='--',lw=0.75)
plt.axhline(1.804482 - std_err,color='blue',ls='--',lw=0.75)

plt.axhline(1.804482 + std_err*1.5,color='red',ls='--',lw=0.75)
plt.axhline(1.804482 - std_err*1.5,color='red',ls='--',lw=0.75)

buy = w[w < 1.804482 - std_err]
sell = w[w > 1.804482 + std_err]

plt.plot(buy,color='g',linestyle='None',marker='*')
plt.plot(sell,color='r',linestyle='None',marker='*')

ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('%b-%-y'))
fig.autofmt_xdate()

plt.xticks(rotation=45,fontsize=12)
plt.yticks(fontsize=12)

plt.grid(b=True)


text:
Q: Android - Gradle - How to download transitive dependencies for an included jar I have included a jar in my android project,

build.gradle

as
implementation files('libs/dependency_a.jar');

But there are dependencies with are needed by this jar file, which can be downloaded from the internet but don't get downloaded while building.
How do i get Gradle to download those dependencies automatically.
Thanks.

A: The dependencies won't be downloaded automatically in this case. You have to specify all the dependencies of your jar as dependencies for your app, in your app module's build.gradle file.
android {
    ...
}

dependencies {
    //Dependencies of your app
              +
    //Dependencies of your jar

}


text:
Q: GA-H170N-WIFI motherboard compatible memory I bought GA-H170N-WIFI and since it can handle 32GB of DDR4 I want to buy two 16GB modules but can't find them. I found some cheap 16GB modules selling at my location but they are marked Buffered (or ECC). I checked motherboard's specifications and this is what I found:
2 x DDR4 DIMM sockets supporting up to 32 GB of system memory
Dual channel memory architecture
Support for DDR4 2133 MHz memory modules
Support for ECC UDIMM 1Rx8/2Rx8 memory modules (operate in non-ECC mode)
Support for non-ECC UDIMM 1Rx8/2Rx8/1Rx16 memory modules

Will those 16GB ECC modules work or not?

A: Without knowing exactly what brand and spec the modules are, we wouldnt be able to answer that. However, on the support page for you mobo there is a link where you can download a pdf that contains a list of compatible modules. Here you go..
http://www.gigabyte.com/products/product-page.aspx?pid=5552#memory%20support%20list


text:
Q: JSON POST Empty Using cURL Command I have a cURL call in a PHP 7.2 script running on CentOS 7 that is passing empty data to an endpoint. In diagnosing the issue, I have tried replicating the issue using cURL on the command-line, and not using the PHP code. Here's the command I am running (I was told to send a Content-Length of 0):
/usr/bin/curl -H "App-Key: 321321321313" -H "App-Token: 321321321312" -H "Content-Length: 0" -H "Accept: application/json" -H "Content-Type: application/json" -d '{"reportCustomFields":[{"label":"THIS","value":"THAT","shown":true},{"label":"UP","value":"DOWN","shown":true}]}' "https://url.here/endpoint_debug.php"
In the endpoint script I am printing the input stream.
$data = file_get_contents('php://input');

print "HEADERS:\n\n";
print_r(apache_request_headers()) . "\n\n";

print "RAW Data:\n\n";
print "'" . $data . "'\n\n";

No matter what I have done, the $data variable is always empty. The result I see is always ''. I also tried sending it to https://webhook.site/ and it, too, shows that the "Form values" are empty.
I have tried with -X POST and without. I tried changing the order of the calls so the URL is before the data (-d) switch. I have tried --data as well.
What could be the issue? I have replicated this on 2 different servers calling the same endpoint. Other code in the same project handles file_get_contents('php://input') properly, so I don't think that's it.
Any guidance would be appreciated!

A: TLDR: You need to remove -H "Content-Length: 0"
It doesn't make sense why you were instructed to send this if you want a response.
I tried your command unmodified with a webhook.site url, and it can return the content body (for example) without sending the head, and return nothing if sending the header:
Quite simply, this command:
/usr/bin/curl -H "App-Key: 321321321313" -H "App-Token: 321321321312" -H "Accept: application/json" -H "Content-Type: application/json" -d '{"reportCustomFields":[{"label":"THIS","value":"THAT","shown":true},{"label":"UP","value":"DOWN","shown":true}]}' 'https://webhook.site/27f6128e-2f82-4157-99da-99464f22122f'

Returns the body.   Whereas this command:
/usr/bin/curl -H "Content-Length: 0" -H "App-Key: 321321321313" -H "App-Token: 321321321312" -H "Accept: application/json" -H "Content-Type: application/json" -d '{"reportCustomFields":[{"label":"THIS","value":"THAT","shown":true},{"label":"UP","value":"DOWN","shown":true}]}' 'https://webhook.site/27f6128e-2f82-4157-99da-99464f22122f'

Obviously returns nothing
The server response headers indicate as much :
> Accept: application/json
> Content-Type: application/json
> Content-Length: 0
>
* upload completely sent off: 112 out of 112 bytes
< HTTP/1.1 200 OK
< Server: nginx/1.14.2


text:
Q: Applying custom css class using TWIG and SCSS Mixin (Style not applying) Good morning,
This has been quite a brain turner for me, learning Twig and Scass at the same time. I'm sure this fix is a simple line of code adding or removing somewhere, but since I do not understand how it works, I cannot understand how to fix it. With the current code the TWIG Include is appling the class 'Opacity_20' (or Opacity_40 etc) as selected. However this class is supposed to change the background style - but its not.
Below is the snip of HTML of the include and where the custom class will apply

{{ title|raw }}

Below is the SCSS for the div - I removed all other styles for ease of reading
.info-container{

    &:before{

    }

    &:after{

        @include white_opacity;

'white_opacity' is the include in question
{% include 'include/banner.html.twig' with {
        'title': 'Unplaceables',
        'subtitle': 'Placeholder subtitle...',
        'text': 'Lorem ipsum ',
        'background':  '/img/banners/roadshow/roadshow-banner.jpg',

        'white_opacity': 'opacity_20'
    }
%}
{% endblock %}

Below is the SCSS that is applying the class but not the style
@mixin white_opacity{

}

@mixin opacity_20 {

        background-color: rgba(255, 255, 255, 0.20);
        @include white_opacity;
}

@mixin opacity_40 {
    @include white_opacity;
        background-color: rgba(255, 255, 255, 0.40);
}

@mixin opacity_60 {
    @include white_opacity;
        background-color: rgba(255, 255, 255, 0.60);
}

@mixin opacity_80 {
        background-color: rgba(255, 255, 255, 0.80);
        @include white_opacity;
}

A: I think you might have misunderstood a crucial thing about mixins: they don't generate any output unless explicitly included, so your compiled stylesheet doesn't have any opacity_* classes defined, since those are mixins themselves. That's why it isn't applying any style: it doesn't match any selector.
You would have to change your scss to:
@mixin white_opacity {
}

.opacity_20 {
/*...*/
}

However, mixins are reusable code blocks, an empty mixin doesn't do anything. Mixins are just like functions and can also receive parameters to change the output, that's precisely what you want here.
@mixin white_opacity($opacity: 100) {
    /* Solid white if invoked without arguments */
    background-color: rgba(255, 255, 255, 0.01 * $opacity);
}

.opacity_20 {
    @include white_opacity(20);
}

/* Other styles */

But you can also apply DRY principles and generate all your classes in one go using other dynamic features of scss.
/* Define all styles to generate */
$transparencies: 20, 40, 60, 80;

@each $value in $transparencies {
  .opacity_#{$value} {
    @include white_opacity($value);
  }
}

You can read up on variables and loops in the documentation.