text:
Q: How to display all the data from table? 1.This is my code for my HTML table where I'm unable to display the data from it using my javascript code below.

      Type
      SimiScore
      Rank
      Introversion/Extraversion
      Intuitive/Observant
      Thinking/Feeling
      Judging/Perceiving

    {% for doc in docs %}

      {{doc["type"]}}
      {{doc["Simiscore"]}}
      {{doc["Rank"]}}
      {{doc["Introversion/Extraversion"]}}
      {{doc["Intuitive/Observant"]}}
      {{doc["Thinking/Feeling"]}}
      {{doc["Judging/Perceiving"]}}

    {% endfor %}

<input type="button" id="bt" value="Show Table Data" onclick="showTableData()" />

2.This is my javascript code to display the data, but I'm unable to display it

A: {
   $(document).ready(function()
 {
$.ajax({
    url: "getjson.php",
    type: "POST",
    dataType:"json",
    success: function (response)
    {
      var trHTML = '';
      $.each(response, function (key,value) {
         trHTML +=
            '
' + value.id +
            '	' + value.konu +
            '	' + value.aciklama +
            '	' + value.giris_tarih +
            '	' + value.degistirilme_tarih +
            '	' + value.ad_soyad +
            '	' + value.email +
            '
';
      });

        $('#records_table').append(trHTML);
    }
});

});
 }

this is an example you can use


text:
Q: How to make a Java function that checks if data from a POST request is already in the database? So I'm making an API using Java Spring-boot and JBDC with PostgreSQL as the database and Postman for testing. All the basic CRUD function is already implemented, but I'm trying to validates if a value in the POST request is already in the database or not so there are no duplicate data.
Here's the model:
package com.akuntansi.akuntansi.model;

import java.sql.Timestamp;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

public class mAkuntansi {
    private Integer id_md_jurnal_Integer;
    private Integer id_dd_wilayah_kerja;
    private String kode_file;
    private String file_id;
    private String tanggal;
    private String debet_kredit;
    private String kode_coa;
    private long nominal;
    private Integer flag;
    private Integer id_akmt_subledger;
    private Integer id_referensi;
    private String no_bukti;
    private Timestamp created_date;

    public mAkuntansi(){}

    public mAkuntansi(Integer id_md_jurnal_Integer, Integer id_dd_wilayah_kerja, String kode_file, String file_id, String tanggal, String debet_kredit, String kode_coa,
    long nominal, Integer flag, Integer id_akmt_subledger, Integer id_referensi, String no_bukti, Timestamp created_date){
        this.id_md_jurnal_Integer = id_md_jurnal_Integer;
        this.id_dd_wilayah_kerja = id_dd_wilayah_kerja;
        this.kode_file = kode_file;
        this.file_id = file_id;
        this.tanggal = tanggal;
        this.debet_kredit = debet_kredit;
        this.kode_coa = kode_coa;
        this.nominal = nominal;
        this.flag = flag;
        this.id_akmt_subledger = id_akmt_subledger;
        this.id_referensi = id_referensi;
        this.no_bukti = no_bukti;
        this.created_date = created_date;
    }

    public mAkuntansi(Integer id_dd_wilayah_kerja, String kode_file, String file_id, String tanggal, String debet_kredit, String kode_coa,
    long nominal, Integer flag, Integer id_akmt_subledger, Integer id_referensi, String no_bukti, Timestamp created_date){
        this.id_dd_wilayah_kerja = id_dd_wilayah_kerja;
        this.kode_file = kode_file;
        this.file_id = file_id;
        this.tanggal = tanggal;
        this.debet_kredit = debet_kredit;
        this.kode_coa = kode_coa;
        this.nominal = nominal;
        this.flag = flag;
        this.id_akmt_subledger = id_akmt_subledger;
        this.id_referensi = id_referensi;
        this.no_bukti = no_bukti;
        this.created_date = created_date;
    }
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getid_md_jurnal_int(){
        return id_md_jurnal_Integer;
    }

    public void setid_md_jurnal_int(Integer id_md_jurnal_Integer){
        this.id_md_jurnal_Integer = id_md_jurnal_Integer;
    }

    public Integer getid_dd_wilayah_kerja(){
        return id_dd_wilayah_kerja;
    }

    public void setid_dd_wilayah_kerja(Integer id_dd_wilayah_kerja){
        this.id_dd_wilayah_kerja = id_dd_wilayah_kerja;
    }

    public String getkode_file(){
        return kode_file;
    }

    public void setkode_file(String kode_file){
        this.kode_file = kode_file;
    }

    public String getfile_id(){
        return file_id;
    }

    public void setfile_id(String file_id){
        this.file_id = file_id;
    }

    public String gettanggal(){
        return tanggal;
    }

    public void settanggal(String tanggal){
        this.tanggal = tanggal;
    }

    public String getdebet_kredit(){
        return debet_kredit;
    }

    public void setdebet_kredit(String debet_kredit){
        this.debet_kredit = debet_kredit;
    }

    public String getkode_coa(){
        return kode_coa;
    }

    public void setkode_coa(String kode_coa){
        this.kode_coa = kode_coa;
    }

    public long getnominal(){
        return nominal;
    }

    public void setnominal(long nominal){
        this.nominal = nominal;
    }

    public Integer getflag(){
        return flag;
    }

    public void setflag(Integer flag){
        this.flag = flag;
    }

    public Integer getid_akmt_subledger(){
        return id_akmt_subledger;
    }

    public void setid_akmt_subledger(Integer id_akmt_subledger){
        this.id_akmt_subledger = id_akmt_subledger;
    }

    public Integer getid_referensi(){
        return id_referensi;
    }

    public void setid_referensi(Integer id_refrensi){
        this.id_referensi = id_refrensi;
    }

    public String getno_bukti(){
        return no_bukti;
    }

    public void setno_bukti(String no_bukti){
        this.no_bukti = no_bukti;
    }

    public Timestamp getcreated_date(){
        return created_date;
    }

    public void setcreated_date(Timestamp created_date){
        this.created_date = created_date;
    }

}

Let say for example I want to validates the kode_coa. There's a POST request with kode_coa of K1 but in the database, a data with value K1 already exist, how do you prevent a duplicate data from getting inserted into the database?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Acceleration in ios simulator I have an app that processes location updates when the user is moving in a car.I need to get the acceleration as well as braking events from the app.
I use the "freeway drive option" in the simulator to simulate motion of a car.
If I switch from "freeway drive" to "city run" I am able to get braking events, but vice versa I cant get acceleration.
Does anyone know how I can get acceleration events ?


text:
Q: How to repair a hard drive file system used for Samsung smart tv I'm having a problem with my hard drive I use for my Samsung smart tv. Apparently it is a known problem, as the Samsung D-model TVs sometimes ruins the hard drivers file system, so I found a guide online on how to repair it.
I had to get ubuntu and plug in the hard drive. I should have received an error message saying something like "Cannot mount the driver I/O error", but I didn't.
After this I should write the command "sudo xfs_repair -L /dev/sdc" (I also tried with sdc1) in Terminal. I did that, and got the message "Phase 1 find and verify superblock..bad primary superblock - bad magic number !!! attempting to find secondary superblock...sorry could not find valid secondary superblock. Exiting now."
I tried searching online for different things to do. I tried the following commands:
sudo fdisk -l
--> giving me:
Disk /dev/sdc: 500.1 GB, 500107835392 bytes
255 heads, 63 sectors/track, 60801 cylinders, total 976773116 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xd5f0e851

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1            2048   976769023   488383488    7  HPFS/NTFS/exFAT
ubuntu@ubuntu:~$ sudo mount /dev/sdc

I also tried:
sudo badblocks /dev/sdc

--> it gave me:
1024
1025
1026
1027

And I tried:
sudo fsck /dev/sdc

--> it gave me:
fsck from util-linux 2.20.1
e2fsck 1.42 (29-Nov-2011)
fsck.ext2: Superblock invalid, trying backup blocks...
fsck.ext2: Bad magic number in super-block while trying to open /dev/sdc

The superblock could not be read or does not describe a correct ext2
filesystem.  If the device is valid and it really contains an ext2
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
    e2fsck -b 8193 <device>

ubuntu@ubuntu:~$ sudo e2fsck -b 8193 /dev/sdc
e2fsck 1.42 (29-Nov-2011)
e2fsck: Bad magic number in super-block while trying to open /dev/sdc

The superblock could not be read or does not describe a correct ext2
filesystem.  If the device is valid and it really contains an ext2
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
    e2fsck -b 8193 <device>

I'm a very inexperienced linux user and I have no idea what is wrong or how to fix it. I do NOT want to format my hard drive as I have important files on there.
I would really appreciate some help.

A: The fdisk output says that it is an NTFS file system:
/dev/sdc1            2048   976769023   488383488    7  HPFS/NTFS/exFAT

So you don't need linux to correct it, you need windows and run chkdsk /f on the drive. xfs_repair is for the XFS file system and fsck is for most of the linux native file systems. Linux doesn't have proper tools to fix an NTFS file system, since NTFS is not linux native, but Microsoft's proprietary file system.

A: If you want to fix the NTFS partition under Linux, please have a look at the manpage of ntfsfix and decide for yourself.
I've never used it and can't give any recommendation.


text:
Q: MVC3 HTML button I am using MVC3 and I dont want to use Microsoft.Web.Mvc
How do I convert this code  to be used in MVC3 ? The view engine is .aspx
Html.Button ("abc", "Button abc", HtmlButtonType.Button)

and also this script
$("button[name=abc]").attr("disabled",true);

Any feedback is appreciated ?

A: HTML Markup for your button:
<input type="button" name="abc" disabled="true" value="Button abc" />

ASP.NET MVC 3 does not have a built-in HtmlHelper extension method for a button.  You could always easily create on:
public static class YourMvcButtonExtensionMethod
{
    public static MvcHtmlString Button(this HtmlHelper helper, string text,
                                     IDictionary<string, object> htmlAttributes)
    {
        // generate the markup for the input/button
    }
}

So you really have two options:

*

*use raw HTML markup in your View

*create your custom extension method (see above)

A: "I am using MVC3 and I dont want to use Microsoft.Web.Mvc"
That just sounds confusing...
Anyway you can use the button element instead.
<button disabled='true'>Button abc</button>


text:
Q: converting a string of tags into a dict in python I have a string, which isn't really XML, but appears just to be a list of tags. Nothing is hierarchical. I just want to get out a dict of key/value pairs.
The string just has tags that start with tag name and end with value. It looks like this:
str = '<tag name="image_num_t" value="1"/><tag name="image_pixel_depth" type='A' value="6"/>'

I'd like to create a dict like this:
d = {'image_num' : 1, 'image_pixel_depth':6}

(No need for type or anything)
This looks like a pretty decent pain to code up from scratch, and also feels unnecessary. I looked at a variety of packages (like lxlm, etc) thinking maybe I could transform it into proper XML then parse it like a mature adult, but nothing works.
Can anyone advise me on the best way to convert a string of tags into a dict using python 2.7? Thanks.

A: If the only thing missing from your string to be qualified as XML is a root element, as shown in question, then the fix should be as easy as adding a temporary root element. From this point you can use any XML parser to extract the information and store it in dictionary :
from xml.etree import ElementTree as ET

str = '''<tag name="image_num_t" value="1"/><tag name="image_pixel_depth" type='A' value="6"/>'''
source = '<root>' + str + '</root>'

root = ET.fromstring(source)
d = {t.attrib['name']: int(t.attrib['value']) for t in root.findall('tag')}

test: https://eval.in/928392


text:
Q: Where should be the location for coturn or ice setting for sipjs 0.11.0? I am moving from sipjs 0.7x to sipjs 0.11
After reading the Git issue https://github.com/onsip/SIP.js/pull/426#issuecomment-312065734
and
https://sipjs.com/api/0.8.0/sessionDescriptionHandler/
I have found that the ice options (coturn, turn, stun) is not in User Agent anymore,
but the problem is that I am not quite understand where should I use the
setDescription(sessionDescription, options, modifiers)
I have seen that the ice is set in options, using
options.peerConnectionOptions.rtcConfiguration.iceServers
below is what I haved tried
session.on('trackAdded', function () {
            // We need to check the peer connection to determine which track was added
            var modifierArray = [
                SIP.WebRTC.Modifiers.stripTcpCandidates,
                SIP.WebRTC.Modifiers.stripG722,
                SIP.WebRTC.Modifiers.stripTelephoneEvent
                ];
            var options = {
            peerConnectionOptions:{
                rtcConfiguration:{
                    iceServers : {
                                [{urls: 'turn:35.227.67.199:3478',
                                username: 'leon',
                                credential: 'leon_pass'}]
                    }
                }
            }
        }
            session.setDescription('trackAdded', options,modifierArray);

            var pc = session.sessionDescriptionHandler.peerConnection;

            // Gets remote tracks
            var remoteStream = new MediaStream();
            pc.getReceivers().forEach(function (receiver) {
                remoteStream.addTrack(receiver.track);
            });
            remoteAudio.srcObject = remoteStream;
            remoteAudio.play();

            // Gets local tracks
            // var localStream = new MediaStream();
            // pc.getSenders().forEach(function(sender) {
            //     localStream.addTrack(sender.track);
            // });
            // localVideo.srcObject = localStream;
            // localVideo.play();
        });
    }

I have tried this and it seems that the traffic is not going to the coturn server.
I have used Trickle Ice "https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/" to test and it is fine, but I have found there is not traffic going through the coturn server. You could also use this one and I do not mind.
There is even no demo on the official website to show how could we use the setDescription(sessionDescription, options, modifiers). In this case can I please ask some recommendations?

A: Configure STUN/TURN servers in the parameters passed to new UserAgent.
Here is sample, it seems to be working on v0.17.1:
const userAgentOptions = {
  ...
  sessionDescriptionHandlerFactoryOptions: {
    peerConnectionConfiguration: {
      iceServers: [{
        urls: "stun:stun.l.google.com:19302"
      }, {
        urls: "turn:TURN_SERVER_HOST:PORT",
        username: "USERNAME",
        credential: "PASSWORD"
      }]
    },
  },
  ...
};
const userAgent = new SIP.UserAgent(userAgentOptions);

When using SimpleUser - pass it inside SimpleUserOptions:
const simpleUser = new Web.SimpleUser(url, { userAgentOptions })


text:
Q: Why do I get a "cannot assign" error when do assertion? req is a interface{} and PostAccountRequest,CreateAccountRequest is struct, when I do this, I get cannot assign *account.PostAccountRequest to v (type *account.CreateAccountRequest) in multiple assignment
v, ok := req.(*account.CreateAccountRequest)
if ok {
    if v, ok = req.(*account.PostAccountRequest); ok {
        panic(ok)
    }
}

A: The snippet of code defines one variable v with type *account.CreateAccountRequest.   The second type assertion attempts to assign a *account.PostAccountRequest to the variable v.  This is an error.
The code will compile if you create a second variable v:
v, ok := req.(*account.CreateAccountRequest)
if ok {
    if v, ok := req.(*account.PostAccountRequest); ok { // note ":"
      panic(ok)
  }
}

... but does not make sense because v can only be one of the struct types.
Perhaps you are looking for something like this:
var name, token string
switch v := v.(type) {
case *account.CreateAccountRequest:
 // v is a *account.CreateAccountRequest in this branch of the switch
 name = v.Name
 token = v.Token
case *account.PostAccountRequest:
 // v is a *account.PostAccountRequest in this branch of the switch
 name = v.Name
 token = v.Token
default:
 // panic?
}


text:
Q: What is the recommended way to use ActiveRecord in CodeIgniter models? I believe this has been asked before with different words, I already did a search on similar questions and found:

*

*CodeIgniter instance of model class

*Usind models in CodeIgniter
However, being mainly a C# developer I sometimes find difficult to separate previous knowledge of the language with other tools, such as PHP. My philosophy is to follow the de facto standards of the language itself.
That being said, I have used several ORM tools such as Db4objects, DevExpress XPO, EntityFramework and many more. What I find quite different from the .Net approach to the ActiveRecord implementation in CodeIgniter is how Models are used, for example, in CI you´d normally have a model instance loaded and use it almost like a static method to do all operations and then pass some sort of data as parameter either as an array or several parameters:
$this->load->model('User_model');
$this->User_model->save($username, $password);

Or:
$this->load->model('User_model');
$this->User_model->save(array(
  'user' => 'theuser',
  'password' => 'thepassword'
));

So you´ll end up using the same instance to do all operations, but sometimes that can be confusing, especially coming from another object oriented language, I often find myself doing this:
$user = new User_model();
$user->username = 'theusername';
$user->password = 'thepassword';
$user->save();

As seen, I invoke a method on an instance to do actual work, the save method would look like:
function save() {
  $this->db->set('username', $this->username);
  $this->db->set('username', md5($this->password));
  $this->db->insert('User');
}

Is there some recommended standard to do this kind of operations in CI? I do know there must be pros and cons but I don´t see anything about this topic on the CI Documentation.
Thanks in advance!


text:
Q: TikZ data visualization (still?) not working properly for external file? I have some troubles using external files for the data visualization library of TikZ. This is my MWE:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{datavisualization}
\begin{document}

\begin{tikzpicture}
\datavisualization [scientific axes, visualize as line]
data [read from file=foo.csv] ;

\end{tikzpicture}
\end{document}

Where foo.csv is basically just
x,y
0,0
1,1
2,2

The same problem has been described in this topic a year ago. Compilation produces the error
! Package PGF Math Error: Sorry, an internal routine of the floating point     unit got an ill-formatted floating point number `'. The unreadable part was near ''..

See the PGF Math package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.7 ... scatter ] data [ read from file=foo.dat ];

One solution is to replace all commas with spaces in foo.csv and to add separator=\space to the data options. However, this ONLY works if column headlines are specifically named x and y, despite the pgf manual stating otherwise.
To sum it up: importing data in \datavisualization only works for space separated values and only if the columns are named x and y for me.
Is this a bug? Am I missing something?


text:
Q: PHP Warning: PHP Startup: Unable to load dynamic library xxx I'm trying to write a custom extension to PHP but for some reason, I always get this error
error

PHP Warning:  PHP Startup: Unable to load dynamic library 'deneme' (tried: /usr/lib/php/20190902/deneme (/usr/lib/php/20190902/deneme: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/deneme.so (libc.musl-x86_64.so.1: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP 7.4.9 (cli) (built: Oct 26 2020 15:17:14) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies
    with Xdebug v2.9.6, Copyright (c) 2002-2020, by Derick Rethans

php.ini
extension=deneme

deneme.so file location path
/usr/lib/php/20190902/deneme.so


text:
Q: Creating NSArray of repeated numbers I want to initialize NSArray with given numbers of zeros. I need it to create an array of counters and in the end of the function return an index of the counter with highest value.
So the question is how to initialize NSArray of zeros of given length? Is there a good way to do it in 1-2 lines? Maybe there is a better way to count objects? How would you do it?
Thanks!
UPD: Here is the code of my existing function. It returns the maximum number of cards, which have the same rank.
+ (int)ranksMatched:(NSArray *)cards
{
    NSMutableArray *ranksCounter = [[NSMutableArray alloc] initWithCapacity:[PlayingCard maxRank]];
    for (int i = 0; i < [PlayingCard maxRank]; ++i) {
        [ranksCounter addObject:[NSNumber numberWithInt:0]];
    }
    int maxIndex = 0;
    int maxCount = 0;
    for (PlayingCard *card in cards) {
        int currentCount = [ranksCounter[card.rank] intValue] + 1;
        if (maxCount < currentCount) {
            maxCount = currentCount;
            maxIndex = card.rank;
        }
    }
    return maxCount;
}

A: I guess you want the group the cards by rank and return the rank of the largest group:
+ (int)ranksMatched:(NSArray *)cards
{
    NSCountedSet *ranks = [NSCountedSet setWithArray:[cards valueForKeyPath:@"rank"]];

    NSNumber *maxRank = nil;
    NSUInteger maxCount = 0;

    for (NSNumber *rank in ranks) {
        NSUInteger rankCount = [ranks countForObject:rank];
        if (rankCount > maxCount) {
            maxRank = rank;
            maxCount = rankCount;
        }
    }

    return [maxRank intValue];
}

assuming you have
@interface PlayingCard : NSObject

@property (nonatomic, assign) int rank;

…

@end

And cardsis an array of PlayingCard.


text:
Q: Flex div has height of 228px even though there is no content inside of it and I haven't specified size anywhere For some reason, a div whose parent has a display: flex property is having a height of 228px even though there's no content inside of it.
Image example

    .sights-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        flex: 1;
        background-color: #ffffff;
    }
    .sights-list div {
        flex-basis: 48%;
        flex-shrink: 0;
        display: flex;
        padding: 10px;
    }

A: you can use

 {
  min-height: 100%;

}


text:
Q: Tensorflow models not loading with gunicorn I am trying to move the machine learning workloads to production, rightnow the workloads are running in Flask but it's not made for production and I am facing some performance issues as well.
I tried to use gunicorn with Flask but I am facing some issues with loading tensorflow models and gunicorn server starts before loading the models. Following is the code.
wsgi.py
from ml_service import service_api as application
import time
if __name__ == "__main__":
    # initialize the session
    ml_service.init()
    # load model
    ml_service.load_models()
    application.run()

ml_service.py
def init(num_gpu=1, num_cpu=1, num_cores=4):

    global session

    init_op = tf.global_variables_initializer()

    configuration = tf.ConfigProto(
        intra_op_parallelism_threads=num_cores,
        inter_op_parallelism_threads=num_cores, allow_soft_placement=True,
        # gpu_options=gpu_options,
        device_count={'CPU': num_cpu, 'GPU': num_gpu}
    )
    session = tf.Session(config=configuration)
    session.run(init_op)

def load_models():
    try:
        #Do Stuff
    except:
        #Do Stuff

@service_api.route("/serviceendpoint", methods=["POST"])
def get_prediction():
    #Do Stuff
    return

if __name__ == "__main__":
    service_api.run(host='0.0.0.0')

Command to run gunicorn:
gunicorn --bind 0.0.0.0:5000 wsgi

Output:
[2019-12-17 14:16:18 +0000] [7] [INFO] Starting gunicorn 20.0.4
[2019-12-17 14:16:18 +0000] [7] [INFO] Listening at: http://0.0.0.0:5000 (7)
[2019-12-17 14:16:18 +0000] [7] [INFO] Using worker: sync
[2019-12-17 14:16:18 +0000] [10] [INFO] Booting worker with pid: 10
Using TensorFlow backend.

Expected Output:
Using TensorFlow backend.
2019-12-17 13:17:00.497866: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-12-17 13:17:02.556270: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:964] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-12-17 13:17:02.556854: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1432] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:04.0
totalMemory: 11.17GiB freeMemory: 11.10GiB
2019-12-17 13:17:02.556902: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2019-12-17 13:17:02.970751: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-12-17 13:17:02.970851: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988]      0
2019-12-17 13:17:02.970879: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0:   N
2019-12-17 13:17:02.971248: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10759 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)
2019-12-17 13:17:03.197540: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2019-12-17 13:17:03.197611: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-12-17 13:17:03.197626: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988]      0
2019-12-17 13:17:03.197636: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0:   N
2019-12-17 13:17:03.197822: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10759 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7)
../posenet/converter/config.py:9: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
  cfg = yaml.load(cfg_f)
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)


text:
Q: CakePHP email smtp not sending I'm having a problem with the CakePHP smtp not sending any email and I'm using the Google smtp service.
The Cake Version that I'm using is CakePHP v2.4.1
After the user registers, it calls a CronJob and it runs an email function from within the ApiController.
Here is the function that it is calling:
    public function processEmailQueue(){

      ScriptLockComponent::lock(__FUNCTION__);
      $emails = $this->Email->find('all', array(
        'conditions' => array(
            'Email.status' => Email::STATUS_NOT_SEND,
            'Email.instance_id' => ''
        ),
        'recursive' => 1,
        'order' => array('Email.priority DESC'),
        'limit' => self::BATCH_LIMIT
            )
    );
    // creating new email object
    $cakeEmail = new CakeEmail();

   $date = new DateTime();
    foreach ($emails as $emailData) {
    $cakeEmail->reset();
        $priorityValue = intval($emailData["Email"]["priority"]) + 1;
        //Getting email template from database
        $emailManagement = $this->EmailTemplate->getEmailTemplate($emailData["Email"]["email_template_id"], json_decode($emailData["Email"]["content"], TRUE));
        // setting email configurations, and sending email

        // setting unsubscribe url in the mail footer
        $templateId = $emailData["Email"]["email_template_id"];
        if (in_array($templateId, $this->emailTemplateIds)) {
            $autoLoginToken = $this->Otp->createOTP(array(
                'email' => $emailData["Email"]["to_email"]
            ));
            $email = base64_encode($emailData["Email"]["to_email"]);
            $unsubscribeUrl = Router::Url('/', TRUE) . 'unsubscribe?setting=' .$templateId. '&auto_login_token=' . $autoLoginToken .'&email=' . $email ;
        } else {
            $unsubscribeUrl = '';
        }
        try {
            $cakeEmail->config('gmail')
                    //->template('default')
                    ->viewVars(array('unsubscribe' => $unsubscribeUrl ))
                    ->emailFormat('html')
                    ->to($emailData["Email"]["to_email"])
                    ->subject($emailManagement['EmailTemplate']['template_subject'])
                    ->setHeaders(array('List-Unsubscribe' => $unsubscribeUrl))
                    ->send($emailManagement['EmailTemplate']['template_body']);
            $this->Email->set(array(
                'id' => $emailData["Email"]["id"],
                'sent_date' => $date->format('Y-m-d h:i:s'),
                'status' => Email::STATUS_SEND
            ));
            $this->Email->save();
            } catch (Exception $e) {
            $this->Email->set(array(
                'id' => $emailData["Email"]["id"],
                'priority' => $priorityValue,
                'status' => Email::STATUS_NOT_SEND
            ));
            $this->Email->save();
        }
    }

The problem is that no emails is being sent out why would that be the case.
Thank you,
Kevin

A:             $this->Email->set(array(
                'id' => $emailData["Email"]["id"],
                'sent_date' => $date->format('Y-m-d h:i:s'),
                'status' => Email::STATUS_SEND
            ));
             ///////HERE //////////
            $this->Email->send();
            ////////////////////
            } catch (Exception $e) {
            $this->Email->set(array(
                'id' => $emailData["Email"]["id"],
                'priority' => $priorityValue,
                'status' => Email::STATUS_NOT_SEND
            ));
            $this->Email->save();


text:
Q: back button still working after disabling it in cordova app I have implemented code so as to disable the android device back button but it isn't working. When i run my app and tap the back button, it simply exits. I have included cordova.js in my index.html file. What am i doing wrong?
here is my code:
JS
document.addEventListener('deviceready', function () {
      document.addEventListener("backbutton", onBackKeyDown, false);
          function onBackKeyDown(e) {
               e.preventDefault();
           }

}, false);

index.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="mobile-web-app-capable" content="yes">

 <link href="css/style.css" rel="stylesheet">

app.js
// We use an "Immediate Function" to initialize the application to avoid leaving anything behind in the global scope
(function () {
    Handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) {

    var operators, result;

    if (arguments.length < 3) {
        //throw new Error("Handlerbars Helper 'compare' a besoin de 2 parametres");
    }

    if (options === undefined) {
        options = rvalue;
        rvalue = operator;
        operator = "===";
    }

    operators = {
        '==': function (l, r) { return l == r; },
        '===': function (l, r) { return l === r; },
        '!=': function (l, r) { return l != r; },
        '!==': function (l, r) { return l !== r; },
        '<': function (l, r) { return l < r; },
        '>': function (l, r) { return l > r; },
        '<=': function (l, r) { return l <= r; },
        '>=': function (l, r) { return l >= r; },
        'typeof': function (l, r) { return typeof l == r; }
    };

    if (!operators[operator]) {
        //throw new Error("Handlerbars Helper 'compare' ne connait pas l'operateur " + operator);
    }

    result = operators[operator](lvalue, rvalue);

    if (result) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

 LangueView.prototype.template = Handlebars.compile($("#langue-tpl").html());
  $('body').html(new LangueView().render().$el);

            /* ---------------------------------- Local Variables ---------------------------------- */

      //  var pictureSource; // picture source
      //var destinationType; // sets the format of returned value
      // Wait for device API libraries to load
      //
  /*var service = new EmployeeService();
     service.initialize().done(function () {
     $('body').html(new HomeView(service).render().$el);
    });*/

    /* --------------------------------- Event Registration -------------------------------- */
    //$('.search-key').on('keyup', findByName);
    /*$('.help-btn').on('click', function() {
        alertjqry("Employee Directory v3.4");
    });*/

 /*
  window.addEventListener('orientationchange', function () {   //window.orientation=='-90' || window.orientation=='90'
    if(window.innerHeight < window.innerWidth){
    if(window.orientation=='-90' || window.orientation=='90')
       alertjqry("Attention: Si vous avez un iphone 6, veuillez retourner en mode portrait sinon certaines fonctions de l'application pourront mal fonctionner avec cette orientation de votre appareil!");
    }else{
          $("#mydialog").dialog('close');
    }
   }, false);
 */

    document.addEventListener('deviceready', function () {
    FastClick.attach(document.body);
    //console.log(navigator.contacts);
    // console.log(navigator.camera);
  //console.log(FileTransfer);
  //window.open= cordova.InAppBrowser.open;

  //pictureSource = navigator.camera.PictureSourceType;
  //destinationType = navigator.camera.DestinationType;
/*
    if (navigator.notification) { // Override default HTML alert with native dialog
      window.alert = function (message) {
          navigator.notification.alert(
              message,    // message
              null,       // callback
              "Beezlink", // title
              'OK'        // buttonName
          );
      };
    }

*/
   document.addEventListener("backbutton", onBackKeyDown, false);

   }, false);

  function onBackKeyDown(e) {
     e.preventDefault();
   }

   //console.log(FileTransfer);

    /* ---------------------------------- Local Functions ---------------------------------- */

}());

A:
try adding e.stopPropagation() or e.stopImmediatePropagation()
  instead of   e.preventDefault();

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        document.addEventListener("backbutton", function (e) {
            e.preventDefault(); OR e.stopPropagation();
        }, false );
}

Common mistake is that development is performed on desktop and cordova
  script is excluded. One then forgets to include the cordova script for
  the mobile version.

A: It's possible u need prevent other event of window like popstate.
Try this:
window.addEventListener("popstate", function(e) {
   //try e.preventDefault() or e.stopImmediatePropagation()
   e.stopImmediatePropagation()
   e.preventDefault();
}, false);

A: I skipped onDeviceReady, so I just have:

  document.addEventListener("backbutton", onBackKeyDown, false);
  function onBackKeyDown(e) {
    e.preventDefault();
  }

And that worked for me


text:
Q: Is there a way to define type with template that takes optional specific enum and infinite types? I have enum with some values and struct that converts it to a type.
enum class Types : uint8_t {
    ...
};

template<Types type>
struct enum_ {
    ...
}

I also have main template class Action, which is a lambda-like struct with overloaded operator(), depending on passed types
template<typename...>
struct Action;

template<typename T>
struct Action<T> { ... };

template<typename T, typename R>
struct Action<T, R> { ... };

The problem is that some of template parameters can be enums (e.g T = enum_<Types::type>)
Is it possible to do something like that:
template<typename... Args>
using ActionType = Action<Args...>;

template<Types type, typename... Args>
using ActionType = Action<enum_<type>, Args...>;

so in this case T is an optional enum type. I now I can use like this ActionType<enum_<Types::type>, ...>, but I am interested if this problem has a workaround.


text:
Q: Can nginx be used as a reverse proxy for a backend websocket server? We're working on a Ruby on Rails app that needs to take advantage of html5 websockets. At the moment, we have two separate "servers" so to speak: our main app running on nginx+passenger, and a separate server using Pratik Naik's Cramp framework (which is running on Thin) to handle the websocket connections.
Ideally, when it comes time for deployment, we'd have the rails app running on nginx+passenger, and the websocket server would be proxied behind nginx, so we wouldn't need to have the websocket server running on a different port.
Problem is, in this setup it seems that nginx is closing the connections to Thin too early. The connection is successfully established to the Thin server, then immediately closed with a 200 response code. Our guess is that nginx doesn't realize that the client is trying to establish a long-running connection for websocket traffic.
Admittedly, I'm not all that savvy with nginx config, so, is it even possible to configure nginx to act as a reverse proxy for a websocket server? Or do I have to wait for nginx to offer support for the new websocket handshake stuff? Assuming that having both the app server and the websocket server listening on port 80 is a requirement, might that mean I have to have Thin running on a separate server without nginx in front for now?
Thanks in advance for any advice or suggestions. :)
-John

A: Out of the box (i.e. official sources) Nginx can establish only HTTP 1.0 connections to an upstream (=backend), which means no keepalive is possibe: Nginx will select an upstream server, open connection to it, proxy, cache (if you want) and close the connection. That's it.
This is the fundamental reason frameworks requiring persistent connections to the backend would not work through Nginx (no HTTP/1.1 = no keepalive and no websockets I guess). Despite having this disadvantage there is an evident benefit: Nginx can choose out of several upstreams (load balance) and failover to alive one in case some of them failed.
Edit: Nginx supports HTTP 1.1 to backends & keepalive since version 1.1.4. "fastcgi" and "proxy" upstreams are supported. Here it is the docs

A: For anyone that wondering about the same problem, nginx now officially supports HTTP 1.1 upstream. See nginx documentation for "keepalive" and "proxy_http_version 1.1".

A: How about Nginx with the new HTTP Push module: http://pushmodule.slact.net/. It takes care of the connection juggling (so to speak) that one might have to worry about with a reverse proxy.  It is certainly a viable alternative to Websockets which are not fully in the mix yet.  I know developer of the HTTP Push module is still working on a fully stable version, but it is in active development.  There are versions of it being used in production codebases.  To quote the author, "A useful tool with a boring name."

A: You can't use nginx for this currently[it's not true anymore], but I would suggest looking at HAProxy. I have used it for exactly this purpose.
The trick is to set long timeouts so that the socket connections are not closed. Something like:
timeout client  86400000 # In the frontend
timeout server  86400000 # In the backend

If you want to serve say a rails and cramp application on the same port you can use ACL rules to detect a websocket connection and use a different backend. So your haproxy frontend config would look something like
frontend all 0.0.0.0:80
  timeout client    86400000
  default_backend   rails_backend
  acl websocket hdr(Upgrade)    -i WebSocket
  use_backend   cramp_backend   if websocket

For completeness the backend would look like
backend cramp_backend
  timeout server  86400000
  server cramp1 localhost:8090 maxconn 200 check

A: I use nginx to reverse proxy to a comet style server with long polling connections and it works great. Make sure you configure proxy_send_timeout and proxy_read_timeout to appropriate values. Also make sure your back-end server that nginx is proxying to supports http 1.0 because I don't think nginx's proxy module does http 1.1 yet.
Just to clear up some confusion in a few of the answers: Keepalive allows a client to reuse a connection to send another HTTP request. It does not have anything to do with long polling or holding connections open until an event occurs which is what the original question was asking about. So it doesn't matter than nginx's proxy module only supports HTTP 1.0 which does not have keepalive.

A: How about use my nginx_tcp_proxy_module module?
This module is designed for general TCP proxy with Nginx. I think it's also suitable for websocket.  And I just add tcp_ssl_module in the development branch.

A: nginx (>= 1.3.13) now supports reverse proxying websockets.
# the upstream server doesn't need a prefix!
# no need for wss:// or http:// because nginx will upgrade to http1.1 in the config below
upstream app_server {
    server localhost:3000;
}

server {
    # ...

    location / {
        proxy_pass http://app_server;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_redirect off;
    }
}


text:
Q: How do 'assimilation effects' work, in Endless Legend? There's very little specific data about this in the game; for instance,

… does that 5% bonus apply to every unit you ever build? Or just Geldirus units they gift you / you build? What about the 'per village' part; is that per Geldirus village anywhere in the world (i.e. if I pacify Geldirus in several regions, can I get that bonus up to like 30%? Or is it forever locked to the 5/10% you can get from the one or two villages in the region you assimilate?)
Similar questions about city-bonuses from other minor factions.
(Also, how does this apply to Cultists? Do we get these bonuses from Converting, or only from Assimilating?)
(P.S.: I ask, because if it doesn't apply to multiple units, I'm not sure I see the point in assimilating any minor faction that you don't want the unit from.)

A: The bonus is multiplied by the number of pacified villages within your empire. This can easily be seen by pacifying 1 of 2 villages in a region you control and assimilating them. If you check the appropriate bonus immediately before and after pacifying the second you'll see it go up. This can make it worthwhile to assimilate a minor faction that is present in multiple regions to get a 3+ multiplier on your benefit.
The bonus applies to every unit you own, it is not applied when the unit is built. Unless of course it's a City or Army bonus.
I don't know the specifics of Cultist Assimilation


text:
Q: Add text to different columns I'm learning HTML and CSS, while doing so I'm creating a web page which replicates a already existing page that I'm using as reference.
The page that I use as reference has a nice header that contains different text in 3 columns.
I am trying to do something similar to that, however it seems im only able to add text to the first column and not the 2nd or 3rd one.
I'm sure this is possible I'm just not sure how.

A: Maybe...

text 1

text 2

text 3

header {
 display: flex;
 flex-flow: row nowrap;
}

div {
 flex: 0 1 33,3%;
}


text:
Q: Write a wrapper to expose existing REST APIs as SOAP web services? I have existing REST APIs, written using Django Rest Framework and now due to some client requirements I have to expose some of them as SOAP web services.
I want to know how to go about writing a wrapper in python so that I can expose some of my REST APIs as SOAP web services. OR should I make SOAP web services separately and reuse code ?
I know this is an odd situation but any help would be greatly appreciated.

A: You can say, SOAP and REST are basically apples and oranges.
You basically need something, where you can consume the REST API's.
As I see, you have some options:

*

*Use a SOAP service separately running on another port (endpoint). For that I would say, use framework's like Spyne check out sample hello world

*Use the clients preferred way, either SOAP via WSGI or SOAP via HttpRPC

*Invoke the same REST API endpoints which you created via the methods in SOAP.
We had used an internal api wrapper in one of application, which is as:

def wrap_internal_api_call(requests_api_method, uri,
                           data, cookies=None, headers=None):

    return requests_api_method(uri, data=data, files=files,
               cookies=cookies, headers=headers)
How you can use this?
import requests

from django.core.urlresolvers import reverse
from django.conf import settings

from spyne.service import Service
from spyne.decorator import srpc
from spyne.model import ByteArray, DateTime, Uuid, String, Integer, Integer8, \
    ComplexModel, Array

# This method will hit the internal API which is written in DJANGO REST FRAMEWORK
def build_internal_uri(uri):
  return 'http://localhost:{0}{1}'.format(settings.INTERNAL_API_PORT, uri)

class RequestHeader(ComplexModel):
  some_field = String

class SomeService(Service):
    # Headers related doc
    # https://github.com/arskom/spyne/blob/68b9d5feb71b169f07180aaecfbe843d8ba500bf/doc/source/manual/06_metadata.rst#protocol-headers
    __in_header__ = RequestHeader

  @srpc(String, _returns=String)
  def echo_string(s):
    headers = ctx.in_header.some_field

    # Reverse url from the urls.py file
    local_order_fetch_url = build_internal_uri(reverse('website:order_details')) + '?order_id=' + order_id

    response = wrap_internal_api_call(requests.get, local_order_fetch_url,
            { 'data': 'sample_data' }, None, headers)

    return response['data'] # Some string data

app = Application([SomeService], 'tns', in_protocol=HttpRpc(parse_cookie=True),
                out_protocol=HttpRpc())

Now there are some of examples which you can look into, being the Django configuration for making it available

A: Lets Discuss both the Approaches and their pros and cons
Seperate SOAP Service

*

*Reusing Same Code -  if you are sure the code changes will not impact the two code flow ,it is good to go.

*Extension of Features - if you are sure that new feature extension will not impact other parts it is again best to go.

*Scalablity - if new API are part of same application and you are sure that it will be scalable with more load ,it is again a good option.

*Extension - if you are sure in future adding more API will not create a mess of code, it is again good to go for.

Soap Wrapper Using Python (my favourate and suggested way to go)

*

*Seperation of Concern with this you can make sure ,what ever code you write is sperate from main logic and you can easly plug in and plug out new things.

Answer for all the above question in case of this is YES.
Your Call ,
Comments and critisicsm are most welcome


text:
Q: UTC time is wrong when local computer settings are wrong Since the update to Stack Overflow, I noticed that when I hover my username at the top, it shows a new box, and in that box at the bottom, it says UTC time [time].
The thing is that the time represented there is the time on my computer. And my computer's clock is wrong, so the "UTC" time is also wrong!
So... Should't it be using the server's time and translate it to UTC?

A: In the next build there's an offset detection on page load, meaning we compare server time to your local time when the page loads and use that offset to (very closely) display server-time in the popup, rather than strictly your local time as UTC.
If you change your time while the page is open...well that's a bit unreasonable, you're still on your own there :)


text:
Q: Array subset of another array descending order binary search. Here's my code. It always prints "false" this is the boolean method I need
public static boolean isSubsetOf(int a[], int b[]){

for (int i=0;i<b.length;i++){
    if (binarySearch(a,0 ,a.length-1, b[i])==false) return false;
}
return true;
}

and this is the binary search for descending order
private static boolean binarySearch(int[] a, int i, int j, int k) {
int mid;
if (i<=j){
    mid=(i+j)/2;
    if (a[mid]==k) return true;
    else if (a[mid]<k) binarySearch(a, i,j=mid-1, k);
    else binarySearch(a,i=mid+1,j,k);
}
return false;
}
}

A: You were ignoring the return values of the recursive binarySearch calls.
Here's a corrected version [please pardon the gratuitous style cleanup]:
private static boolean
binarySearch(int[]a, int i, int j, int k)
{
    int mid;
    boolean match;

    if (i <= j) {
        mid = (i + j) / 2;

        if (a[mid] == k)
            return true;

        if (a[mid] < k)
            match = binarySearch(a, i, j = mid - 1, k));
        else
            match = binarySearch(a, i = mid + 1, j, k);
        if (match)
            return match;
    }

    return false;
}

But, binary search can often be done [faster] without recursion:
private static boolean
binarySearch(int[]a, int i, int j, int k)
{
    int mid;

    while (i <= j) {
        mid = (i + j) / 2;

        if (a[mid] == k)
            return true;

        if (a[mid] < k)
            j = mid - 1;
        else
            i = mid + 1;
    }

    return false;
}


text:
Q: React Testing Library: Why does the order of the tests matter? Here's a link to codesanbox
Reordering the below tests would make find one after the other test to pass.
Another way to make it pass would be to make should be able to find 3 directly test to pass, for example, by making it find 2 instead of 3.
describe("Counter", () => {
  test("should be able to find 3 directly", async () => {
    render(<Counter />);

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });

  test("find one after the other", async () => {
    render(<Counter />);

    const one = await waitFor(() => screen.findByText(/1/i));
    expect(one).toBeInTheDocument();

    const two = await waitFor(() => screen.findByText(/2/i));
    expect(two).toBeInTheDocument();

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });
});

So the question is, why does the order of the tests matter? Why is the clean up not working?

A: It looks like waitFor has reach its timeout as waiting for the counter to 3 which means it is unrelated to ordering in this case I guess.
You would fix by increase the timeout to wait your counter as following:
test("should be able to find 3 directly", async () => {
  render(<Counter />);

  const three = await waitFor(() => screen.findByText(/3/i), {
    timeout: 3e3, // 3s wait would find 3
  });

  expect(three).toBeInTheDocument();
});


text:
Q: Where does autoconf/configure look for include files I'm trying to compile SDL version 1.2 and when I run configure I see a bunch of output, some of which is the configure tool searching for some c/c++ headers:
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes

Does it look for these include files in the standard order as an unmodified gcc/g++ would? What about (and more importantly to me) the following case: I'm using a toolchain for cross compilation, which contains a pre-configured g++ that only searches within the toolchain, not the standard locations on the host machine?

A:
Does it look for these include files in the standard order as an unmodified gcc/g++ would?

It uses the order built into the toolchain.  Options set by the user (e.g. CFLAGS="--sysroot=/some/dir", etc.) also affect the search for headers/libraries.

I'm using a toolchain for cross compilation, which contains a pre-configured g++ that only searches within the toolchain, not the standard locations on the host machine?

As above, it uses the order built into the cross compiler toolchain.  So without any user options set it should search only within the cross compiler toolchain for headers/libraries.


text:
Q: How to save a two dimensional char type array row-wise to a .txt file in c? I have a two dimensional char array[100][100] and I want to save it row-wise to a .txt file. By row-wise I mean first all the characters in the first row are printed, then second row and so on...
I can write the code for console output but don't know how to save it to .txt file:
for (int x=0;x<100;x++)
{
    for(int y=0;y<100;y++)
    {
        cout<<array[x][y];
    }
}

Please help me in this regards. Thank you.

A: #include<iostream>
#include<fstream>
using std::cout;

int main(){
ofstream out("file_name.txt");
for(int x=0;x<100;x++){
        for(int y=0;y<100;y++){

              out << array[x][y];
        }
        out << "\n";

}
file.close();
return 0;

}

using "\n"; rather than endl; will make your code faster since endl will flush your file stream buffer and write it to your file every row, which is 100 times. so it's better to not flush your file stream buffer until the end. in this case the close function will flush your buffer and close it automatically.

A: Try this:
#include <fstream>

int main()
{
    std::ofstream out("file_to_store_the_array.txt");
    for(int x = 0; x < 100; x++) {
        for(int y = 0; y < 100; y++) {
            out << array[x][y];
        }
    }
    out.close();
    return 0;
}

A: #include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  for (int x=0;x<100;x++)
  {
    for(int y=0;y<100;y++)
    {
      myfile<<array[x][y];
    }
    myfile<<endl;
  }
  myfile.close();
  return 0;
}

Don't know if it compiles, but roughly should show you how's done. (the << ENDL; is for emitting a CR (or CR/LF depending on system) between rows)


text:
Q: How to solve invalid parameter error using Codeigniter and Pesapal Am trying to test my payment module using codeigniter and pesapal but I keep getting this error "Problem: parameter_rejected | Advice: invalid_value_for_amount> oauth_parameters_rejected | Ksh.4%2C999".
Where Ksh. 4%2C999 is the bill ksh. 4999. I have used the right Pesapal keys so I don't know what am doing wrong.

A: Problem
Your amount has a thousand separator ... something like this Ksh.4,999 instead of passing a value that's an integer like 4999.
Either you are passing in the amount with the comma (which you can fix by removing the comma in your logic) or the number_format() method is adding the thousand separator (explanation given below in solution).
Solution
According to the PHP docs number_format() does something like this (basic case only)...
// english notation (default)
$english_format_number = number_format($number);
// 1,235

Note how it's added a , as the thousand separator. This is what is being converted(encoded) to %2C. Pesapal doesn't understand numbers with the , which is what you are passing to them. ... to stop the function from using the thousands operator do something like this ...
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

3rd parameter specifies the decimal separator (which is .) and the 4th specifies the thousand separator (which is an empty string).
But as @BabyAzerty has said, without code there's nothing much that we can work with to assist you. I'll amend the answer the more context you give to your problem but the above is pretty much what I've seen wrong with your implementation elaborated in the question and comment above.

A:         $amount1 = (integer)$data->amount;
        $amount = number_format($amount1, 2, '.', '');//format amount to 2 decimal places
        $desc = $data->phone_type;
        $type = "MERCHANT"; //default value = MERCHANT
        $reference = $data->reference;//unique order id of the transaction, generated by merchant
        $first_name = $data->name1;
        $last_name = $data->name2;
        $email = $data->email;
        $phonenumber = $data->mobile;//ONE of email or phonenumber is required

A: This error means that your account on Pesapal has a limit on the amount it can transact. By default the amount is usually set to USD 10 or the equivalent of it in local currency.
You need to contact the team at support.pesapal.com to complete your sign-up by submitting contract and documents for your business in order to have the account activate for full transactions.


text:
Q: Tutorial for searching before posting It seems in comments and answers that it is hammered home the fact that people need to search the website before posting.
If this is the case, then why is there no tutorial on searching the site?
If it is mission critical for a user to search the site, it would be good to have a better tutorial or page to help users to search the site.


text:
Q: Allow Site and Server acces from single computer? I have a local site that I use to run a web application for my business.  Only one or two computers need to be able to access the site.
I want to allow access to only those computers (not by IP) with the application acting like a typical web app when they try to access, and block everybody else.
I need to be able to access the site from my local network, as well as from an unspecified number of remote locations that I will not know the IP adress for in advance.  I also need the site to be allowed to access several remote sites for REST/AJAX calls.
Is there a simple (relatively) way to do this?

A: Put it behind a firewall and allow VPN access to it. Then, just configure those computers to connect to it via VPN when they need to.


text:
Q: How to add image to a Freemarker template with JavaMail Now before this question gets marked as a duplicate,
Add image to freemarker template for mail?
This question does not provide the Solution to my Problem.
So I want to add Image as a Background in a Freemarker HTML template which I am attaching to a Google Gmail API Program in Java.
Here is the Code for the Freemarker:-
<style>
    body{
background-image: url("cid:${image.jpg}");
}
     .container {
              position: absolute;
              padding:25px;
              margin:25px;
              border:5px;
              text-align: justify;
              text-justify: inter-word;
              font-family: "Times New Roman";
              font-style: italic;
            }
 </style>

And the Way I am Inserting an Image using the Google Gmail API is:-
Multipart multipart = new MimeMultipart();
    MimeBodyPart bodyPart = new MimeBodyPart();
    Template t = freemarkerTemlate.getTemplate("OneEmployee.ftl");
    String mailContent = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
    bodyPart.setContent(mailContent, "text/html");
    multipart.addBodyPart(bodyPart);

    DataSource fds = new FileDataSource(Mailer.class.getClassLoader().getResource("images/image1.jpg").getFile());
    bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(fds));
    bodyPart.setHeader("Content-ID", "<image.jpg>");
    multipart.addBodyPart(bodyPart);

My Images are in the Resources Directory which contains another Image Directory
Now I have tried almost all variations of the code possible such as using the
<img src="">

Adding the cid: within the ${} and also without using the "" but it just does not seem to set the Image in any case.
In some of the Cases it runs without attaching an Image and in some cases it runs but throws an Error on the Console also:-
Application failed at {image1.jpg}:- Missing or Null Argument

The Model that I am using is:-
 Map model = new HashMap();
 model.put("emailNames", emailNames);

I havent added anything else to the Model since this is the Only other thing apart from the Image that I am inserting into the freemarker template
Is there anything that I am doing wrong or missing out on ?
EDIT 2
I have also tried inserting the Image via the Model by setting it as a Key
Code has been Attached for Reference
Map model = new HashMap();
 model.put("emailNames", emailNames);
 model.put("image.jpg", Mailer.class.getClassLoader().getResource("images/image1.jpg").getFile())

It Still fails to work!
EDIT 2
Interestingly I noticed that when I do not define cid then it does adds the background Image as an Attachment, but whenever I add the cid syntax it does not add as an Attachment but it simply ignores the mail.
I read on the net that according to the tutorials you do not pass the Image to be inserted as a part of the model but rather add it as an Attachment defining the content_id (cid) of the Image.
Thank You

A: So Finally I was able to get the Answer to the Solution
The way I was loading an Image from the Images Folder in Resources was wrong
File file = new ClassPathResource("image").getFile();

This is the way to do it
And when passing it to the Freemarker Template you simply need to do cid:imageURL that's all and it should work.
Also you should follow the Comments given by @Bill Shannon and  @Mark Rotteveel


text:
Q: Rails/Ruby asking for "@localhost" password on deploy:setup I'm  still pretty new to this. I've been trying to get this software
running: https://github.com/r888888888/danbooru
But I'm stuck on the deployment step . After trying to deploy, it asks me to login to the user "@localhost", and rejects every password I try. I feel like there should be a name before "@localhost", but I'm a bit lost. I've been able to google and figure out everything else up to this point.
Here's a picture of what I'm seeing: imgur.com/ONp69.png
and also the text:
   danbooru@teemo:~/danbooru$ bundle exec cap development deploy:setup
 [9951bc77] Running /usr/bin/env [ -d ~/.rbenv/versions/2.1.5 ] on localhost
 [9951bc77] Command: [ -d ~/.rbenv/versions/2.1.5 ]
@localhost's password:
@localhost's password:
@localhost's password:
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host localhost: Authentication failed for user @localhost
Net::SSH::AuthenticationFailed: Authentication failed for user @localhost
Tasks: TOP => rbenv:validate
(See full trace by running task with --trace)

A: Capistrano's actually prompting you to log in to a nameless user; "localhost" refers to your computer. You can see on Github that the production and staging deployment configuration includes a :user setting, but that's not defined in the development config.
The development environment is normally used by programmers making changes to the code; if you're trying to deploy the site so it's publicly available, then you should edit your copy of the production configuration to refer to a user account & server you have access to, then run bundle exec cap production deploy.


text:
Q: I am trying to make a "robot" appear to be talking on my website. The mouth must sync with sound and I am thinking....flash? I have seen that some websites offer talking characters (very human looking avatars), but I do not want to pay HUGE money for those.  So I started thinking about some of the cartoons I used to watch and if there was a talking computer, their way of visually portraying speech was with an equalizer.
For the "robot", I would just have 2 dots for the eyes, a nose, and a "mouth", but this mouth would really be an equalizer, and I could animate that with flash so that when there is loud sound, the mouth would open wider than it would for a soft sound ( if you watch an equalizer, the bars go way up and turn red when the music is loud, and remain low and green when sound is soft )
The only web technology that I imagine could do such a thing is flash, but I know very very little flash.  I have been searching and searching and searching and all of the equalizer tutorials I have found are just bars with random movements that do not sync with the audio.  Can I sync audio and flash to make an equalizer?

A: To get the sound spectrum use SoundMixer.computeSpectrum(), this will fill a supplied array with 512 values (256 for each channel, left & right), ranging from -1 to 1. I use this to draw the little bars to show that sound is being sent. I create a Timer so it is called a couple times a second and it makes for a great effect.
To get what you want really easily you could draw a 512 px horizontal line, each px being a value from the array, then scale vertically accordingily to how big you want the flash app to appear (e.g. multiply the value by 100 to get a 200px high movie).
Here's an example I did a few years ago http://lakehousemusic.net/player/index.html?num=3


text:
Q: Телеграм бот не заносит в базу данных новых пользователей Вот код самого бота
import random
import telebot
from dbWorker import *

bot = telebot.TeleBot('<TOKEN>')
prepareDb('db/database.db')

def rand():
    i = random.randint(1, 16)
    return i

@bot.message_handler(commands=['start'])
def start(message):
    init_user('db/database.db', message.from_user.first_name)
    bot.send_message(message.chat.id, 'Приветик любители выпить! Что желаете выпить?')
    bot.send_message(message.chat.id, 'Пиво - /drinkbeer \n'
                                      'Вино - /drinkwine \n'
                                      'Водка - /drinkvodka \n')

@bot.message_handler(commands=['drinkbeer'])
def drinkbeer(message):
    user_name = message.from_user.first_name
    currentLitres = getLitres('db/database.db', user_name, "beer")
    r = rand()
    s = currentLitres+r
    bot.send_message(message.chat.id, f'<em>{user_name}, вы выпили - {r} л пива.  </em>\n'
                                      f'Всего вы выпили - {s} л пива', parse_mode='html')
    setLitres('db/database.db', user_name, "beer", s)

@bot.message_handler(commands=['drinkwine'])
def drinkwine(message):
    user_name = message.from_user.first_name
    currentLitres = getLitres('db/database.db', user_name, "wine")
    r = rand()
    s = currentLitres + r
    bot.send_message(message.chat.id, f'<em>{user_name}, вы выпили - {r} л вина. \n'
                                      f'Всего вы выпили - {s} л вина </em>\n', parse_mode='html')
    setLitres('db/database.db', user_name, "wine", s)

@bot.message_handler(commands=['drinkvodka'])
def drinkvodka(message):
    user_name = message.from_user.first_name
    currentLitres = getLitres('db/database.db', user_name, "vodka")
    r = rand()
    s = currentLitres + r
    bot.send_message(message.chat.id, f'<em> {user_name}, вы выпили - {r} л водки. \n'
                                      f'Всего вы выпили - {s} л водки </em>\n', parse_mode='html')
    setLitres('db/database.db', user_name, "vodka", s)

bot.polling(none_stop=True)

Вот код файла
import sqlite3
from sqlite3 import Error

def init_conn(path):
    conn = None
    try:
        conn = sqlite3.connect(path)
        print ("Connection established!")
    except Error as e:
        print (e)
        print ("Connection failed!")
    return conn

def init_tables(connection):
    sql = "CREATE TABLE IF NOT EXISTS users( id integer PRIMARY KEY, user_name text NOT NULL, beer real NOT NULL, wine real NOT NULL, vodka real NOT NULL);"
    connection.execute(sql)

def prepareDb(name):
    conn = init_conn(name)
    init_tables(conn)
    conn.close()

def init_user(db, name):
    connection = init_conn(db)
    cursor = connection.cursor()
    users = cursor.fetchall()
    usersAmount = len(users)
    if usersAmount == 0:
        sql = "INSERT INTO users(`user_name`, `beer`, `wine`, `vodka`) VALUES('{}', 0, 0, 0);".format(name)
        cursor.execute(sql)
        connection.commit()
        connection.close()
    else:
        sql = "SELECT * FROM users WHERE `user_name`='" + name +"';"
        connection.set_trace_callback(print)
        cursor.execute(sql)

def setLitres(db, name, type, amount):
    sql = "UPDATE users SET `{}`={} WHERE `user_name`='{}';".format(type, amount, name)
    connection = init_conn(db)
    cursor = connection.cursor()
    cursor.execute(sql)
    connection.commit()
    connection.close()

def getLitres(db, name, type):
    sql = "SELECT {} FROM users WHERE `user_name`='{}';".format(type, name)
    connection = init_conn(db)
    cursor = connection.cursor()
    cursor.execute(sql)
    items = cursor.fetchall()
    litres = int(items[0][0])
    connection.commit()
    connection.close()
    return litres

Вот такая ошибка выдает, если команду использует человек которого нет в базе данных. Почему не хочет заносить?

A: def init_user(db, name):
    connection = init_conn(db)
    cursor = connection.cursor()
    users = cursor.fetchall()
    usersAmount = len(users)
    if usersAmount == 0:

А где у вас тут собственно запрос, который проверяет наличие пользователя name в таблице users? У вас пропущена строка cursor.execute(sql) и сам запрос sql отсутствует.
Тут должно быть так же, как и в других функциях, где делаются запросы:
def init_user(db, name):
    sql = "..." # тут запрос на то, что запись для user = name есть в users
    connection = init_conn(db)
    cursor = connection.cursor()
    cursor.execute(sql) # тут вызов запроса
    users = cursor.fetchall()
    usersAmount = len(users)
    if usersAmount == 0:


text:
Q: What is a lattice of elliptic curve $y^2=x^3-x$? It is well known that isomorphism class of elliptic curve and lattice up to homeothetic corresponds bijectively.
But I don't have concrete examples. Can we figure out lattice from given weierstrass equation?
For example,

What is a lattice of elliptic curve $y^2=x^3-x$ ?

A: The curve you asked about ($y^2 = x^3 - x$) is LMFDB 32.a3. Here the Weierstrass
invariants are $\,g_2=-1/4,\, g_3=0\,$ and this is known as the
pseudo-lemniscate case. See DLMF 23.5.iv
for some details. The lattice for this curve is a square lattice with side length
$$\Gamma(1/4)^2/\sqrt{2\pi}=5.244115108584239620\dots$$
and the period parallelogram is a
square one of whose diagonals is along the real axis.


text:
Q: mobile developement and screen sizes I'm developing an app for the iphone / andriod that should fit inside the browser screen perfectly so that I can safely disable scaling and scrolling but there is no way I know to get the actual screen size. What I mean is the dimensions of the screen after the little top bar and the bottom bar of controls. When I'm on my itouch I get screen.height == 420 instead of 380. How do I detect it for both ios and andriod?

A: Android will scale your application to fit the screen size, I have no iOS experience but I know android will change your application to fit the size. Although making different drawables for the different sizes will help make it all look better, but isn't always needed, but recommended.
So with that, why do you need to know the screen size Android devices aren't 'cookie cutters' there is a lot of variation in the market, different resolutions and sizes. So you can't really make the app for a specific size only, you could, but then it would only display properly on that one device and similiar ones. The app is made and scaled to fit, but you as the developer can do things to make it look its' best on each type of screen.
Android has 4 densities, either 'ldpi' 'mdpi' 'hdpi' or 'xhdpi'
everything I have mentioned can be read more in depth here.
http://developer.android.com/guide/practices/screens_support.html


text:
Q: How to query within the same table I need to query a single table based on the contents of the same table
currently i have used in within and, which is taking a lot of time to query & i know its not the smartest way
PID CID Status
1   1   1
1   2   0
1   3   1
1   4   1
1   5   1
2   1   1
2   2   1
2   3   1
2   4   0
2   5   0

from the above table i need results which satisfy the following combination
Select PID from Tablename where
(CID in (1) AND status 1)
AND
(CID in (2,3) AND status = 1)
AND
(CID in (4) AND status = 1)
AND
(CID in (5) AND status = 1)

So as per above requirement, i should get only PID 1

A: This should get all the PIDs which exist in all the select statements:
SELECT PID FROM TableName WHERE CID = 1 AND Status = 1
INTERSECT
SELECT PID FROM TableName WHERE CID IN (2, 3) AND Status = 1
INTERSECT
SELECT PID FROM TableName WHERE CID = 4 AND Status = 1
INTERSECT
SELECT PID FROM TableName WHERE CID = 5 AND Status = 1

A: You seem to want:
Select PID
from Tablename
where status = 1
group by PID
having sum(case when CID in (1) then 1 else 0 end) > 0 and
       sum(case when CID in (2, 3) then 1 else 0 end) > 0 and
       sum(case when CID in (4) then 1 else 0 end) > 0 and
       sum(case when CID in (5) then 1 else 0 end) > 0;

Your query only tests values within a single row.  The where condition can never evaluate to true.
Here is a db<>fiddle, showing that this returns PID = 1 for the data in your example.


text:
Q: Alphabetical order does not compare from left to right? I thought that in .NET strings were compared alphabetically and that they were compared from left to right.
string[] strings = { "-1", "1", "1Foo", "-1Foo" };
Array.Sort(strings);
Console.WriteLine(string.Join(",", strings));

I'd expect this (or the both with minus at the beginning first):
1,1Foo,-1,-1Foo

But the result is:
1,-1,1Foo,-1Foo

It seems to be  a mixture, either the minus sign is ignored or multiple characters are compared even if the first character was already different.
Edit: I've now tested OrdinalIgnoreCase and i get the expected order:
Array.Sort(strings, StringComparer.OrdinalIgnoreCase);

But even if i use InvariantCultureIgnoreCase  i get the unexpected order.

A: There is a small note on the String.CompareTo method documentation:

Notes to Callers:
Character sets include ignorable characters. The
CompareTo(String) method does not consider such characters when it
performs a culture-sensitive comparison. For example, if the following
code is run on the .NET Framework 4 or later, a comparison of "animal"
with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two
strings are equivalent.

And then a little later states:

To recognize ignorable characters in a string comparison, call the
CompareOrdinal(String, String) method.

These two statements seem to be consistent with the results you are seeing.

A: Jon Skeet to the rescue here
Specifically:

The .NET Framework uses three distinct ways of sorting: word sort,
  string sort, and ordinal sort. Word sort performs a culture-sensitive
  comparison of strings. Certain nonalphanumeric characters might have
  special weights assigned to them. For example, the hyphen ("-") might
  have a very small weight assigned to it so that "coop" and "co-op"
  appear next to each other in a sorted list. String sort is similar to
  word sort, except that there are no special cases. Therefore, all
  nonalphanumeric symbols come before all alphanumeric characters.
  Ordinal sort compares strings based on the Unicode values of each
  element of the string.

But adding the StringComparer.Ordinal makes it behave as you want:
string[] strings = { "-1", "1", "10", "-10", "a", "ba","-a" };
Array.Sort(strings,StringComparer.Ordinal );
Console.WriteLine(string.Join(",", strings));
// prints: -1,-10,-a,1,10,a,ba

Edit:
About the Ordinal, quoting from MSDN CompareOptions Enumeration

Ordinal   Indicates that the string comparison must use successive
  Unicode UTF-16 encoded values of the string (code unit by code unit
  comparison), leading to a fast comparison but one that is
  culture-insensitive. A string starting with a code unit XXXX16 comes
  before a string starting with YYYY16, if XXXX16 is less than YYYY16.
  This value cannot be combined with other CompareOptions values and
  must be used alone.

Also seems you have String.CompareOrdinal if you want the ordinal of 2 strings.
Here's another note of interest:

When possible, the application should use string comparison methods
  that accept a CompareOptions value to specify the kind of comparison
  expected. As a general rule, user-facing comparisons are best served
  by the use of linguistic options (using the current culture), while
  security comparisons should specify Ordinal or OrdinalIgnoreCase.

I guess we humans expect ordinal when dealing with strings :)


text:
Q: Join two table and get not common data in MySQL I have two tables all_jobs and jobs_applied. Problem is I want to get the list of jobs from all_jobs table. At the moment I have this query but it is only giving me common records from both table.
SELECT b.uid
     , a.jobtitle
     , a.job_id

  FROM job_posting a
  left
  join job_applied b
    on a.job_id = b.job_id
Where b.uid != 10 and disable=0 and draft =0

Edit
in job_posting table there are 24 records. in job_applied table there are 2 records. Both table have job_id field. When I execute the query I am expecting 23 records because one record is common in both table. But I am getting single record.
I have checked this question. What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN? but not sure how can I use it in my situation.
Edit 2 (table structure)
job_posting
job_id,
title,
skills,
post_date

job_applied
id,
job_id,
uid,
apply_date

What I am trying to achieve: I want to get the list of records from job_posting table but those records shouldn't be exist in job_applied table with specific uid. So, it means i will have to add two things in where clause one for uid and another one for job_id.
I also tried below query but it is returning 0 records.
SELECT
          a.jobtitle
         , a.job_id

      FROM job_posting a
      left
      join job_applied b
        on a.job_id = b.job_id
Where (b.job_id is null and a.disable=0 and a.draft =0 and b.uid !=10)

Edit 3
I am using this query now and it is returning correct result.
Select a.jobtitle, a.job_id from job_posting a where
a.job_id not in (select b.job_id from job_applied b WHERE b.uid=1)
AND a.disable=0 AND a.draft =0

Let me know if I am doing anything wrong.

A: After all your comments, I understood that b.uid is a reference to some users table. So the job_applied is a kind of association table for many-to-many relation. It seems your query should look like that:
SELECT a.jobtitle, a.job_id
FROM job_posting a
WHERE a.disable=0 AND a.draft =0
AND job_id NOT IN (
SELECT job_id FROM job_applied b
WHERE b.uid = 1)

This will remove matched rows from table b for user with uid = 1. This should be provided via some parameter in a procedure or something.
I have prepared a fiddle for you to test: http://sqlfiddle.com/#!9/91792/7/0
Let me know if that helps.

A: Have you tried a left outer join? I think the join you are using will only display the common results.

A:
in job_posting table there are 24 records. in job_applied table there
  are 2 records. Both table have job_id field. When i execute the query
  i am expecting 23 records because one record is common in both table

I think a left join on job_posting should return all the records on that table (matching the conditions), despite a record on the another table is related with two or more. You probably are seeing 23 records on your results because of the conditions, check it:
Where b.uid != 10 and disable=0 and draft =0

A: When you want to get data from this query with loop you should try to like this :
`SELECT a.jobtitle as jTitle, a.job_id as jId
FROM job_posting a
WHERE a.disable=0 AND a.draft =0
AND job_id NOT IN (
SELECT job_id FROM job_applied b
WHERE b.uid = 1)`

like foreach <?=$query['jTitle']?>

A: You may get the same result with better performance in this way.
SELECT a.jobtitle, a.job_id
    FROM job_posting a
    LEFT JOIN job_applied b ON a.job_id=b.job_id
WHERE b.job_id IS NULL and a.disable=0 and a.draft =0 and b.uid=1;


text:
Q: How to update react context between components? I have two sibling components (A & B) that I'm trying to pass react context between. Not static context. The context is created and updated in component A like so:
  export const ModelContext = React.createContext({ model: '' });

function Models() {
    const [check, setCheck] = useState({});
    const [alert, setAlert] = useState(false);
    let model = useContext(ModelContext);

    const handleChange = (event) => {
        const arr = Object.keys(check);
        if (arr.length === 1 && arr.includes(event.target.name) === false) {
            setAlert(true);
        } else if (arr.length === 1 && arr.includes(event.target.name) === true) {
            setAlert(false);
            setCheck({});
            model = check;
            console.log(model);
        } else {
            setCheck({ ...check, [event.target.name]: event.target.checked });
            setAlert(false);
        }
    };

I update the context (ModelContext) in this component in the handleChange. I can see from the console.log(model) that the context is updating as I desire.
However, in component B the context (ModelContext) is not being updated. I'm not sure where to go from here. Here is component B:
import { ModelContext } from './index';

function Fields() {
    const modelSelected = useContext(ModelContext);

}
Is it possible to update the context in this fashion or should I take another approach?

A: What you are seeing in the console log is after updating the model object. It is no longer referring to the context. It has a new reference now after model=check.
First of all, if you want to pass the context between 2 siblings, the common parent should be wrapped around with context providers. You can create a context provider component.
const ModelContext = useContext({model: ''});
const ContextProvider = ({children, modelData}) => {
   const [model, setModel] = useState(modelData);
   return <ModelContext.Provider value={{model, setModel}}>{children}</ModelContext.Provider>
}

const Parent = () => {
    return (
        <ContextProvider modelData={your model data}>
           <Models />
           <Fields/>
        </ContextProvider>
    )
}

const Models = () => {
    const [check, setCheck] = useState({});
    const [alert, setAlert] = useState(false);
    const {model, setModel} = useContext(ModelContext);

    const handleChange = (event) => {
        const arr = Object.keys(check);
        if (arr.length === 1 && arr.includes(event.target.name) === false) {
            setAlert(true);
        }
        else if (arr.length === 1 && arr.includes(event.target.name)===true) {
           setAlert(false);
           setCheck({});
           setModel(check);
           console.log(model);
        } else {
           setCheck({ ...check, [event.target.name]: event.target.checked });
           setAlert(false);
        }
   };

   const Fields = () => {
      const {model: modelSelected} = useContext(ModelContext);
      console.log(modelSelected);
   }

You have to do this because, the context doesn't automatically get to the siblings if you do not wrap their parent with the context provider. This
blog might be helpful for you to understand the usage of context


text:
Q: python - should I use static methods or top-level functions I come from a Java background and I'm new to python.  I have a couple scripts that share some helper functions unique to the application related to reading and writing files.  Some functions associated with reading, some with writing.  While searching for the correct approach, I saw this: Static methods in Python?
He mentions in his answer:

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.

I don't understand top-level functions very well and I'm not sure given this simple example which is better: 1) create a class for a reader with static reader functions and the same for a writer or 2) to declare these helpers as global functions and why?
EDIT: REALLY good article about this subject i just found http://tomayko.com/writings/the-static-method-thing

A: Its a question of namespace pollution. If you have a module with multiple classes and some functions that only make sense for a certain class and its descendents, then make that a static method. The static method can be called either by using the class name or by using an object of the class.
>>> class A(object):
...     @staticmethod
...     def static_1():
...             print 'i am static'
...     def a(self):
...             self.static_1()
...
>>> A.static_1()
i am static
>>> a=A()
>>> a.a()
i am static
>>> a.static_1()
i am static
>>> class B(A):
...     pass
...
>>> b=B()
>>> b.static_1()
i am static
>>>

A: If the function is related to a class, then make it a static method.  For example:
class DBobject():
    name = StringProperty()

    @staticmethod
    def get_by_name(name):
        return db.select('select * from DBobject where name = "%s"' % name)

python = DBobject.get_by_name('python')

That is, the method is completely related to the DBobject class so it should be a static method.

A: In Java there's the (IMHO wrong) idea to use classes everywhere, even just group together static functions that don't share any state (and thus such classes will never be instantiated).
Python here begs to differ; if you have functions that don't have some shared state1 (and thus in Java would typically be static functions) and aren't tightly related to a "real" class (=one that is actually instantiated) you just use free functions inside a module.
The reasoning behind this is that a class is needed only when you actually want to instantiate it, thus having a class just as a container for several functions that don't need to share an instance-specific state is useless.
Actually, you can somewhat think of a module as a static class - i.e. a container of functions (=static methods), module variables (=static fields) and types.
The nice thing in Python is that having top-level function doesn't give global namespace pollution problems, since in Python top-level functions/objects/... are still module-scoped. Thus, you can still group functions by module, without the unnecessary class-tax.

*

*actually, they can have some shared state, in form of module-level variables (so, singletons); again, the analogy modules-static classes seems to hold.

A: One other aspect of Python static methods is that when called on instances, they are polymorphic on the type of the variable they are called on, despite not having an instance of self.
For example:
class BaseClass:
    @staticmethod
    def my_method():
        return 0

class SubclassLeft:
    @staticmethod
    def my_method():
        return "left"

class SubclassRight:
    @staticmethod
    def my_method():
        return "right"

instances = [BaseClass(), SubclassLeft(), SubclassRight()]

for i in instances:
    print(i.my_method())

Running this results in
$ python example.py
0
left
right

A: From the Zen of Python (import this) :

Namespaces are one honking great idea -- let's do more of those!

One of the main reasons to create static methods in a language like Java is to ensure that those methods don't wind up polluting the global namespace. (Although Java enforces its own namespace conventions by disallowing "package-level" functions entirely !) In Python, all "top-level" functions are automatically placed within the namespace of the module containing those functions, so there's no danger of polluting the global namespace this way.
In other words, like many other languages, Python can create namespaces in a few different ways. In this case, there's little need to create a class containing only static methods, when a module serves the same namespacing purpose without the clutter (or cognitive load) associated with defining a class.


text:
Q: how to write double queries from one table in SQL Lets say I have 2 kind of devices to work on number of points for each day.
I want to get the current, average and also maximum points in each day.
The table structure is similar to:
working_date           device    point_number
2020-03-12                A         1
2020-03-12                A         2
2020-03-12                B         3
2020-03-12                B         4
2020-03-14                A         5
2020-03-14                A         6
2020-03-16                B         7
2020-03-17                A         8
2020-03-17                B         9

Each row representatives 1 point. First thing first, I have created query to show number of points and device for each date
select working_date, count(distinct device), count(point_number) from table1 group by working_date order by working_date

and it resulted:
working_date    points_qty        device_qty
2020-03-12         4                 2
2020-03-14         2                 1
2020-03-16         1                 1
2020-03-17         2                 2

Choosing 2020-03-18 as the report date, I want to get the last working_date which is 2020-03-17 and I want to get the current point that being done on that day and maximum points that being done by the device/point/day.
The current qty is the result from points_qty / device_qty, while the maximum points is the maximum points from all working_date
The desired result:
report_date    last_working_date    current_point_qty      maximum_qty
2020-03-18      2020-03-17                  1                 4

I am lost at writing the full query to get the desired results. How should I write my query for this?
Thanks in advance

A:      select (working_date::date + '1 day'::interval) report_date,working_date,
   sum(countdevice)/sum(countnumber) current_point_qty,   max(countnumber)
   maximum_qty from (
    select  working_date, count(distinct device)countdevice,
    count(point_number)countnumber  from table1 group by working_date order by working_date )t
    group by (working_date::date + '1 day'::interval),working_date
    order by working_date desc limit 1

A: Since I have used group by working_date in my previous answer aggregation will be based on that group by. In this answer I have done the same thing with window function so that the select statement is no more tied with the group by clause. Though all the aggregation is partitioned by working_date but to find overall average I didn't use partition by clause to get average on all the rows:
 select (working_date::date + '1 day'::interval) report_date,working_date,
   sum(countdevice)over(partition by working_date)/sum(countnumber)over(partition by working_date) current_point_qty,
   max(countnumber) over(partition by working_date),avg(countnumber/countdevice)over(order by (select 1))
   maximum_qty from (
    select  working_date, count(distinct device)countdevice,
    count(point_number)countnumber  from table1 group by working_date order by working_date )t
    order by working_date desc limit 1


text:
Q: Update list of data in room database column I have a list of data and i want to update in room database column but I can't find any method to update my data
@Query("UPDATE student_db")
default void update(List<Student> student) {
}

A: You can use (see notes/comments)
@Update
int update(List<Student> student)

*

*as long as the Student's in the list are ALL set with the appropriate values especially that the PrimaryKey field/member is correct as Room determines the Student(s) to update according to the PrimaryKey.

If using @Query then you have to be more specific about what is to be updated (the convenience @Update covers common scenarios not all).
If you used
@Query("UPDATE student_db SET the_column=:the_new_value")
void update(String the_new_value);

The this would update ALL rows with the same value (as there is no WHERE clause).
To update a single student (assuming the primary key field/member) then you could use:-
@Query("UPDATE student_db SET the_column=:the_new_value WHERE id=:id")
void update(String the_new_value, long id);

If you want to have a method with a body (as you appear to want) then instead of using an interface use an abstract class (you cannot have methods with bodies in an interface).
e.g.
@Dao
abstract class theDao {

    @Query("UPDATE student_db SET the_column=:the_new_value WHERE id=:id ")
    abstract void update(String the_new_value,long id)

    @Transaction
    @Query("")
    abstract default void update(List<Student> student) {
      for(Student s: student) {
          update("The new value for this student",s.id);
      }
    }
}

*

*@Trasnaction as in the example multiple updates are executed

*Query("") to fool room into handling the entire method as being in a transaction.


text:
Q: Website down after changing permalinks to postname just spent quite some time searching on Google and Stack Overflow for my problem, changed the .htaccess already but no changes.
I changed the permalink settings to postname, saved, refreshed my site and got the error: Forbidden
You don't have permission to access / on this server.
Apache Server at arnoldnumerouno.de Port 80
After searching I changed the .htaccess to:
SetEnv PHP_VER 5_3
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

--
The page is still down and I can't access the wp-admin to set it to default again.
I really need some help :-( Just spent several hours on writing posts and now the page is down and I have no clue what to do.
Really appreciate any help from you guys,
thanks in advance

A: Try removing:
SetEnv PHP_VER 5_3
Also, make sure that your files and directories have the proper permissions: 755 for directories, 644 for files.
EDIT
Also, try adding the following to the beginning of your .htaccess:
Options +FollowSymLinks

A: When generating new permalinks,
if you have the wrong site url and home url settings,
wordpress will give an error like:
You don't have permission to access / on this server
(...actually it's not finding the directory),
if you've changed them recently, I suggest you check.

to edit site url and home url directly in database use phpmyadmin,
change siteurl and home row in the option table


text:
Q: Working sms script for zabbix Could anyone provide a working script for sending sms from zabbix. I would like to use free service provider. I couldn't find any useful script for this.

A: you can use this script
#!/usr/bin/perl

print "content-type: text/html\n\n";
use CGI;
$cgi = new CGI;

$cel = $ARGV[0];
$title = $ARGV[1];
$msgx = $ARGV[2];

&enviasms;

# SOAP (Simple Object Access Protocol)
############################################

sub enviasms{

$dispatch = "send";
$account = "myaccount";
$code = "mypassword";
$msg = "$msgx";
$from = "Zabbix";
$to = "$cel";
$id = time();
$user = $id - 1;
$schedule = "";
$callbackOption = "";

use LWP::Simple;
#$result = get("http://system.human.com.br:8080/GatewayIntegration/msgSms.do?dispatch=send&account=$account&code=$cod e&msg=$msg&from=$from&to=$to&id=$id&schedule=$sche dule&callbackOption=$callbackOption");

if(!$result){
use strict;
use warnings;
open (my $fs, '>>', 'log');
print $fs "that is Error\n";
close $fs;
} else{
use strict;
use warnings;
open(my $fs, '>>','log');
print $fs "msg is: ";
print $fs $ARGV[2];
print $fs "::::>phone:";
print $fs $ARGV[0];
print $fs "\n";
close $fs;}}

A: You can check Pagerduty which is not free but is not expensive and brings great value with the android and iPhone apps and it has great integration with Zabbix.
Check this guide:
http://www.pagerduty.com/docs/guides/zabbix-integration-guide-2/