text:
Q: What is the synonym of "spy"? I know the word "watch" is used as a synonym of spy. Are there other synonyms that are used by native speakers?

A: Maybe the word "snoop" could be a good synonym.

I caught him snooping around in my office.
Reporters were snooping on the celebrities

A: You can also use "notice", "observe", "monitor", "track", "keep an eye on", "keep track of", "keep tabs on" -- all these have slightly different meanings, depending on what you mean to convey when you'd use spy.

*

*Use notice if you mean to say that you suddenly noticed a detail of some sort.

*Use observe if you mean to say that you're dispassionately watching something unfold, or noticing a detail or series of details with emotional detachment.

*Use monitor if you mean to say that you're continually watching something with some measurement in mind that would prompt you to step in or take action if the measurement goes outside a certain range.

*All of the keep... phrases are informal ways of saying that you're going to spend some casual effort going forward to (essentially) monitor something -- they're mostly casual ways of using the monitor sense of spy.

Notice that, strictly speaking, spy can carry a connotation of secret, covert behaviour. When you spy you have an agenda of some sort, or a secret purpose. The most neutral version of spy is to suddenly notice something: the longer the activity spent observing, the more you convey a sense of secretness.

A: To spy, in the sense of watching someone or something, could also mean keeping that thing under surveillance.
In that sense, spy (the verb) has approximately the same meaning as surveil.

A: If you mean to spy then you can use snoop (informal), keep under surveillance/observation, keep a watch on, keep an eye on, observe, spot.
If you mean spy used as noun, then you can use secret agent, undercover agent, intelligence agent, double agent, mole, snoop.
Which word/phrase suits better depends on the context.

A: infiltrator, undercover agent

A: This depends on context and connotation.
There are spies-heroes and there are sneaks, sneakers, snitches, informers, finks, noses, squeakeres, denunciators, questmans, talebearers, whistlers, grass, nark, noser, stool pigeon, checker, squeal, zuch, rat, rounder, delator, etc.
Seems like negative characters are always have better and more specific characteristic terms than positive ones.


text:
Q: Counting rows in datagridview using c# I used following code to count datagrid rows, but it works on button only. I want the total number of rows in a textbox, but it doesn't increment itself as the number of rows increase.
int numRows = dataGridView1.Rows.Count;

txtTotalItem.Text = numRows.ToString();

A: If I've understood your question correctly you want the TextBox value to change automatically when rows are added or removed because at the moment you have to press a button to refresh. Am I right?
If so just subscribe to the .RowsAdded and .RowsRemoved events and update the TextBox from there.
dataGridView1.RowsAdded += RowsAdded;
dataGridView1.RowsRemoved += RowsRemoved;

private void RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    txtTotalItem.Text = dataGridView1.Rows.Count.ToString();
}

private void RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
    txtTotalItem.Text = dataGridView1.Rows.Count.ToString();
}

A: When you assign the number, the textbox will display only that number, it will not update.
You can use an event and assign the new number to the textbox.
dataGridView1.RowsAdded+=(s,a)=>OnRowNumberChanged;

private void OnRowNumberChanged()
{
    txtTotalItem.Text = dataGridView1.Rows.Count.ToString();
}

Following Equalsk's answer, you need to have the event for removed rows as well. You can subscribe to both events with the same function since you need to just check the number.
dataGridView1.RowsRemoved+=(s,a)=>OnRowNumberChanged();

A: the datagridview will count the last empty row so make sure to

look for AllowUserToAddRows property of datagridview and set it to False.

Or add this to your code, in my case i used a label and i named it labelTotalResult, do this if you want to keep the property as true
                    labelTotalResult.Text = (dataGridView1.RowCount - 1).ToString();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read command line arguments in assembly language? I'm using the TASM assembler and I can't seem to find a way to save my command line arguments or even output them. I tried doing int 21h while dx=0081h and ah=09h. It doesn't do anything although I've read that it is the way to do it.
I've added the code of what I think should work to copy and display an argument I type in:
mov dx, 81h
mov ah, 09h
int 21h

A: The command line resides in the Program Segment Prefix (PSP), and there from position 81h. At position 80h you find the length of the string. This string always ends with a 0Dh, not $ (Pay attention for that if you want to use int 21h/ah=09h).
At the start of an .exe program the segment registers DS and ES point to that PSP. This is the reason why you have to load DS at the beginning of the program with the DATA segment (mov ax, @data;mov ds, ax). Let's skip that one:
MODEL small
.STACK 100h

.CODE

main PROC

    ; http://www.ctyme.com/intr/rb-2791.htm
    mov ah, 40h         ; DOS 2+ - WRITE - WRITE TO FILE OR DEVICE
    mov bx, 1           ; File handle = STDOUT
    xor ch, ch
    mov cl, ds:[0080h]  ; CX: number of bytes to write
    mov dx, 81h         ; DS:DX -> data to write (command line)
    int 21h             ; Call MSDOS

    ; http://www.ctyme.com/intr/rb-2974.htm
    mov ax, 4C00h       ; AH=4Ch, AL=00h -> exit (0)
    int 21h             ; Call MSDOS
main ENDP

END main


text:
Q: im trying to convert C code to MIPS program int s3[] = {3,5,7,5,0};
int x = 5
int c = 0
while(s3[0] != 0){
if(s3[i] == x){
c += 1;
s3 += 1;

}
im trying to convert this C code into mips program assembly

A: As pointed out in the comments. Your C code is not valid. But assuming you want to count the number of 5's in your array this would do the job:
.data
s3: .word 3,5,7,5,0

.text
.globl main

main:
la $t3, s3      # load adress of s3 into $t3
li $t4, 5       # load x=5 in $t4
li $t5, 0       # load c=0 in $t5
li $t6, 0       # $t6 will be list index i starting with 0

while:
add $t7, $t6, $t3   # get adress of s3[i]
lw $t8, 0($t7)      # load word from s3[i]
beq $t8, $t1, exit  # if s3[i] == 0 break

bne $t8, $t4, if    # if s3[i] != x jump to if:
addi $t5, $t5, 1    # increment counter
if:

addi $t6, $t6, 4    # increment list index
j while
exit:

Assuming this is as your correct C-Code:
int s3[] = {3,5,7,5,0};
int x = 5;
int c = 0;
int i = 0;
while(s3[i] != 0){

  if(s3[i] == x){
    c ++;
  }

i++;
}


text:
Q: Dynamic passing of php array to javascript I try to pass my array in my php code javscript . I want to get the result of my foreach . The problem is that I only get the last array. How to get each arrays in the console.log() ?
PHP CODE :
function users_nb_match($value){
  $tab_nb_match_par_user = array();
  $mois_choisi = "";
  $match_ou_catego = "matching";//"categorisation";
  if(strlen($mois_choisi)==0){
      $res = sql_dico("SELECT MAX(mois) AS zemois FROM stats_".$match_ou_catego."_univers WHERE LENGTH(mois)=7");//mois de janvier
      if($res && $rez = mysql_fetch_object($res))
          $mois_choisi = $rez->zemois;
  }
  //echo formate_pieChart("Column",$tab_values,$_GET['univers']);
  $zedate = "";
  $res = sql_dico("SELECT mois, login, nb_match FROM   stats_".$match_ou_catego."_univers
  WHERE login != '' ".((strlen($value)>0)?"
  AND univers = '".$value."'":"")." ".((strlen($mois_choisi)>0)?"
  AND mois IN ('".$mois_choisi."')":"")."
  AND LENGTH(mois)=7 ORDER BY nb_match DESC");

  //tab_value_user c'est le nb matching par utilisateurs
  while($res && $rez = mysql_fetch_object($res)){
      if(isset($tab_nb_match_par_user[$rez->login]))
          $tab_nb_match_par_user[$rez->login] += $rez->nb_match;
      else
          $tab_nb_match_par_user[$rez->login] = $rez->nb_match;
      $zedate = $rez->mois;
  }
  arsort($tab_nb_match_par_user);
  return $tab_nb_match_par_user;}

  foreach($tab_bases as $key => $values){
      $tab_nb_match_par_user = users_nb_match($values);
  }

Javascript (on the same page)

$tab_base contains database_name, so for each database name there are one query, and with this query I build an array
EDIT POST :
on this platform  when I select  " Tous les univers " I get only the last array . I do not dynamically retrieves my others javascript array .
I generate my graph like this :
function formate_pieChart(){
 $PieChart = "

";
 return  $PieChart;}

   function formate_barChart(){
  $BarChart = "

";
  return $BarChart;}

function formate_imageChart(){
$imgMi = "

";
return $imgMi;}

function genere_code($choix){
switch($choix){
    case 0:{
        return formate_barChart();
        break;
    }
    case 1:{
        return formate_pieChart();
        break;
    }
    case 2:{
        return formate_imageChart();
        break;
    }
    default:{
        return formate_barChart();
        break;
    }
  }}
if($univers=="tous") {//la variable $bdd est fixe à cet endroit
  echo genere_code(1);
}
foreach($tab_bases as $key => $values){
    $tab_nb_match_par_user = users_nb_match($values);
    $tab_mois_nb_match = mois_nb_match($values);
    echo genere_code(1);

}

If I click on ec_be or  ect the charts loading but if I click on "tous les univers" only the last chart is running...
note : the value of the  is "tous" for "tous les univers"

A:
I want to get the result of my foreach . The problem is that I only
  get the last array. How to get every arrays in the console.log() ?

Change
foreach($tab_bases as $key => $values)
{
      $tab_nb_match_par_user = users_nb_match($values);
}

to
foreach($tab_bases as $key => $values)
{
      $tab_nb_match_par_user[] = users_nb_match($values);
}


text:
Q: Solving a rectangular system of nonlinear equations with GSL I want to program a C++ code able to solve a set of equation systems which are generally nonlinear.
I am already able to solve a system of m equations with n variables using GSL when m = n by following its documentation.
However, often I have fewer equations than variables. Can I use the same functionality of GSL, or do I have to opt for a different approach or another library? Why is there not a section about solving rectangular systems in the documentation?
This is what I've tried:
#include <cmath>
#include <gsl/gsl_vector.h>
#include <iostream>
#include <gsl/gsl_multiroots.h>

void print_vector(gsl_vector *gsl) {
  printf("[");
  for (int r = 0; r < gsl->size; r++) {
    if (r != gsl->size - 1) {
      printf("%+.5f; ", gsl->data[r]);
    } else {
      printf("%+.5f", gsl->data[r]);
    }
  }
  printf("]\n");
}

int evaluate(const gsl_vector *x, void *params, gsl_vector *f) {
  const double x0 = gsl_vector_get(x, 0);
  const double x1 = gsl_vector_get(x, 1);
  const double x2 = gsl_vector_get(x, 2);

  const double y0 = 0.1 * pow(x0, 2) + 0.1 * pow(x1, 2) + 2 - x2;

  // alone not working
  gsl_vector_set(f, 0, y0);

  // with this not working
  // gsl_vector_set(f, 1, 0);
  // gsl_vector_set(f, 2, 0);

  // with this not working
  // gsl_vector_set(f, 1, y0);
  // gsl_vector_set(f, 2, y0);

  return GSL_SUCCESS;
}

int main() {
  const size_t n = 3;

  const gsl_multiroot_fsolver_type *T;
  T = gsl_multiroot_fsolver_hybrids; // "iteration is not making progress towards solution"
//  T = gsl_multiroot_fsolver_hybrid; // "iteration is not making progress towards solution"
//  T = gsl_multiroot_fsolver_broyden; // "gsl: lu.c:266: ERROR: matrix is singular"
//  T = gsl_multiroot_fsolver_dnewton; // "gsl: lu.c:147: ERROR: matrix is singular"
  gsl_multiroot_fsolver *s = gsl_multiroot_fsolver_alloc(T, n);

  gsl_multiroot_function f_multiroot_function = {evaluate, n, nullptr};

  gsl_vector *x_gsl = gsl_vector_alloc(n);
  gsl_vector_set(x_gsl, 0, 3.4);
  gsl_vector_set(x_gsl, 1, 2.7);
  gsl_vector_set(x_gsl, 2, 3.8);

  std::cout << "x_gsl: ";
  print_vector(x_gsl);

  gsl_multiroot_fsolver_set(s, &f_multiroot_function, x_gsl);

  int status;
  size_t iter = 0;
  do {
    iter++;
    status = gsl_multiroot_fsolver_iterate(s);

    std::cout << "s->x=" << std::endl;
    print_vector(s->x);

    if (status) {
      std::cout << "STOPPING: " << gsl_strerror(status) << "." << std::endl;
      break;
    }

    status = gsl_multiroot_test_residual(s->f, 1e-5);
  } while (status == GSL_CONTINUE && iter < 20);

  return 0;
}

And this
x_gsl: [+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
s->x=
[+3.40000; +2.70000; +3.80000]
STOPPING: iteration is not making progress towards solution.

Process finished with exit code 0

or this
x_gsl: [+3.40000; +2.70000; +3.80000]
gsl: lu.c:147: ERROR: matrix is singular
Default GSL error handler invoked.

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

is what I get.


text:
Q: Flutter overlay image over listtile title What is the best way to layout an image, title and icon like this

When using a ListTile with a leading image, title and trailing I get this

A: Here is my implementation using 'Stack'.
Because there is a fixed size value, I think whether it is best solution.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _buildBody() {
    return Container(
        height: 70,
        color: Color(0XFFFFA000),
        child: Container(
          margin: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
          child: Stack(
            alignment: Alignment.center,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 30,
                    ),
                    margin: EdgeInsets.only(left: 30),
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.circular(5),
                    ),
                    child: Text(
                      'El ilustre',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                        fontSize: 25,
                      ),
                    ),
                  ),
                  Icon(Icons.arrow_forward, color: Colors.white),
                ],
              ),
              Positioned(
                left: 0,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(35.0),
                  child: Image.network(
                    'https://i.ibb.co/1vXpqVs/flutter-logo.jpg',
                    width: 50,
                    height: 50,
                    fit: BoxFit.fill,
                  ),
                ),
              )
            ],
          ),
        ));
  }
}

A: Here you go :
with using Stack widget, we first added a container with text widget and then a CircleAvatar widget so that CircleAvatar can lay over the text widget.
            Stack(
              alignment: Alignment.centerLeft,
              children: [
                Container(
                  width: 300,  //define the size of text widget here
                  margin:
                      EdgeInsets.only(left: 20, top: 10, bottom: 10, right: 10),
                  padding:
                      EdgeInsets.only(left: 50, top: 10, bottom: 10, right: 10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5),
                    color: Colors.black,
                  ),
                  child: Text(
                    'Mr. Bun Burgers',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 25,
                        fontWeight: FontWeight.bold),
                  ),
                ),
                CircleAvatar(
                  radius: 30,
                  child: Icon(Icons.photo),   // Replace this icon widget with your Image asset widget.
                ),
              ],
            ),

output :


text:
Q: Is it a good style to write constants on the left of equal to == in If statement in C++? Are there any recommendations about writing constants on the left of comparison operator equal to == in If statement in C++ to avoid bug if assignment will be mistyped. Is it a good practice ? or this will reduce code readability and not recommended to do that, as there is a Compiler Warning (level 4) C4706 in case if assignment within conditional expression will be written.
const int maxValue = 15;

1)
if (currentValue == maxValue)
{
    // do something
}

(
if  operator equal to == will mistyped to assignment operator =, currentValue = maxValue the if will be always true as anything that isn't zero is "true"
Or better to write
2)
if (maxValue == currentValue)
{
   // do something
}


text:
Q: Reading slice of maps with Golang viper I am trying to read slice of maps with golang viper with the following code (suggested by: Reading a slice of maps with Golang Viper)
package main

import (
    "bytes"
    "fmt"

    "github.com/davecgh/go-spew/spew"
    "github.com/spf13/viper"
)

type conf struct {
    key string `mapstructure:"key"`
}

func main() {
    viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")

    // any approach to require this configuration into your program.
    var yamlExample = []byte(`
list:
- key: 'value_string1'
- key: 'value_string1'
`)

    viper.ReadConfig(bytes.NewBuffer(yamlExample))
    var confSlice []conf
    err := viper.UnmarshalKey("list", &confSlice)
    if err != nil {
        fmt.Println("unmarshal failed, malformat?", err)
        return
    }

    spew.Dump(confSlice)
}

The output is a slice of 2 empty struct, like
([]main.conf) (len=2 cap=2) {
 (main.conf) {
  key: (string) ""
 },
 (main.conf) {
  key: (string) ""
 }
}

Tried several different ways but still not found one worked. Anyone who can provide me a hint? Thanks.
PS: It is a slice of map with some kv pairs, not just with 1 kv pair. I cut it for brevity.


text:
Q: can't set a div inside a div perfectly? Here is My Demo
My wrapper div is not rendering inside my second div.
I am trying to place a div inside a second div, but wrapper div is created above the second div.
I couldn't find the bug. So can anyone help fix this?
body {
margin:0px;
}

.homebar
{
height:40px;
background-color:#242c3c;
display:block;

}
#nicebody
{
display:block;
min-width:960px;
}

#wrapperdiv
{

border:3px solid green;
height:28px;
width:163px;

}

my home.aspx

<form id="form1" runat="server">

       SGIPC

</form>

A: It actually is rendering inside div#seconddiv --> I gave it position: relative; and top: 200px; or so…
Check it: JSFiddle
You just need to position it, but I would suggest using margin and not position + top.

A: I think to put css Float:left; for both div #seconddiv and #wrapperdiv
lky below
CSS:
#seconddiv { float:left; }

#wrapperdiv{
   float:left;
   border:3px solid green;
   height:28px;
   width:163px;
}


text:
Q: How do I change master page for a specific applicaiton page in sharepoint I created  custom access denied page through OOB. Now i would like to change the master page. Can anyone explain how to do that.

A: You can create Application page for the same, as you need to apply different Master Page for particular Page and also Page should be visible to person who does not have permission for the particular item or page....
You can also inherit the Master page and layout from the exiting access denied page and customize as per your requirement..
Below links may help you solve your problem:
Create Custom access denied Page:
http://social.technet.microsoft.com/wiki/contents/articles/31253.sharepoint-2013-how-to-create-a-custom-access-denied-page.aspx
How to set Custom Access Denied Page:
https://social.msdn.microsoft.com/Forums/sharepoint/en-US/5c40d604-bdb4-405a-88d6-a0d3b4eb0af1/how-to-set-custom-access-denied-pages-in-sharepoint-2013?forum=sharepointdevelopment


text:
Q: What's causing our long multi-network 2.4GHz wifi drop-outs? I live a small, low-density town. Within 50m radius, there are 10 houses, no offices. Normally, I can see ~8 APs on 2.4GHz, one of which is ours. They're well spread across the band. It also functions at 5GHz, but obviously, I can only see ours within the house.
All in all, a fairly standard, low interference  scenario.
But for the past couple of months, every so often 2.4GHz dies. And I mean dead. Our 2.4GHz-only devices drop off the network. When I scan from laptops, phones, dongles, I can only see our 5GHz network. Even the neighbours —who between them normally cover the entire spectrum— have dropped off the face of the earth. This lasts for minutes... And then everything Just Works™ again.
This is low-density population. I don't think our 80yo or middle-aged family neighbours are likely to be using a for-purpose Wi-Fi-blocker but that's really how this presents. Like a high-interference sustained fuzzing of the band.
The only change to note is a set of roadworks that has slowly been moving past our house. Temporary traffic lights might have causes some interference and I'd have bought this when they were right outside but they're about 100m away now.
So I'm stumped. Any ideas? Assuming this is interference, is there anything I can do to track it (without spending billions)? Even if that's just registering that there is interference coming from somewhere.

A: As you don't see any networks when this issue happens, the source of the interference is likely to be a non-WiFi protocol. This could be any device that works on 2.4GHz.
To find the source of these transmissions, you would need a receiver tuned for 2.4GHz. Preferably this would be a spectrum analyzer, so you can see the bandwidth of the interference. Connect the spectrum analyzer to a directional antenna tuned for 2.4GHz (Yagi design for example) and you will be able to "home in" on the source of the interference.
Decent spectrum analyzers are quite expensive. You might be able to find something usable in the "hacker/maker" community for cheap SDR receivers (RTLSDR with a downconverter or a HackRF). Another idea is to find a radio amateur or hackerspace in your area, they could have that kind of equipment and a usually happy to help.

A: Found the likely culprit: Google Chromecast.
Our closest next door neighbour recently bought a couple of Chromecasts. These little apparently have a bug that floods their network with hundreds of thousands of MDNS discovery packets. The reports do only suggest a DOS on their own networks, but it's still 2.4GHz data being blurted out. It's going to cause some interference at that sort of rate.
I expect time to fix this now it's being confirmed but in short order, I've asked them to unplug the one nearest us and we've not had any drop-outs since.


text:
Q: Reorder table with jQuery How can I reorder table rows?

        Prekės pavadinimas
        Kiekis
        Kaina
        Suma

                <input type="text" class="form-control" id="product" name="product" placeholder="Prekė">

                <input type="text" class="form-control" id="quantity" name="quantity" placeholder="Kiekis">

                <input type="text" class="form-control" id="price" name="price" placeholder="Kaina">

                <input type="text" class="form-control" id="total" name="total" placeholder="Suma" disabled>

$('tr td span:nth-of-type(1)').on('click', function() {
    moveup = $(this).parent();
    moveup.prev().before(moveup);
});

$('tr td span:nth-of-type(2)').on('click', function() {
    movedown = $(this).parent();
    movedown.next().after(movedown);
});

And here is how my code now working with jQuery:
http://jsfiddle.net/zJ8hd/21/
Thanks for help in advance! :)

A: moveup =  $(this).parent();

Here, this refers to the span, so its parent is a td not the row. If you want to move the whole row, you should give a look at .closest()(1) and then use .prev() or .next().
Your are close to the solution, I'll let you work a little ;)
1 -> https://api.jquery.com/closest/

A: Your logic for traversal and amending the DOM isn't quite right. You need to get the parent tr element and then insert it before/after the prev/next tr, something like this:
$('tr td span:nth-of-type(1)').on('click', function() {
    var $row = $(this).closest('tr')
    if ($row.index() == 1)
        return;
    $row.insertBefore($row.prev());
});

$('tr td span:nth-of-type(2)').on('click', function() {
    var $row = $(this).closest('tr')
    $row.insertAfter($row.next());
});

Working example
Note I added foo and bar as default field values in the fiddle only to make the movement more obvious.


text:
Q: Do unused properties cause overhead? Suppose we had a generated class with a lot of redundant accessors.  They are just accessors, they are not fields.  They are not called anywhere.  They just sit there being redundant and ugly.
For example:
public class ContrivedExample
{
    public int ThisOneIsUsed { get; set; }

    public int ThisOneIsNeverCalled0 { get { /* Large amounts of logic go here, but is never called. */ } }
    public int ThisOneIsNeverCalled1 { get { /* Large amounts of logic go here, but is never called. */ } }
    public int ThisOneIsNeverCalled2 { get { /* Large amounts of logic go here, but is never called. */ } }
    //...
    public int ThisOneIsNeverCalled99 { get { /* Large amounts of logic go here, but is never called.*/ } }
}

ContrivedExample c = new ContrivedExample() { ThisOneIsUsed = 5; }

The only overhead I can think of is that it would make the .DLL larger.  I expect that there would be zero runtime penalties.
Does this cause any other overhead?  Even a tiny overhead of any kind?

A: It is unlikely to have any measurable run-time overhead. In any case since it is performance question - measure your usage and make decisions for your case if in doubt.
Unreferenced methods do not get compiled by JIT nor cause direct run-time overhead.
Metadata for the class will be bigger (along with size of assembly as you've mentioned).
You may get indirect impact if the class is used in some code that involves a lot of reflection, also if code repeatedly reflects over the same class it is likely wrong by itself.


text:
Q: One object per distinct field / value I have this schema that represents a "File object" :
{
"_id" : ObjectId("59f7184aedd1712cdd6a148a"),
"file" : {
    "part" : ".part000010",
    "creation_time" : "2017-10-26T14:01:42.309597",
    "archive_time" : "2017-10-30T12:17:14.770871",
    "inode" : 18644328,
    "size" : 733326,
    "tags" : null,
    "group" : "ssc_hpci",
    "uuid" : "408bf97c-bd6c-11e7-a854-de7a7d6f0f6c",
    "filename" : "build/hpca/base_library.zip",
    "owner" : "anl001",
    "gid" : 66026,
    "uid" : 66799,
    "checksum" : null,
    "symlink" : false
},
"archivename" : "build",
...
}

Many files will have the same archivename.
I need one object per distinct archivename. Obj1 would have an archive named "build", Obj2 an archive named "build1", etc.
Projection is not suitable for this, aggregate neither.
I'm using pymongo.


text:
Q: Finding local maxima and minima of function
I am supposed to find the local extreme of function $z=xy$ on set
  $x^2+y^2=1$.

I used substitution:$ x=\cos \theta ,y=\sin \theta $, where $\theta \in \left [ 0,2\pi \right ]$.
So:
$z=\cos \theta \sin \theta \iff$ $z=\frac{\sin 2\theta }{2}$, but I do not know, how to continue.
Can anyone help me, please?

A: Let $\phi=2\theta$, so we're looking for the extremes of $z=\dfrac{\sin2\theta}2=\dfrac{\sin\phi}2.$
Since $-1\le \sin\phi\le 1$, the extremes occur when $\sin\phi=\sin2\theta=\pm1$; i.e., $z=\pm\dfrac12$.

Another approach would be to look for extremes of $z^2=x^2(1-x^2)=x^2-x^4;$
the derivative is zero when $2x-4x^3=2x(1-2x^2)=0$.

Another approach uses a Lagrange multiplier:
$xy-\lambda(x^2+y^2-1)$
$y-2\lambda x=0, x-2\lambda y=0, x^2+y^2=1$
$y=2\lambda x=4\lambda^2y$ so $\lambda^2=\frac14$ so $\lambda=\pm\frac12$ so $y=\pm x$ and $x^2+y^2=1...$

A: $$1 = x^2 + y^2 \ge 2 |x|\cdot|y| $$
$$ \rightarrow 1 \ge 2|z| $$
$$ \rightarrow \frac{1}{2} \ge z \ge -\frac{1}{2} $$
$ \rightarrow $ local extreme of $z$ is $ \pm\frac{1}{2} $

A: The sine function reaches its maximum at $\pi/2\pm2n\pi,$ so you'd have $$ 2\theta = \frac \pi 2 \pm 2n\pi $$
$$
\theta = \frac \pi 4 \pm n\pi
$$
This corresponds to two points on the circle:
\begin{align}
& \theta = \frac\pi4, \text{ so that } (x,y) = \left( \frac{\sqrt 2} 2, \frac{\sqrt 2} 2 \right) \\[10pt]
& \theta = \frac \pi 4 + \pi, \text{ so that } (x,y) = \left( \frac{-\sqrt 2} 2, \frac{-\sqrt 2} 2 \right)
\end{align}


text:
Q: container in bootstrap is not working In bootstrap 3.3.6 version dist folder I have a index.html file and which contain the following code but these is not working. With bootstrap folder we have cs,js,font folder and index.html
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Bootstrap 101 Template</title>

  <link href="css/bootstrap.min.css" rel="stylesheet">

Left Side

Middle

Left Side

A: Use col-md-* and not mid

<link href="css/bootstrap.min.css" rel="stylesheet">

Left Side

Middle

Left Side

A: heres is the solution:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Bootstrap 101 Template</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Left Side

Middle

Left Side

check this :https://jsfiddle.net/x4qapovk/3/


text:
Q: use Instagram Basic Display API with Static site like Hugo and localhost? im working on a website built With the static site generator Hugo.
I want to display the 5 latest instagram images from my own feed but having problem with the new Instagram Basic Display API.
question:
Can i use my localhost:1313 as reference when setting the
Valid OAuth Redirect URIs, Deauthorize Callback URL and Data Deletion Request URL? if not, do i need to use a https url? got a http error when i tried against a live domain.


text:
Q: Android Retrofit start another request from success method I'm using retrofit to add a task.
private void addTask(Map<String, String> map) {

    ApiClient.getPptApiClient().addTask(map, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            Log.d("TAG", "add task success");
            downloadTasks(id)

        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Log.d("TAG", "add task failed");
        }
    });
}

after add task succes i want to refresh my list, and for that i have method below:
private void downloadTasks(int id) {
    ApiClient.getPptApiClient().getTasks(id, new Callback<ArrayList<TaskModel>>() {
        @Override
        public void success(ArrayList<TaskModel> taskModels, Response response) {
            Log.d("TAG", "download task success");
            taskAdapter.clear();
            taskAdapter.addAll(taskModels);
            lvTasks.setAdapter(taskAdapter);

        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Log.e("TAG", "download task failed");

        }
    });
}

My problem is : downloadTask is never called.
Can you explain why?


text:
Q: Sending message to existing form class hope someone can help me with this issue. I have been trying different things for a while and I have tried a few solutions that I found on here and other site to no avail but as I am a novice, I think I have probably missed something. Here goes.
I am writing an application and I want to add in the ability for users to send messages to each other and have them pop on the screen. This is fine, the message is delivered and the form pops but if the user sends another message, it creates a new instance of the class. It doesn't appear to be finding the open form. I have tried a few things to search through open forms:
    //Receive message is started by the OpenListeningSocket function
    //ProcessingThread = new Thread(() => ReceiveMessage());

    private void ReceiveMessage()
    {
        Socket newSocket = tempServerSocket;
        NetworkStream netStream = new NetworkStream(newSocket);
        BinaryReader br = new BinaryReader(netStream);
        BinaryWriter bw = new BinaryWriter(netStream);
        String message;
        String sender;
        try
        {
            do
            {
                message = br.ReadString();
                sender = br.ReadString();

            } while (br.PeekChar() > 0);
            /*
            //FormCollection fc = Application.OpenForms;
            for(int i = 0; i <= Application.OpenForms.Count; i++)
            //foreach (Form frm in Application.OpenForms)
            {
                if(Application.OpenForms[i].Text == sender)
                //if (frm is Message)
                {
                    Message liveMessage = (Message)Application.OpenForms[i];
                    if (liveMessage.Text == sender)
                    {
                        MessageBox.Show("liveMessage Message detected");
                        liveMessage.lbMain.Items.Add(sender + ": " + message);
                        liveMessage.cbUsers.Text = sender;
                        liveMessage.cbUsers.Enabled = false;
                        liveMessage.TopMost = true;
                        liveMessage.TopMost = false;
                        liveMessage.ShowDialog();
                        //liveMessage.Visible = true;
                    }
                }
                else if(Application.OpenForms[i] is Message)
                {
                    newMsg = new Message();
                    newMsg.Text = sender;
                    newMsg.userName = userName;
                    newMsg.cbUsers.Text = sender;
                    newMsg.cbUsers.Enabled = false;
                    newMsg.lbMain.Items.Add(sender + ": " + message);
                    //msgList.Add(newMsg);
                    newMsg.ShowDialog();
                }

            }

            */

            if (msgList.Count < 1)
            {
                Message newMsg = new Message();
                newMsg.Text = sender;
                newMsg.userName = userName;
                newMsg.cbUsers.Text = sender;
                newMsg.cbUsers.Enabled = false;
                newMsg.lbMain.Items.Add(sender + ": " + message);
                msgList.Add(newMsg);

                newMsg.Visible = true;

            }
            else
            {
                foreach (Message msg in msgList)
                {
                if (msg.Text == sender)
                    {
                        //Message msg = (Message)frm;
                        msg.lbMain.Items.Add(sender + ": " + message);
                        msg.cbUsers.Text = sender;
                        msg.cbUsers.Enabled = false;
                        newMsg.Visible = true;
                        //msg.Visible = true;
                    }
                }
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
     }

I have tried looking through all the open forms in the Form Collection and if the form is of the Message class, cast it to Message. I couldn't get this to work. I tried adding all new Message instances to a Generic List of type Message and then iterating through them but this didn't work, maybe being disposed by the ProcessingThread?
I have tried looking at some instant messaging application examples but I haven't come across how they send the new message to the existing form.
If anyone has any helpful hints or could point me in the right direction, it would be greatly appreciated. Thanks, Cameron.


text:
Q: Has anyone successful used oracledb with Mac M1 I have 2021 MacBook Pro M1 and I have nodes project where I am trying to use oracledb package and when I run I get the following error message:
Error: DPI-1047: Cannot locate a 64-bit Oracle Client library: "dlopen(/Users/.../mac_client/instantclient_19_8/libclntsh.dylib, 0x0001): tried: '/Users/.../mac_client/instantclient_19_8/libclntsh.dylib' (mach-o file, but is an incompatible architecture (have (x86_64), need (arm64e)))". See https://oracle.github.io/node-oracledb/INSTALL.html for help
I have gone to the site and cannot find instructions on how to resolve my issue.  I have also done several searches and have not found anything.  I am just wondering if anyone in this community has run into this issue and how did you resolve it.
Any and all help is appreciated.


text:
Q: Hibernate Criteria API result narrowing on foreign key I'm using Hibernate Criteria API in my web project. Currently I got stuck in a serious problem. I've following scenario.

I want to get all students of a particular school (say with S_ID=1), but unable to do so. The problem is that I don't know what restriction to add to criteria.

A: Try:
 session.createCriteria(Student.class).createAlias("your_class_property", "class").createAlias("class.your_school_property", "school").add(Restrictions.eq("school.id", 1)).list()


text:
Q: Travis CI build running deploy stage on master even though tag condition is not met I have the following .travis.yml file in my project, configured to build always and to deploy only when the build is triggered by a GitHub tag matching a certain version string:
language: java
sudo: false
cache:
  directories:
    - "$HOME/.cache"
jobs:
  include:
    - stage: build
      os: linux
      jdk: oraclejdk8
    - stage: build
      os: linux
      jdk: openjdk8
    - stage: build
      os: linux
      jdk: oraclejdk11
    - stage: build
      os: linux
      jdk: openjdk11
    - stage: deploy
      os: linux
      jdk: openjdk8
stages:
  - build
  - name: deploy
    if: tag =~ ^[0-9]+\.[0-9]+\.[0-9]+
install:
  - gpg --version
  - mvn process-resources -B -V -e
script:
  - mvn test -B -V -e
deploy:
  - provider: script
    script:
      - openssl aes-256-cbc ... -in .travis.gpg.enc -out .travis.gpg -d
      - openssl aes-256-cbc ... -in .travis.settings.xml.enc -out .travis.settings.xml -d
      - gpg --import .travis.gpg
      - cp .travis.settings.xml $HOME/.m2/settings.xml
      - mvn clean deploy -Dmaven.test.skip=true -Dmaven.javadoc.skip=true -P sign -B -V -e
    skip_cleanup: true
  - provider: releases
    api_key:
      secure: CKKEi9hoN...xbzZByUU80Q=
    file_glob: true
    file:
      - $HOME/.m2/repository/path/to/project-*.pom
      - $HOME/.m2/repository/path/to/porject-*.pom.asc

This worked fine when I pushed my branch: The Travis CI build ran and said it was skipping the deploy stage because the condition wasn't met. However, when I merged this branch into master, the Travis CI build ran against master (correct) and invoked the deploy stage (incorrect), attempting to deploy to Maven/GitHub (and failing due to what I believe is an unrelated error).
Oddly, it's not that it started the deploy job (it didn't; it only started the build jobs). It added the deploy stage to the first four (build) jobs (the ones that say stage: build). This is shown in the screenshot below, where you can see that it ran the four build jobs, and they all failed (specifically, they all failed on the deploy stage, but they shouldn't have tried to deploy; only the deploy job should deploy).

So, two questions:

*

*What did I do wrong here that made it try to deploy from master even though it wasn't a tag?

*Any idea what the following error is that (thankfully) made the deploy fail, and what I need to do to fix it?

Deploy error:
$ rvm $(travis_internal_ruby) --fuzzy do ruby -S gem install dpl
Successfully installed dpl-1.10.6
Parsing documentation for dpl-1.10.6
Installing ri documentation for dpl-1.10.6
Done installing documentation for dpl after 0 seconds
1 gem installed
dpl.1
Installing deploy dependencies
Successfully installed dpl-script-1.10.6
Parsing documentation for dpl-script-1.10.6
Installing ri documentation for dpl-script-1.10.6
Done installing documentation for dpl-script after 0 seconds
1 gem installed
/home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/cli.rb:54:in `system': wrong first argument (ArgumentError)
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/cli.rb:54:in `shell'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-script-1.10.6/lib/dpl/provider/script.rb:19:in `push_app'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/provider.rb:199:in `block in deploy'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/cli.rb:41:in `fold'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/provider.rb:199:in `deploy'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/cli.rb:32:in `run'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/lib/dpl/cli.rb:7:in `run'
    from /home/travis/.rvm/gems/ruby-2.4.1/gems/dpl-1.10.6/bin/dpl:5:in `<top (required)>'
    from /home/travis/.rvm/gems/ruby-2.4.1/bin/dpl:23:in `load'
    from /home/travis/.rvm/gems/ruby-2.4.1/bin/dpl:23:in `<main>'

A: So, I've discovered the answer to both questions.
First, the weird error was due to this:
deploy:
  - provider: script
    script:
      - do something
      - do something else
      - do another thing

The normal script directive in Travis CI builds accepts a sequence, but the script directive within the script deploy provider is different and only accepts a single string, which it invokes as a single command. You can't even pass in a multi-line string. Still doesn't work. I filed this bug with Travis about that and, until that is fixed, found a temporary workaround for that issue using before_deploy (below).
Second, if you use the top-level deploy directive, then deployment will run as part of the build stage instead of as its own stage. The documentation is not clear on this, but it was an easy fix.
Finally, you can only encrypt a single file, not multiple files, so you if you have multiple secret files, you have to use a Tar archive and encrypt that.
Here's the working Travis build after I worked out all my issues:
language: java
sudo: false
cache:
  directories:
    - "$HOME/.cache"
jobs:
  include:
    - stage: build
      os: linux
      dist: trusty
      jdk: oraclejdk8
    - stage: build
      os: linux
      dist: trusty
      jdk: openjdk8
    - stage: build
      os: linux
      dist: xenial
      jdk: oraclejdk11
    - stage: build
      os: linux
      dist: xenial
      jdk: openjdk11
    - stage: deploy
      os: linux
      dist: xenial
      jdk: openjdk8
      before_deploy:
        - openssl aes-256-cbc -in .travis.secrets.tar.enc -out .travis.secrets.tar -d
        - tar -xvf .travis.secrets.tar
        - rm .travis.secrets.tar
        - gpg --import travis.gpg
        - rm travis.gpg
        - mv settings.xml $HOME/.m2/settings.xml
      deploy:
        - provider: script
          script: "mvn clean deploy -Dmaven.test.skip=true -Dmaven.javadoc.skip=true -P sign -B -V -e"
          on:
            tags: true
          skip_cleanup: true
        - provider: releases
          api_key:
            secure: CKKEi9hoN...xbzZByUU80Q=
          file_glob: true
          file:
            - $HOME/.m2/repository/io/path/to/project-*.pom
            - $HOME/.m2/repository/io/path/to/project-*.pom.asc
          on:
            tags: true
stages:
  - build
  - name: deploy
    if: tag =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$
install:
  - gpg --version
  - mvn process-resources -B -V -e
script:
  - mvn test -B -V -e


text:
Q: Making Word document embedded in a web page editable or read-only I'm embedding some Word documents into our web page using iframe like this:
<iframe src="ftp://ftp.example.com/www/uploads/Image/test.doc" width="100%" height="400">
    Alternative
</iframe>

The problem is that the embedded Word control allows the user to edit the documents and shows an icon to save them, but doesn't actually save anything. Is it possible to setup Word to save edits back to the FTP server? If not, is there someway we can make the document read-only so the user doesn't get the idea that they can make changes? We're using IE7 and Word 2003.
(I just asked a related question about getting Word to save to a FTP server: Possible for Word to edit documents directly off an web server without Sharepoint?)

A: You can use ActiveX component like EDraw OfficeView or UltraOffice to embbed office and give you few control against the save and edit the document. You can also send it back to server for save.

A: There are a number of solutions to your problem, the easiest in my oppinion is a commercial app: https://crocodoc.com/. Developers have unlimited preview time but production use requires a license, don't know if thats an option in your case? To get this working in IE7 you will also need  http://html5boilerplate.com/ together with http://code.google.com/p/html5shiv/.
Not sure if this solution will remain free but it is at the moment: https://cloudconvert.org/page/api. They provide an api to convert documents to html, you could write a script to convert docs to html on upload and then store html to show on site.
Another good option is http://www.phpdocx.com/ they have a conversion plugin to convert docx to HTML, pdf and such.
As for making your existing solution read only, i read somewhere you can do it with the method below but i am unable to test as i am on a mac and currently have no access to a machine with IE right now.
<object id="msword" width="100%" height="100%" classid="clsid:67F2A879-82D5-4A6D-8CC5-FFB3C114B69D" data='[insert document name].doc'>
    <PARAM NAME="src" VALUE="file:////[insert full document path here].doc" >
    <PARAM NAME="readonly" value=true>
</object>

Hope these suggestions help you with your project!

A: I would recommend converting the file to an mht file.  this will provide cleaner lines when shown in the browser and prevent the user from editing or saving the file.


text:
Q: facing problems with vi editor in CLT My keyboard keys are not working properly in Command line terminal when i use "vi" command to edit a file or write a program.backspace doesn't work. arrow keys doesn't work and are printing A B C D instead of moving the cursor.

A: You need to install it first, because by default vim-tiny is installed.
sudo apt-get install vim


text:
Q: In a constructor, set the constructed object to another To help in my logging, I created a convenience function that create a winston.Logger and set it with the correct transports, and return that logger.
Everything works fine, but ESLint is complaining I am calling what it see as a constructor without using new.
While I could just ignore the warning, I like to have strict rules, and seeing const logger = Logger('foo') is indeed confusing.
Renaming Logger to something like getLogger seems ugly to me, but ESLint don't complain.
What I thought was to make Logger a constructor, that directly point to the result of new winston.Logger.
Obviously, this = new winston.Logger didn't worked, but I am pretty sure there is a clean way to do this.
Current snippet of log.js:
module.exports = (file) => {
    let transports = getTransports(file),
        logger = new (winston.Logger)({
            rewriters: [
                (level, msg, meta) => {
                    meta.app = file + '.js';
                    return meta;
                }
            ],
            transports: transports
        });
    return logger;
    // this = logger;
};

Use:
'use strict';

const Logger = require('./log.js'),
    logger = Logger('foo');

logger.debug('foo');

A: As you probably know, the warning is there because functions with initially-capped names are normally constructor functions in JavaScript.
If you want, you can call your existing Logger with new. That will create and throw away an object, but that's harmless. It works because if a constructor function returns a non-null object reference, the result of new is that object reference instead of the object created by new. Your function returns logger, which is a non-null object reference, so it'll work. (If it were me, I'd probably call it getLogger and just call it normally, to make it clear what it's doing, but that's a matter of style and you've said you don't want to, which is fair enough.)
Here's a simpler example to demonstrate this behavior of new and constructor functions:

var obj = {
  note: "I'm the one object Singleton always returns"
};
function Singleton() {
  this.note = "This object is thrown away, so you never see this object";
  return obj;
}
function Normal() {
  this.note = "This object isn't thrown away";
}

var o1 = Singleton();
console.log("o1", o1);
var o2 = new Singleton();
console.log("o1 === o2? ",  o1 === o2);  // true
console.log("o1 === obj?", o1 === obj); // true
var n1 = new Normal();
console.log("n1", n1);
var n2 = new Normal();
console.log("n1 === n2?", n1 === n2);   // false


text:
Q: find the local time zone's difference from GMT in minutes I have timezone in format GMT+09:00 and GMT+10:00. I am using Linux (Open Suse) and C++17.
I am trying to find out the local time zone's difference from GMT in minutes.
Here is my sample program.
static constexpr time_t const NULL_TIME = -1;

// returns difference in mintues
long tz_offset(time_t when = NULL_TIME) {
  if (when == NULL_TIME)
    when = std::time(nullptr);
  auto const tm = *std::localtime(&when);
  std::ostringstream os;
  os << std::put_time(&tm, "%z");
  std::string s = os.str();
  // s is in ISO 8601 format: "±HHMM"
  int h = std::stoi(s.substr(0, 3), nullptr, 10);
  int m = std::stoi(s[0] + s.substr(3), nullptr, 10);
  return h * 60 + m;
}

int main() {
  for (auto &timezone :  {"GMT+08:00", "GMT+09:30", "GMT+10:00", "GMT+10:30", "GMT+11:00"}) {
    setenv("TZ", timezone, 1);
    tzset();
    std::cout << "----------- TZ Changed to " << timezone << "---------------\n";
    std::cout << "difference in mins =" << tz_offset() << std::endl;
    auto tz_env_var = getenv("TZ");
    if (tz_env_var != nullptr) {
      std::cout << "TZ=" << tz_env_var << "\n";
    }
  }

  return 0;
}

But I am getting the difference in the negative, they should be positive.
----------- TZ Changed to GMT+08:00---------------
difference in mins =-480
TZ=GMT+08:00
----------- TZ Changed to GMT+09:30---------------
difference in mins =-570
TZ=GMT+09:30
----------- TZ Changed to GMT+10:00---------------
difference in mins =-600
TZ=GMT+10:00
----------- TZ Changed to GMT+10:30---------------
difference in mins =-630
TZ=GMT+10:30
----------- TZ Changed to GMT+11:00---------------
difference in mins =-660
TZ=GMT+11:00

Any pointer why I am getting them in the negative?

A: These strings are known as POSIX timezones and are defined here.  This definition says this about the UTC offset:

If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west (which may be indicated by an optional preceding '+' ).

Meanwhile std::put_time is defined in terms of the C/Posix strftime which says this about offset:

%z is replaced by the offset from UTC in the ISO 8601 format ''−0430'' (meaning 4
  hours 30 minutes behind UTC, west of Greenwich), or by no characters if no time
  zone is determinable. [tm_isdst]

In summary, there's one convention for posix time zone strings (negative means east of the prime meridian), and another for just about everyone else, including other parts of posix (negative means west of the prime meridian).
So your code is actually getting the correct answer.
Fwiw, here is a C++17 free, open-source, header-only Posix time zone library which can to the job without changing the global environment variable TZ, and does it with simpler syntax:
#include "date/ptz.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    using date::operator<<;

    for (auto &timezone : {"GMT+08:00", "GMT+09:30", "GMT+10:00", "GMT+10:30", "GMT+11:00"})
    {
        auto offset = Posix::time_zone{timezone}.get_info(system_clock::now()).offset;
        std::cout << "difference is " << duration_cast<minutes>(offset) << '\n';
        std::cout << "TZ is " << timezone << "\n\n";
    }
}

Output:
difference is -480min
TZ is GMT+08:00

difference is -570min
TZ is GMT+09:30

difference is -600min
TZ is GMT+10:00

difference is -630min
TZ is GMT+10:30

difference is -660min
TZ is GMT+11:00


text:
Q: Is there a way to achieve what that code wants to do with scrolling down instead of clicking on Next? Based on an answer to my previous question here , I learned about pagination in Django and I can go to next pages after clicking on Next .
Views:
def All( request  ):
    p=product.objects.all()
    pa=Paginator(p,20)
    page=request.GET.get('page')
    pro=pa.get_page(page)
    return render(request,'home.html',{'pro':pro})

Template:

         {%for p in pro%}

{{p.description}}

                        <button > ${{p.price}} buy</button>

         {%endfor%}
         {% if pro.has_next %}
            Next
         {% endif %}

This code wants to show me the next pages:
 {% if pro.has_next %}
    Next
 {% endif %}

Is there a way to achieve what that code wants to do with scrolling down instead of clicking on Next?


text:
Q: How to sort 10 most called numbers from the list of called numbers with counter I am working on phonebook app in android which contains frequently called numbers activity too.I have got the list of numbers with the counter that how many times its have been called.But now i want only 10 most called numbers from that list.
Here is the working code:
I have sorted data using map.
Basically i wanted to sort the data by value which is counter of called numbers.
 ListView list_view2;
String[] PERMISSIONS = {Manifest.permission.READ_CALL_LOG};
ArrayList<Integer> listdata2;
ArrayList<Integer> key;
ArrayList<Integer> value;
int maxIndex = 0;
Integer val;

HashMap<String, Integer> map = new HashMap<String, Integer>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frequently_called);

    list_view2 = findViewById(R.id.list_view2);
    listdata2 = new ArrayList<Integer>();

    getCallDetails();

}

@SuppressLint("LongLogTag")
private String getCallDetails() {

    StringBuffer sb = new StringBuffer();
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_CALL_LOG)
            != PackageManager.PERMISSION_GRANTED) {
        requestContactsPermissions();
        return requestContactsPermissions();
    }

    Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);

    Integer number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);

    while (managedCursor.moveToNext()) {
        String phNumber = managedCursor.getString(number);
        Integer callType = managedCursor.getInt(type);
        Integer callDate = managedCursor.getInt(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        Integer callDuration = managedCursor.getInt(duration);

        Log.e("Phone number", phNumber + "");
        Log.e("call type", callType + "");
        Log.e("call duration", callDuration + "");
       // Log.e("call date", callDate + "");
        Log.e("call day time", callDayTime + "");

        String dir = null;
        int dircode = new Integer(callType);
        switch (dircode) {
            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                dir = "INCOMING";
                break;

            case CallLog.Calls.MISSED_TYPE:
                dir = "MISSED";
                break;
        }

        if (map.get(phNumber) == null) {
            map.put(phNumber+"", 1);
        } else {
            Integer scount = map.get(phNumber).intValue();
            scount++;
            map.put(phNumber+"", scount);

            //Log.e("map values", map + "");
        }
    }
    managedCursor.close();

    //Log.e("map.keySet()",map.keySet().toString());

    HashSet<String> numbersset=new HashSet<String>(map.keySet());

    ArrayList<String> numbers= new ArrayList<String>();
    ArrayList<Integer> counts= new ArrayList<Integer>();

    Iterator iterator=numbersset.iterator();

    while(iterator.hasNext()) {
        String no = iterator.next().toString();
        numbers.add(no);
        counts.add(map.get(no));
        }

    Log.e("number count ",numbers.size()+"|");
    Log.e("count count ",counts.size()+"|");

    for (int i=0;i<counts.size();i++){
        for(int j=0;j<counts.size();j++){
            int t1=counts.get(i);
            int t2=counts.get(j);

            if(t1 > t2){
                for(t1=0;t1>=10;t1++) {
                    for(t2=0;t2>=10;t2++) {
                        int temp = counts.get(j);
                        counts.set(j, counts.get(i));
                        counts.set(i, temp);

                        String temps = numbers.get(j);
                        numbers.set(j, numbers.get(i));
                        numbers.set(i, temps);
                    }
                }
            }
        }
    }

//Sorting data in reverse
    for (int i=0;i<counts.size();i++){
        Log.e("sort-"+numbers.get(i),counts.get(i)+"");
    }

    return sb.toString();
}

    private String requestContactsPermissions () {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CALL_LOG)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
        } else {
            ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
        }
        return null;
    }
}

A: For your count array.This will sort your counts array in descendingorder.
Comparator mycomparator = Collections.reverseOrder();

Collections.sort(counts,mycomparator);

now if you want to get 10 elements from your ArrayList.
ArrayList<Integer> popular_counts= new ArrayList<Integer>();

for(int i = 0; i< 9; i++){
   popular_counts.add(counts.get(i));
}

popular_counts is your final ArrayList.

A: You can create loop that will be 10 times and another one which will search every time for the biggest counter and add the coresponding number to the new list.
@Override
protected void onCreate(Bundle savedInstanceState) {  // Exaple to show result
    ArrayList<String> number = new ArrayList<>();
    number.add("0521392");
    number.add("0521396");
    number.add("0521397");
    number.add("0521398");
    number.add("0521391");
    ArrayList<Integer> counts = new ArrayList<>();
    counts.add(10);
    counts.add(5);
    counts.add(6);
    counts.add(10);
    counts.add(7);

    for (String n : mostCalled(number, counts, 8)){   // Calling the function and printing the output
        Log.i("go", "phone number: " + n);
    }
}

private ArrayList<String> mostCalled(ArrayList<String> number, ArrayList<Integer> counts, int howMuchNumbersToShow){   // function that get list of phone numbers and list of how meany times each number called and return the howMuchNumbersToShow most called numbers (who called the most times)
    if (number.size() != counts.size()){
        return new ArrayList<>();
    }
    int biggerNumber = -1; // will store the current biggest number
    int lastBiggerNumber = 10000000;  // will store the last bigger number
    int biggerNumberPlace = -1;     // will store the place of the biggest number in the array
    ArrayList<Integer> biggerNumberLocationList = new ArrayList<>();   // will store all the places of the biggest numbers in the array

    if (howMuchNumbersToShow > number.size())
        howMuchNumbersToShow = number.size();
    for (int l=0; l<howMuchNumbersToShow; l++){
        for (int x=0; x<counts.size(); x++){
            if (!biggerNumberLocationList.contains(x))      // to get each number one time (help in case more then one phone number called the same amount)
                if (counts.get(x) >= biggerNumber && counts.get(x)<= lastBiggerNumber){
                    biggerNumber = counts.get(x);
                    biggerNumberPlace = x;
                }

        }
        lastBiggerNumber = biggerNumber;
        biggerNumber = -1;
        biggerNumberLocationList.add(biggerNumberPlace);
    }

    ArrayList<String> mostCalledPhoneNumbers = new ArrayList();
    int place_in_array;
    String phoneNumber;

    for (int f=0; f<biggerNumberLocationList.size() ; f++) {
        place_in_array = biggerNumberLocationList.get(f);
        phoneNumber = number.get(place_in_array);
        mostCalledPhoneNumbers.add(phoneNumber);
   //     Log.i("go", "place in array " + biggerNumberLocationList.get(f) + ", the phone number "  + number.get(biggerNumberLocationList.get(f)) + " called " + counts.get(biggerNumberLocationList.get(f)) + " times ");
    }
    return mostCalledPhoneNumbers;
}

It would be easier to use HashMap for this job or even  ArrayList<> of type object that stores string and int.

A: after studying a lot i made this custom code .which worked perfect.i guess its lengthy.but still.again thanks to @Tejas Pandya and @guy.
 //putting above data into hashmap
    HashMap<String,Integer>  hm = new HashMap<String,Integer>();
    for(int i = 0; i < counts.size(); i++) {
        hm.put(numbers.get(i),counts.get(i));
    }

    //create list from elements of hashmaps
    List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());

    //sort the list
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> stringIntegerEntry,
                           Map.Entry<String, Integer> t1) {
            return (t1.getValue()).compareTo(stringIntegerEntry.getValue());
        }
    });

    HashMap<String,Integer> temp = new LinkedHashMap<String,Integer>();
            for(Map.Entry<String,Integer> aa : list){
                temp.put(aa.getKey() , aa.getValue());
                Log.e("descending",aa.getValue()+"");
                Log.e("descending",aa.getKey()+"");
            }
                String temp2 = String.valueOf((list.subList(0, 10)));
    Log.e("final",temp2+"");


text:
Q: Understanding the definition of arbitrage opportunities (one period model) The setting is the one period model of a financial market with $d+1$ assets, where the $0$-th asset is a riskless bond:
Let $(\Omega, \mathcal{F}, \mathbb{P})$ be a probability space. Let $\overline\pi \in \mathbb{R}_+^{d+1}$ be an initial price vector with $\pi^0 := 1$. Let $\overline S:=(S^0,S^1,\dots,S^d)$ be the final price vector, where $S^0 \equiv 1+r, r>-1$ and $S^i, i \ge 1$ are non-negative RVs. At inital time, a portfolio $\overline\xi \in \mathbb{R}^{d+1}$ can be chosen. $\overline\pi \cdot \overline\xi$ is the initial price of the porfolio, $\overline\xi \cdot \overline S$ is the final value of the portfolio, where the dot denotes the standard inner product.

Definition: $\overline\xi \in \mathbb{R}^{d+1}$ is an arbitrage opportunity, if
$\quad$1. $\overline\pi \cdot \overline\xi \le 0$,
$\quad$2. $\mathbb{P}(\overline\xi \cdot \overline S \ge 0 ) = 1$
and
$\quad$3. $\mathbb{P}(\overline\xi \cdot \overline S > 0 ) > 0$.

The book summarizes the definition as follows:

Intuitively, an arbitrage opportunity is an investment strategy that yields with
strictly positive probability a strictly positive profit and is not
exposed to any downside risk.

But if I had to make this "intuitive" definition precise, I would rather drop the first requirement and replace $\overline\xi \cdot \overline S$ by $\overline\xi \cdot \overline S-\overline\xi \cdot \overline \pi$ in the second and third requirement. What is wrong with my understanding of the model?

A: This appears to be the authors way of saying
$$\overline S \cdot \overline\xi \ge \overline\pi \cdot \overline\xi$$
with an arbitrary $0$ point between them.


text:
Q: How to create distribution function from sketch? I'm playing with image manipulation based on various mathematical algorighms (such as edge detection).

I'm also changing the colors in various ways just to see what comes out of it. Regarding this, I usually need to find good consequent function for the value distribution - disconsequent functions provide ugly results.
For example, I wanted to distribute lightness as following (drawn in inkscape):

This would enhance high values and suppress the small ones, which is good for edge detection.
But I can't figure this function out. Is there an universal solution to aproximate any sketched function by real function?
Note that I don't care how does the resulting function behave outside my region of <0, 1>.
So far, I'm distributing the values only using $x^n$ where $n$ is constant greater than 0.

A: On the one hand, I feel that your question is almost too general for math.se, but on the other hand I also think it is a fairly interesting one! In the following, I will provide some basic ideas regarding your question (just enough so that you will be able to research further on your own!) and also provide a suggestion for your particular case.
The question you ask is the following:  "Is there an universal solution to aproximate any sketched function by real function?"
This can be formalized as follows: You have a set of tuples $(x_i, y_i), i=0,\dotsc,n$ (which in case of a sketch would be many!) and want to define a function $f$ such that $f(x_i) \approx y_i$. One way to do this is by interpolation, this means that you are actually looking for a function $f$ such that $f(x_i) = y_i$ holds exactly $\forall i$. For example, there exists exactly one polynomial of degree $n$ which interpolates your points. This is instable though for high $n$. Another simple way, would be to just linearly interpolate between your points. To produce a smoother interpolating function you can also use splines of higher order.
Another way to do this, is by means of approximation theory. You usually define a parametric form for your function and then try to find the parameters which minimize a particular error measure, often the sums of squares.
Of course, in your particular case, you are actually looking for a distribution function whose support lies in $[0,1]$. For example this means that your tuples include $(0,0), (1,1)$ and your function is not decreasing. In order to estimate a distribution functions a variety of methods exist (e.g.the empirical CDF). These methods though usually assume that you have random points which were generated from these distributions rather than the $(x_i,y_i)$ tuples. Still here you could use non-linear least squares with parametric assumptions on the form of your distribution function.
For your case there actually exists an interesting result, if you are willing to further assume that your distribution function has a continuous density on $[0,1]$. In this case, (see Theorem 1 in  Diaconis, Persi, and Donald Ylvisaker. "Quantifying prior opinion." Bayesian statistics 2 (1985): 133-156.) the density can be approximated to an arbitrary precision by a mixture of densities of Beta distributions. Hence this is also the case for the distribution function. Thus, using a mixture of Beta distribution, you should be able to approximate any distribution you sketch on $[0,1]$.
This actually brings me to the actual answer: I think for your use case, it might be enough to experiment with a single Beta distribution. Then you would just have to play around with two parameters. (Have a look at the different shapes the Beta distribution function can take in the figures of the Wikipedia article.) As a matter of fact, the $x^n$ you have been using is a special case of the Beta distribution, namely $B(n+1,1)$.
I hope this helps!


text:
Q: Serverless task in Snowflake I am executing below statement for serverless task it's throwing an error
CREATE OR REPLACE TABLE TASK_TABLE_2(TBL_NAME VARCHAR, LAST_INSERTED_DATE TIMESTAMP);

CREATE OR REPLACE TABLE TASK_TABLE_3(TBL_NAME VARCHAR, LAST_INSERTED_DATE TIMESTAMP);

create or replace task DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
as
EXECUTE IMMEDIATE
$$
BEGIN
insert into TASK_TABLE_2 values (2_1,SYSDATE());
insert into TASK_TABLE_2 values (2_2,SYSDATE());
insert into TASK_TABLE_3 values (3_1,SYSDATE());
END
$$
;

Error Message:
Uncaught exception of type 'STATEMENT_ERROR' on line 3 at position 0 : No active warehouse selected in the current session. Select an active warehouse with the 'use warehouse' command.
But the same executing successfully if i use the warehouse in the TASK
CREATE OR REPLACE TABLE TASK_TABLE(TBL_NAME VARCHAR, LAST_INSERTED_DATE TIMESTAMP);
CREATE OR REPLACE TABLE TASK_TABLE_1(TBL_NAME VARCHAR, LAST_INSERTED_DATE TIMESTAMP) ;

create or replace task DEMO_TASK
WAREHOUSE = COMPUTE_WH
SCHEDULE ='1 minutes'
as
EXECUTE IMMEDIATE
$$
BEGIN
insert into TASK_TABLE values (0_1,SYSDATE());
insert into TASK_TABLE values (0_2,SYSDATE());
insert into TASK_TABLE_1 values (1_1,SYSDATE());
END
$$
;

A: This worked for me, looks like you forgot to add USE Warehouse for creation of task, as creation of task is not metadata based action , so please use "USE WAREHOUSE  " sql statement before you execute create task
create or replace task DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
as
EXECUTE IMMEDIATE
$$
BEGIN
insert into TASK_TABLE_2 values (2_1,SYSDATE());
insert into TASK_TABLE_2 values (2_2,SYSDATE());
insert into TASK_TABLE_3 values (3_1,SYSDATE());
END
$$

;

A: The case is reproducible and my hypothesis is a serverless task does play well with standalone Snowflake Scripting BEGIN END block.
Initial setup(tested using Snowsight UI):
CREATE OR REPLACE TABLE TASK_TABLE_2(TBL_NAME VARCHAR, LAST_INSERTED_DATE TIMESTAMP);
CREATE OR REPLACE TABLE TASK_TABLE_3(TBL_NAME VARCHAR, LAST_INSERTED_DATE TIMESTAMP);

SELECT CURRENT_VERSION();
-- 7.5.2

Task test:
EXECUTE TASK DEMO_TASK_2 ;

SELECT *
FROM TABLE(information_schema.task_history())
ORDER BY scheduled_time DESC;

Use case 1:
CREATE OR REPLACE TASK DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
AS
EXECUTE IMMEDIATE
$$
BEGIN
insert into TASK_TABLE_2 values ('2_1',SYSDATE());
insert into TASK_TABLE_2 values ('2_2',SYSDATE());
insert into TASK_TABLE_3 values ('3_1',SYSDATE());
END
$$;

-- Task DEMO_TASK_2 successfully created.

Output:

Uncaught exception of type 'STATEMENT_ERROR' on line 2 at position 0 : No active warehouse selected in the current session.  Select an active warehouse with the 'use warehouse' command.

Use case 2
No EXECUTE IMMEDIATE, only Snowflake Scripting block
CREATE OR REPLACE TASK DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
AS
BEGIN
insert into TASK_TABLE_2 values ('2_1',SYSDATE());
insert into TASK_TABLE_2 values ('2_2',SYSDATE());
insert into TASK_TABLE_3 values ('3_1',SYSDATE());
END;

-- Task DEMO_TASK_2 successfully created.

Output:

Uncaught exception of type 'STATEMENT_ERROR' on line 2 at position 0 : No active warehouse selected in the current session.  Select an active warehouse with the 'use warehouse' command.

Use case 3:
EXECUTE IMMEDIATE with BEGIN END block including only single statement:
CREATE OR REPLACE TASK DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
AS
EXECUTE IMMEDIATE
$$
BEGIN
insert into TASK_TABLE_2 values ('2_1',SYSDATE());
END;
$$;

-- Task DEMO_TASK_2 successfully created.

Uncaught exception of type 'STATEMENT_ERROR' on line 3 at position 0 : No active warehouse selected in the current session.  Select an active warehouse with the 'use warehouse' command.

Use case 4:
EXECUTE IMMEDIATE no BEGIN END and single statement:
CREATE OR REPLACE TASK DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
AS
EXECUTE IMMEDIATE
$$
insert into TASK_TABLE_2 values ('2_1',SYSDATE());
$$;

-- Task DEMO_TASK_2 successfully created.

Output:

SUCCEEDED

Use case 5:
BEGIN END block with single statement:
CREATE OR REPLACE TASK DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
AS
BEGIN
insert into TASK_TABLE_2 values ('2_1',SYSDATE());
END;

-- Task DEMO_TASK_2 successfully created.

Output:

Uncaught exception of type 'STATEMENT_ERROR' on line 2 at position 0 : No active warehouse selected in the current session.  Select an active warehouse with the 'use warehouse' command.

Use case 6:
Single statement:
CREATE OR REPLACE TASK DEMO_TASK_2
USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL'
SCHEDULE ='1 minutes'
AS
insert into TASK_TABLE_2 values ('2_1',SYSDATE());

-- Task DEMO_TASK_2 successfully created.

Output:

SUCCEEDED

Outcome:

*

*Task creation - succeeded  in all 6 cases

*Task run - succeeded only in case 4,6 (no BEGIN END block)

It should be reported to Snowflake Support.


text:
Q: C# Referencing the value of a variable I'm having difficulty understanding how I can reference the return value of a variable to create another in C#.
string name = Console.ReadLine();

List<Thing> name = new List<Thing>();

For example, user inputs "Cats" and thus a new list Cats is created.
Or in this scenario:
for (int i = 0; i < 5; i++)
 {
    List<Thing> (animal + i) = new List<Thing>();
 }

Where the lists created becomes animal0, animal1, animal2... etc.
Thank you

A: You cannot do that in C# at least not naturally.
Variable are determined at the compile time.
Value you are talking about (Cats, animal0, ...) are determined at the runtime, when the code is really running, which occurs after the compilation. So those values cannot become variable names.

A: You cannot create variables dynamically at runtime, so every variable you would like to use needs to be declared on compile time. Nevertheless, a List<Thing> can hold multiple instances of a Thing at the same time, representing - in your sense - multiple variables.
For example:
var things = new List<Thing>();

for (int i = 0; i < 5; i++) {
  things.Add(new Cat()); // if Cat derives from Thing
}

// access the list items by index
Console.WriteLine(thing[0]);
Console.WriteLine(thing[1]);
...


text:
Q: Micropython: How to use utime.mktime() without knowing the weekday/yearday? I'm trying to convert an ISO time string like '2021-05-11T18:21:35Z' to an int (seconds from epoch), which mktime() does, except it seems strange to me that it requires the weekday and yearday as part of the argument. In general, it seems unlikely that you would know this, and in my situation I don't.
Obviously in python this is doable with things like datetime, but in uPython these don't exist and I haven't seen a non-external-library way to do this.

A: Much like with regular Python, the values of weekday and yearday are ignored (they get computed from the other values and are only accepted so that you can pass mktime the tuple returned by e.g. localtime).
You can run:
MicroPython v1.14 on 2021-03-07; ESP module with ESP8266
Type "help()" for more information.
>>> import time
>>> res = time.mktime((2021, 5, 11, 18, 21, 35, 0, 0))
>>> res
674072495
>>> time.localtime(res)
(2021, 5, 11, 18, 21, 35, 1, 131)


text:
Q: Нет исключения при неверном регулярном выражении Во всех языках (и в Си++) при создании неверной  регулярки бросается исключение. Но с билдеровским классом TRegEx этого почему-то не происходит. Как исправить?
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  TRegEx *reg;

  try
  {
    reg = new TRegEx("*.ts", (TRegExOptions)roIgnoreCase);
  }
  catch (...)
  {
    ShowMessage("catch");
  }
}

A: На форуме разработчиков Embarcadero предложен такой код:
function CheckRegEx(const Value: string): Boolean;
    var
        myRegEx: TRegEx;
    begin
    try
        myRegEx := TRegEx.Create(Value, [roNotEmpty, roCompiled]);
        result := true;
    except
        result := false;
    end;
end;


text:
Q: segfaults when compiling on newer version of glibc ( 2.3 -> 2.10 ) I try to modify ssh session logging patch to sshd from kdvelectronics site.
Code hasn't changed much from openssh 4.x to 5.x , but now sshd segfaults when script_open function calls ( as gdb says )

Core was generated by `sshd: root [priv]        '.
Program terminated with signal 11, Segmentation fault.
#0  0x00007f687910ae69 in vfprintf () from /lib/libc.so.6
(gdb) bt
#0  0x00007f687910ae69 in vfprintf () from /lib/libc.so.6
#1  0x00007f68791a98c2 in __fprintf_chk () from /lib/libc.so.6
#2  0x000000000044ed03 in script_open ()
#3  0x000000000040ad2c in main ()

The code that crashes is:
strftime(logname, sizeof(logname), "%F.%T", gmtime(&tvec));

or
snprintf(fname, sizeof(fname), "%s/openssh.%s.%08x.typescript", SCRIPTDIR, username, rnd);

Full script.c listing is here http://pastebin.com/48B39K8s , I've commented line 50 and removed logname variable from line 53 .
I just wanna know, what changed in glibc since 2.3 that these functions cause segfault or where to read about it.

A: Ok, it turned out to be pretty simple. I've changed mentioned strings to
strftime(logname, FILENAME_MAX+1, "%F.%T", gmtime(&tvec));
snprintf(fname, FILENAME_MAX+1, "%s/openssh.%s.%08x.typescript", SCRIPTDIR, username, rnd);
Ofc it's dirty, but works.

A: I believe that the reason your code crashes is that (with line 50 commented out) you have left logname with undefined contents when you use it at line 60.  You mentioned that you removed the logname reference from line 53 along with commenting out line 50 -- perhaps you just forgot to also remove it from line 60 in that case?


text:
Q: How can I improve those voltage annotations In France, we draw an arrow above or below a dipole to represent the potential difference between its two poles. I'm trying to automate this using the ideas of the tikz circuits library (not circuitz). The code is adapted from the direction info code.
I have the following code. It works but it is far from perfect.

*

*It allows upsidedown labels.

*Sometimes labels overlap the arrow.

*I have the feeling that it complies only partially with tikz's way of handling styles and options.

*It is verbose (not refactored).

What and how should I do to improve this?

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{circuits.ee.IEC}

\tikzset{%
  voltage info/.is family,
  voltage info/vertical offset/.initial = .5,
  voltage info/arrow direction/.initial = ->,
  voltage info/horizontal offset/.initial = 2,
  voltage info/label position/.initial = above,
  voltage info/label rotate/.initial = 0,
  voltage info/label/.initial = {}
}

\tikzset{%
  voltage arrow/.style = {%
    /utils/exec = {%
      \pgfsetarrowoptions{direction ee}{%
        .4*\the\tikzcircuitssizeunit+.3*\the\pgflinewidth}},
    > = direction ee},
  voltage info sloped/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.north)+(0,\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},transform shape,rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  },
  voltage info' sloped/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,label position = below,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.south)+(0,-\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},transform shape,rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  },
  voltage info/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.north)+(0,\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  },
  voltage info'/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,label position = below,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.south)+(0,-\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  }
}

\begin{document}
\begin{tikzpicture}[circuit ee IEC]
  \draw (0,0) to[resistor = {%
    voltage info = {label = $u_R$},
    voltage info' = {label = $u_R$}}] (2,2);
  \draw (2,0) to[resistor = {%
    voltage info sloped = {label = $u_R$},
    voltage info' sloped= {label = $u_R$}}] (4,2);
  \begin{scope}[shift = {(4.5,2)}]
    \draw (0,0)
          to[resistor = {voltage info sloped = {label = $u_R$}}]
          ++ (2,0)
          to[resistor = {voltage info sloped = {label = $u_R$}}]
          ++ (0,-2)
          to[resistor = {voltage info sloped = {label = $u_R$}}]
          ++ (-2,0);
  \end{scope}
\end{tikzpicture}
\end{document}

A: I believe I can help with your first two points.

*

*It allows upsidedown labels.

This is because you have the sloped option set. If you turn that off, then your right-hand example becomes

That fixes the upsidedown labels. But then...

*

*Sometimes labels overlap the arrow.

This can be fixed by giving the auto option for your voltage info nodes. This results in...

The only problem is that your left-hand example still looks a bit off...

But that's fixed by using the auto,swap options for your voltage info' nodes, which puts those labels on the other side of their arrows.

Complete code follows.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{circuits.ee.IEC}

\tikzset{%
  voltage info/.is family,
  voltage info/vertical offset/.initial = .5,
  voltage info/arrow direction/.initial = ->,
  voltage info/horizontal offset/.initial = 2,
  voltage info/label position/.initial = above,
  voltage info/label rotate/.initial = 0,
  voltage info/label/.initial = {}
}

\tikzset{%
  voltage arrow/.style = {%
    /utils/exec = {%
      \pgfsetarrowoptions{direction ee}{%
        .4*\the\tikzcircuitssizeunit+.3*\the\pgflinewidth}},
    > = direction ee},
  voltage info sloped/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.north)+(0,\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},transform shape,rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  },
  voltage info' sloped/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,label position = below,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.south)+(0,-\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},transform shape,rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  },
  voltage info/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.north)+(0,\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},auto,rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  },
  voltage info'/.style = {%
    append after command = {%
      \bgroup
        [voltage info/.cd,label position = below,#1]
        [current point is local=true]
        [every voltage info/.try]
        [shift={($(\tikzlastnode.south)+(0,-\pgfkeysvalueof{/tikz/voltage info/vertical offset}\tikzcircuitssizeunit)$)}]
        [voltage arrow,\pgfkeysvalueof{/tikz/voltage info/arrow direction}]
        (-\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
        edge[line to]
        node[\pgfkeysvalueof{/tikz/voltage info/label
          position},auto,swap,rotate = \pgfkeysvalueof{/tikz/voltage
          info/label rotate}] {\pgfkeysvalueof{/tikz/voltage info/label}}
        (\pgfkeysvalueof{/tikz/voltage info/horizontal offset}\tikzcircuitssizeunit,0)
      \egroup
    }
  }
}

\begin{document}
\begin{tikzpicture}[circuit ee IEC]
  \draw (0,0) to[resistor = {%
    voltage info = {label = $u_R$},
    voltage info' = {label = $u_R$}}] (2,2);
  \draw (2,0) to[resistor = {%
    voltage info sloped = {label = $u_R$},
    voltage info' sloped= {label = $u_R$}}] (4,2);
  \begin{scope}[shift = {(4.5,2)}]
    \draw (0,0)
          to[resistor = {voltage info = {label = $u_R$}}]
          ++ (2,0)
          to[resistor = {voltage info = {label = $u_R$}}]
          ++ (0,-2)
          to[resistor = {voltage info = {label = $u_R$}}]
          ++ (-2,0);
  \end{scope}
\end{tikzpicture}
\end{document}

A: I've made, this, but not with tikz, with PSTricks and especiallythe package pst-circ that can draw circuits diagrams... I believe it is more powerful (and handier), but it's my point of view...
I've made a MWE down below.
It's the line labelangle=:U that determines the angle between the component and the direction of the label (and the name too). :U will put it in the same sense, but you can specify any angle you want.
\documentclass[a4paper, 11pt]{article}
\usepackage[frenchb]{babel}

\usepackage{pst-circ}

\begin{document}
\begin{pspicture}[showgrid=true](0, -1)(12, 4)
\pnode(0, 0){A}
\pnode(3, 3){B}
\pnode(4, 0){C}
\pnode(7, 3){D}
\pnode(8, 3){E}
\pnode(11, 3){F}
\pnode(11, 0){G}
\pnode(8, 0){H}
\resistor[labeloffset=0,
    labelangle=:U,
    tensionlabel=$u_R$,
    tensionoffset=0.7,
    tensionlabeloffset=1](A)(B){$R$}
\resistor[labeloffset=0,
    tensionlabel=$u_R$,
    tensionoffset=0.7,
    tensionlabeloffset=1](C)(D){$R$}
\resistor[labeloffset=0,
        tensionlabel=$u_R$,
    tensionoffset=-0.7,
    tensionlabeloffset=-1,
    directconvention=false](F)(E){$R$}
\resistor[labeloffset=0,
    %labelangle=:U,         TO PUT THE R IN THE SAME SENSE AS THE RESISTOR
    tensionlabel=$u_R$,
    tensionoffset=-0.7,
    tensionlabeloffset=-1,
    directconvention=false](G)(F){$R$}
\resistor[labeloffset=0,
    tensionlabel=$u_R$,
    tensionoffset=-0.7,
    tensionlabeloffset=-1,
    directconvention=false](H)(G){$R$}
\end{pspicture}
\end{document}

Here is the ouput :


text:
Q: Como concatenar HTML dentro de PHP <options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + '</option>';

Estou com  esse código e quero adicionar mais uma atributo depois do NomeCidade, se alguém poder ajudar agradeço.
O código é um HTML gerado por JavaScript.
Tenho um select cidades e quero adicionar na tag option, depois do NomeCidade, o ValorTarifa que é recebido no mesmo select da cidade através do CodCidade.
O problema é: como colocar o ValorTarifa no mesmo option?
Funcionou com o exemplo que Baccon postou, obrigado a todos breve volto com mais duvidas.

A: Em JS
Você pode usar tanto o concat quanto o +:
 options.concat( '<option value="', j[i].CodCidade, '">',
                 j[i].NomeCidade, ' ', j[i].ValorTarifa, '</option>' );

O concat pode ser interessante neste caso, pois você pode usar com vários parâmetros, e tem a previsibilidade de ser tratado como string. Veja em funcionamento:

var options = '';
var i;
var j = [
          { 'CodCidade':1, 'NomeCidade': 'Taubate' , 'ValorTarifa':'19,90' },
          { 'CodCidade':2, 'NomeCidade': 'Campinas', 'ValorTarifa':'25,00' },
          { 'CodCidade':3, 'NomeCidade': 'Queluz'  , 'ValorTarifa':'46,50' }
        ];

for ( i = 0; i < 3; i++ ) {
  options = options.concat( '<option value="', j[i].CodCidade,'">', j[i].NomeCidade, ' ', j[i].ValorTarifa, '</option>' );
}

document.body.innerHTML += '<select>' + options + '</select>';

Usando += e + também funciona neste caso. Só tem que tomar cuidado com problemas de interpretação quando misturar números e strings.

var options = '';
var i;
var j = [
          { 'CodCidade':1, 'NomeCidade': 'Taubate' , 'ValorTarifa':'19,90' },
          { 'CodCidade':2, 'NomeCidade': 'Campinas', 'ValorTarifa':'25,00' },
          { 'CodCidade':3, 'NomeCidade': 'Queluz'  , 'ValorTarifa':'46,50' }
        ];

for ( i = 0; i < 3; i++ ) {
  options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + ' ' + j[i].ValorTarifa + '</option>';
}

document.body.innerHTML += '<select>' + options + '</select>';

resposta original, antes dos comentários e atualização da pergunta pelo autor:
Em PHP
O operador de concatenação do PHP é o .
$options .= '<option value="'.$j[$i]['$CodCidade'].'">'.$j[$i]['NomeCidade'].'</option>';

Note que no seu exemplo, ele já estava sendo usado aqui: j[i].CodCidade, provavelmente por engano.
Será que você não quis dizer isto: j[i]['CodCidade']ou mesmo isto: j[i]->CodCidade? Além disso, se é PHP, estavam faltando os prefixos que indicam variável: $j[$i] etc...

A: Aqui ficam variantes diferentes para concatenar:
$codCidade = 20; // só para o exemplo, podias ter sando o $j[$i]['$CodCidade'] em baixo
$nomeCidade = 'Lisboa';
$options = '';

$options.= '<option value="'.$codCidade.'">'.$nomeCidade.'</option>';
$options.= "<option value=\"$codCidade\">$nomeCidade</option>";
$options.= "<option value='$codCidade'>$nomeCidade</option>";
echo $options;
// outras variantes :
echo '<option value=', $codCidade, '>', $nomeCidade, '</option>';
echo implode('', Array('<option value="', $codCidade, '">', $nomeCidade, '</option>'));

A primeira é no fundo o que procuras e o que o @bacco respondeu.
A segunda é uma interpolação, usando aspas duplas escapadas.
A terceira é parecida com a segunda mas usando aspas simples (plicas) no HTML que funciona na mesma.
A quarta é uma maneira possível caso uses o echo isolado. Talvez não se aplique ao teu caso, mas é aplicável em casos semelhantes.
A ultima é como eu uso mais frequentemente em JavaScript. Criando arrays e depois concatenado tudo.
ideone (exemplo): https://ideone.com/foKFTL

A: Isso parece um HTML sendo gerado por JavaScript. Então a coisa é um pouco diferente do que pede. Para fazer o PHP escrever isso, terá que escolher qual tipo de delimitador usar no PHP e então definir o delimitador que será escapado.
Exemplo, mantendo a forma original:
<options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + '</option>';

Para colocar isso dentro de uma variável PHP ficaria assim:
$foo = "<options += '<option value=\"' + j[i].CodCidade + '\">' + j[i].NomeCidade + '</option>';";

Aqui usamos a double quote como delimitador, por isso, todas as double quotes da string devem ser escapadas com backslash
Outro modo, usando heredoc
$foo = <<<HTML
<options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + '</option>';
HTML;

A vantagem é que não precisa escapar nada, exceto em casos muito específicos.  Então basta jogar tudo na forma original.
Tome cuidado com o fechamento. No exemplo acima, HTML; não pode conter espaços ou tabulação no início.
Isso é bem mais limpo e prático para lidar com templates pois não precisa fazer escapes. É muito conveniente para atribuir códigos extensos onde daraia muito trabalho para fazer todos os escapes.
Vamos complicar mais com um exemplo de output buffering
<?php
ob_start();
?>
<options += '<option value="' + j[i].CodCidade + '">' + j[i].NomeCidade + '</option>';
<?
echo ob_get_clean();

O output control é usado para casos específicos. Obviamente não usa-se para casos simples e corriqueiros onde podemos resolver com concatenação ou heredoc. Um exemplo de uso do output buffering é compilação de templates.
*termos usados:
double quote -> aspa dupla
backslash -> barra invertida


text:
Q: SQL Server 2012 Availability group disk configuration options Background
I am quite far into the process of setting up a 2 server SQL Server 2012 Always on availability cluster to provide redundancy with a readable secondary replica of all our databases.
Since the hardware was ordered we've had a professional DBA audit our database and he's suggested separating our data, logs and tempdb. Unfortunately we do not have the capacity for the ideal configuration he's suggested. I therefore need feedback on my ideas for a suitable compromise...
Current setup
single server has 8 hard drive slots. We have a 2 disk RAID 1 for the OS, a 4 disk RAID 10 for data, logs and tempdb and 2 spares. I want to change this to increase performance.
Proposed setup
2 servers, each with 8 slots. Synchronous replication in the AG with auto-failover and the secondary to be readable for backups and reporting.
OS leave as is, a 2 disk RAID 1
tempdb has the most stalls by a long way so first off I'd like to put that on a separate drive, a single SSD for optimal random reads and writes.
data The read/write ratio of our data files is about 12:1 so read performance is key here. Ideally for this drive we would use RAID 10 or 0+1 with 4 disks for redundancy but we don't have enough slots. As we have the redundancy and auto-failover of the AG (the data is replicated on an identical drive on another server) I'm proposing a 2 disk RAID 1.
logs We have 3 slots left and need optimal write performance. Again, redundancy is not an issue as the 2nd host in the AG will have a replica of the logs. I am leaning towards a 2 disk RAID 0 here to avoid the write overhead of RAID 1.
We would then have a slot spare for backups and anything else non-critical.
Question

*

*Should the log disk be RAID 1, RAID 0 or other?

*Is the overall solution above the best option for me? If not, why

A: *

*I would only use RAID 0 for the logs if you're okay with having reduced disaster recovery capability. You won't be able to make log tail backups in the event of a disk failure, and will only be able to restore to your most recent backup. However, this may be less of an issue if you're running Availability Groups, particularly with synchronous mirroring. You generally won't have any performance overhead for RAID 1 vs. a single non-RAID disk, but you will have better I/O performance with RAID 0 instead of RAID 1 for an equal number of disks.

*Be aware that tempdb also has both data files and log files, and those could end up interfering with each other (performance wise) if placed on the same volume. You may want to consider foregoing the spare disk and using it for tempdb logs instead if performance still isn't acceptable. If your C: array is large enough, you might be able to get away with using it for on-disk backups, though you should probably partition it to prevent runaway backups from filling your OS disk.