text:
Q: React.js Duplicate key and Unreachable code BUGS Hi I'm learning React.js and I'm making a ChatApp right now.
Here is my bug and codes.

./src/App.js   Line 10:7:  Duplicate key 'currentUsername'
  no-dupe-keys
./src/components/ChatScreen.jsx  Line 35:5:  Unreachable code
  no-unreachable
Search for the keywords to learn more about each warning.To ignore,
  add // eslint-disable-next-line to the line before.

import React, { Component } from 'react'
import Chatkit from '@pusher/chatkit-client'

class ChatScreen extends Component{
  constructor(props) {
    super(props)
    this.state = {
      currentUser: {}
    }
  }

  componentDidMount() {
    const chatManager = new Chatkit.ChatManager({
      instanceLocator: 'v1:us1:1308c34d-00c3-4257-b1c3-647cf56fd5fa',
      userId: this.props.currentUsername,
      tokenProvider: new Chatkit.TokenProvider({
        url: 'http://localhost:3000/authenticate',
      }),
    })

    chatManager
      .connect()
      .then(currentUser => {
        this.setState({ currentUser })
      })
      .catch(error => console.error('error', error))
  }

  render() {
    return (

    )
    const styles = {
      container: {
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
      },
      chatContainer: {
        display: 'flex',
        flex: 1,
      },
      whosOnlineListContainer: {
        width: '300px',
        flex: 'none',
        padding: 20,
        backgroundColor: '#2c303b',
        color: 'white',
      },
      chatListContainer: {
        padding: 20,
        width: '85%',
        display: 'flex',
        flexDirection: 'column',
      },
    }

    return (

Who's online PLACEHOLDER

Chat PLACEHOLDER

    );
  }
}

export default ChatScreen;

Could you help me?

A:
./src/components/ChatScreen.jsx Line 35:5: Unreachable code no-unreachable

This lint error is warning you that you have a return statement at the top of your render method, followed by code that will never execute below it. Ie, this code makes the rest of the function useless:
return (

)

Duplicate key 'currentUsername' no-dupe-keys

This error is occurring in App.js, which you havn't shared with us. But it's telling you that you've given an object the property currentUsername twice. For example, maybe you have something like:
const myObject = {
  currentUsername: 'bob',
  currentUsername: 'alice',
}

Or are trying to create a component with the same issue:
<ChatScreen
  currentUsername="bob"
  currentUsername="alice"
/>

A: First warning

./src/App.js Line 10:7: Duplicate key 'currentUsername' no-dupe-keys

You have a duplicate key in your state declaration
constructor() {
    super();
    this.state = {
      currentUsername: '',
      currentUsername: 'WhatIsYournameScreen',
    }
    this.onUsernameSubmitted = this.onUsernameSubmitted.bind(this)
  }

You need to remove either currentUsername: '' or currentUsername: 'WhatIsYournameScreen' line according to your needs.
Second warning

./src/components/ChatScreen.jsx Line 35:5: Unreachable code no-unreachable

You have two return statements inside your render method. You need to delete the first one.
import React, { Component } from 'react'
import Chatkit from '@pusher/chatkit-client'

class ChatScreen extends Component{
  constructor(props) {
    super(props)
    this.state = {
      currentUser: {}
    }
  }

  componentDidMount() {
    const chatManager = new Chatkit.ChatManager({
      instanceLocator: 'v1:us1:1308c34d-00c3-4257-b1c3-647cf56fd5fa',
      userId: this.props.currentUsername,
      tokenProvider: new Chatkit.TokenProvider({
        url: 'http://localhost:3000/authenticate',
      }),
    })

    chatManager
      .connect()
      .then(currentUser => {
        this.setState({ currentUser })
      })
      .catch(error => console.error('error', error))
  }

  render() {
    return (

Who's online PLACEHOLDER

Chat PLACEHOLDER

    );
  }
}

const styles = {
      container: {
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
      },
      chatContainer: {
        display: 'flex',
        flex: 1,
      },
      whosOnlineListContainer: {
        width: '300px',
        flex: 'none',
        padding: 20,
        backgroundColor: '#2c303b',
        color: 'white',
      },
      chatListContainer: {
        padding: 20,
        width: '85%',
        display: 'flex',
        flexDirection: 'column',
      },
    }

export default ChatScreen;

A: ChatScreen.jsx:
import React, { Component } from 'react'
import Chatkit from '@pusher/chatkit-client'

class ChatScreen extends Component{
  constructor(props) {
    super(props)
    this.state = {
      currentUser: {}
    }
  }

  componentDidMount() {
    const chatManager = new Chatkit.ChatManager({
      instanceLocator: 'v1:us1:1308c34d-00c3-4257-b1c3-647cf56fd5fa',
      userId: this.props.currentUsername,
      tokenProvider: new Chatkit.TokenProvider({
        url: 'http://localhost:3000/authenticate',
      }),
    })

    chatManager
      .connect()
      .then(currentUser => {
        this.setState({ currentUser })
      })
      .catch(error => console.error('error', error))
  }

  render() {
    const styles = {
      container: {
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
      },
      chatContainer: {
        display: 'flex',
        flex: 1,
      },
      whosOnlineListContainer: {
        width: '300px',
        flex: 'none',
        padding: 20,
        backgroundColor: '#2c303b',
        color: 'white',
      },
      chatListContainer: {
        padding: 20,
        width: '85%',
        display: 'flex',
        flexDirection: 'column',
      },
    }
    return (

Who's online PLACEHOLDER

Chat PLACEHOLDER

    );
  }
}

export default ChatScreen;

App.js:
import React, { Component } from 'react'
import UsernameForm from './components/UsernameForm'
import ChatScreen from './components/ChatScreen'

class App extends Component {
  constructor() {
    super();
    this.state = {
      currentUsername: '',
      currentScreen: 'WhatIsYournameScreen',
    }
    this.onUsernameSubmitted = this.onUsernameSubmitted.bind(this)
  }

  onUsernameSubmitted(username) {
    fetch('http://localhost:3000/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username }),
    })
      .then(response => {
        this.setState({
          currentUsername: username,
          currentScreen: 'ChatScreen'
        })
      })
      .catch(error => console.error('error', error))
  }

  render() {
    if (this.state.currentScreen === 'WhatIsYourUsernameScreen') {
      return <UsernameForm onSubmit={this.onUsernameSubmitted} />
    }
    if (this.state.currentScreen === 'ChatScreen') {
      return <ChatScreen currentUsername={this.state.currentUsername} />
    }
    return (

Hoş geldin

        <UsernameForm onSubmit={this.onUsernameSubmitted} />

    );
  }
}

export default App;


text:
Q: PHP adding JavaScript elements dynamically issue I'm having a little issue adding JavaScript/Jquery elements dynamically in a PHP file due to the ' and " issue.
So, I echo the HTML code using:
<?php
     $entryId = $_GET['entryId'];
     echo '
     <!doctype html>

When adding elements dynamically I'm using the following:
$.ajax({
        url: "getDriverDVLAChecks.php",
        data: {ni: ni},
        dataType : "text",
        success: function(data)
        {
         var arr = data.split("##");
         for (var i = 0; i < arr.length - 1; i++)
         {
          var tmp = arr[i].split("#-");
          var tile = "

tmp[0]

";
          $("#dvlaCheckRow").append(tile);
         }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          console.log(errorThrown);
        }
});

I'm having an issue with the following line:
var tile = "

tmp[0]

";

As you can see I'm using quotation marks to represent the string, but when I'm declaring classes and ids to the elements, it seems to think I'm closing the string (Obviously).
What is the best way to go about doing this? I cannot use ' instead of " because the PHP file will recognise it as PHP code.
I have tried the following with no luck:
var tile = String(

tmp[0]

);

The error PHP returns: Uncaught SyntaxError: Unexpected identifier
Thanks!

A: You need to 'escape' the double quotes with a backslash, so:
var tile = "
...

A: You cannot use nested quotes...
Please refer how to work with strings
You can use any of following..
var tile = "

tmp[0]

";

OR
var tile = '

tmp[0]

';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variables in path name and getting path not found error I'm pulling my hair out.  The mkdir works with year (integer), but doesn't work with month (string) added.
year = 2013
month = MonthName(1)

'I have also tried just putting "January" in there as well

This works:
Path1 = "\\TEST\" & year & "\"

But this doesn't:
Path1 = "\\TEST\" & year & "\" & month & "\"

Suggestions? Thanks!
Final Fix:
Split Path1 into:
Path1: "\\TEST\" & year & "\"

Path2:  "\\TEST\" & year & "\" & month & "\"

With the checks:
If Len(Dir(Path1, vbDirectory)) = 0 Then
        MkDir Path1
End If
If Len(Dir(Path2, vbDirectory)) = 0 Then
        MkDir Path2
End If

A: You cannot create "\\TEST\" & year & "\" & month & "\" via MkDir unless "\\TEST\" & year & "\" already exists.
So expanding on your posted code, you could do this:
Path1 = "\\TEST\" & year & "\"
If DIR$(Path1, vbDirectory) <> "" then mkdir Path1
Path1 = "\\TEST\" & year & "\" & month & "\"
If DIR$(Path1, vbDirectory) <> "" then mkdir Path1


text:
Q: How to convert binary image to RGB with PIL? I have PIL Image in binary and I need to convert it in RGB. I did this diskew image
binary image

I need this way:

I already tried this which is not working
from PIL import Image as im

img = im.fromarray((255 * Image).astype("uint8")).convert("RGB")

A: I still don't understand why you convert to RGBA if you want RGB, but this code converts your image to RGB as you ask:
#!/usr/local/bin/python3

import numpy as np
from PIL import Image

# Open input image
im = Image.open('text.png').convert('RGB')

# Invert
npim = 255 - np.array(im)

# Save
Image.fromarray(npim).save('result.png')


text:
Q: Does the scope for 'Alter Any Database' operate similar to 'Create Any Database'? Does the scope for 'Alter Any Database' operate similar to 'Create Any Database', as in, only those databases created by Login-A under the 'Create Any Database' umbrella can be altered, and not the other databases on the server?

A: Why is this so hard to test for yourself? As sa or similar:
CREATE LOGIN Jake WITH PASSWORD = N'x', CHECK_POLICY = OFF;
GO
GRANT ALTER ANY DATABASE TO Jake;
GO
CREATE DATABASE IBelongToAaron;
GO

Now log in as Jake:
CREATE DATABASE IBelongToJake;
GO
ALTER DATABASE IBelongToJake SET RECOVERY FULL; -- success!
GO
ALTER DATABASE IBelongToAaron SET RECOVERY FULL; -- success!

So no, ALTER ANY DATABASE works as advertised, which is probably why it's not called ALTER ANY DATABASE THAT I CREATED OR OWN.


text:
Q: Need or not need to update state form prev state? React If I was setting the value of a state variable by a number but it was not dependent on the prev value, would I need to update based on prev state?
i.e
const [value, setValue] = React.useState<number>(7);

const handleClick = () => {
   setValue(30);
}

would I need to handle the prev value in the handle click ? this is not a counter or anything.

A: If your next state does not depend on the previous state then you don't need to pass a callback. setValue(30) is perfectly fine.
Though you could setValue(() => 30). Or for readability and self-documenting purpose you can define const reset = () => 30; and then use it in the component setValue(reset).
What you should NOT do is setValue(value + 30).


text:
Q: Linux 32b MySQL periodically crashing with signal 11 and OOM errors I have a MySQL DB with mostly InnoDB tables that I'm fairly certain isn't tuned properly based on what's happening, but I don't have enough know how to pinpoint what to change.  The server is a 8G 32b Linux system with the following in my.cnf:
[mysql]
port                           = 3306
socket                         = /var/run/mysqld/mysqld.sock
[mysqld]
user                           = mysql
default_storage_engine         = InnoDB
socket                         = /var/run/mysqld/mysqld.sock
pid_file                       = /var/run/mysqld/mysqld.pid
key_buffer_size                = 64M
myisam_recover                 = FORCE,BACKUP
max_allowed_packet             = 16M
max_connect_errors             = 1000000
datadir                        = /var/lib/mysql/
tmpdir                         = /tmp
tmp_table_size                 = 64M
max_heap_table_size            = 64M
query_cache_type               = 0
query_cache_size               = 0
max_connections                = 200
thread_cache_size              = 50
open_files_limit               = 65535
table_definition_cache         = 8192
table_open_cache               = 8192
innodb_flush_method            = O_DIRECT
innodb_log_files_in_group      = 2
innodb_log_file_size           = 128M
innodb_flush_log_at_trx_commit = 2
innodb_file_per_table          = 1
innodb_buffer_pool_size        = 2G
log_error                      = /var/log/mysql/mysql-error.log
log_queries_not_using_indexes  = 0
slow_query_log_file            = /var/log/mysql/mysql-slow.log
slow_query_log                 = 1
long_query_time                = 2
general_log                    = 0
general_log_file               = /var/log/mysql/general.log
[isamchk]
key_buffer                     = 16M
[mysqldump]
quick
quote-names
max_allowed_packet             = 16M

Currently, here are the non-zero global status stats:
Aborted_clients 28
Aborted_connects    667
Bytes_received  283596894
Bytes_sent  3709581404
Com_admin_commands  24456
Com_change_db   10267
Com_delete  167
Com_insert  1355
Com_kill    1
Com_select  1018481
Com_set_option  19563
Com_show_processlist    74
Com_show_status 30
Com_show_table_status   1
Com_show_tables 22
Com_show_variables  5
Com_update  2208
Connections 11157
Created_tmp_disk_tables 5131
Created_tmp_files   6
Created_tmp_tables  11044
Flush_commands  1
Handler_commit  1019009
Handler_delete  160
Handler_read_first  29551
Handler_read_key    3051320
Handler_read_last   3
Handler_read_next   5038745
Handler_read_prev   251210
Handler_read_rnd    685831
Handler_read_rnd_next   22756239
Handler_rollback    38
Handler_update  1166988
Handler_write   557183
Innodb_adaptive_hash_cells  8850419
Innodb_adaptive_hash_heap_buffers   1630
Innodb_adaptive_hash_hash_searches  4990439
Innodb_adaptive_hash_non_hash_searches  4315600
Innodb_background_log_sync  4145
Innodb_buffer_pool_pages_data   129440
Innodb_buffer_pool_pages_dirty  4
Innodb_buffer_pool_pages_flushed    9952
Innodb_buffer_pool_pages_LRU_flushed    237
Innodb_buffer_pool_pages_made_young 273289
Innodb_buffer_pool_pages_misc   1631
Innodb_buffer_pool_pages_old    47761
Innodb_buffer_pool_pages_total  131071
Innodb_buffer_pool_read_ahead   607
Innodb_buffer_pool_read_ahead_evicted   1325
Innodb_buffer_pool_read_requests    35806735
Innodb_buffer_pool_reads    373297
Innodb_buffer_pool_write_requests   30891
Innodb_checkpoint_age   365
Innodb_checkpoint_max_age   216721613
Innodb_checkpoint_target_age    209949063
Innodb_data_fsyncs  5575
Innodb_data_read    1834913792
Innodb_data_reads   401613
Innodb_data_writes  17424
Innodb_data_written 332080128
Innodb_dblwr_pages_written  9952
Innodb_dblwr_writes 431
Innodb_dict_tables  27606
Innodb_history_list_length  1979
Innodb_ibuf_free_list   9
Innodb_ibuf_merged_delete_marks 13
Innodb_ibuf_merged_deletes  3
Innodb_ibuf_merged_inserts  201
Innodb_ibuf_merges  144
Innodb_ibuf_segment_size    11
Innodb_ibuf_size    1
Innodb_log_write_requests   5819
Innodb_log_writes   6591
Innodb_lsn_current  77982531271
Innodb_lsn_flushed  77982531271
Innodb_lsn_last_checkpoint  77982530906
Innodb_master_thread_1_second_loops 4131
Innodb_master_thread_10_second_loops    411
Innodb_master_thread_background_loops   15
Innodb_master_thread_main_flush_loops   15
Innodb_master_thread_sleeps 4130
Innodb_max_trx_id   576268483
Innodb_mem_adaptive_hash    62128140
Innodb_mem_dictionary   109012014
Innodb_mem_total    2179465216
Innodb_mutex_os_waits   779
Innodb_mutex_spin_rounds    36022
Innodb_mutex_spin_waits 5369
Innodb_oldest_view_low_limit_trx_id 576268482
Innodb_os_log_fsyncs    3498
Innodb_os_log_written   5761024
Innodb_page_size    16384
Innodb_pages_created    94
Innodb_pages_read   374004
Innodb_pages_written    9952
Innodb_purge_trx_id 576267172
Innodb_rows_deleted 160
Innodb_rows_inserted    1323
Innodb_rows_read    28554644
Innodb_rows_updated 2078
Innodb_s_lock_os_waits  1278
Innodb_s_lock_spin_rounds   40952
Innodb_s_lock_spin_waits    2563
Innodb_x_lock_os_waits  132
Innodb_x_lock_spin_rounds   4893
Innodb_x_lock_spin_waits    176
Key_blocks_unused   57983
Key_blocks_used 10
Key_read_requests   6724
Key_reads   7
Key_write_requests  1441
Max_used_connections    25
Open_files  11
Open_table_definitions  8192
Open_tables 8192
Opened_files    138868
Opened_table_definitions    117810
Opened_tables   126475
Queries 1062631
Questions   1062631
Select_full_join    1211
Select_range    17271
Select_scan 27709
Slow_queries    4
Sort_range  215835
Sort_rows   723648
Sort_scan   20726
Table_locks_immediate   1055875
Threads_cached  21
Threads_connected   4
Threads_created 25
Threads_running 1
Uptime  4148
Uptime_since_flush_status   4148

And finally, ulimit -a:
ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 64613
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 64613
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Does anything pop out that is clearly mis-configured?

A: There's nothing really standing out as being poorly-tuned.  The innodb_buffer_pool_size is, quite possibly, the single most important configuration parameter for optimum performance, and the general rule is that you want it as large as possible, as much as 80% of system memory on a dedicated server (unless, of course, you have a very small data set)... but on a system where you're sharing resources with anything, and especially Apache, it has to be much, much smaller.
In your case, 2G or 25% of system memory, seems like it should be perfectly reasonable in theory, but it might not be true in your case.
The memory for the InnoDB buffer pool is requested from the operating system in a single block when MySQL starts, and this block never grows or shrinks... so changing this parameter will, without exception, change the total baseline amount of memory MySQL requires, with no connection at all to the size of your data set or your load.  Of course, reducing the size of the InnoDB buffer pool will free up some memory but will also negatively impact performance.
Many of MySQL's other memory needs are handled by allocating and freeing memory from the OS as needed, and the bottom line is that it will request exactly the amount of information from the operating system that it needs, in order to handle its workload:

"The truth is that you can't put an upper bound on MySQL's memory consumption. It is not a tightly regulated database server that controls memory allocation."
Schwartz, Baron; Zaitsev, Peter; Tkachenko, Vadim (2012-03-05). High Performance MySQL: Optimization, Backups, and Replication (Kindle Locations 12193-12194). OReilly Media - A. Kindle Edition.

Of course, the exact same thing is true about Apache.

You can, and should, control the MaxRequestWorkers setting so that your server does not spawn so many children it starts swapping. This procedure for doing this is simple: determine the size of your average Apache process, by looking at your process list via a tool such as top, and divide this into your total available memory, leaving some room for other processes.
http://httpd.apache.org/docs/2.4/misc/perf-tuning.html

Well, "simple" seems like a bit of an overstatement, since if you don't allow sufficient Apache worker threads to meet your application's demands, your performance will deteriorate here, too.
It is, of course, very bad for a server running MySQL or Apache to start swapping; however, this doesn't mean you don't need swap space... you should have it for emergencies (light swapping is much better than crashing, after all)... so if you don't have it, you should... and if you do -- and that's getting maxed too -- then you actually already had a significant problem on your hands before the crashes began.
I recently wrote a simple stored procedure intended to crash MySQL by maxing out the system's memory, only to find that "merely" running out of memory is not actually enough to crash MySQL.  Review of the source revealed that many out of memory events are handled quite gracefully, with only (for example) a query failing, not a complete meltdown... but the fact that many such events are handled well does not by any means suggest that all such events are, or even necessarily could be.
The bottom line is that unless you can find some cruft, you may simply be trying to do too much with too little... but activating some swap space (if you haven't already), then trying to tame the Apache children, and then reducing the buffer pool size would be the places I would start.


text:
Q: Unable to read kinesis data stream from Node App I have setup a kinesis data stream to capture RDS changes and adding data to this stream. Data is feeding to this stream as i can see from stream dashboard. But I'm unable to create consumer, I tried KCL sample code for node but it just keep running not printing anything..

import boto3
import json
import random
import calendar
import time
from datetime import datetime
import psycopg2
from psycopg2.extras import LogicalReplicationConnection

my_stream_name = 'Foo'
kinesis_client = boto3.client('kinesis', region_name='us-east-1')
my_connection  = psycopg2.connect(
               "dbname='postgres' host='mypgdb.abcdefghijk.us-east-1.rds.amazonaws.com' user='repluser' password='replpass'" ,
               connection_factory = LogicalReplicationConnection)
cur = my_connection.cursor()
cur.drop_replication_slot('wal2json_test_slot')
cur.create_replication_slot('wal2json_test_slot', output_plugin = 'wal2json')
cur.start_replication(slot_name = 'wal2json_test_slot', options = {'pretty-print' : 1}, decode= True)

def consume(msg):
kinesis_client.put_record(StreamName=my_stream_name, Data=json.dumps(msg.payload),     PartitionKey="default")
print (msg.payload)

cur.consume_stream(consume)

https://github.com/awslabs/amazon-kinesis-client-nodejs/tree/master/samples/basic_sample/consumer
Below is my kcl implementation as provided above
'use strict';

var util = require('util');
var kcl = require('aws-kcl');

function recordProcessor() {
  var shardId;
  return {
initialize: function(props, completeCallback) {
  shardId = initializeInput.shardId;

  console.log('recordProcessor');
  completeCallback();
},

processRecords: function(processRecordsInput, completeCallback) {
  if (!processRecordsInput || !processRecordsInput.records) {
    completeCallback();
    return;
  }
  var records = processRecordsInput.records;
  var record, data, sequenceNumber, partitionKey;
  for (var i = 0 ; i < records.length ; ++i) {
    record = records[i];
    data = new Buffer(record.data, 'base64').toString();
    sequenceNumber = record.sequenceNumber;
    partitionKey = record.partitionKey;
    console.log(util.format('ShardID: %s, Record: %s, SeqenceNumber: %s, PartitionKey:%s', shardId, data, sequenceNumber, partitionKey));
  }
  if (!sequenceNumber) {
    completeCallback();
    return;
  }
  // If checkpointing, completeCallback should only be called once checkpoint is complete.
  processRecordsInput.checkpointer.checkpoint(sequenceNumber, function(err, sequenceNumber) {
    console.log(util.format('Checkpoint successful. ShardID: %s, SeqenceNumber: %s', shardId, sequenceNumber));
    completeCallback();
  });
},

leaseLost: function(leaseLostInput, completeCallback) {
    console.log(util.format('Lease was lost for ShardId: %s', shardId));
  completeCallback();
},

shardEnded: function(shardEndedInput, completeCallback) {
    console.log(util.format('ShardId: %s has ended. Will checkpoint now.', shardId));
  shardEndedInput.checkpointer.checkpoint(function(err) {
    completeCallback();
  });
},

shutdownRequested: function(shutdownRequestedInput, completeCallback) {
  shutdownRequestedInput.checkpointer.checkpoint(function (err) {
    completeCallback();
  });
}
  };
}

kcl(recordProcessor()).run();

A: Run app with java bootstraper
../../../bin/kcl-bootstrap --java /usr/bin/java -e -p ./sample.properties


text:
Q: pgf Weird error "Missing number treated as zero" I am preparing a dissertation. I'm using Visual Studio Code and Miktex. After reading many related questions here about "Missing number, treated as zero", I still do not understand why the following example results in such an error message. I used Geobra Classic to generate this code.
\documentclass[10pt]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usepackage{mathrsfs}
\usetikzlibrary{arrows}
\pagestyle{empty}
\begin{document}
\definecolor{ccqqqq}{rgb}{0.8,0,0}
\definecolor{qqwuqq}{rgb}{0,0.39215686274509803,0}
\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=1cm,y=1cm]
    \begin{axis}[
            x=1cm,y=1cm,
            axis lines=middle,
            xmin=-5.912600483813963,
            xmax=10.112505461619168,
            ymin=-5.0000004190058975,
            ymax=5.000000419005901,
            xtick={-5,-4,...,10},
            ytick={-5,-4,...,5},]
        \clip(-5.912600483813963,-5.0000004190058975) rectangle (10.112505461619168,5.000000419005901);
        \draw[line width=2pt,color=qqwuqq,smooth,samples=100,domain=-2.791287717641796:0.9999998864501113] plot(\x,{sqrt((\x)^(3)-6*(\x)+5)});
        \draw[line width=2pt,color=qqwuqq,smooth,samples=100,domain=1.791293439719924:10.112505461619168] plot(\x,{sqrt((\x)^(3)-6*(\x)+5)});
        \draw[line width=2pt,color=ccqqqq,smooth,samples=100,domain=-2.791287717641796:0.9999998864501113] plot(\x,{0-sqrt((\x)^(3)-6*(\x)+5)});
        \draw[line width=2pt,color=ccqqqq,smooth,samples=100,domain=1.791293439719924:10.112505461619168] plot(\x,{0-sqrt((\x)^(3)-6*(\x)+5)});
        \begin{scriptsize}
            \draw[color=qqwuqq] (-2.753604403186806,0.22489541633604176) node {$f$};
            \draw[color=ccqqqq] (-2.753604403186806,0.026150629806518583) node {$g$};
        \end{scriptsize}
    \end{axis}
\end{tikzpicture}
\end{document}

The error message say:
<to be read again>
                   n
l.26    \end{axis}

A number should have been here; I inserted `0'.
(If you can't figure out why I needed to see a number,
look up `weird error' in the index to The TeXbook.)

Why am I getting the Missing number, treated as zero error?
Thanks 3000!

A: Thanks to everyone, Ulrike Fischer found the answer for my question.
All I need is change my funtion to plot(\x,{sqrt(abs((\x)^(3)-6*(\x)+5))});


text: Q: How to interpolate time series df into monthly so that if you were to resample it by mean, it would get back to same quarterly start point in python How to take a pandas time series df, interpolate it into monthly so that if you were to resample it by mean, it would get back to same quarterly start point.


text:
Q: Newtonian potential is harmonic I got this problem in page 321 from Advaced Calculus, written by Friedman:
"Let $\sigma(x,y,z)$ be a continuous function, and let $S$ be a continuously differentiable surface. The Newtonian potential at a point $(x,y,z)$ outside $S$ due to a mass distribution $\sigma$ on $S$ is the integral
$$U(x,y,z) = \int \int_S \frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}}dS$$
Prove the U is harmonic, that is, $U_{xx}+U_{yy}+U_{zz}=0$"
I want to know if I can use Leibniz Integral Rule in this case... I know that writing $\dfrac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}} = f(x,y,z)$, we have that $\frac{d^2f}{dx^2}+\frac{d^2f}{dy^2}+\frac{d^2f}{dz^2}=0$. So if
$$U_{xx}=\int \int_S \frac{d^2}{dx^2}\frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}}dS$$
$$U_{yy}=\int \int_S \frac{d^2}{dy^2}\frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}}dS$$
$$U_{zz}=\int \int_S \frac{d^2}{dz^2}\frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}}dS$$
then,
$$U_{xx}+U_{yy}+U_{zz} =$$
$$\int \int_S  \left(\frac{d^2}{dx^2}\frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}} + \frac{d^2} {dy^2}\frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}} + \frac{d^2}{dz^2}\frac{\sigma(\xi,\eta,\zeta)}{[(x-\xi)^2+(y-\eta)^2+(z-\zeta)^2]^{\frac{1}{2}}}\right)dS$$
$$U_{xx}+U_{yy}+U_{zz}=\int \int_S 0 dS =0$$
But I'm not sure if I can use Leibniz Rule here, because I don't have the integration limits, and beyond that if $S=r(u,v)=(x(u,v), y(u,v), z(u,v))$ does the second derivatives of $f(r(u,v))$ still be 0 when added to each other? So I was hoping someone could clarify this for me, and if the rule can't be used here, does someone can give a hint or a solution, please?


text:
Q: How can i customize Render content elements With the TS variant, the article is displayed completely with media. How can I use an own template?
Or is there a way to transfer Media to Fluid template?
I use following code for News->content element
<f:if condition="{newsItem.contentElements}">
   <f:cObject typoscriptObjectPath="lib.tx_news.contentElementRendering">
</f:if>

In TS:
lib.tx_news.contentElementRendering = RECORDS
lib.tx_news.contentElementRendering {

         tables = tt_content
         source.current = 1
         dontCheckPid = 1

How can i customize Render content elements in a own template?
However, this documentation describes a fluid template
with a debug issue I get no media for the content
https://docs.typo3.org/p/georgringer/news/main/en-us/Tutorials/Templates/RenderContentElements/Index.html

A: You could change the templates of fluid_styled_content and add a condition based on the pid of the record which would be the one of the sysfolder where the news is saved. that would be the easiest solution I guess.

A: In the original news extension detail template media is rendered like this:
<n:renderMedia news="{newsItem}" imgClass="img-responsive" videoClass="video-wrapper" audioClass="audio-wrapper">
    <f:if condition="{newsItem.teaser}">

            <f:format.html>{newsItem.teaser}</f:format.html>

    </f:if>

    <f:if condition="{newsItem.contentElements}">

        <f:cObject typoscriptObjectPath="lib.tx_news.contentElementRendering">{newsItem.contentElementIdList}</f:cObject>
    </f:if>

    <f:render partial="Detail/MediaContainer" arguments="{media: newsItem.mediaNonPreviews, settings:settings}" />

        <f:format.html>{newsItem.bodytext}</f:format.html>

</n:renderMedia>

Maybe this can solve your problem. But you will have to make the ViewHelper available by adding this first line to your custom template:
{namespace n=GeorgRinger\News\ViewHelpers}


text:
Q: How to reverse a Path object? I have created an arch from a path object like this:
path.addArc(rect, 0f, -180f) //and this draws my path CCW.

//and if i wanted it drawn CW:
path.addArc(rect, -180f, 180f)//reverse

but i wish i did not have to do this. i wish there  was a function like:
path.reverse().
I noice there is a path directions class:   but i dont see how to use it  with Arc.... any idea how i can reverse a path better ?

A: Instead of revert the arc, you could reverse the step counter of your animation...
pathMeasure = new PathMeasure(yourArcPath, false);
  Matrix mxTransform = new Matrix();
    float eachStepLen = pathMeasure.getLength() / 200; //200 animation steps
    if (currentStep <= 110 && !reverseActive) {

        currentStep ++; // --- Going forward...

        pathMeasure.getMatrix(
                eachStepLen * currentStep,
                mxTransform,
                PathMeasure.POSITION_MATRIX_FLAG);

        canvas.drawBitmap(image, mxTransform, null);

    } else {
        reverseActive = true;

        pathMeasure.getMatrix(
                eachStepLen * currentStep,
                mxTransform,
                PathMeasure.POSITION_MATRIX_FLAG);

        canvas.drawBitmap(image, mxTransform, null);

        currentStep --; // --- Going backwards...

        if (currentStep == 0){
            reverseActive = !reverseActive;
        }

    }


text:
Q: How to create Group Membership in TFS? I want to create a group membership with below Template for created team project (not for new one):
<group name="Active" description="Active">
          <permissions>
            <permission name="GENERIC_READ" class="PROJECT" allow="true" />
            <permission name="DELETE_TEST_RESULTS" class="PROJECT" allow="false" />
            <permission name="PUBLISH_TEST_RESULTS" class="PROJECT" allow="false" />
            <permission name="VIEW_TEST_RESULTS" class="PROJECT" allow="false" />
            <permission name="GENERIC_READ" class="CSS_NODE" allow="true" />
            <permission name="WORK_ITEM_READ" class="CSS_NODE" allow="true" />
            <permission name="WORK_ITEM_WRITE" class="CSS_NODE" allow="true" />
            <permission name="MANAGE_TEST_PLANS" class="CSS_NODE" allow="true" />
            <permission name="MANAGE_TEST_ENVIRONMENTS" class="PROJECT" allow="false" />
            <permission name="MANAGE_TEST_CONFIGURATIONS" class="PROJECT" allow="false" />
          </permissions>
        </group>

note that in the existing wizard for creating new group membership(Context Menu>Team Project Settings>Group Membership), I can not set WORK_ITEM_WRITE and WORK_ITEM_READ permission!

A: In the XML, it says class="CSS_NODE". This means that WORK_ITEM_WRITE and WORK_ITEM_READ permissions are set for each Area in a Team Project, rather than the Team Project itself.
Area-level permissions are specific to a single project's users and groups. You can set these permissions by right-clicking the project in Team Explorer, clicking Areas and Iterations, and on the Area tab, clicking Security.
See 'Area-level permissions' on the Team Foundation Server Permissions page on MSDN.


text:
Q: How can I use keras to predict on a pretrained model from the VideoCapture of OpenCV? My code is
model = ResNet50(weights='imagenet')

def read_cam(video_capture):
    if video_capture.isOpened():
        windowName = "yolo"
        cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
        cv2.resizeWindow(windowName, 1280, 720)
        cv2.moveWindow(windowName, 0, 0)
        cv2.setWindowTitle(windowName, "Yolo Object Detection")
        while True:
            # Check to see if the user closed the window
            if cv2.getWindowProperty(windowName, 0) < 0:
                break

            ret_val, frame = video_capture.read()
            print(frame)
            frame = np.expand_dims(frame, axis=0)
            frame = preprocess_input(frame)

            preds = model.predict(frame)
            # print(preds)
            print('Predicted:', decode_predictions(preds, top=3)[0])

However, this causes a few errors. First, apparently, it's expecting a different sized array:
ValueError: Error when checking input: expected input_1 to have shape (224, 224, 3) but got array with shape (720, 1280, 3)

A: Use the cv2. resize function to change the frame before calling model.predict as the pretrained model you are using accepts only image of the size 224x224.
 frame=cv2.resize(frame,(224,224))


text:
Q: Improper Integrals and convergence of the limit of an integral Prove that if $f$ is a non-negative valued continuous function with domain $[1,\infty)$ such that $lim_{n \to \infty} \int_{1}^n f(x)dx$ exists then the improper integral $\int_{1}^\infty f(x)dx$ converges and $\int_{1}^\infty f(x)dx$=$lim_{n \to \infty} \int_{1}^n f(x)dx$
I know that for the improper integral to converge would imply that the sequence is bounded and this would also mean that the corresponding sequence of partial sums would need to be bounded. I am unsure of where to go at this point or how to answer this problem.

A: Suppose that $f$ is both non-negative and continuous and that
$$\lim_{n \to \infty} I_n =\lim_{n \to \infty} \int_1^n f(t) \, dt = L.$$
Then, as $\lfloor x \rfloor$ is an integer,
$$\lim_{x \to \infty} \int_1^{\lfloor x \rfloor} f(t) \, dt = L.$$
Note that
$$0 \leqslant \int_1^x f(t) \,dt - \int_1^{\lfloor x\rfloor } f(t) \,dt = \int_{\lfloor x\rfloor }^x f(t) \,dt \leqslant \int_{\lfloor x\rfloor }^{\lfloor x\rfloor+1} f(t) \,dt.$$
We have by the Cauchy criterion, $|I_{n+1} - I_n| < \epsilon$ for all $n$ sufficiently large since the sequence $(I_n)$ is convergent. Hence, the limit of the integral on the RHS must be zero as $x \to \infty$.
Therefore,
$$\lim_{x \to \infty} \int_1^x f(t) \,dt = \lim_{x \to \infty} \int_1^{\lfloor x\rfloor } f(t) \,dt = L.$$


text:
Q: Scala type class for obtaining the most concrete type for a type member Consider the following Scala code:
trait Elem
class MyElem extends Elem

trait Holder {
  type EP <: Elem
  def get: EP
}

class MyHolder(e: MyElem) extends Holder {
  type EP = MyElem
  def get = e
}

Depending on whether I have an object typed Holder or MyHolder, calling get may return an Elem or MyElem, respectively. I'm trying to make that information available at type level, but I'm not getting any results. Consider, for example, a Getter type class like this:
trait Getter[From] {
  type Out
  def get(from: From): Out
}

object Getter {
  type Aux[From, Out0] = Getter[From] { type Out = Out0 }

  def apply[From](implicit getter: Getter[From]): Getter.Aux[From, getter.Out] = getter

  // some way to create a `Getter[H <: Holder]`
  // where `Out` is the most specific type known for `H#EC`
}

Getter[MyHolder] // should return a MyHolder { type Out = MyElem }
Getter[Holder] // should return a Holder { type Out = Elem }

I'm trying to create the implicit constructor for Getter[H <: Holder] missing in the snippet but even though I tried several ways of constraining the types, I'm not getting any results that work for both examples above.
Is this possible to do with the Scala compiler? Does any type class from shapeless or scalaz help me do that?

A: What you're asking sounds like an application of Path Dependent Types
Wherein you can type something based on the type defined in some trait/class without knowing the concrete implementation:
val x: Holder#EP = ???

I hope this is what you're looking for, if not I'm afraid I don't fully understand your question.


text:
Q: i have trouble making a discord.py lyrics finder bot pls help me find a code that works
this code I wrote edosent work as well
async def lyrics(self, ctx, artist,*, title):
async with aiohttp.ClientSession() as session:
           async with session.get(f"https://api.lyrics.ovh/v1/{artist}/{title}") as response:
                data = await response.json()
                lyrics = data['lyrics']
                if lyrics is None:
                    await ctx.send("Song not found! Please enter correct Artist and Song title")
                if len(lyrics) > 2048:
                     lyrics = lyrics[:2048]
                emb = discord.Embed(title = f"{title}" , description = f"{lyrics}")
                await ctx.send(embed=emb)
        await session.close()```


text:
Q: FFmpeg does not always fully concat video? I'm trying to concat two video clips, sometimes i end up with only three fourths of the video, sometimes I only get one half, and sometimes i manage to get the whole thing. Anyone ever deal with this? Here is my ffmpeg command:
ffmpeg -i "concat:videos/clip1.ts|videos/clip2.ts"  -ar 44100  -b:a 128k -b:v 800k -vcodeclibx264 -bsf:v h264_mp4toannexb -f mpegts -t 120 videos/output.ts

I just dont understand why sometimes it works perfectly and other times i only get part of the video.

A: Its very easy and you needn't ffmpeg to concat videos. Our videos: video1.mp4, video2.mp4
cat video* > full_video.mp4

Another option, create a playlist, (a text file containing the names of the videos)
Create Playlist.txt or playlist.m3u8  and add in to this file put the path of videos:

video1.mp4
video2.mp4

and the call to ffmpeg is:
ffmpeg - i playlist.txt - codec .... fullvideo.ts


text:
Q: Powershell Git Hook Exit Code I have the following in my .git/hooks/pre-commit file
#!/bin/sh
exec c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -Command " Get-Location | % { '$_\pre-commit-hook.ps1'} | % { & $_ }"
exit

This successfully executes the code in the pre-commit-hook.ps1 file in the same directory, but does not capture the exit code. According to tldp.org the last exit code will be returned if only exit is specified. Git hooks will fail if the exit code is non-zero, but even though my powershell script returns a status code of 1, it always succeeds. What can I do to capture the exit code from the powershell script so the hook will function correctly?

A: Keep the invocation of the ps1 script simple and you should have it working. The following works for me:
#!/bin/sh
echo
exec powershell.exe -ExecutionPolicy RemoteSigned -File '.\.git\hooks\pre-commit-hook.ps1'
exit

The ps1 script just had an exit 1 and the commit did not happen.
When you are doing stuff like -command, Powershell is not known to work properly and you might have to do something like -command {& .\test.ps1; exit $lastexitcode}


text:
Q: How to customise React AsyncSelect style I am trying to customise the style of AsyncSelect component, but seems not able to do it.
import AsyncSelect from 'react-select/async';
<AsyncSelect
  classNamePrefix='testSelect'
  ......
/>

scss file:
Both ways are not working
.testSelect__menu {
  box-shadow: 5px 5px 15px -5px #ccc, -5px 5px 15px -5px #ccc !important;
  background-color: black !important;
  z-index: 10 !important;
}

.testSelect {
  &__menu {
    box-shadow: 5px 5px 15px -5px #ccc, -5px 5px 15px -5px #ccc !important;
    background-color: black !important;
    z-index: 10 !important;
  }
}

Anyone knows how to solve the issue? Thanks in advance.

A: I have made a codesandbox & the css class testSelect__menu is applied to the inner elements. Which results in the output -

Maybe you want to look into if scss is configured correctly or not?


text:
Q: Error: Could not execute statement on remote server I am getting error using similar syntax. With numeric it works, but for varchar it doesn't:
This is OK:
DECLARE @DATA1 NUMERIC(3)
SET @DATA1 = 0

EXECUTE ('BEGIN PPC.PRUEBA (?); END;', @DATA1 OUTPUT) AT [GETESTING]
SELECT @DATA1

But this code:
DECLARE @DATA2 varchar(50) SET @DATA2 = '' EXECUTE ('BEGIN PPC.PRUEBA_CHAR (?); END;',@DATA2 OUTPUT) AT GETESTING SELECT @DATA2

throws this error:

Msg 7215, Level 17, State 1, Line 9
  Could not execute statement on remote server 'GETESTING'.

A: After lot of tests with a pair of similar Windows Servers and also Windows 10 desktop I found that the source of the issue is the version of Oracle Drive.
We are runnig Oracle 11 and till now we install 11 drivers for Sql-Plus or Toad.
But with this new Windows Servers 2012 and newer Sql-Server 2016, SSMS 17.3 looks like the old Oracle client has issues like reported in this post.
After installing Oracle Driver, same we have in servers that ths Procedure call worked it begun to work were it previously doesn't. Even from Window 10 with SSMS.
Thank you


text:
Q: Ancient method to study Archimedean spiral It is well-known the properties of Archimedean spiral  ($\rho = k\phi$) which is the locus of points corresponding to the locations over time of a point moving away from a fixed point with a constant speed along a line which rotates with constant angular velocity. For example, any ray from the origin intersects successive turnings of the spiral in points with a constant separation distance. The properties were studied by Archimedes by means of math available at the time.
However, let's look at the length of Archimedean spiral which requires more advanced tools:
$S(\phi) = \frac{k}{2} \left[ \phi \sqrt{1 + \phi^2} + \ln \left( \phi + \sqrt{1 + \phi^2}\right) \right]$,
$\lim_{\phi \to \infty} S''(\phi)=k$
In other words we observe a movement with uniform acceleration along the Archimedean spiral (the junction point of the line which rotates with constant angular velocity and Archimedean spiral moves along Archimedean spiral with uniform acceleration).
So, my question is to understand if there is a simple way to figure "uniform acceleration" out with a tool available at the times?
Now, we can calculate the limit, but does that mean that Archimedes failed to discover the property?
I searched in Archimedes Palimpsest, but it is unclear if Archimedes has a tool to realise the uniform acceleration which appears for the curve he studied.
http://en.wikipedia.org/wiki/Archimedes_Palimpsest

A: Archimedes might have tried to bound the arclength of the $i$th whorl of the spiral between the circumferences of two circles (of radii $ki$ and $k(i+1)$).  If you consistently take, say, the lower bound, or the upper bound, or any sensible weighted average of the two, then you're adding a constant amount of arclength with each whorl.  The particle can traverse this extra length in the same time by accelerating uniformly.
Of course, this isn't completely accurate, as mentioned by Aaron Meyerowitz in the comments.  But as the angle between the tangent vectors to the spiral and to the circle decreases, the error approaches zero.   Archimedes was fairly comfortable handling the error intuitively in limiting arguments like this, as far as I know.
But this is a boring story.  I prefer to imagine that one day Archmedes carefully cut an unrolled papyrus scroll in half along one of its diagonals (either on a whim, or out of frustration with the math that he'd been trying to write on it).  When the halves are rolled back up, they're approximately parabolic in cross-section.  He would have instantly recognized the parabola, after all that time he spent cutting cones in half.  I don't know whether Archimedes knew that the parabola is the curve of constant acceleration, though.


text:
Q: Python Azure function used in Data Factory returns: "Response Content is not a valid JObject" I have created a very basic HTTP Trigger in Python that I can validate and test with success. However when I plug it in Data Factory and no matter what I do I get the message:

Response Content is not a valid JObject

From the Azure Python function I tried returning:

return func.HttpResponse(json.dumps(f"Hello Test!"), mimetype='application/json')

and also:

return json.dumps(f"Hello Test!")

But in both cases I always get the not valid JObject error message. Any ideas what is going on?

A: Did you write it with a mistake of "f"
return json.dumps(f"Hello Test!")
And could you please try to modify your code to
a = {'name': 'wang'}
json.dumps(a)


text:
Q: Permission Denied on Cabal Update I'm getting a "permission denied" error when I try the following command:
$ cabal update

I'm on Mac OS 10.6. Does anyone know how to fix this? Thanks!

A: First: are you sure you're running it as the correct user?  Have you somehow set in your ~/.cabal/config (or wherever the settings are kept on OSX) that it should do it as a global install?
Also check the permissions of where the tarball will be downloaded to:
$ ls -l ~/.cabal/packages/
$ ls -l ~/.cabal/packages/hackage.haskell.org/00-index.*

This should show that your user is indeed allowed to download the list of packages.


text:
Q: Most efficient way to loop though PHP array I need to iterate over an array and do something where the actual value of the array is not needed.  What is the most efficient way to do so?  If I do need to use the array element value, does the answer change?  I've given two possible solutions below.
<?php
$sql='INSERT INTO bla(x,y,z) ';
$myarray=array(4,3,6,9,6,3,6);

for ($i = 0; $i <= count($myarray); $i++) {
    //Do something where $myarray[$x] is not needed such as make a sting
    $sql.='(1,2,?),';
}

foreach($myarray as $arrayElement) {
    //Do something where $arrayElement is not needed such as make a sting
    $sql.='(1,2,?),';
}
?>

A: As far as I know, for is slightly faster than foreach, thus making it more efficient. Of course, the difference is so small that I doubt anyone can notice it in most occasions.
But foreach seems to be a more elegant way, and also in case of associative array it is your only choice.

A: If you don't need to use the value, then for is a bit faster.
If you need to alter the values of the array then the foreach loop with reference is the fastest.
See https://stackoverflow.com/a/3433065/2078780


text:
Q: Passing params to Stored Procedure-Special case ALTER  PROCEDURE [dbo].[usp_SaveUserCustomerXRef]
    @Username varchar(48),
    @LinkID varchar(48)
AS
DELETE FROM UserCustomerX WHERE UserName=@UserName AND LinkID=@LID
INSERT INTO UserCustomerX(Username, LID)
VALUES (@Username, @LID)

is executed As-

*

*EXEC usp_SaveUserCustomerXRef '10026:ttmm19',2H0;//Syntax error

*EXEC usp_SaveUserCustomerXRef '10026:ttmm19',A1;//Executed+Inserted

*EXEC usp_SaveUserCustomerXRef '10026:ttmm19',2;//Executed+Inserted

*EXEC usp_SaveUserCustomerXRef '10026:ttmm19','2H0';//Executed+Inserted
The columns in the table UserCustomerX  are of type Varchar.My problem is with case no:2 why does it insert values though there is no single quotes.But Case No:1 gave syntax error.Case 3&4 are normal conditions. Why does case 2 work? without quotes?

A: Your second paramter @LinkID  is a varchar, so you better force and generalize the use of quotes when executing your stored procedure.
And as Nicarus said, it's probably an implicit conversion to number which provoke the syntax error.


text:
Q: Why git repack fails in `filter-repo`? I have a repo where git fsck --strict --full returns 0 and
I now add a file .gitattributes to every commit with git filter-repo script here or here the equival. command:
FILTER_BRANCH_SQUELCH_WARNING=1 \
    git filter-branch -f \
    --index-filter \
    "cp -f '$outDir/.gitattributes' .gitattributes && git add .gitattributes" \
    --tag-name-filter cat \
    --prune-empty -- --all

Which fails with
Repacking your repo and cleaning out old unneeded objects
Counting objects: 100% (571811/571811), done.
Delta compression using up to 14 threads
Compressing objects: 100% (108091/108091), done.
error: bad packed object CRC for e9975de53768c33397b84bdad69b9c3e7a0aaba6
error: bad packed object CRC for e9975de53768c33397b84bdad69b9c3e7a0aaba6
fatal: packed object e9975de

I am completely out of any hope here, I dont know what I am doing wrong? if the disk would be full, wouldn't there be another failure, and I checked I have enought space, also on the system...?
Note: I am on ubuntu:focal with git build 2.27.0 on a Virtual Box 6.1 with a Windows Host, with a SSD where the repo is in a
.vdi Image.
Update: Sometimes it fails, and sometimes it passes ???


text:
Q: How to keep a log of all urls browsed by means of programming? I know a lot of keyloggers and kids monitoring agents out there. My question is how do I simply get to hold the list of urls the user browsed using that particular browser by means of programming? I am not interested in using any kind of keylogger or any other monitoring tools. Thanx a lot.

A: Programmatic methods will vary between browsers and operating systems but browsing history is often stored in an SQLite database.
For example, Chrome on Windows 7 stores its history in:
C:\Users\[username]\AppData\Local\Google\Chrome\User Data\Default\History

You can programmatically access this History file using the SQLite API or interactively using an SQLite manager such as SQLite Expert.
It is wise to open it read-only or otherwise make sure Chrome is closed before accessing it.
The visits table is a good place to start.


text:
Q: Send emails from a container in gitlab ci I am using a openSUSE Tumbleweed container in a gitlab ci pipeline which runs some script. In that script, I need to send an email at some point of time with certain content.
In the container, I am installing postfix and configuring that relay server in /etc/postfix/main.cf.
The following command works on my laptop using that same relay server:
echo "This is the body of the email" | mail -s "This is the subject" -r sender@email.com receiver@email.com

but doesn't work from the container, even having the same postfix configuration.
I've seen some tutorials that show how to use the postfix/smtp configuration from the host, but since this is a container running in gitlab ci, that's not applicable.

A: So, finally opted for a python solution and call the script from bash, this way I really don't need to configure postfix, smtp or any other thing. You just export your variables in bash (our use argparse) and run this script. Of course, you need a relay server without auth (normally on port 25).
import os
import smtplib
from email.mime.text import MIMEText

smtp_server = os.environ.get('RELAY_SERVER')
port = os.environ.get('RELAY_PORT')
sender_email = os.environ.get('SENDER_EMAIL')
receiver_email = os.environ.get('RECEIVER_EMAIL')

mimetext = MIMEText("this is the body of the email")
mimetext['Subject'] = "this is the subject of the email"
mimetext['From'] = sender_email
mimetext['To'] = receiver_email

server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.sendmail(sender_email, receiver_email.split(','), mimetext.as_string())


text:
Q: Recommended place/folder to put single jar server app for deployment? I have a single jar server app (simple web portal) built with Spring Boot. I run it:
java -jar myapp.jar
Locally, the jar file is under my Eclipse project folder. Now it's ready to be deployed on a Linux server as a service. What folder should I create on the server to put the jar file? In that folder (working directory), I will be putting the application.yaml file plus some other config files. The service will run as root.

A: Create a directory under either /opt or /usr and have your jar run from there.
If your app creates one log file, configure it for /var/log. If it's going to write a few create a directory  /var/log/<your app>.


text:
Q: Using ObjectLoader to load JSON that contains a BufferGeometry with multiple materials doesn't work I have created a sphere, with multiple materials, like so:
const materials = [
    new THREE.MeshPhongMaterial({});
    new THREE.ShaderMaterial({ visible: false});
]

const geometry = new THREE.SphereBufferGeometry(2,100,100);
geometry.addGroup(0, Infinity, 0);
geometry.addGroup(0, Infinity, 1);

const mesh = new THREE.Mesh(geometry, materials);
scene.add(mesh);

The scene, light, camera are also defined (but not included here since they are not an issue).
This all works when the page loads (initialization).
Later I'm exporting the entire scene with scene.toJSON(). Then, later, I might want to load that JSON back in and replace the entire scene. I'm doing this with:
const loader = new THREE.ObjectLoader();
loader.parse(jsonObject, function(object) {

    // instance is an object containing a bunch of things,
    // including the current scene.
    // So I replace the current scene with the new one from the JSON

    instance.scene = object;
}

At this point, the scene gets replaced correctly, but the object does not appear (and I know the JSON is formed correctly).
I've tried, instead to create the sphere with
const geometry = new THREE.SphereGeometry(2,100,100);

If I do that, then when loading the JSON the object appears correctly.
I'd prefer to use SphereBufferGeometry() but I'm not sure why it doesn't work. What am I missing/doing wrong?
Here are two examples. In both you should see a blank sphere, but in #1 you do not:

*

*With SphereBufferGeometry: https://codepen.io/anon/pen/BgQmMq

*With SphereGeometry: https://codepen.io/anon/pen/agBEbp

A: There are two issues with your code.

*

*When using the built-in geometry generators, three.js assumes that you do not modify the geometry data. But you are actually doing this by adding groups. These data are lost during the serialization/deserialization process. So the idea is to create a new BufferGeometry object and copy over the buffer attributes and indices. You can then freely define new data or overwrite existing ones.

*Besides, Infinity is a bad choice since it can't be serialized. It's better to set the value representing the last vertex for non-indexed geometry or the last index for an indexed geometry. I've updated your codepen with both fixes.

https://codepen.io/anon/pen/MMbQgv
three.js R105


text:
Q: Where do string substition Variables get saved? I've searched for this a lot, but couldn't find an answer.
I'm searching for the exact location of the Config File for the variables you can add in Eclipse at "preferences > Run/Debug > String Substituion".
My idea is to automatically check for several variables that i need for an simulator, and write them directly to the "string substitution"file.

A: Theses variables are accessed using the IStringVariableManager interface:
IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();

The variables on the Run/Debug preferences are 'value variables' which you create with:
IValueVariable vv = manager.newValueVariable("name", "description", "value");

you must add the created variables to the manager to make them permanent:
manager.addVariables(variables array);

The API does not specify where these values are stored. They appear to be stored in the org.eclipse.core.variables.prefs file in the workspace .metadata/.plugins/org.eclipse.core.runtime/.settings directory. Changing this file directly will probably not update the list in the variables manager.


text:
Q: Transformation Identities of the $_2F_1$ function From Wolfram Functions we have the following identities for the hypergeometric function $_2F_1$:
$$\begin{align}
_2F_1\left(a,c-b;c;\tfrac{z}{z-1}\right)&=(1-z)^a\,_2F_1(a,b;c;z)\tag1\\
_2F_1\left(a,a+\tfrac12;c;z(2-z)\right)&=\left(1-\tfrac{z}2\right)^{-2a}\,_2F_1\left(2a,2a-c+1;c;\tfrac{z}{2-z}\right)\tag2\\
_2F_1\left(a,b;2b;\tfrac{4z}{(z+1)^2}\right)&=(1+z)^{2a}\,_2F_1\left(a,a-b+\tfrac12;b+\tfrac12;z^2\right),\tag3
\end{align}$$
where $$_2F_1(a,b;c;z)=\frac{\Gamma(c)}{\Gamma(b)\Gamma(c-b)}\int_0^1t^{b-1}(1-t)^{c-b-1}(1-zt)^{-a}dt.\tag{$\star$}$$
As a recreational project, I have been trying to prove the three above identities using $(\star)$.
So far, I've been able to prove $(1)$. The proof is very simple and uses transformation $t\mapsto1-t$ in the integral. The identity follows immediately after simplification.
This prompted me to try to prove the other two identities using substitutions in the integral $(\star)$
At this point, I have been able to rewrite $(2)$ as
$$\,_2F_1\left(2a,2a-c+1;c;z\right)=(1+z)^{-2a}\,_2F_1\left(a,a+\tfrac12;c;\tfrac{4z}{(z+1)^2}\right)$$
via the substitution $\tfrac{z}{2-z}\mapsto z$.This rewritten form looks very similar to $(3)$, suggesting that they are related. Beyond this I have no leads.
I have however examined the function
$$U(\alpha,\beta,\gamma,\delta;z)=\int_0^1(1+t)^\alpha t^\beta (1-t)^\gamma (1-zt)^\delta dt,$$
considering its transformation identities given by substitutions which send $[0,1]$ to itself in the integral.
This seems related, as clearly
$$_2F_1(a,b;c;z)=\frac{\Gamma(c)}{\Gamma(b)\Gamma(c-b)}U(0,b-1,c-b-1,-a;z).$$
For example, the substitution $t\mapsto \tfrac{1-t}{1+t}$ gives the identity
$$U(\alpha,\beta,\gamma,\delta;z)=2^{1+\alpha+\gamma}(1-z)^{-\delta}U\left(-\alpha-\beta-\gamma-\delta-2,\gamma,\beta,\delta;\frac{z+1}{z-1}\right).$$
And while setting $\alpha=\beta+\gamma+\delta+2=0$ yields
$$\,_2F_1(-\delta,\beta+1;\beta+\gamma+2;z)=2^{\gamma+1}(1-z)^{-\delta}\,_2F_1\left(-\delta,\gamma+1;\beta+\gamma+2;\frac{z+1}{z-1}\right),$$
this is not one of the transformation identities I was trying to prove.
So, I would like some hints on how to prove $(2)$ and $(3)$, if it is possible just using the integral $(\star)$.

A: A way to prove the second identity is to use the series representation $$\,_2F_1\left(a,b;c;z\right)=\sum_{n=0}^{\infty} \frac{(a)_{n}(b)_{n}}{(c)_{n}} \frac{z^{n}}{n!} \, , \quad |z| <1, $$ where $(a)_{n} = a(a+1) \cdots (a+n-1) = \frac{\Gamma(a+n)}{\Gamma(a)}.$
As was mentioned in the question, the second identity can be rewritten as $$\,_2F_1\left(2a,2a-c+1;c;z\right)=(1+z)^{-2a}\,_2F_1\left(a,a+\frac{1}{2};c;\frac{4z}{(1+z)^2}\right). $$
Starting on the right side of the identity, we have
$\begin{align} \frac{\,_2F_1\left(a,a+\frac{1}{2};c;\frac{4z}{(z+1)^2}\right)}{(1+z)^{2a}} &= \frac{1}{(1+z)^{2a}}\sum_{n=0}^{\infty} \frac{(a)_{n} \left(a+ \frac{1}{2} \right)_{n}}{n!(c)_{n}} \frac{(4z)^{n}}{(1+z)^{2n}} \\ &= \sum_{n=0}^{\infty} \frac{(a)_{n} \left(a+ \frac{1}{2} \right)_{n}}{n!(c)_{n}} (4z)^{n}\frac{1}{(1+z)^{2a+2n}} \\ &\overset{(1)}{=} \sum_{n=0}^{\infty} \frac{(a)_{n} \left(a+ \frac{1}{2} \right)_{n}}{n!(c)_{n}} (4z)^{n} \sum_{m=0}^{\infty} \binom{2a+2n+m-1 }{m} (-z)^{m} \\  &\overset{(2)}= \sum_{k=0}^{\infty} \sum_{j=0}^{k} \frac{(a)_{j}\left(a+ \frac{1}{2} \right)_{j}}{j!(c)_{j}} 4^{j} \binom{2a+k+j-1}{k-j} (-1)^{k-j} z^{k} \\ & = \sum_{k=0}^{\infty} \sum_{j=0}^{k} \frac{(a)_{j}\left(a+ \frac{1}{2} \right)_{j}}{j!(c)_{j}} 4^{j} \frac{\Gamma(2a+k+j)}{\Gamma(2a+2j)}\frac{1}{(k-j)!}(-1)^{k-j} z^{k} \\ & \overset{(3)}{=} \sum_{k=0}^{\infty} \sum_{j=0}^{k} \frac{1}{\Gamma(2a)j!(c)_{j}} \Gamma(2a+k+j) \frac{1}{(k-j)!} (-1)^{k-j} z^{k} \\ &= \sum_{k=0}^{\infty} \sum_{j=0}^{k} \frac{1}{\Gamma(2a)j!(c)_{j}} \Gamma(2a+k+j) \frac{(-k)_{j}}{k!}(-1)^{k} z^{k} \\ &= \sum_{k=0}^{\infty} \sum_{j=0}^{k} \frac{1}{\Gamma(2a)j!(c)_{j}} (2a+k)_{j} \Gamma(2a+k)\frac{(-k)_{j}}{k!}(-1)^{k} z^{k} \\ &= \sum_{k=0}^{\infty} \frac{(-1)^{k}(2a)_{k}}{k!}z^{k} \sum_{j=0}^{k} \frac{(2a+k)_{j}(-k)_{j}}{j!(c)_{j}} \\ & \overset{(4)}{=} \sum_{k=0}^{\infty} \frac{(-1)^{k} (2a)_{k}}{k!}z^{k} \frac{(c-2a-k)_{k}}{(c)_{k}} \\ &\overset{(5)}{=} \sum_{k=0}^{\infty} \frac{(2a)_{k}(2a-c+1)_{k}}{k!(c)_{k}} z^{k} \\ &= \,_2F_1\left(2a,2a-c+1;c;z\right).\end{align}$

$(1)$ Generalized binomial theorem
$(2)$ Cauchy product
$(3)$ Gamma duplication formula
$(4)$ Chu-Vandermonde identity
$(5)$ $(-x)_{k} = (-1)^{k}(x-k+1)_{k}$


text:
Q: mongo sort before match in aggregation Given a collection of a few million documents that look like:
{
    organization: ObjectId("6a55b2f1aae2fe0ddd525828"),
    updated_on: 2019-04-18 14:08:48.781Z
}

and 2 indices, on both keys {organization: 1} and {updated_on: 1}
The following query takes ages to return:
db.getCollection('sessions').aggregate([
        {
                "$match" : {
                        "organization" : ObjectId("5a55b2f1aae2fe0ddd525827"),
                }
        },
        {
                "$sort" : {
                        "updated_on" : 1
                }
        }
])

One thing to note is, the result is 0 matches. Upon further investigation, the planner in explain() actually returns the following:
{
    "stage" : "FETCH",
    "filter" : {
        "organization" : {
            "$eq" : ObjectId("5a55b2f1aae2fe0ddd525827")
        }
    },
    "inputStage" : {
        "stage" : "IXSCAN",
        "keyPattern" : {
            "updated_on" : 1.0
        },
        "indexName" : "updated_on_1",
        "isMultiKey" : false,
        "multiKeyPaths" : {
            "updated_on" : []
        },
        "isUnique" : false,
        "isSparse" : false,
        "isPartial" : false,
        "indexVersion" : 2,
        "direction" : "forward",
        "indexBounds" : {
            "updated_on" : [
                "[MinKey, MaxKey]"
            ]
        }
    }
}

*

*Why would Mongo combine these into one stage and decide to to sort ALL documents BEFORE filtering?

*How can I prevent that?

A: MongoDB will use the index on to $sort because it's a heavy operation even if matching before will limit the result to be sorted,
You can either force using the index for $match:
db.collection.aggregate(pipeline, {hint: "index_name"})

Or create a better index to solve both problems, see more informations here
db.collection.createIndex({organization: 1, updated_on:1}, {background: true})

A:
Why would Mongo combine these into one stage and decide to to sort ALL
  documents BEFORE filtering? How can I prevent that?

The sort does happen after the match stage. The query plan doesn't show the SORT stage - that is because there is an index on the sort key updated_on. If you remove the index on the updated_on field you will see a SORT stage in the query plan (and it will be an in-memory sort).
See Explain Results - sort stage.
Some Ideas:
(i) You can use a compound index, instead of a two single field indexes:
{ organization: 1, updated_on: 1 }

It will work fine. See this topic on Sort and Non-prefix Subset of an Index.
(ii) Also, instead of an aggregation, a find() query can do the same job:
db.test.find( { organization : ObjectId("5a55b2f1aae2fe0ddd525827") } ).sort( { updated_on: 1 } )

NOTE: Do verify with explain() and see how they perform. Also, try using the executionStats mode.


text: Q: What is the generator of the group of the units in the field $\mathbb{F}_3[x]/(x^3+2x+2)$? I have shown that $\mathbb{F}_3[x]/(x^3+2x+2)$ is a field. Then the question asks what is the generator of the group of the units? no idea how to proceed from there....


text:
Q: CMS page with layered navigation not working I've added a CMS page wich shows all the products listed under the "All Products" category by creating a CMS page with a "two column with left sidebar" layout, and in the content tabs, I've added the following code:
{{block type="catalog/product_list" category_id="2" template="catalog/product/list.phtml"}}

I was reading about it and the layered navigation should be showing already. However, I've set "Is anchor" to yes, but it doesn't work. I can't make it to appear. What am I missing here? Is there a better way to create this catalog page?
Thanks in advance.

A: To display layered navigation on cms page you have to set root category to Is Anchor=Yes.

A: Please check the below link for calling layer navigation in CMS Page
http://www.webdesign-gm.co.uk/news/web-design/magento-web-design/layered-navigation-on-home-page-or-any-cms-page-magento.php
Or you can try this Design tab->Page Layout->Layout Update XML:
 <reference name="left">
        <!-- Layered Navigation Block -->
        <block type="catalog/layer_view" name="catalog.leftnav" template="catalog/layer/view.phtml" >
                <action method="setCategoryId"><category_id>40</category_id></action>
        </block>
</reference>

<reference name="content">
        <block type="catalog/product_list" name="home" template="catalog/product/list.phtml">

                <!-- Product List View -->
                <action method="setCategoryId"><category_id>40</category_id></action>
                <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
                        <block type="page/html_pager" name="product_list_toolbar_pager"/>
                </block>
                <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>

        </block>
</reference>

A: Open CMS->Pages->[your page]  in Magento Admin Panel.
Add the following layout instructions to Design tab->Page Layout->Layout Update XML

<block type="catalog/product_list" name="product_list"

  template="catalog/product/list.phtml">

  <action method="setCategoryId"><category_id>3</category_id></action>

  <block type="catalog/product_list_toolbar" name="product_list_toolbar"

      template="catalog/product/list/toolbar.phtml">

    <block type="page/html_pager" name="product_list_toolbar_pager"/>

  </block>

  <action method="addColumnCountLayoutDepend">

      <layout>empty</layout>

      <count>6</count>

  </action>

  <action method="addColumnCountLayoutDepend">

      <layout>one_column</layout>

      <count>5</count>

  </action>

  <action method="addColumnCountLayoutDepend">

      <layout>two_columns_left</layout>

      <count>4</count>

  </action>

  <action method="addColumnCountLayoutDepend">

      <layout>two_columns_right</layout>

      <count>4</count>

  </action>

  <action method="addColumnCountLayoutDepend">

      <layout>three_columns</layout>

      <count>3</count>

  </action>

  <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>

</block>

<block type="catalog/layer_view" name="cms_layer" as="cms_layer" before="-">

    <action method="setCategoryId"><category_id>3</category_id></action>

</block>

Also insert ID of desired category  in 3 (2 times).
Open desired category of your store through Catalog->Manage Categories. Make sure that Is Anchor=Yes on Display Settings tab.

A: One possible reason layered navigation does not show is because you also need to configure your attributes to show in layered navigation.


text:
Q: How to publish or deploy .NET website without delays How to publish or deploy .NET website without delays?
I have look for websites that are build over .NET technologies, like StackOverflow, and I never saw them down because an update is being made. For my web sites, I got down time in minors updates, like correcting some bugs on my Controllers (I use MVC), not by doing something bigger like database or server movements.
So how can I prevent site loading delays due to ASP.NET Startup?
I know that it require "ASP.NET worker process" to compile the code, but how can I prevent the traffic issues.

A: The typical way of doing this is creating a farm of multiple web servers and, when you want to update the site, take each server offline and update them one at a time. Investigate How to create an ASP.NET web farm?.

A: It's all about the server setup. Most companies have at least 2-3 server: 2 Frontend servers and a backend server. Then you can take one of the frontend servers down, point all traffic to the other one, upgrade the server which is down, and then take that server up, and continue the process with the other.
In some cases you would use load balancing to make sure the two servers are synchronized.
You will notice that sometimes you cannot post here on Stackoverflow because of updates. That's because the database is a shared server, which "can be down", if you need an upgrade. Yes, there are also options against this, but it can gives problems if everyone writes to the database while the site is up, hence the "readonly mode" from time to time.


text:
Q: Get values from json_encode with jQuery I insert several(array) value with json_encode in one row from database table, now want echo they as order with jquery.
This is output from my PHP code:
[{
    "guide": null,
    "residence": [{
        "name_r": "jack"
    }, {
        "name_r": "jim"
    }, {
        "name_r": "sara"
    }],
    "residence_u": [{
        "units": ["hello", "how", "what"],
        "extra": ["11", "22", "33"],
        "price": ["1,111,111", "2,222,222", "3,333,333"]
    }, {
        "units": ["fine"],
        "extra": ["44"],
        "price": ["4,444,444"]
    }, {
        "units": ["thanks", "good"],
        "extra": ["55", "66"],
        "price": ["5,555,555", "6,666,666"]
    }]
}]

I want as(output):

jack hello & 11 & 1,111,111 how & 22 & 2,222,222 what & 33
  & 3,333,333,

jim fine & 44 & 4,444,444

sara thanks & 55 & 5,555,555 good & 66 & 6,666,666

How is it?

A: Assuming

*

*you already know how make the ajax request that fetches this information from your PHP script

*there is always one element in the top-level array (if not, you could add one more level of iteration)

*by output you mean access the corresponding elements - I've put in calls to console.log but you could alert() or put into a DOM element or whatever

you could do something like this in jQuery (here's an example fiddle without the network part. You'll see the output in your console)
var data = response[0]; //response is the data received by the jQuery ajax success callback
var residences = data.residence;
var residence_u = data.residence_u;

$.each(residences, function(index, val){
    var name = val.name_r;
    console.log(name);

    var info = residence_u[index]; //get the corresponding residence_u element

    $.each(info.units, function(index, val){
        var unit = val;
        var extra = info.extra[index];
        var price = info.price[index];
        console.log( val + " & " + extra + " & " + price);
    });
});


text:
Q: How can I change all the form's text when I choose a language in combobox? Like facebook when changing its language, it change all.. need help to rebuild my codes here. I have 3 forms and my combobox where I used to choose the language is in the 1st form. When I choose language in combobox in my 1st form, I want my other 2 forms will change its language also.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedItem.ToString() == "English")
    {
        ChangeLanguage("en");
    }
    else if (comboBox1.SelectedItem.ToString() == "Spanish")
    {
        ChangeLanguage("es-ES");
    }
    else if (comboBox1.SelectedItem.ToString() == "French")
    {
        ChangeLanguage("fr-FR");
    }
}

private void ChangeLanguage(string lang)
{
    foreach (Control c in this.Controls)
    {
        ComponentResourceManager crm = new ComponentResourceManager(typeof(Form1));
        crm.ApplyResources(c, c.Name, new CultureInfo(lang));
    }
}

A: You can use a base class, that holds a static event of "LanguageChanged", and a function to trigger it.
If all your forms are derivative class of that base class, the event could be handled within it.
Something like:
public partial class Form1 : BaseLanguageForm
{

    public Form1()
    {
        InitializeComponent();

    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedItem.ToString() == "English")
        {
            this.TriggerLanguageChange("en");
        }
        else if (comboBox1.SelectedItem.ToString() == "Spanish")
        {
            this.TriggerLanguageChange("es-ES");
        }
        else if (comboBox1.SelectedItem.ToString() == "French")
        {
            this.TriggerLanguageChange("fr-FR");
        }
    }

}

/// <summary>
/// The event that should be passed whenever language needs to be changed
/// </summary>
public class LanguageArgs:EventArgs
{
    string _languageSymbol;
    /// <summary>
    /// Gets the language symble.
    /// </summary>
    public string LanguageSymbol
    {
        get { return _languageSymbol; }
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="LanguageArgs"/> class.
    /// </summary>
    /// <param name="symbol">The symbol.</param>
    public LanguageArgs(string symbol)
    {
        this._languageSymbol = symbol;
    }
}

/// <summary>
/// A base class that your class should derivative from
/// </summary>
public class BaseLanguageForm:Form
{
    /// <summary>
    /// Triggers the language change event.
    /// </summary>
    /// <param name="languageSymbol">The language symbol.</param>
    protected void TriggerLanguageChange(string languageSymbol)
    {
        if (Form1.onLanguageChanged != null)
        {
            LanguageArgs args = new LanguageArgs(languageSymbol);
            Form1.onLanguageChanged(this, args);
        }
    }

    /// <summary>
    /// This should be triggered whenever the combo box value chages
    /// It is protected, just incase you want to do any thing else specific to form instacne type
    /// </summary>
    protected static event EventHandler<LanguageArgs> onLanguageChanged;

    /// <summary>
    /// This will be called from your form's constuctor
    /// (you don't need to do anything, the base class constuctor is called automatically)
    /// </summary>
    public BaseLanguageForm()
    {
        //registering to the event
        BaseLanguageForm.onLanguageChanged += new EventHandler<LanguageArgs>(BaseLanguageForm_onLanguageChanged);
    }

    /// <summary>
    /// The function that was regidtered to the event
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The e.</param>
    void BaseLanguageForm_onLanguageChanged(object sender, LanguageArgs e)
    {
        string lang = e.LanguageSymbol;
        foreach (Control c in this.Controls)
        {
            ComponentResourceManager crm = new ComponentResourceManager(typeof(Form1));
            crm.ApplyResources(c, c.Name, new CultureInfo(lang));
        }
    }

}

A: Based on what I've understood from your question, I think this is possible if you are trying to call ChangeLanguage(string lang) from the other forms as well.
You'll need a Timer added to every Form you would like to use the void on, and TWO variables. The first is a bool which will be used to detect if ChangeLanguage is required to be called within the other TWO forms, and the second is a string which will indicate the language. These TWO variables must be public and static so that they can be controlled through other forms.
Example

 Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace NameSpaceGoesHere
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static bool _ChangeLanguage = false; //This will indicate if the void needs to be called
        public static string _Language = ""; //This will indicate our new language
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeLanguage("fr-FR");

        }

        private void ChangeLanguage(string lang)
        {
            foreach (Control c in this.Controls)
            {
                ComponentResourceManager crm = new ComponentResourceManager(typeof(Form1));
                crm.ApplyResources(c, c.Name, new CultureInfo(lang));
                _Language = lang; //Sets the language to lang
                _ChangeLanguage = true; //Indicates that the void needs to be called through the TWO other forms as well
            }
        }

    }
}

 Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace NameSpaceGoesHere
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        public static bool _ChangeLanguage = false; //Required for the third form
        private void Form2_Load(object sender, EventArgs e)
        {
            Timer Timer1 = new Timer(); //Initialize a new Timer object
            Timer1.Tick +=new EventHandler(Timer1_Tick); //Link its Tick event with Timer1_Tick
            Timer1.Start(); //Start the timer
        }
        private void ChangeLanguage(string lang)
        {
            foreach (Control c in this.Controls)
            {
                ComponentResourceManager crm = new ComponentResourceManager(typeof(Form1));
                crm.ApplyResources(c, c.Name, new CultureInfo(lang));
                _ChangeLanguage = true;
            }
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (Form1._ChangeLanguage)  //Indicates if ChangeLanguage() requires to be called
            {
                Form1._ChangeLanguage = false; //Indicates that we'll call the method
                ChangeLanguage(Form1._Language); //Call the method
            }
        }
    }
}

 Form3.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace NameSpaceGoesHere
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }
        private void Form3_Load(object sender, EventArgs e)
        {
            Timer Timer1 = new Timer(); //Initialize a new Timer object
            Timer1.Tick += new EventHandler(Timer1_Tick); //Link its Tick event to Timer1_Tick
            Timer1.Start(); //Start the timer
        }
        private void ChangeLanguage(string lang)
        {
            foreach (Control c in this.Controls)
            {
                ComponentResourceManager crm = new ComponentResourceManager(typeof(Form1));
                crm.ApplyResources(c, c.Name, new CultureInfo(lang));
            }
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (Form2._ChangeLanguage) //Indicates if ChangeLanguage() requires to be called
            {
                Form2._ChangeLanguage = false; //Indicates that we'll call the method
                ChangeLanguage(Form1._Language); //Call the method
            }
        }
    }
}

Thanks,
I hope you find this helpful :)


text:
Q: Do we need to put an article after "by"? I've encountered many phrases like the following:

It was performed by band the Beatles
It was made by machine
...which was built by architect [name]

So, I guess when we want to state that something came into existence (or something was done to it) by someone, we omit the definite article before that someone, is that right?
Could you please give the exact rule on this topic?

A: Whether the is required in your examples depends on the context:

It was made by machine

is a way of saying that it was made mechanically and not by hand.

It was made by a machine

means that it was made by a machine that has not been identified.

It was made by the machine

means that it was made by a machine that you have already identified.
You cannot say: It was designed/built by architect without an article.
Either: It was designed by an architect (who has not been identified)
Or: It was designed by the architect (whom you have already referred to)
Thus you could write either: It was designed by John Smith, (who is) an architect, or: It was designed by John Smith, the architect (which assumes that John Smith is well known as an architect.
The same rule applies to band. Music is not performed by band, but either by a band (unidentified) or the band (already identified).


text:
Q: BibTeX files: How to concatenate BibTeX files from different folders and keep valid links for referenced files? My BibTeX files contain references to files, like PDF files. I use the field "file" to indicate the referenced files. This is useful to associate files with a BibTeX entry. Moreover one can directly open the file from some software, such as JabRef.
I would like to concatenate BibTeX files located in different folders and keep valid relative links. Valid links will allow to access the files from the concatenated BibTeX file.
A dummy command cat will lose all relative links.
Here is an example of what I except from the concatenation.
Below are two BibTeX files located in two different folders.
The field 'file' indicates the location of the referenced file.
In the concatenated result file, these 'file' fields are modified to take into account the location of the files.
Root dir
|- RootA
|  - A.bib
|- RootB
|  - B.bib

with A.bib
@MISC{XY,
  title = {John Doe's Book},
  author = {John Doe},
  file = {johnDoe.pdf:johnDoe.pdf:pdf},
}

with B.bib
@MISC{XX,
  title = {Jane Doe's Book},
  author = {Jane Doe},
  file = {janeDoe.pdf:janeDoe.pdf:pdf},
}

I would like the concatenation of the two files to look like this:
@MISC{XY,
  title = {John Doe's Book},
  author = {John Doe},
  file = {johnDoe.pdf:RootA/johnDoe.pdf:pdf},
}

@MISC{XX,
  title = {Jane Doe's Book},
  author = {Jane Doe},
  file = {janeDoe.pdf:RootB/janeDoe.pdf:pdf},
}

The tools I have used so far do not do such things...
The basic idea I have to do this, is to use a combination of command lines tools such as sed and cut. But it seems painful and not robust. And I should also mention that one should make difference between absolute links and relative links. Finally, the result file depends on where we run the concatenation command...
Does anyone has a better idea, or know a software that performs that operation?

A: BibTool is a powerful tool to manipulate BibTeX files.
One thing it can do is rewrite a certain field using regular expressions.
BibTool accepts commands either from an external file or directly on the command line preceded by --. The command rewrite.rule={file "foo" "bar"} replaces each foo inside any file entry with bar, where foo can be a (grep-style) regular expression.
Obviously the regular expression depends on how your data is structured, but assuming that every file looks like {label:filename:filetype} and there are no colons in your filenames, you could use the following command to insert RootA before each file in A.bib, printing the result to the screen.
bibtool -- 'rewrite.rule={file ":\([^/].*\):" ":RootA/\1:"}' -- 'rewrite.limit=1' A.bib

The rule also requires the first character of the filename to be something other than /, which will leave absolute paths alone.

A: As @NathanGrigg mentionned, one can use bibtool to do this.
If one wants to use shell variables to perform substitution, one can not use quotes, and one has to escape all special characters.
The following command adds the directory name to the file field value with the shell variable dirToAdd
dirToAdd=RootA
bibtool -- rewrite.rule={file\ \":\\\([^/].*\\\):\"\ \":${dirToAdd}/\\1:\"} -- rewrite.limit=1 A.bib

Run on this following bibtex entry
@MISC{XY,
  title = {John Doe's Book},
  author = {John Doe},
  file = {johnDoe.pdf:johnDoe.pdf:pdf},
}

the previous command will produce
@MISC{XY,
  title = {John Doe's Book},
  author = {John Doe},
  file = {johnDoe.pdf:RootA/johnDoe.pdf:pdf},
}

pybtex is also a good solution to parse bibtex file.


text:
Q: Proper touch-input handling on Android in a game I'm actually quite familiar with handling touch events in Android. I however have now hard-coded everything. I mean alot of comparing like if (e.getX()<0.1*v.getX) , for both game-objects and for the hud.
Now i'm actually looking for proper handling touch-events. I also tried storing both the x and y values onTouch, however this gets messy too, especially when I also have to test for ACTION_DOWN or ACTION_MOVE etc...
so anyone knows the best 'architecture or something for this?

A: Your game probably has a main loop on a different thread since in Android you're supposed to stay off the event thread. If this is the case, I would set up a separate InputBuffer class to receive and store incoming touch events. When I have done this, InputBuffer was the OnTouchListener for the SurfaceView.
When there is an incoming event, InputBuffer just makes a copy of it and returns. This keeps the event thread free and helps prevent ANRs.
Then in the main loop, game objects who need to know about user input have access to InputBuffer so they can get info about the stored event. This moves your input processing code out of the view and into the game objects where it makes more sense.
Depending on the speed of your game, you may also want to put in a block so that incoming events don't update the stored copy while the game objects are updating. Instead, the stored copy is updated after the main loop updates, and this way all game objects are working with the same event.


text:
Q: How to serialize my model to get desired output I want to serialize my model which having multiple object. I want to nest them.
this is my model
class model8():
   country = foreign key
   a_image = "ImageField"
   b_image = "ImageFiled"
   a_url = char filed
   b_url = char filed

and my desired output is
  {
 " a_images":[
   {
        "image": "",
        "url": ""
   },
   {
       "image": "",
        "url": ""
   }
],
"b_images":[
   {
      "image": "",
      "url": ""
   },
  {
      "image": "",
      "url": ""
   }
 ]
}

can any one help solve this huddle

A: You need to define serializers as below and learn about SerializerMethodField.
class imageSerializer(serializers.ModelSerializer):
    a_images = serializers.SerializerMethodField()
    b_images = serializers.SerializerMethodField()

    class Meta:
        model = model8
        fields = ('__all__')
    def get_a_images (self, instance):
        return (model8.objects.values_list('a_image ', 'a_url'))
    def get_b_images (self, instance):
        return (model8.objects.values_list('b_image ', 'b_url'))

Set values of the field "FIELDS" as you need.


text:
Q: Reshaping data to use for panel data studies, using tidyr or dplyr I have a data frame, with 28 rows and 26 columns. Each column represents a day, and each row represents a time period t. It looks like this:
dput(head(training_data,10))
structure(list(X11950.0 = c(1L, 15L, 15L, 18L, 31L, 57L, 96L,
134L, 235L, 291L), X11952.0 = c(0L, 15L, 11L, 18L, 45L, 76L,
97L, 115L, 200L, 234L), X11955.0 = c(0L, 13L, 14L, 10L, 30L,
49L, 86L, 114L, 193L, 239L), X11956.0 = c(0L, 15L, 10L, 8L, 38L,
41L, 96L, 117L, 222L, 227L), X11957.0 = c(0L, 10L, 8L, 14L, 33L,
61L, 84L, 143L, 211L, 249L), X11958.0 = c(0L, 18L, 14L, 16L,
48L, 49L, 87L, 117L, 209L, 258L), X11959.0 = c(0L, 14L, 14L,
17L, 33L, 57L, 93L, 100L, 189L, 241L), X11962.0 = c(0L, 8L, 8L,
16L, 29L, 48L, 88L, 126L, 202L, 211L), X11963.0 = c(0L, 8L, 10L,
14L, 44L, 51L, 98L, 148L, 228L, 218L), X11964.0 = c(0L, 15L,
16L, 12L, 39L, 59L, 109L, 138L, 227L, 233L), X11965.0 = c(0L,
14L, 13L, 18L, 34L, 46L, 89L, 154L, 199L, 264L), X11966.0 = c(0L,
18L, 13L, 15L, 37L, 49L, 93L, 142L, 183L, 236L), X11969.0 = c(0L,
7L, 10L, 15L, 34L, 34L, 84L, 136L, 206L, 233L), X11970.0 = c(0L,
12L, 14L, 25L, 36L, 50L, 121L, 145L, 206L, 238L), X11971.0 = c(0L,
17L, 8L, 20L, 36L, 47L, 92L, 108L, 144L, 147L), X12088.0 = c(0L,
5L, 10L, 9L, 35L, 55L, 92L, 112L, 215L, 241L), X12089.0 = c(1L,
8L, 10L, 15L, 15L, 0L, 46L, 118L, 221L, 241L), X12090.0 = c(0L,
8L, 10L, 15L, 46L, 43L, 101L, 106L, 225L, 235L), X12091.0 = c(0L,
5L, 13L, 19L, 40L, 40L, 80L, 119L, 214L, 208L), X12092.0 = c(0L,
9L, 13L, 18L, 41L, 41L, 89L, 100L, 205L, 200L), X12095.0 = c(0L,
8L, 13L, 6L, 32L, 55L, 69L, 112L, 199L, 202L), X12096.0 = c(0L,
7L, 12L, 27L, 40L, 36L, 102L, 119L, 216L, 228L), X12097.0 = c(0L,
9L, 15L, 14L, 43L, 51L, 94L, 122L, 220L, 231L), X12098.0 = c(0L,
10L, 15L, 14L, 47L, 39L, 90L, 117L, 223L, 221L), X12099.0 = c(0L,
9L, 13L, 16L, 39L, 52L, 94L, 110L, 220L, 216L), X12102.0 = c(0L,
9L, 10L, 9L, 51L, 43L, 82L, 98L, 175L, 196L)), .Names = c("X11950.0",
"X11952.0", "X11955.0", "X11956.0", "X11957.0", "X11958.0", "X11959.0",
"X11962.0", "X11963.0", "X11964.0", "X11965.0", "X11966.0", "X11969.0",
"X11970.0", "X11971.0", "X12088.0", "X12089.0", "X12090.0", "X12091.0",
"X12092.0", "X12095.0", "X12096.0", "X12097.0", "X12098.0", "X12099.0",
"X12102.0"), row.names = c(NA, 10L), class = "data.frame")

I'm trying to do regression analysis, regressing each time period in a given day on its previous 3 values. For that, I want to mung the data in a way that for each row, column 1 yt would contain the value for the time t and columns 2 to 4 would contain y(t-1) till y(t-3).
My code so far is this:
a <- stack(training_data)[,1, drop=FALSE]
panel.data <- read.csv(text="indiv, t, yt, y.t.1, y.t.2, y.t.3",
                   colClasses = c(integer(), integer(), integer(),
                                  integer(), integer(), integer()),
                   stringsAsFactors = FALSE )
for(block.id in (0: ((nrow(a)/28) -1))) {
  # day blocks
  block <- a[(28*(block.id)+1) : (28*(block.id+1)), ]
  yt <- block[4:28]
  first.time.period <- block[3:27]
  second.time.period <- block[2:26]
  third.time.period <- block[1:25]

  insert.block <- c((25*(block.id)+1) : (25*(block.id+1)))
  panel.data[insert.block, ]$yt <- yt
  panel.data[insert.block, ]$y.t.1 <- first.time.period
  panel.data[insert.block, ]$y.t.2 <- second.time.period
  panel.data[insert.block, ]$y.t.3 <- third.time.period

}

Remember again that there are 28 time periods for each day.
This works, but it was a lot of struggle to make it, and it's ugly and not really reusable. For example, now I have another data set which looks like this but has different number of rows, and I want to join this table with another table, etc. It's a headache.
My question: Is there a way to do this, preferably with Hadley's packages (tidyr, dplyr) more cleanly? I've studied these two a bit, and maybe spread() would do it? I'm a beginner in those packages and even though I've tried for a few hours now I haven't been able to solve this.

A: Here is a solution. I am assuming that you don't want to overlap days (ie. that t-1 for the first period of the second day should not be the last period of the first day). If this is not the case, just remove the group_by() statement. The slice() removes the first three periods of each day.
gather(df,day,y) %>%
  group_by(day) %>%
  mutate(t1=lag(y),
         t2=lag(t1),
         t3=lag(t2)) %>%
  slice(-c(1:3))


text:
Q: How do I read this notation and what does it mean? The notation is ⊢P{Q}R. To give context, the notation is from a paper called "An Axiomatic Basis for Computer Programming". From what I know, the symbol ⊢ is used to show that something(B) is derivable from another(A); i.e A⊢B, or B is a partition of A.

A: See Hoare logic :

A Hoare triple describes how the execution of a piece of code changes the state of the computation. A Hoare triple is of the form

$$\{ P \} C \{ Q \}$$

where $P$ and $Q$ are assertions and $C$ is a command. $P$ is named the precondition and $Q$ the postcondition: when the precondition is met, executing the command establishes the postcondition.

Ref to C.A.R. Hoare's An Axiomatic Basis for Computer Programming (1969) page 577 for the original notation: $P \{ Q \} R$.
And see footnote 1:

If $P \{ Q \} R$ can be proved in our formal system, we use the familiar logical symbol for theoremhood : $\vdash P \{ Q \} R$.

See Turnstile symbol for $\vdash$.


text:
Q: watched scope is empty after route change I have a controller I'm using for 3 different views that collects data. I'm watching 2 scopes in it.
This is an excerpt:
  // predefine place before Google Maps API GET
  $scope.place = {
    formatted_address: '',
    url: ''
  };

  // watch place in case of change (doesn't work otherwise)
  $scope.$watch('place', function () {
    $scope.poll.Poll.Location    = $scope.place.formatted_address;
    $scope.poll.Poll.UrlLocation = $scope.place.url;
  });

Everything works fine on view 1, the $scope.poll.Poll.Location and the $scope.poll.Poll.Location gets filled with data of the Google Maps api.
But when I click on a button which changes my route (ui-sref="view2"), which is using the same controller, the scopes are empty.
How can I transfer the watched scopes between multiple views with the same controller?

A: If you have multiple states using the same controller, then both states get it's own instance of the controller. You have to pass the data as a param to the second state.
Like this:ui-sref="view2({poll: poll})"
Don't forget to add the param to the state definition in $stateProvider.
$stateProvider.state("homepageState", {
    url: "/home/",
    templateUrl: "templates/homePage.html",
    controller: "HomePageController",
    params: {
       poll: null //initial
    }
});

In your controller you can get the value by calling $stateParams.poll
You also could make use of angular services. A service is instantiated only once and is reusable.
If you have to wait for data from an unknown source, then you have to take a look at Promise.when()

when(value, [successCallback], [errorCallback], [progressCallback]);
Wraps an object that might be a value or a (3rd party) then-able
  promise into a $q promise. This is useful when you are dealing with an
  object that might or might not be a promise, or if the promise comes
  from a source that can't be trusted.

A: Put then on $rootScope may works
$scope.$watch('place', function () {
  $rootScope.poll.Poll.Location    = $scope.place.formatted_address;
  $rootScope.poll.Poll.UrlLocation = $scope.place.url;
});


text:
Q: How to check If the system Date is 30 days back How to check in java whether the   system Date is 30 days back
Means for example if today is May 26 then if i pass April 26 , it should tell that this is of Last Month Data
If(SystemDate-30)

A: http://joda-time.sourceforge.net/faq.html#datediff

A: Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DATE, -30);
cal.set(HOUR, 0);
cal.set(MINUTE, 0);
cal.set(SECOND, 0);
cal.set(MILLISECOND, 0);
Date dateBefore30DayFromStartDate = cal.getDate();

Now you can compare


text:
Q: Synchronizing on an array. Does it synchronize on all the elements or on the array object? If I synchronize on an array, does this mean that I'm synchronizing on all the elements in it or am I synchronizing on the array object? If the latter is true, then how can I synchronize on all the elements in an array at once so that I can make sure non will be accessed while executing a certain block?
E.g.
Lets say we have an array of bank accounts and we want to make sure no thread can access any account when a certain block of code is being executed.

A: It synchronizes on the monitor for the array itself.
Even if you could synchronize on all the elements, that wouldn't ensure that they weren't accessed - because synchronization is only advisory.
The solution here is probably encapsulation: don't allow other code to see the array itself at all. That way you can control how other code is able to access the members of the array, via your own methods (like ArrayList does, for example).
Note that even if you do all of this, it won't stop other code from fetching the array element before your exclusive code starts running, and then using that reference while your exclusive code is running (e.g. mutating the object it refers to). You haven't really given us much information about what you're trying to do, but you may need to take a different approach.

A: Java 9 handles memory differently and has more options for synchronizing on array elements. For a detailed technical explanation see "Using JDK 9 Memory Order Modes" http://gee.cs.oswego.edu/dl/html/j9mm.html
If this link goes away in the future, google "java varhandle" to learn more.