text:
Q: Displaying an integer in a TextView In my Player.java object class I have the following code
private static int playerAge;

with
playerAge = 18;
in my constructor method
    public static int getplayerAge() {
    return playerAge;
}

But when trying to get the player age in my java class which extends activity it always shows "0" instead of "18" like it's supposed too. Here's my code for that.
TextView playerAge = (TextView) findViewById(R.id.tvPlayerAge);
        playerAge.setText("Age: " + Integer.toString(Player.getplayerAge()));

What am I doing wrong? Thanks!
By the way if I change private static int playerAge; from the very top, to
private static int playerAge = 18; it works, just don't get why it doesn't work from the constructor method.
Player.java class
public class Player extends Object {

    //Instance Data
    private static String playerName;
    private static int playerAge = 1;
    private static boolean sterile;

    //Default Constructor
    public Player() {
        playerName = "";
        playerAge = 5; //For some reason you have to inetiate the playerAge in the instance data for
                            //it to be able to read it...
        sterile = true; //Default Value
    }

    //Constructor
    public Player(String pName, int pAge, boolean isSterile)    {
        playerName = pName;
        playerAge = pAge;
        sterile = isSterile;
    }

    //Accessor Methods (Getters)
    public static String getplayerName() {
        return playerName;
    }

    public static int getplayerAge() {
        return playerAge;
    }

    public static boolean getplayerDiseasedState() { //Sterile or not?
        return sterile;
    }

    //Mutator Methods (Setters)
    public static void setPlayerName(String name) {
        playerName = name;
    }

    public static void setplayerAge(int age) {
        playerAge = age;
    }

    public static boolean setSterileState(boolean diseased) {
        return sterile = diseased;
    }

    //toString (Accessor)
    public String toString() {
        String toString =   "Player Name: "+ playerName + "\n" +
                "Player Age: " + playerAge + "\n" +
                "Player Diseased: "  + sterile + "\n";
    return toString;
        }

     }

A: You don't need the Integer.toString() bit. Just use:
player.setText("Age: " + Player.getPlayerAge());


text:
Q: How to parse big data? I have an express.js application. Users request mysite.com/something and they receive a large amount of text. After each request I need to parse data (for example, to find something in  thetext and put it into my Redis database).
app.get('something', function (req, res) {
    var data = //getting data
    res.send(data);
    //parsing data
});

The problem is that parsing data takes too much time and it's synchronous which means users must wait until it finishes to get their data.
Is there any way to parse data in another .js file and allow the users to get results immediately ?

A: If the data amount is large, you should consider using node streams in order to parse it.   Use through2 to easily create transform streams.  Using streams you will process one data chunk (one object, one csv line, one xml tag) at a time immediately streaming it to response chunk by chunk.
Also you should never use any synchronous code in your app.  Everything should be asynchronous.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to define references in a loop without array im trying to make a reference to a multidimentional array columns,
and i need to make an $i ammount of references to the array values as string.
for example 1st row:
for ($i=0; $i<count($array[0][column[$i]]);$i++)
{
   $value_1 = &$array[0][column[$i]];
}

is there a way to name the "$value_x" variable with $i identificator?
similar to echo "$value_$i";
im lacking experience with references, any advise would be appreciated.

A: You can set multiple variables with a name based on the loop index with ${"value_$i"}:
<?php

for ($i=0; $i<10;$i++)
{
   ${"value_$i"} = &$array[0][column[$i]];
}

I've created a working example showcasing this here :)


text:
Q: Pass a PHP array to a JavaScript function I am trying to get a PHP array variable into a JavaScript variable.
This is my code:
<html>
    <head>
        <script type="text/javascript">
              function drawChart(row,day,week,month,date)
              {
                  // Some code...
              }
        </script>
    </head>

    <body>
        <?php
            for($counter = 0; $counter<count($au); $counter++)
            {
                switch($au[$counter]->id)
                {
                    case pageID.'/insights/page_active_users/day':
                        $day[] = $au[$counter]->value;
                    break;
                    case pageID.'/insights/page_active_users/week':
                        $week[] = $au[$counter]->value;
                    break;
                    case pageID.'/insights/page_active_users/month':
                        $month[] = $au[$counter]->value;
                    break;
                }
            }
        ?>
        <script>
            drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>', '<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day')))); ?>');
        </script>
    </body>
</html>

I can't get value of the PHP array.
How do I fix this problem?

A: In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
    day = new Array(<?php echo implode(',', $day); ?>);
    week = new Array(<?php echo implode(',',$week); ?>);
    month = new Array(<?php echo implode(',',$month); ?>);

    <!--  Then pass it to the JavaScript function:   -->

    drawChart(<?php echo count($day); ?>, day, week, month);
</script>

A: You can pass PHP arrays to JavaScript using json_encode PHP function.
<?php
    $phpArray = array(
        0 => "Mon",
        1 => "Tue",
        2 => "Wed",
        3 => "Thu",
        4 => "Fri",
        5 => "Sat",
        6 => "Sun",
    )
?>

<script type="text/javascript">

    var jArray = <?php echo json_encode($phpArray); ?>;

    for(var i=0; i<jArray.length; i++){
        alert(jArray[i]);
    }

 </script>

A: Use  JSON.
In the following example $php_variable can be any PHP variable.
<script type="text/javascript">
    var obj = <?php echo json_encode($php_variable); ?>;
</script>

In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)

In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);

A: Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });


text:
Q: Modify parameter values of sections in INI files Python I have a .ini file which I want to modify a particular section.
So for example,
[Section1]
Param1: Hello
Param2: World

[Section2]
fontsize = 10

[Section3]
integers = 971 508 1076 561

I want to modify the integers in section 3 and replace them with other integers. I have tried:
lis = "971 508 1076 561; 920 543 973 648 ; 831 492 936 544 ; 936 403 988 508"
config.set('sfr',lis)

But I'm getting errors; how can I fix this?
import configparser
config = configparser.ConfigParser()
config.read("C:\\Users\\Folder\\example.ini")
print(config.sections())
lis = "971 508 1076 561; 920 543 973 648 ; 831 492 936 544 ; 936 403 988 508"
config.set('sfr',lis)

A: You're missing the section and field to change the values of, try with:
config.set("Section3", "integers", lis)

Keep in mind that after changing the values you still need to save your config:
with open("C:\\Users\\Folder\\example.ini", "w") as f:
    config.write(f)


text:
Q: Stepper vs servo or DC motor My friend and I are currently working on a robotic vehicle project, and he had some spare steppers lying around from a previous project. Instead of using DC motors or servo motors, is it viably to use steppers to drive a small vehicle?

A: Are you in mechatronics? I've used steppers in direct drive applications with some success. You can avoid most missed step events by driving them carefully, i.e. writing good code and implementing proper acceleration profiles + doing micro stepping when necessary to decrease torque ripple.
Having said all that, You should stick to a continuous rotation servo, or either of direct or geared drive through a DC motor for your project. You will draw less current, almost certainly, for a given speed. You will save the headache of writing a lot of extra code to get your steppers working optimally. In short, you don't want to have to worry about the particulars of using steppers if you also need to worry about the bigger picture, which is getting your project done well.


text:
Q: How to set mask textfield cursor at start position? I'm using react mask textfield component . When I click on it , input cursor always shows up at the end of the mask . How to make when input is focused set that cursor after "+7(" ?
 <MaskedTextfield
    inputId="masktextfield"
    className="tf"
    reference={this.props.reference}
    maskedValue={this.props.maskedValue}
    numOfErrorMsgs={1}
    showMask
    guide
  />

A: You can use setSelectionRange(0,0);.
First get the reference to the element, then apply that function. In plain JS the onFocus or onClick function would be like this:
var textfield = document.getElementById('masktextfield');
textfield.setSelectionRange(0,0);


text:
Q: Not sure why I'm getting this error, "System.QueryException: unexpected token: " Not sure why I'm getting this error, "System.QueryException: unexpected token:
 public class InputLookupComponentControllerTest{
     testMethod public static void testGetRecords(){

         List<String> userL = new List<String>();
         userL.add(UserInfo.getName());
         String searchV = UserInfo.getName();
         InputLookupComponentController.getRecords(userL, searchV);

    }
}

// This is the InputLookupComponentController Class
public with sharing class InputLookupComponentController {

    /**
     * The maximum number of records returned from the query.
     * This is limited to prevent long round trip times from sending too much data
     * back to the client.
     */
    private static final Integer MAX_RECORDS = 10;

    /** This is a lightning component controller. It should never be instantiated. */
    private InputLookupComponentController() {

    }

    /**
     * Does a sosl search against the types of objects given with the search val
     * Defaults to search Name fields and returning Id, Name for each type
     * Limits to 10 return records for better UX.
     *
     * @param types Array of API strings
     * @param searchVal the value we are searching for
     * @return list of records who name fields match our search
     */
    @AuraEnabled
    public static SObject[] getRecords(final String[] types, final String searchVal) {
        if (types.isEmpty()) {
            throw new IllegalArgumentException('sobjectType cannot be null or white space.');
        } else if (String.isBlank(searchVal)) {
            throw new IllegalArgumentException('searchField cannot be null or white space.');
        }

        String sosl = 'FIND \'*' + String.escapeSingleQuotes(searchVal) + '*\'' + ' IN NAME FIELDS RETURNING ';
        for (Integer i = 0, n = types.size(); i < n; i++) {
            final String s = String.escapeSingleQuotes(types[i]);
            sosl += s + '(Id, Name)';
            if (n > 1 && i != n - 1) { sosl += ','; }
            sosl += ' ';
        }
        sosl += 'LIMIT ' + MAX_RECORDS;

        List<SObject> ret = new List<SObject>();
        for (List<SObject> lst : Search.query(sosl)) {
            ret.addAll(lst);
        }

        return ret;
    }
}

A: You may have problem in " searchVal " variable. Try to debug the " searchVal " and " Types " in your code. I have executed the below code and it's not throwing error.
List<String> types = new List<String>{'Lead','Contact'};
String sosl = 'FIND \'*' + String.escapeSingleQuotes('Alex') + '*\'' + ' IN
NAME FIELDS RETURNING ';
for (Integer i = 0, n = types.size(); i < n; i++) {
        final String s = String.escapeSingleQuotes(types[i]);
        sosl += s + '(Id, Name)';
        if (n > 1 && i != n - 1)
        {
            sosl += ',';
        }
        sosl += ' ';
    }
sosl += 'LIMIT 10';
System.debug('&& sosl ----->'+sosl);
Search.query(sosl);


text:
Q: PyCharm is not doing code inspection on non-project files I'm working on a Python project in PyCharm and I wanted to edit a python script outside the project.
PyCharm doesn't inspect the code and doesn't give any PEP8 violations.
Hoped that there would be a setting for that but couldn't find anything so far.
Does anyone know how to enable code inspection on non-project files in PyCharm?

A: I am able to reproduce the problem (with 5.0.5 Pro Linux version).
The inspection is actually active and the PEP8 checks are all enabled, I even got a blank line at end of file flag raised, but not an unresolved reference one:

Looks like Arnaud P may be right, as the exact same file content in a project file raises the unresolved reference flags:

I suppose Pycharm considers it doesn't know enough to complain about
  unresolved variables, since this file might be part of another
  project. – Arnaud P 22 mins ago

Confirmed by JetBrains:

This is the answer I've got from them: "This is expected behavior,
  this inspection is suspended if file is outside of current project.
  PyCharm doesn't know configuration, source roots, etc of other
  projects/other files." So I mark your suggestion as the accepted
  answer. – Sinan Çetinkaya 5 mins ago

As a workaround you could have a (re-usable) project with one (or more) files in which you paste non-project file contents just for the purpose of running inspections.
Or just create a project for that file.


text:
Q: WSO2 Api Manager Sample Code for User Own Java API The WSO2 Api manager documentation only shows how to setup youtube statistics as api, but there is no example found about how to use developers own web service to be exported as API using publisher
My Question is
How can I use user defined java web service calls to be managed thru WSO2 API Manager?

A: Best example will be trying out PizzaShack sample inside API Manager. There are two java based web applications pizza-shack-web and pizza-shack-api in the sample which will be deployed as web services in WSO2 Application Server.
Then 3 APIs will be created in WSO2 API Manager as Delivery API, Order API and Menu API which are consuming the pizza-shack-api service.
Please follow the README inside the sample.
Steps to setup sample

*

*Go to WSO2_AM_HOME/samples/PizzaShack and execute mvn clean install from there. It will download the required artifacts to run the sample including the README.

Note: If you are using WSO2 API Manager 1.5.0, please change the WSO2_AM_HOME/samples/PizzaShack/pre-processor/pom.xml with below change and then follow instruction 1 above.
Replace https://svn.wso2.org/repos/wso2/carbon/platform/branches/4.2.0/products/apimgt/1.5.0/modules/samples/PizzaShack/PizzaShack.zip
with
https://svn.wso2.org/repos/wso2/carbon/platform/branches/turing/products/apimgt/1.5.0/modules/samples/PizzaShack/PizzaShack.zip


text:
Q: simple sentiment analysis with java I am very new to Sentiment analysis. How can I judge if a given word or sentence is positive or negative. I have to implement it with java. I tried to read something like lingpipe, rapidminer tutorial, but I do not understand. In their examples they use a lot of data. In my case I do not have much data. All I have is a word or a sentence, lets say. I tried to read the questions from stackoverflow too. But they do not help me much.
Thanks in advance.

A: Computers don't know about a human thing like sentiment unless they learn it from examples that a human has labeled as positive or negative.
The goal of Machine Learning is in fact to make the most informed decision about a new example based on the empirical data of previous examples. Statistically, the more data, the better.
To "judge" the sentiment of a sentence, you'll need to have trained a model or classifier on some sentences labeled for sentiment. The classifier takes an unlabeled sentence as input and outputs a label: positive or negative.
First get training examples. I'm sure you can find some labeled sentiment data in the public domain. One of the best data set repositories is the UCI KDD Archive. You may then train a classifier on the data to judge new examples. There are a host of learning algorithm resources available. My favorites are jBoost, which can output a classifier as Java code, and Rapidminer, which is better for visual analysis.

A: You could use an existing web-service which is trained from prior data.  For example:
Chatterbox Sentiment Detection API
Which has libraries for Java & Android.
(Disclosure: I work for the company that builds this API)

A: This is not really programming related (neuro-linguistic programming is not programming), and in general there is no reliable solution.
My best idea is to make it work like Google "Pigeon"Rank, i.e. collect words and sentences, and then collect human feedback whether they are positive or negative, and then use Bayesian matching with this data.

A: Your can try to use Wordnet for searching word's Semantic Orientation based on "distance" calculation between your word and "good" or "bad" words.Shorter distance will give you word's SO. Results seems will be a bit weak but not a lot of data(or time) is necessary for this approach.


text:
Q: For every 3 unique ids group together and set groupid without using CASE Expression Table table_name

id

1

2

3

4

4

5

6

6

7

7

7

8

9

9

10

Following SQL will give me the answer Demo but I need to hardcode each case and I need to know the MAX(id) in the first place.
SELECT id,
CASE
WHEN id > '0' AND id <= '3' THEN 1
WHEN id > '3' AND id <= '6' THEN 2
WHEN id > '6' AND id <= '9' THEN 3
WHEN id > '9' AND id <= '12' THEN 4
END AS groupid
FROM table_name

How to improve it without me hardcode using the CASE. Since id column will continue increasing and it will runout of case sometime later.
(SQL Server 2014 - build v12.0.6108.1)
Result:

id
groupid

1
1

2
1

3
1

4
2

4
2

5
2

6
2

6
2

7
3

7
3

7
3

8
3

9
3

9
3

10
4

A: SELECT id, CEILING(id/3.0) AS groupid
FROM table_name


text:
Q: Socket.io - Multiple connections when there should only be one per browser window I've noticed that when loading into my app it creates multiple socket connections.
This bug seems quite intermittent, I've been looking around for a solution but nothing seems to be working thus far.
Here's my server-side code:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var path = require('path');

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/client/index.html');
});

app.use('/client',express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, 'skin')));

serv.listen(8081);
console.log("Server started");

var io = require('socket.io')(serv,{});
var socketCount = 0;
io.sockets.on('connection', function(socket){
    console.log('Socket ' + socketCount + ' connected');
    socketCount++;

    socket.emit('socketConnected', true);

    socket.on('disconnect',function(){
        console.log('Socket ' + socketCount + ' disconnected');
        socketCount--;
        delete SOCKET_LIST[socket.id];
        delete PLAYER_LIST[socket.id];
    });

    ...

When refreshing the page, the disconnect function on the server fires, but only once despite the fact that there is supposedly several sockets. I then get multiple socket connecting, again.
When putting a breakpoint on the frontend (listening for socketConnected) it triggers multiple times. Can anyone point out any flaws in the code above that may cause this issue?
Thanks.
New development after some further debugging:
I've noticed that when I emit socketConnected as seen above, I have assumed that I am able to grab some further data from the frontend.
When sending data from the frontend back to the server again, I run my calculations on the server with it and then run a second socket.emit('something .. from the server to the frontend. - This takes several attempts before actually hitting a breakpoint on the frontend. During these attempts to emit the data from the server, this is where the several other connections are made.
However, if I wrap the second server emit in a setTimeout function it works fine and maintains the current connection without creating multiple more. Has anyone else encountered this issue? - If so, is there a solution that avoids using setTimeout?


text:
Q: Make chat onebox HTTPS links When I paste a link like http://www.xkcd.com/975 on chat, it promptly oneboxes the comic. However if I post the HTTPS version of that https://www.xkcd.com/975 it doesn't. This is true for all other oneboxable links from sites that let you access through HTTPS like YouTube.
Can we get HTTPS links oneboxed as well?


text:
Q: Exception handling in earth engine I have a function that computes 2 numbers which determine whether the function should stop or continue its execution. In short, I would like the function to throw an error whenever x is not equal to y as illustrated in the code below.
function er (x,y){
  x = ee.Number(x)
  y = ee.Number(y)
  return ee.Algorithms.If({
    condition: x.eq(y),
    trueCase: x.multiply(y),
    falseCase: 'Stop and throw this error!'
  })
}

print(er(2,1))


text:
Q: Why am I getting undefined function in my script? I am having some trouble with a PHP contact form, when submitted this form returns only
phone number: and also enquiry: undefined . It should return Name, Phone Number and my Enquiry. Any idea why its not returning name and why Enquiry is undefined?
MY PHP
    $name=$_POST['name'];
    $phone=$_POST['phone'];
    $enquiry=$_POST['enquiry'];

    $subject="NINJA2k - EMAIL INQUIRY FROM: $name";
    $message="
          Phone:

          $phone

          Enquiry:

          $enquiry

    ";

    mysql_close();

    include("class.phpmailer.php");
    include("class.smtp.php");

    $mail = new PHPMailer();
    $mail->IsSMTP();// send via SMTP
    $mail->Host = "localhost"; // SMTP servers
    $mail->SMTPAuth = false; // turn on/off SMTP authentication
    $mail->From = "user1@mydomain.com";
    $mail->FromName = "http://mail.mydomain.com/";
    $mail->AddAddress("user1@mydomain.com");
    $mail->AddReplyTo("user1@mydomain.com");
    $mail->WordWrap = 50;// set word wrap
    //now Attach all files submitted

    $mail->Body = $message;
    //
    $mail->IsHTML(true);// send as HTML
    $mail->Subject = $subject;

    if($mail->Send())
    {
        echo "Thank You $name
Your email has been sent.";
    }
    else
    {
        echo "There was a problem sending the mail. Please check that you filled in the form correctly.";
    }
?>

$('.contact_form').dialog({
        width:500,
        height:450,
        modal:true,
        buttons: {
            "Send": function() {
                if(($("#ct_name").val()=="") || ($("#ct_phone").val()=="") || ($("#ct_enquiry").val()=="") || ($("#ct_captcha").val()==""))
                    alert("You must fill all the field");
                else
                {
                    var capt=$(div_list[ind]).attr("id");
                    if(capt!=$("#ct_captcha").val().toLowerCase())
                        alert("Captcha Code is Invalid!");
                    else
                    {
                        var send_string;
                        send_string="name=";
                        send_string+=$("#ct_name").val();
                        send_string+="&phone=";
                        send_string+=$("#ct_phone").val();
                        send_string+="&enquiry=";
                        send_string+=$("#ct_enquiry").val();

                        $.ajax({
                             type: "POST",
                             url: "send_mail.php",
                             data:   send_string,
                             async: false,
                             success: function(msg){
                                alert("Your mail was sent successfully!");
                             } ,
                             error: function(msg){
                                alert("Sorry! We couldn't send email");
                             }
                        });
                    }
                }

            }
        }
    });

MY HTML

Name	<input type="text" id="ct_name"/>

Phone Number	<input type="text" id="ct_phone"/>

Enquiry Data	<textarea rows="4"></textarea>

        Captcha

            <input type="text" style="margin-top:15px" id="ct_captcha"/>

A: You need to use name attribute in your HTML to be able to reach the value. So instead of

Name	<input type="text" id="ct_name"/>

you should have

Name	<input type="text" name="name" id="ct_name"/>

EDIT
The "trick" is that name value is used as input's key in $_POST array. But if you at the same work with i.e. jQuery, then you may still need id or class as it's easier to reach the input using them in DOM than using name.


text:
Q: How to remove the hability to focus next EditText when we push the return key? When I'm writing in an EditText, if I push the next/done key then the focus will move to the next EditText. How to forbid this behaviour (programmatically)?

A: Just setFocusable(true) to the mother view of your edittext

A: You may try this code :
yourEditText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                // do something with next printed on your editText

            }
            return true;
        }
    });

You can manage cases for different option like other action(Done/Next/Search etc.) too.


text:
Q: NodeJS: Reached heap limit Allocation failed - JavaScript heap out of memory I have a VPS (Debian) with 2 GB RAM where I run pm2 in order to execute a node.js server application. I have a cache and every night, at 3 am I want to dump it into a file as a backup.
Every day at 3, I got the following error:

<--- Last few GCs --->
[717119:0x63345b0] 66921944 ms: Mark-sweep 956.0 (1043.7) -> 954.9
(1043.7) MB, 737.3 / 0.0 ms  (average mu = 1.000, current mu = 0.349)
allocation failure; scavenge might not succeed [717119:0x63345b0]
66922975 ms: Mark-sweep 962.8 (1043.7) -> 961.9 (1059.7) MB, 978.0 /
0.0 ms  (average mu = 0.999, current mu = 0.052) allocation failure; scavenge might not succeed
<--- JS stacktrace --->
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap
out of memory  1: 0xb6e500 node::Abort() [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
2: 0xa7e632  [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
3: 0xd47f20 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char
const*, bool) [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
4: 0xd482c7
v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char
const*, bool) [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
5: 0xf25685  [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
6: 0xf37b6d
v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace,
v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node
/home/userName/web/appName.com/public_html/appNameServer/stoc> 7:
0xf1226e
v8::internal::HeapAllocator::AllocateRawWithLightRetrySlowPath(int,
v8::internal::AllocationType, v8::internal::AllocationOrigin,
v8::internal::AllocationAlignment) [node /home/userName/web/app> 8:
0xf13637
v8::internal::HeapAllocator::AllocateRawWithRetryOrFailSlowPath(int,
v8::internal::AllocationType, v8::internal::AllocationOrigin,
v8::internal::AllocationAlignment) [node /home/userName/web/stoc> 9:
0xef3b80 v8::internal::Factory::AllocateRaw(int,
v8::internal::AllocationType, v8::internal::AllocationAlignment) [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
10: 0xeeb5f4
v8::internal::FactoryBase<v8::internal::Factory>::AllocateRawWithImmortalMap(int,
v8::internal::AllocationType, v8::internal::Map,
v8::internal::AllocationAlignment) [node /home/userName/web/stoc>11:
0xeed988
v8::internal::FactoryBase<v8::internal::Factory>::NewRawTwoByteString(int,
v8::internal::AllocationType) [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
12: 0x131ddec v8::internal::IncrementalStringBuilder::Extend() [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
13: 0x10349d8
v8::internal::JsonStringifier::SerializeString(v8::internal::Handle<v8::internal::String>)
[node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
14: 0x1035c52 v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>15:
0x10378af v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>16:
0x10378af v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>17:
0x10378af v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>18:
0x10378af v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>19:
0x10378af v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>20:
0x10378af v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/di>21:
0x1037f13
v8::internal::JsonStringifier::SerializeJSReceiverSlow(v8::internal::Handle<v8::internal::JSReceiver>)
[node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
22: 0x1039897 v8::internal::JsonStringifier::Result
v8::internal::JsonStringifier::Serialize_(v8::internal::Handle<v8::internal::Object>,
bool, v8::internal::Handle<v8::internal::Object>) [node /home/d>23:
0x103ae5f v8::internal::JsonStringify(v8::internal::Isolate*,
v8::internal::Handle<v8::internal::Object>,
v8::internal::Handle<v8::internal::Object>,
v8::internal::Handle<v8::internal::Object>) [node /hom>24: 0xdcdbf7
v8::internal::Builtin_JsonStringify(int, unsigned long*,
v8::internal::Isolate*) [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]
25: 0x16e9af9  [node
/home/userName/web/appName.com/public_html/appNameServer/appNameServer.js]

I know the error is straight forward and the trivial answer would be to add more RAM, but I still want to share some more data:

*

*Before the crash, the app consumed 640mb (gross), meaning the cache itself consumes less than that.

*When I run this node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(1024*1024))' the result is 1662.

*When I run the caching dump locally, it takes around 3 seconds to export the items but viewing pm2 logs on the server, it takes 14 seconds between trying to export the cache items until the server is back up again, as if the export takes much longer or maybe the crash/restart takes that much, not sure.

2022-12-27T03:00:00.016Z: exporting to json 2|appName|

2022-12-27T03:00:14.747Z: server is running on https at port...

Based on the numbers above, 640mb (gross) and the fact that there's at least one more 1gb left for node, I don't understand why there's a heap out of memory in the first place.
Please advise, thanks

A: NODE_OPTIONS (--max_old_space_size)
In my case
$ node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(1024*1024))'
4144

but
$ export NODE_OPTIONS=--max_old_space_size=8192 && node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(1024*1024))'
8240

so maybe you can modify amount of available memory using this variable.
Writing file using buffer
Probably you are writing file using
fs.writeFileSync('/tmp/test.txt', content);

but maybe you can switch to
fs.createWriteStream(path, [options])

then you will not have to store all content of file in memory in the same time.
Profiling using IDE
I solved similar cases using tools like this:
https://www.jetbrains.com/help/webstorm/v8-cpu-and-memory-profiling.html#ws_node_cpu_profiling
in console you can simply start your script with --porf flag. It will created huge, hard to read, but very detailed logs telling about memory allocation.


text:
Q: Convert LPTSTR to long I am getting a compile error while I am trying to initialize a long variable.
long return_val;

HKEY register_key;
LPTSTR REGISTRY_KEY_FM =
#if FDK_LIBRARY_VERSION==0x13000000
            _T("RL13.FR.Document");
#elif FDK_LIBRARY_VERSION==0x09000000
            _T("RL9.FR.Document");
#elif FDK_LIBRARY_VERSION==0x08000000
            _T("RL80.FR.Document");
#endif

return_val = HKEY_CLASSES_ROOT, REGISTRY_KEY_FM, 0, KEY_QUERY_VALUE, &register_key);

The error message in the last line is "value of type "long" cannot be used to initialize an entity of type LPTSTR"
I am using Visual studio 2017 and also tried with visual studio 2013, but the error is same. However not getting the message in VS 2010. is there some type casting issue with the compiler of VS 2013 and VS2017? How to overcome this issue?

A: Your preprocessor dispatch is missing an #else.  When the library version isn't recognized, this is what you get:
LPTSTR REGISTRY_KEY_FM = return_val = /* something */;

and that tries to initialize an LPTSTR with a value of type long.
When you add the typeid for the new library version, also add these lines to prevent such problems in the future:
#else
#error Unsupported FDK_LIBRARY_VERSION


text:
Q: Category-dependent custom permalink My website uses a custom permalink structure of the type:
/blog/%year%/%monthnum%/%day%/%postname%/

Now, I created a new post category, which needs to have the permalink:
/guide/%postname%/

In order to do that, I added
function custom_permalink( $permalink, $post, $leavename)
    {
    if (has_category("Guide"))
        {
        $permalink = trailingslashit(home_url('/guide/'.$post->post_name.'/'));
        }
    return $permalink;
    }

add_filter('post_link', 'custom_permalink', 10, 3);

This works, in the sense that if I write:
www.mydomain.com/guide/somepage/

I am brought to the correct page. However the URL in the address bar changes back to /blog/yyyy/mm/dd/somepage.
How do I prevent the URL to change?


text:
Q: Given a list of tuples, return a string by concatenation def display(xs):
    string1 = ''
    for i in range(len(xs)):
        string1+=str(xs[i])+'-'
    return string1

Given a list of tuples as xs = [(2,3),(4,4),(5,5),(6,6)].Return this list as a string, by adding them up with dashes '-'.
So I wan to return a string that looks something like '(2,3)-(4,4)-(5,5)-(6,6)'.
What my code does is it correctly adds the dashes but the errors I am getting is that is doesn't read in the first value and it also ends up with an extra dash at the end.
My code returns a string that looks like '(4,4)-(5,5)-(6,6)-' which is wrong. I have shown my code above and need help fixing this.

A: You are on the right track. However, it'd be better to use .join() in this case to not append - to the last tuple in the list:
>>> def display(xs):
...    return "-".join(map(str, xs))

>>> display([(2,3),(4,4),(5,5),(6,6)])
'(2, 3)-(4, 4)-(5, 5)-(6, 6)'

If you don't want the whitespace between tuple items, you gotta format them yourself:
>>> def display(xs):
...     return "-".join("({},{})".format(*t) for t in xs)

>>> display([(2,3),(4,4),(5,5),(6,6)])
'(2,3)-(4,4)-(5,5)-(6,6)'

Here is the modified version of your function:
>>> def display(xs):
...     string1 = ""
...     for i in range(len(xs)):
...         string1 += str(xs[i])
...         if i != len(xs) - 1:
...             string1 += "-"
...     return string1


text:
Q: При использовании api.update_status_with_media выходит ошибка Создаю код для репоста с телеграмм канала в твиттер, но в 61 строке появляется ошибка. Что я сделал не так?
Ошибка:
Traceback (most recent call last):
File "twibot.py", line 61, in main
api.update_status_with_media(text, file)
UnboundLocalError: local variable 'file' referenced before assignment

Вот сам код:
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import tweepy

#настройка бота в твиттер
#введите соответствующую информацию из менеджера приложений Twitter:
CONSUMER_KEY = '...' #оставьте кавычки, а между ними добавьте ваш ключ
CONSUMER_SECRET = '...' # оставьте кавычки, а между ними добавьте ваш секретный ключ
ACCESS_TOKEN = '...' # оставьте кавычки, а между ними добавьте ваш токен доступа
ACCESS_SECRET = '...' # оставьте кавычки, а между ними добавьте ваш секретный токен доступа

#настройка телеграмм бота
CHANNEL_ID = "test_channel_for_bots_aiogram" # айди телеграмм канала, главное что бы вы добавили бота в канал

bot = Bot(token="5698093182:AAEEhrGntOmO14-ZepAy6Kw1YaBSBsOvW48") #токен бота

##############################
# дальше идёт код

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

api = tweepy.API(auth)

dp = Dispatcher(bot)

async def send_message(channel_id: int, text: str):
    await bot.send_message(channel_id, text)

@dp.channel_post_handler()
async def main(msg: types.Message):
    text = msg.text
    site = ('далее', f't.me/{CHANNEL_ID}')
    try:
      photo = msg.photo.file_id
      file = await bot.get_file(photo)
      file = file.file_path
      await bot.download_file(file, "photo.png")
      file = f"{file}\photo.png"
    except:
      photo = None
    try:
      video = msg.video.file_id
      file = await bot.get_file(photo)
      file = file.file_path
      await bot.download_file(file, "video.mp4")
      file = f"{file}\video.mp4"
    except:
      video = None

    if len(str(text)) < 280:
       text = text[:270] + text[270:] and f'... {site}'

    try:
       api.update_status_with_media(text, file)
    except:
      api.update_status(text)

if __name__ == '__main__':
    executor.start_polling(dp)

Если вы встретите ещё какие то ошибки то тоже покажите.
Заранее спасибо!!!


text:
Q: Stored procedure to insert 1st date to the end date of current month I have been trying to have a crack at this for some time now and I made some progress into figuring out to inserting the rest of the days from today to the end of the month but I'm having no luck to figuring out how to make it so that @start_date selects from the start of the current month. The stored procedure is as follows:
    BEGIN
    SET @start_date = NOW();
    SET @end_date = DATE_ADD(NOW(), INTERVAL 30 DAY);
    WHILE(@start_date< @end_date) DO
        INSERT INTO date (date) VALUES (@start_date);
        SET @start_date = DATE_ADD(@start_date, INTERVAL 1 DAY);
    END WHILE;
END

I'm hoping to get some explanation as to what is it that I need to replace the NOW() value to to make it so that it dynamically retrieves the start date of the current month? Of course hard coding the date works but since this stored procedure is meant to have a monthly routine, hard coding isn't the best applicable scenario. Thank you in advance!

A: Fixed it! To anyone who's having the same problem or something of the similar sort, here's my solution.
BEGIN
    SET @start_date = DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))-1 DAY);
    SET @end_date = DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH,'%Y-%m-01');
    WHILE(@start_date < @end_date) DO
        INSERT INTO date (date) VALUES (@start_date);
        SET @start_date = DATE_ADD(@start_date, INTERVAL 1 DAY);
    END WHILE;
END


text:
Q: Any way to automagically `puts` the last expression in a Ruby script? I'm working on implementing Project Euler solutions as semantic Ruby one-liners. It would be extremely useful if I could coerce Ruby to automatically puts the value of the last expression. Is there a way to do this? For example:
#!/usr/bin/env ruby -Ilib -rrubygems -reuler

1.upto(100).into {|n| (n.sum.squared - n.map(&:squared).sum)

I realize I can simply puts the line, but for other reasons (I plan to eval the file in tests, to compare against the expected output) I would like to avoid an explicit puts. Also, it allots me an extra four characters for the solution. :)
Is there anything I can do?

A: You might try running it under irb instead of directly under a Ruby interpreter.
It seems like the options -f --noprompt --noverbose might be suitable (.
#!/usr/bin/env irb -f --noprompt --noverbose -Ilib -rrubygems -reuler

'put your one-liner here'

The options have these meanings:

*

*-f: do not use .irbrc (or IRBRC)

*--noverbose: do not display the source lines

*--noprompt: do not prefix the output (e.g. with =>)

A: result of eval is last executed operation just like any other code block in ruby
is doing
puts eval(file_contents)

an option for you?
EDIT
you can make use of eval's second parameter which is variables binding
try the following:
do_not_puts = true
eval(file_contents, binding)

and in the file:
....
result = final_result
if defined?(do_not_puts)
  result
else
  puts(result)
end

A: result = calculate_result

puts result if File.exist?(__FILE__)

A: Is it an option to change the way you run scripts?
script.rb:
$_= 1.upto(100).into {|n| (n.sum.squared - n.map(&:squared).sum)

invoke with
echo nil.txt | /usr/bin/env/ruby -Ilib -rrubygems -reuler -p script.rb, where nil.txt is a file with a single newline.


text:
Q: Force a parent's height with hidden child element in CSS If I have a hidden child element (with either display: none or visibility: hidden), how can I have the parent div keeps it's height so that when the child is made visible, the parent height does not change?
Do I need to set an absolute height on the parent or can I still have it calculate its height from the child?

A: display:none removes the element from the flow, so no way to make the parent keept the height (other than hard-coding a fixed value). It should also hide it from screen readers and crawlers.
visiblity:hidden keeps the element in the flow, and therefore, keeps the space reserved for it, so the parent will keep the height just as if the element was visible.
opacity:0 will also act just like visibility:hidden, while allowing the reveal of the element to be transitioned / animated to opacity:1.
So you should use either visibility:hidden or opacity:0, depending on if you want to show the element in a jumpy reveal or transition.
Edit:
It should also be noted that visibility:hidden will not fire events (such as a click, hover, etc) while opacity:0 will. So there are even some rare cases on which you could use both together. For instance, if you want the element to start hidden, then show up with a transition, and have another event linked to it that should fire only when the element is visible
In the following example, there's a click event linked to the div element that will fire only when visible (so couldn't use just the opacity), but also have a transition when revealing (so couldn't use just visibility)

$('button').click(function() {
  $('.opacity').toggleClass("visible");
});

$('.opacity').click(function() {
  alert("clicked");
});
div {
    width: 100vw;
    height: 100vh;
    transition: opacity 1s ease;
    background: chartreuse;
}

.visibility{
  visibility:hidden;
}

.opacity{
  visibility:hidden;
  opacity:0;
}

.visible{
  opacity:1;
  visibility: visible;
}

<button>
toggle
</button>

 opacity:0

A: If you use visibility: hidden; to hide the child, space will still be reserved for it. You can show it again, by setting visibility: visible;.
To cite the MDN docs for visibility:

The visibility CSS property can show or hide an element without affecting the layout of a document (i.e., space is created for elements regardless of whether they are visible or not).


text:
Q: Roleprovider that supports hierarchical roles/permissions? I am building a web application that will have hierarchical roles.
For example, an admin, mod, user roles.
If a user was a moderator, and a .IsInRole("User") was done, then it would return true because mod is on top of user. There will also be a permissions table to have allow(true)/deny(false) for a variety of actions for the different roles.
There would also be different 'starting' roles that would branch down; admin2, mod2, user2, but a regular mod would not be considered a user2, only a regular user.
Are there any libraries that allow this type of role/permissions functions?

A: I would strongly look at using a claims based scheme instrad of roles.  However, my firat reaction would be to create a custom IPrincipal object, override the IsInRole method, and use bitwise flag enum for your roles (you know, 1, 2, 4, 8) values.
My open source project has a working implementation of claims based.
https://github.com/wcpro/scaffr-generated


text:
Q: iOS ARC ram grows up only Hello my question is maybe General I am not asking for code etc.
I developing only for iPhones with iOS6.1 and above
When I run my application the RAM it uses only grows up(when I switching between views (I have like 15 views)).
However after I ran test with analyzer it didn't find any leaks.
also no leaks were found in instrument leaks.
Despite my application doesn't exceed 20 mb of RAM I am still worried that something may be just not ok there.
I am using ARC ,but the ram still goes up.
Is there any way I can check what can cause 1 sided ram allocation ?

A: If the memory continues to go up, it could be a variety of different things, but "strong reference cycle" is the prime suspect. Sadly, this won't necessarily show up in Leaks tool in Instruments, either.
Do snapshots/generations in the Allocations tool and identify what's not getting released (notably if it consists of any of your classes) and go from there. Specifically, run the app through its paces, then mark snapshot/generation, do a bit more, and then mark another snapshot/generation. Look at that second snapshot and see what's been allocated (but not released) captured since the prior snapshot, with a focus on your classes. You'll find the culprit pretty quickly that way.
See WWDC video iOS App Performance: Memory for practical demonstration.

For example, here is a healthy app that I profiled through the Instruments' "Leaks" tool, but I'm going to focus on the "Allocations" tool:

In this profile, I waited for the app to quiet down, tapped on "Mark Generation" button (resulting with "Generation A", the first flag in my timeline). I then went to a view and then dismissed it, and did "Mark Generation" again, getting "Generation B". The "Growth" column is telling me that between Generation A and B, 100kb was consumed, but not released. But I'm not worried about this yet because there might be some iOS internal cache of UIKit elements. So, I repeat this process one more time to get  "Generation C". Now that's interesting, now reporting a growth of only 8.26kb, which is negligible. This, combined with a clean bill of health from the Leaks instrument makes me feel pretty good about the risk of any serious memory problems.
Now, let's contrast that with some code that has a seriously problematic "strong reference cycle":

Now this is a completely different picture, even though the process was the same "present and dismiss" process, repeated twice. This is now telling me that I had a 14mb growth between generations, and more notably, I can clearly see the problematic growth curve. What's remarkable is that while the Allocations tool is clearly catching a serious problem, the Leaks tool reports nothing.
Now, in practice, the real-world experience with the Allocations tool will probably rest somewhere between these two extremes. Your app may have its own caches or model objects that slowly take up memory, but if you're properly responding to memory warnings, you should be recovering that memory. Frankly, though, most well designed apps should not be generating memory warnings at all (usually accomplished by properly configuring caches, avoiding imageNamed where appropriate, moving to persistent storage for large or infrequently accessed data, etc.). The goal is to get to a point where the app stabilizes around some reasonable baseline memory allocation level, consistently returning back to that baseline.
But it's going to be impossible for us to advise you until you do some basic profiling of your app and diagnose the sorts of memory issues that you're having.


text:
Q: Outputting data from a table with count I'm trying to output data from the following table like this:
Level  1 - [Count Figure]
Level  2 - [Count Figure]
Level  3 - [Count Figure]
Level  4 - [Count Figure]
Level 10 - [Count Figure]

The Headings (Level 1 etc.) have to remain there, and are currently hard coded. I know how many different levels are there, so thats how.
My problem is, how do I detect which level it is and output it's count. I need all the levels there regardless of if there is a count or not.
If there no count figure from the database, then count'll read 0.
The way I'm doing it now is with case. I tried doing it with if(), but failed.
Problem with using case is that, if there's no count for a particular heading type if wont output the heading name, so I can print count as 0
Can you help?
Edit
I don't need to use switch. Anything else will do.
My code
function staticCountArticles($country){
global $conn;
    $countArticles = $conn->prepare('select count(id) as artcCount, artc_type from contributions where artc_status = 2 and artc_country = :country group by artc_type');
    $countArticles->bindParam(':country',$country);
    $countArticles->execute();
    $countArticles->bindColumn('artcCount',$artcCount);
    $countArticles->bindColumn('artc_type',$artcType);
    $hasArticles = $countArticles->rowCount();

    while( $artcData = $countArticles->fetch()) {
        switch($artcType){
            case 1:
            echo 'Level 1
';
            if($artcCount > 0){ echo $artcCount.'
';} else { echo 'Nothing here yet
';}
            break;

            case 2:
            echo 'Level 2
';
            if($artcCount > 0){ echo $artcCount.'
';} else { echo 'Nothing here yet
';}
            break;

            case 3:
            echo 'Level 3
';
            if($artcCount > 0){ echo $artcCount.'
';} else { echo 'Nothing here yet
';}
            break;

            case 4:
            echo 'Level 4
';
            if($artcCount > 0){ echo $artcCount.'
';} else { echo 'Nothing here yet
';}
            break;

            case 10:
            echo 'Level 10
';
            if($artcCount > 0){ echo $artcCount.'
';} else { echo 'Nothing here yet
';}
            break;

            default:
            echo 'Unidentified type encountered
';
        }
    }
}

Data
"id"    "artc_type" "artc_status"   "artc_user" "artc_country"
"1"     "1"         "2"             "1"         "US"
"2"     "1"         "2"             "1"         "US"
"3"     "1"         "2"             "1"         "US"
"4"     "2"         "2"             "2"         "US"
"5"     "2"         "2"             "2"         "US"
"6"     "2"         "2"             "2"         "US"
"7"     "4"         "2"             "2"         "US"
"8"     "4"         "2"             "3"         "US"
"9"     "4"         "2"             "3"         "US"
"10"    "10"        "2"             "3"         "US"
"11"    "10"        "2"             "4"         "US"
"12"    "10"        "2"             "4"         "US"
"13"    "10"        "2"             "4"         "US"
"14"    "10"        "2"             "4"         "US"

A: Try this approach instead. Instead of trying to print the results as you go, we init all counts to 0 and store them in an output array. For output, we loop through the array printing the data. This allows you to print even the 0 values as they wouldn't have been changed by the processing of the DB data
function staticCountArticles($country){
    global $conn;
    $countArticles = $conn->prepare('select count(id) as artcCount, artc_type from contributions where artc_status = 2 and artc_country = :country group by artc_type');
    $countArticles->bindParam(':country',$country);
    $countArticles->execute();
    $countArticles->bindColumn('artcCount',$artcCount);
    $countArticles->bindColumn('artc_type',$artcType);
    $hasArticles = $countArticles->rowCount();

    // Init our output array
    $output = Array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 10 => 0);

    while( $artcData = $countArticles->fetch()) {
        if($artcCount > 0) $output[$artcType] = $artcCount;
    }

    // Print the results
    foreach($output as $level => $item)
    {
        echo 'Level '.$level.'
';
            if($item > 0){ echo $item.'
';} else { echo 'Nothing here yet
';}
    }
}


text:
Q: Using regression instead of classification for multi class classification I have a multi class classification problem. I am using random forest classifier. My boss has asked if it is possible to also view our problem with regression. I understand that for a classification task, it is of course better to use a classifier, but is it possible to implement a regression model.
My data is as such:
I have a dataset consisting of software requirements, these are rated as either 1, 2, 3, 4 or 5.
I am then creating a feature matrix to use for training the model to make predictions on the class, with 10 features such as: num_words, num_sentences, num_syllables, weak_words, flesh_idx etc
My model works quite well with 93% accuracy.
Is there a way I can view this problem using regression? Such that the model would make predictions such as 1.5 for example, where the prediction doesn't fall into the class 1 or 2 but somewhere in the middle? Or maybe 2.2, 3.3 etc as opposed to 1, 2, 3, 4, or 5?
I guess the reason is just to see if we can see the software requirement scores in a continuous way.

A: try Softmax regression (or multinomial logistic regression) with mxnet or  with tensorflow

A: The way you can use regression in classification problems is with Logistic Regressions. You can use this individually to classify 1 vs not 1, 2 vs not 2, and so on for each classification (don't do this), or use Softmax that in simple words, weights each class and returns a probability for each given class, then you just pick the one with the max probability and that will be your predicted class. There are a lot of neural networks that use softmax when working with mutli-class classification.
Here is a great article from scikit-learn's documentation:
https://scikit-learn.org/stable/modules/neural_networks_supervised.html


text:
Q: Reading AppSettings From subsites web.config I have a a subsite placed in my Default website. In the subsite I want to store variables in it's web.config.
However, whenever I try to retrieve the values, they don't exist in the ConfigurationManager.AppSettings.
I have put the website as a website application and created it as virtual directory in IIS, no success...
Does anyone have ane idea?
Thanks!
(btw, I'm using .NET 3.5 and IIS Manager 6)

A: just FYI your subsites are called Virtual Diretories
in the web.config all you need to do is add this into the file:
<configuration>
  <appSettings>
    <add key="myVar1" value="myValue1" />
    <add key="myVar2" value="myValue2" />
  </appSettings>
</configuration>

the <appSettings> is a simple NameValueCollection that you can itenerate in your code like:
NameValueCollection appSettings = ConfigurationManager.AppSettings;

for (int i = 0; i < appSettings.Count; i++)
{
  Console.WriteLine("#{0} Key: {1} Value: {2}",
    i, appSettings.GetKey(i), appSettings[i]);
}

Is this what you are doing?

A: Nevermind,
I've fixed my own issue.
I was using URL Rewrite which caused the server to get a bit confused about the actual location of my project.


text:
Q: Wordpress Slider with rotation animation Does anyone know what this slider?
https://www.crescentheights.com
If you look at the header slider it's kinda rotating with highlights.
Your help is really appreciated.
Thanks.

A: The slider at your example url is powered by FlatFolio from UnCommons. It's available to buy through CodeCanyon.
https://codecanyon.net/item/flatfolio-flat-cool-wp-portfolio/9294349


text:
Q: How to Store Files Locally in Sencha Touch2? How to Store File in Offline in Sencha touch,,,
How to Use database i Sencha Touch Support Daatabase Connectivity?...
I use
 requires:['Ext.data.identifier.Uuid','Ext.data.proxy.Sql',],
    config: {

         identifier: {
    type: 'uuid'
},

      fields: [
         "firstName",
         "lastName",
         {
            name: "dateAdded",
            type: "date",
            defaultValue: new Date()
         }
      ],
      proxy: {
        type: "sql"
      }
    }
 });

Like this but error in sql.js file not Found error...
can any one Help me...

A: Here is what I understand
You normally store data via SQL Proxy (online), but you would like to manage to store data even if you are offline.
Fact is, I don't think you can use SQL to save data offline.
I think you will need to save data in Local Storage under a format you will "developt" and on App's opening and connection established read from that storage and force push an update from the local storage to the sql database.
The best I guess would to serialize you SQL data, save it to local storage, and unserialize when you can push it to the database.


text:
Q: Use the same parameters many times in a find conditions: hash I have a model who holds 2 properties: valid_from and valid_to.
I need to select all instances that are currently valid, i.e. valid_from <= today and valid_to >= today.
i have the following find :
Mymodel.find(:all, :conditions => ["valid_from <= ? and valid_to >= ?", Date.today, Date.today])

I already thought about storing Date.today in a variable and calling that variable, but i still need to call it twice.
my_date = Date.today
Mymodel.find(:all, :conditions => ["valid_from <= ? and valid_to >= ?", my_date, my_date])

Is there a way to improve and do only one call to the variable to match all the "?" in the :conditions ?
thanks,
P.

A: I would use named_scope. In model add:
named_scope :valid,
            :conditions =>
             ["valid_from <= ? and valid_to >= ?", Date.today, Date.today]

And then in your controller you can call:
@mymodels = Mymodel.valid

I think that focusing on reducing two calls to Date.today to only one call is wasting of time. It won't make your application faster or using less memory.

A: I'm not aware of a way to do what you're asking, but even if you could I don't think it would buy you much. I would create a named scope within your model class.
In this example, you can pass the date to the named scope, or it will default to today's date if no date is specified:
named_scope :by_valid_date, lambda { |*args|
            { :conditions => ["valid_from <= ? and valid_to >= ?",
              (args.first || Date.today), (args.first || Date.today)]} }


text:
Q: Comparing data in previous row using shift() function I am working with monthly Citi bike trip data that looks like this:

> head(data)
  tripduration           starttime            stoptime start.station.id       start.station.name end.station.id
1          732 2015-07-01 00:00:03 2015-07-01 00:12:16              489         10 Ave & W 28 St            368
2          322 2015-07-01 00:00:06 2015-07-01 00:05:29              304    Broadway & Battery Pl           3002
3          790 2015-07-01 00:00:17 2015-07-01 00:13:28              447          8 Ave & W 52 St            358
4         1228 2015-07-01 00:00:23 2015-07-01 00:20:51              490          8 Ave & W 33 St            250
5         1383 2015-07-01 00:00:44 2015-07-01 00:23:48              327 Vesey Pl & River Terrace             72
6          603 2015-07-01 00:01:00 2015-07-01 00:11:04              455          1 Ave & E 44 St            367
               end.station.name bikeid   usertype birth.year gender
1            Carmine St & 6 Ave  18669 Subscriber       1970      1
2    South End Ave & Liberty St  14618 Subscriber       1984      1
3 Christopher St & Greenwich St  18801 Subscriber       1992      1
4      Lafayette St & Jersey St  19137 Subscriber       1990      1
5              W 52 St & 11 Ave  15808 Subscriber       1988      1
6       E 53 St & Lexington Ave  17069 Subscriber       1953      1

Each trip has it's own unique record, and only for the month of July there are some 1,085,676 trips.  The raw data in .csv format can be found here on the Citi Bike website.  Normally, bikes start from the station where they ended on the previous trip.  However, this is not always the case.  Sometimes bikes will start at different station than where they ended, which indicates the bikes were "rebalanced" or moved by a truck from one station to the next to meet station demands.  I want to filter out all of the "normal" trips and isolate all of the instances where the bikes started at a different station than where they ended (e.g. start.station.id is not equal to previous end.station.id.)  The unique identifying factor of bikes is bikeid, and this must be used.  Here is a subset of the month's data by one bikeid (the most frequently ridden bike):

head(onebike)
     tripduration           starttime            stoptime start.station.id     start.station.name
1952          691 2015-07-01 07:23:24 2015-07-01 07:34:56              161  LaGuardia Pl & W 3 St
2369          332 2015-07-01 07:38:49 2015-07-01 07:44:22              379        W 31 St & 7 Ave
3879          259 2015-07-01 08:14:34 2015-07-01 08:18:54              472     E 32 St & Park Ave
4310         1112 2015-07-01 08:22:53 2015-07-01 08:41:25              498     Broadway & W 32 St
5795         1509 2015-07-01 08:47:18 2015-07-01 09:12:27              345        W 13 St & 6 Ave
7857         1361 2015-07-01 09:23:50 2015-07-01 09:46:32              348 W Broadway & Spring St
     end.station.id       end.station.name bikeid   usertype birth.year gender
1952            379        W 31 St & 7 Ave  22075 Subscriber       1985      1
2369            472     E 32 St & Park Ave  22075 Subscriber       1986      1
3879            498     Broadway & W 32 St  22075 Subscriber       1986      1
4310            345        W 13 St & 6 Ave  22075   Customer         NA      0
5795            348 W Broadway & Spring St  22075   Customer         NA      0
7857            386   Centre St & Worth St  22075   Customer         NA      0

 The task is now to select instances where the start.station.id of a row does not equal end.station.id of the previous row.
The result should contain the bikeid, the end.station.id, the start.station.id, and the time difference between when the bike was dropped off and picked up (indicating approximately when it was moved).
Is the best way to do this to use the shift() function?
How would one loop through every bike.id in the first dataset (there are about 7000) to reveal all of the hidden movements?

A: I am sure there are hundreds of ways to do this, but since the data is only around 100MB, a simple for loop is very capable and very flexible to modify and extend in this case, so here it is (done in seconds):
raw_data = read.csv("201511-citibike-tripdata.csv")
bikeid <-22075
onebike <- raw_data[ which(raw_data$bikeid== bikeid), ]
output <- data.frame("bikeid"= integer(0), "end.station.id"= integer(0), "start.station.id" = integer(0), "diff.time" = numeric(0))

for(i in 2:nrow(onebike)) {
  if(onebike[i-1,"end.station.id"] != onebike[i,"start.station.id"]){
    diff_time <- as.double(difftime(strptime(onebike[i-1,"stoptime"], "%m/%d/%Y %H:%M:%S"),
                                    strptime(onebike[i,"starttime"], "%m/%d/%Y %H:%M:%S"),units = "mins"))
    new_row <- c(bikeid, onebike[i-1,"end.station.id"], onebike[i,"start.station.id"], diff_time)
    output[nrow(output) + 1,] = new_row
  }
}
output

bikeid end.station.id start.station.id diff.time
1  22075            514              520  181.5667
2  22075            356              502  628.8833

Edit: This is to further answer the question in the comments.
It is an easy extension to include all the bikeids:
raw_data = read.csv("201511-citibike-tripdata.csv")
unique_id = unique(raw_data$bikeid)
#bikeid <-22075

output <- data.frame("bikeid"= integer(0), "end.station.id"= integer(0), "start.station.id" = integer(0), "diff.time" = numeric(0),  "stoptime" = character(),"starttime" = character(), stringsAsFactors=FALSE)

for (bikeid in unique_id)
{
onebike <- raw_data[ which(raw_data$bikeid== bikeid), ]

if(nrow(onebike) >=2 ){
for(i in 2:nrow(onebike )) {
  if(is.integer(onebike[i-1,"end.station.id"]) & is.integer(onebike[i,"start.station.id"]) &
     onebike[i-1,"end.station.id"] != onebike[i,"start.station.id"]){
    diff_time <- as.double(difftime(strptime(onebike[i,"starttime"], "%m/%d/%Y %H:%M:%S"),
                                    strptime(onebike[i-1,"stoptime"], "%m/%d/%Y %H:%M:%S")
                                    ,units = "mins"))
    new_row <- c(bikeid, onebike[i-1,"end.station.id"], onebike[i,"start.station.id"], diff_time, as.character(onebike[i-1,"stoptime"]), as.character(onebike[i,"starttime"]))
    output[nrow(output) + 1,] = new_row
  }
}
}
}
dim(output)
[1] 32589     6
head(output)
  bikeid end.station.id start.station.id        diff.time           stoptime          starttime
1  22545            520              529 24.8166666666667 11/2/2015 08:38:22 11/2/2015 09:03:11
2  22545            520              517 537.483333333333 11/2/2015 09:39:19 11/2/2015 18:36:48
3  22545           2004             3230 563.066666666667 11/2/2015 22:06:27 11/3/2015 07:29:31
4  22545            296             3236 471.783333333333 11/4/2015 23:40:29 11/5/2015 07:32:16
5  22545            520              449 43.4166666666667 11/9/2015 08:24:06 11/9/2015 09:07:31
6  22545            359              519 30.7166666666667 11/9/2015 09:14:46 11/9/2015 09:45:29


text:
Q: Creating directories in remote PC using Java I need to create a directory in another PC using Java, so I used FILE class,
my code structure is
    String path = "\\\\192.148.64.99"+File.separator+"D:"+File.separator+"hello";

    String fname= path+File.separator+"Sample.pdf";
    File file = new File(fname);
    System.out.println("Exists"+file.exists());
    file.getParentFile().mkdirs();

This throwing error.

A: D: in the path you are constructing is not valid. You could use D$ instead if you are admin on the remote machine.
Path should be \\MachineName\ShareName\Folder\SubFolder...


text:
Q: Property 'findAncestors' does not exist on type 'Repository ' Hi i have a problem with my typeorm code.
I followed the example from here: https://github.com/typeorm/typeorm/blob/master/docs/tree-entities.md#materialized-path-aka-path-enumeration.
So my entity looks like:
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    CreateDateColumn,
    UpdateDateColumn,
    Tree,
    TreeChildren,
    TreeParent,
} from 'typeorm';

@Entity()
@Tree('materialized-path')
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @TreeChildren()
    children: Category[];

    @TreeParent()
    parent: Category;

    @CreateDateColumn({
        type: 'timestamp',
        default: () => 'CURRENT_TIMESTAMP(6)',
    })
    public createdAt: Date;

    @UpdateDateColumn({
        type: 'timestamp',
        default: () => 'CURRENT_TIMESTAMP(6)',
        onUpdate: 'CURRENT_TIMESTAMP(6)',
    })
    public updatedAt: Date;
}

In my controller called 'CategoryController' i want to get the whole tree, but i get an error that 'findAncestors' not exists.
import {  getRepository } from 'typeorm';
import {Category} from "../entity/Categories";

export class CategoryController {
    private categoryRepository = getRepository(Category);

    async getCategoryTreeBySingleCategory(category:Category|string){
        {...}
        return await this.categoryRepository.findAncestors(category); // <--- Property 'findAncestors' does not exist on type 'Repository '.
    }
}

Does someone know why and may help me?
Thanks in advance!

A: The member function findAncestors is only defined on type TreeRepository which you get by using getTreeRepository instead of getRepository.
Therefore write
import {  getRepository } from 'typeorm';
import {Category} from "../entity/Categories";

export class CategoryController {
    private categoryRepository = getTreeRepository(Category);

    async getCategoryTreeBySingleCategory(category:Category|string){
        {...}
        return await this.categoryRepository.findAncestors(category);
    }
}

A: If someone is facing a problem when he writes:
Category.find()
and get error find() is not defined or something like that then,
Import BaseEntity from typeorm
export class Category extends BaseEntity


text:
Q: google maps infowindow.close() case in separate function I want to make infowindow-making process in the different function, cause it`s gonna contains much info.
I have a global-defined var infowindow = new google.maps.InfoWindow({});
when im trying to close it in the separate function, infowindow.close() method doesnt works.
Can`t get, wat is wrong here? the infowindow object is successfully passed into the function, cause new infowindows creating successfully
Here is a full code

var locations = [
    ['Bondi Beach', -33.890542, 151.274856, 4],
    ['Coogee Beach', -33.923036, 151.259052, 5],
    ['Cronulla Beach', -34.028249, 151.157507, 3],
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
    ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var markers = [];

///////////
///markers initialization
///////////
function initialize() {
    var myLatlng = new google.maps.LatLng(-33.923036, 151.259052);
    var mapOptions = {
        zoom: 11,
        center: myLatlng
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var num_markers = locations.length;

    //set infowindow global to prevent multiply opening
    var infowindow = new google.maps.InfoWindow({});
    for (var i = 0; i < num_markers; i++) {
        markers[i] = new google.maps.Marker({
            position: {lat:locations[i][1], lng:locations[i][2]},
            map: map,
            id: locations[i][3]
        });

        //here is a special stuff to pass iterator
        google.maps.event.addListener(markers[i], 'click', (function(i,infowindow, map) {
            return function() {
                MakeContent(i,infowindow, map);
            }
        })(i,infowindow, map));

    }
}

google.maps.event.addDomListener(window, 'load', initialize);

function MakeContent(i,infowindow, map){

    var contentString = '
'+
        '
'+
        '
'+
        '
Uluru
'+
        '
'+
        '
Uluru Hop, also referred to as Ayers Rock, is a large ' +
        'sandstone rock formation in the southern part of the '+
        'Northern Territory, central Australia. It lies 335 km (208 mi) '+
        'south west of the nearest large town, Alice Springs; 450 km '+
        '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
        'features of the Uluru - Kata Tjuta National Park. Uluru is '+
        'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
        'Aboriginal people of the area. It has many springs, waterholes, '+
        'rock caves and ancient paintings. Uluru is listed as a World '+
        'Heritage Site.
'+
        '
Attribution: Uluru, '+
        'https://en.wikipedia.org/w/index.php?title=Uluru '+
        '(last visited June 22, 2009).
'+
        '
'+
        '
';

        infowindow.close();
        infowindow = new google.maps.InfoWindow({
           id: markers[i].id,
           content:contentString,
           position:new google.maps.LatLng(locations[i][1],locations[i][2])
        });
        infowindow.open(map, markers[i]);
}

A: The infowindow is local to the initialize function. Make it global (define it outside of any function).  Probably simpler to reuse the existing infowindow than recreate it.
proof of concept jsfiddle

var locations = [
    ['Bondi Beach', -33.890542, 151.274856, 4],
    ['Coogee Beach', -33.923036, 151.259052, 5],
    ['Cronulla Beach', -34.028249, 151.157507, 3],
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
    ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var markers = [];
var infowindow = new google.maps.InfoWindow({});
///////////
///markers initialization
///////////
function initialize() {
    var myLatlng = new google.maps.LatLng(-33.923036, 151.259052);
    var mapOptions = {
        zoom: 11,
        center: myLatlng
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var num_markers = locations.length;

    //set infowindow global to prevent multiply opening

    for (var i = 0; i < num_markers; i++) {
        markers[i] = new google.maps.Marker({
            position: {lat:locations[i][1], lng:locations[i][2]},
            map: map,
            id: locations[i][3]
        });

        //here is a special stuff to pass iterator
        google.maps.event.addListener(markers[i], 'click', (function(i,infowindow, map) {
            return function() {
                MakeContent(i, map);
            }
        })(i,infowindow, map));

    }
}

google.maps.event.addDomListener(window, 'load', initialize);

function MakeContent(i, map){

    var contentString = '
'+
        '
'+
        '
'+
        '
Uluru
'+
        '
'+
        '
Uluru Hop, also referred to as Ayers Rock, is a large ' +
        'sandstone rock formation in the southern part of the '+
        'Northern Territory, central Australia. It lies 335 km (208 mi) '+
        'south west of the nearest large town, Alice Springs; 450 km '+
        '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
        'features of the Uluru - Kata Tjuta National Park. Uluru is '+
        'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
        'Aboriginal people of the area. It has many springs, waterholes, '+
        'rock caves and ancient paintings. Uluru is listed as a World '+
        'Heritage Site.
'+
        '
Attribution: Uluru, '+
        'https://en.wikipedia.org/w/index.php?title=Uluru '+
        '(last visited June 22, 2009).
'+
        '
'+
        '
';

        infowindow.close();
        infowindow.setMap(null);
        infowindow = new google.maps.InfoWindow({
           id: markers[i].id,
           content:contentString,
           position:new google.maps.LatLng(locations[i][1],locations[i][2])
        });
        infowindow.open(map, markers[i]);
}
html, body, #map-canvas {
    height: 500px;
    width: 500px;
    margin: 0px;
    padding: 0px
}


text:
Q: como seleccionar el elemento hijo sobre el que se hace un mouseover Estoy intentando mostrar un elemento oculto dentro de una lista, debería mostrarse al pasar el ratón por encima del elemento padre pero no se como seleccionar ese elemento sin seleccionarlos todos, aqui dejo el ejemplo. Gracias.

$(document).on('mouseover', '.sent > p', function (e) {
    let a = e.firstElementChild;
    $(a).fadeIn();
  });
$(document).on('mouseleave', '.sent > p', function (e) {
    let a = e.firstElementChild;
    $(a).fadeOut();
  });
.sent{
   background: #44494fff;
   border-radius: 15px;
   width: -moz-max-content;
   height: -moz-max-content;
   min-width: 30px;
   vertical-align: middle;
   padding:0 15px;
   list-style: none;
   color: #fff;
}
.action{
   border: 1px solid #0000004d;
   background: #44494c;
   cursor: pointer;
   display: none;
}

primer hijo boton

primer hijo boton

primer hijo boton

A: El error está en tu selector
Recuerda que e es solo el evento, para obtener el elemento tienes que usar e.target
En cuanto al selector, hay que cambiarle de document a .sent porque es el elemento que vamos a modificar

$(".sent").on('mouseover', function (e) {
    $(e.target).find(".action").fadeIn();
});

$(".sent").on('mouseleave', function (e) {
    $(e.target).find(".action").fadeOut();
});
.sent{
   background: #44494fff;
   border-radius: 15px;
   width: -moz-max-content;
   height: -moz-max-content;
   min-width: 30px;
   vertical-align: middle;
   padding:0 15px;
   list-style: none;
   color: #fff;
}
.action{
   border: 1px solid #0000004d;
   background: #44494c;
   cursor: pointer;
   display: none;
}

primer hijo boton

primer hijo boton

primer hijo boton


text:
Q: way to ignore intermediate column in an INSERT SELECT statement? For a insert ... select statement, is there a way to ignore a variable that is required for the select statement but should be inserted?
I'm using a rank function to select which data to insert. Unfortunately the rank function can't be called in the where clause.
insert into target_table(v1
                        ,v2
                        ,v3
                        )
select v1
      ,v2
      ,v3
      ,RANK() over (partition by group_col
                    order by order_col desc
                   ) as my_rank
from source_table
where my_rank > 1

The result is the following error:

Msg 121, Level 15, State 1, Line 1 The select list for the INSERT
  statement contains more items than the insert list. The number of
  SELECT values must match the number of INSERT columns.

I know I can do this using a temporary table but would like to keep it in a single statement if possible.

A: Wrap your main query inside a subquery.
INSERT INTO target_table
    (v1, v2, v3)
    SELECT q.v1, q.v2, q.v3
        FROM (SELECT v1, v2, v3,
                     RANK() OVER (PARTITION BY group_col ORDER BY order_col DESC) AS my_rank
                  FROM source_table) q
        WHERE q.my_rank > 1;

For SQL Server 2005+, you could also use a CTE:
WITH cteRank AS (
    SELECT v1, v2, v3,
           RANK() OVER (PARTITION BY group_col ORDER BY order_col DESC) AS my_rank
        FROM source_table
)
INSERT INTO target_table
    (v1, v2, v3)
    SELECT v1, v2, v3
        FROM cteRank
        WHERE my_rank > 1;


text:
Q: MobX Store Responsibilities I recently started working on a project with MobX. I never used MobX before so I am quite confused about one thing.
What are MobX store responsibilities?
1) Should MobX @action, @computed return html/jsx? In official 10 minutes MobX tutorial https://mobx.js.org/getting-started.html there is a @computed get report. That is just an example right?
@computed get report() {
    if (this.todos.length === 0)
        return "<none>";
    return `Next todo: "${this.todos[0].task}". ` +
        `Progress: ${this.completedTodosCount}/${this.todos.length}`;
}

2) Is it a good idea to call API in @action? Like this?
@action
submitProfileInformation = params => {
  return post("apiendpoint", {
    body: params
  }).then(resp => {
    this.firstName = resp.first_name;
    return "ok";
  });
};

I come from the redux world and the way I see it store should only store and mutate values. Actions would react component let know that something has changed so that they would rerender. Is that correct?

A: *

*It doesn't return any html or jsx. It's just a sample and it returns only string.

*Only the then section should be marked as action.

Concepts are the same. It's up to you to follow the best practices or abusing flexiblity of mobx and doing bad things.
I recommand you to read this article:
https://mobx.js.org/best/store.html

A: MobX store is for storing application states, including observable and non-observable data. (similar to Redux Stores, although Redux doesn't have observable)
MobX actions are any functions that modify the observable data. There's no rule saying that you must put actions in store, but it's good practice to do so.
For you question: Actions would react component let know that something has changed so that they would rerender. Answer is yes and no. Actions are functions that modify observable data. Your observer components react to changes of observable data, not action functions. But since actions always modify observable data, so calling an action function should trigger observer components to react.
@computed decorator simply creates observable data that is computed from other observable data (similar to getter functions)


text:
Q: How do I get something like repeat customers in Django My models look something like this:
class Customer(models.Model):
   name = models.CharField(max_length=100)

class Order(models.Model):
   customer = models.ForeignKey(Customer)
   date = models.DateField()
   total = models.DecimalField(max_digits=5, decimal_places=2)

I then have a queryset of orders:
from datetime import datetime

start_date = datetime(year=2009, month=6, day=1)
end_date = datetime(year=2009, month=11, day=1)
orders = Order.objects.filter(date__lte=end_date).filter(date__gte=start_date)

Now, I want to find out which customers made multiple orders between those times, how many orders they made, and what their average total is.  I get the feeling that I should be using Django 1.1's new aggregation features, but I can't really wrap my head around it.

A: Always base your query around the object in which you are primarily interested in:
repeat_customers = Customer.objects.annotate(order_count=Count('order'))\
                                   .filter(order_count__gt=1)

Then if you want to annotate with their totals (you could alternatively do this in the annotation above, I'm just separating the code for readability):
repeat_customers = repeat_customers.annotate(avg_total=Avg('order__total'))

A: This would be a good use for Django 1.1's annotate() functionality, which is part of aggregateion.  Specifically, you'll probably want to use the values() function.


text:
Q: How to preserve spaces in text input field when echoing php variable I've got:
<input type="text" name="location" value=<?php echo $cand['location']; ?>>

When $cand['location'] is something like "East London", the textbox just says "East" and ignores anything after the first space.
How can I have a text input hold echoed strings with spaces in it?

A: solved:
<input type="text" name="location" value="<?php echo $cand['location']; ?>">


text:
Q: Accessing "hidden" windows in AppleScript I'm trying to set up an applescript which will handle a slightly-annoying VPN login process for me. I use Cisco AnyConnect, and every time I have to log back on, I have to hit connect, accept a certificate warning, enter my username, password, and select the right group, and accept ANOTHER certificate warning.
It's that second certificate warning I can't seem to get around.
Some digging indicates that the warning dialog is owned by a process named vpndownloader, but the odd thing is that Applescript seems convinced that it has no windows and does not exist!
I've been using Accessibility Inspector to get the window IDs and such to make this script work. For this particular dialog, it looks like this (accessibility inspector behind the actual dialog I'm attempting to control)

The strangeness comes in when I try to get the window's ID so I can do things with it.
tell application "System Events" to windows of process "vpndownloader"

{}

Blank. Okay, maybe there's something useful in the properties of the process?
tell application "System Events" to properties of process "vpndownloader"

{has scripting terminology:false
 bundle identifier:"com.yourcompany.vpndownloader"
 file:alias "Macintosh HD:opt:cisco:anyconnect:bin:vpndownloader.app:" of application "System Events"
 creator type:"????"
 subrole:missing value
 entire contents:{}
 selected:missing value
 application file:alias "Macintosh HD:opt:cisco:anyconnect:bin:vpndownloader.app:" of application "System Events"
 orientation:missing value
 role:"AXApplication"
 accepts high level events:true
 file type:"APPL"
 value:missing value
 position:missing value
 id:1212712
 displayed name:"vpndownloader"
 name:"vpndownloader"
 class:application process
 background only:true
 frontmost:false
 size:missing value
 visible:false
 Classic:false
 partition space used:0
 role description:"application"
 maximum value:missing value
 architecture:"i386"
 short name:"vpndownloader"
 focused:missing value
 minimum value:missing value
 help:missing value
 title:"vpndownloader"
 accepts remote events:false
 total partition size:0
 description:"application"
 accessibility description:missing value
 enabled:missing value
 unix id:9053}

(for giggles, note that Cisco didn't set their bundle identifier..)
No contents, no visible windows. Despite the dialog I've got up right in front of me.
So, on one hand it obviously has a window (accessibility inspector can see it), but AppleScript is convinced that it does not.
How do I programmatically locate and access this "phantom" dialog?
Things that didn't work:
tell application "vpndownloader" to windows

error "vpndownloader got an error: Can't get every window." number -1728 from every window

Again the theme of this application being in a weird state between existence and nonexistence comes up
tell application "vpndownloader" to properties

error "vpndownloader got an error: Can't get every property." number -1728 from every property

It has a menu bar, but no windows.
tell application "System Events" to get UI elements of process "vpndownloader"

{menu bar 1 of application process "vpndownloader" of application "System Events"}

A: You can probably just use keystrokes. For example when that window comes up you yourself can probably physically hit the "connect anyway" button by first pressing the "tab" key to change the focussed button and then press the "space bar" to select the focussed button.
NOTE: you may have to enable this functionality by enabling full keyboard access. Do this by going to system preferences->keyboard->shortcuts and checking "all controls" at the bottom of the window.
If you can then you can applescript it. The following will work as long as that window is frontmost when you issue the commands.
tell application "System Events"
    keystroke tab
    delay 0.2
    keystroke space
end tell

Good luck.

A: It works for me (I use anyconnect 3.1.06073).
https://gist.github.com/lotreal/ce43f4a85d8ae73781fa

A: So I found an interesting workaround for this problem that doesn't involve scripting. It turns out the vpndownloader is entirely optional, and it apparently only serves the purpose of updating the client when an update is pushed from the upstream server
A local policy XML can be defined to disable the process. This will cause breakage if an update is pushed (the connection will just abort), but it at least allows the login to be scripted.
On Mac/Linux systems, this file is located in /opt/cisco/anyconnect/AnyConnectLocalPolicy.xml - I had to create one based on the schema file, AnyConnectLocalPolicy.xsd in the same folder. If it already exists, just edit the existing one.
The key line is <BypassDownloader>, which is set to false by default. Setting it to true means that the downloader is simply not run, meaning the second dialog I was trying to access simply never appears!


text:
Q: Can I attach an action to a buttonclick? If i have a button, can I attach an action to it to perform server side processing, or does it have to be wrapped in a form?
For example
<button type="submit" onClick="listco_directory_contents.js"> List </button>

Can this be made to work, or is a form required?

A: You can't have a type="submit" if it's not in a form, there is nothing to submit. What you can do, is having a <button id="myButton">, then attach an event to it:
var myButton = document.selectElementById('myButton');
myButton.addEventListener('click', function() {
  /* do something cool */
}, false);

And the "do something cool" could be an Ajax request so you send data to the server.

A: You can yes but if your aiming to do server side processes i recommend the jquery way.
<!--this button uses javascript-->
<input type="button" onclick="myfunction()" value="button"/>

<!--this button uses jquery-->
<input type="button" id="myfunction" value="button"/>

<script>
//javascript function using the onclick event
function myfunction(){
    alert("an action");
    // or any other function u wish to
    // do once the button is click
}

//jquery using the id of the button
$(document).ready(function(){
    $("#myfunction").click(function(){
        alert("another action");
        // or any other function u wish to
        // do once the button is click
    });
});
</script>

A: You could also just include the js:
<script type="text/javascript" src="listco_directory_contents.js"></script>

and then call whatever function you need from there:
<button onClick="exampleFunction()"> List </button>

Or in case you want to do server side processing with php you can do simply:
<button onClick="$.post('http://example.com/index.php');"> List </button>

A: $(function(){
 $(':submit').on('click',function(){
  alert('hi');
 })
})

also can be type=submit
$(function(){
 $('input[type="submit"]').on('click',function(){
  alert('hi');
 })
})

DEMO


text:
Q: Using write() to create a temporary file in C For homework I have to read from the standard input, save it to a file and then read the file in another process. However, I'm confused as to why this code does not work:
    while((n = read(0,buf,sizeof(buf))) > 0) {
        int tempfile = open("testfile", O_TRUNC | O_CREAT, 0666);
        write ( tempfile , buf , sizeof(buf) );
        close(tempfile);
        process("testfile");
    }

I'm not supposed to use any stdio stuff.
When I look at the file I've created, it has 0 bytes and yet the buffer itself has the correct information....can someone help em see where I've gone wrong?
I can use process on file names and it correctly reads them.

A: You've specified O_TRUNC | O_CREAT for the open flags, but you've failed to specify O_RDWR or O_WRONLY.
You also probably want to write n bytes, not sizeof(buf), as the remaining sizeof(buf) - n bytes are uninitialized.


text:
Q: Import/export data in Adempiere I am quite new to Adempiere. I want to ask if Adempiere have any adapter to help import/export data from other app like excel, sql or sugarcrm ... ? May an interface or API that we can use or extend from would be ok as well. Also can Adempiere communicate with calendar like outlook or google calendar? Thank you for your input

A: I hope the following help..
"import/export data from other app like excel"
http://wiki.adempiere.net/Data_Import
"May an interface or API that we can use"
http://wiki.adempiere.net/Adempiere_Web_Services
regards..


text:
Q: Customise the display of a auto-generated class I have a DB and I created classes to access/manage it using SQLMetal. Now, I use LINQ to SQL, and I want to display the result of queries in a data grid view. when I do that, the columns are named after my columns in the DB table, and all the properties are displayed. I know I could change this by using DisplayName and Browseable attributes, but because the classes are auto-generated I can't just add this attributes where there are needed. I came up with three workarounds:

*

*creating an Adopter to adopt my classes. I'm still not sure how exactly you make an adopter for this case.

*creating another program that will run after the generating of the code that will add the attributes. this seems like an hack, and I prefer to separate between the functionality and the GUI, so this method is on hold.

*using the MetaDataType attribute. I couldn't get this to work, and it's requires, as far as I know, that the classes and the metadata class will be in the same DLL.

How do I do the customization? is there another way? what way should I take and how?
EDIT: forgotten to mention: I'm using winforms, but if it will simplify things, I will move to WPF.

A: You can set a Types Metadata Type at run time by registering it with the TypeDescriptor manually.
That goes something like this.
var type = typeof(Foo);
var metadataType = typeof(FooMetadata);
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType), type);

To show it all in context this will show a single column in the data grid with the header "Custom Bar".
public class Foo
{
    public string Bar { get; set; }
    public string DontShowMe { get; set; }
}

public class FooMetadata
{
    [DisplayName("Custom Bar")]
    public string Bar { get; set; }

    [Browsable(false)]
    public string DontShowMe { get; set; }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var type = typeof(Foo);
        var metadataType = typeof(FooMetadata);
        TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType), type);

        this.dataGridView1.DataSource = new List<Foo> { new Foo { Bar = "Foobar" } };
    }
}

The is also a TypeDescriptor.RemoveProviderTransparent if you want to switch the Metadata Type on the go but keep in mind that setting/unsetting it applies to the whole application domain and so threading needs to be taken into account.

A: By using the WPF DataGrid you can easily customize the auto generated columns by using the AutoGeneratingColumn event.

A: Why can't you use the data grid view's Columns collection to change DisplayNames and Visibles at runtime?