text:
Q: Update MySQL Value Through Img Src Variable Including jQuery Thank-you to all who have helped me over the last few days.. Unfortunately I was working so I couldn't get back to you.  I have included some code into what I thought would work, but for some reason the below code will not update in my SQL Database.  I will provide the code and it's output if someone could please copy the code and see why it's not working... It's really doing my head in! Haha!
(The connection to the MySQL db + table is working fine).
// admin.php
<img src="<?php echo "image.php?url=" . $row[2]; ?>?tid=<?php echo $row[0]; ?>&opn=<?php echo $row[1]; ?>" id="chnge" />
// image.php?url=image.jpg?tid=3&opn=1

I was advised to do it this way to make it easier for me to pass the variables (tid and opn) through the process.
// update.php

$tid  = $_GET['tid'];
$opn  = $_GET['opn'];

if ($opn == "0") { $opn = "1"; } elseif ($opn == "1") { $opn = "0"; }

mysql_query("UPDATE catalogue SET opn = $opn WHERE tid = $tid ; ");

mysql_close();

// it's just a simple script to change a variable from 1 to 0 or 0 to 1 where tid = a specific number...

I have my jQuery stuff all tucked away in a lovely little file, because there is alot of it...
// navigate.js

$.extend({
 getUrlVars: function() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
 return vars;
 }
});

$("#chngeHref").click(function() {
 var tid = $.getUrlVars()['tid'];
 var opn = $.getUrlVars()['opn'];

 $.ajax({
  type: "POST",
  url: "update.php",
  data: "tid="+ tid +"& opn="+ opn,
  success: function(){
   $('#chnge').fadeTo('slow',0.4);
   }
  });
 });

The .extend code i found on the net which finds the parameter and value of all those in the address line.  I THINK this is where my issue might be, because the top code is never actually sending it to the address bar, it's being sent through jQuery to the update.php file.
I can only say thank-you soooo much in advance to anyone who can assist in this.
Phillip.

A: There are a few issues here bsides the SQL Injection vulnerability Nathan mentions, namely you're POSTing, so you need to use $_POST rather than $_GET to retrieve your variables.  Also you have an extra space in the data block, this:
data: "tid="+ tid +"& opn="+ opn,

should be:
data: "tid="+ tid +"&opn="+ opn,

or a bit cleaner using object notation (so it also gets properly encoded):
data { tid: tid, opn: opn },

For the SQL Injection issue, instead of this:
mysql_query("UPDATE catalogue SET opn = $opn WHERE tid = $tid ; ");

At the very least escape the values, like this:
$tid = mysql_real_escape_string($_POST['tid']);
$opn = mysql_real_escape_string($_POST['opn']);

Or, go the parameterized query route, which is what I'd prefer.


text:
Q: Let every class of one group have it's own Log4j2 logging environment My program, behind it's main functionality, contains demon background threads that operate independently and most of the time are idle. If something goes wrong, the threads fail silently (they show a GUI warning, terminate, but program continues). As these threads operate on different context than the main application, it would be nice if every one of them could have their own log file. All threads are running a runnable which is some instance of my Robot class.
The Robot class defines setLogger and getLogger methods and uses given logger to log data. But as long as the logger configuration is same for the whole project, there's no way I could separate log for the demon thread.
Is there even a simple way to do it? Log messages from thread mixed up with main program log are useless.

A: The RoutingAppender may do what you want. The way this works is, each thread sets a unique value in the Log4j2 ThreadContextMap, and the RoutingAppender will use this value to route to a separate log file. The Log4j2 FAQ page contains a detailed example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I loop through a json array, and then display the results in an discord js embed? Thanks for taking a peek at my question. This is my first question, so hopefully I do all the right stuff.
I am using DiscordJS/NodeJS
I have a large(ish) json file that has a list of maps/links to download the map, and an extra field.
[
  {
    "name": "2 Evil Eyes",
    "link": "http://",
    "extra": ""
  },
  {
    "name": "25 To Life",
    "link": "http://",
    "extra": ""
  },
  {
    "name": "Back To School",
    "link": "http://",
    "extra": ""
  },

I created this file myself from a list that was given to me.
The goal of this file was to be able to display the data (maps, link, extra) in a discord embed. I know that having 70+ .addField(s) is not a great idea, but it is what was requested.
So I thought that I would just have a little loop through and display the data that way, but my issue is that it keeps posting an embed for each result it gets. Here is my code below:
fs.readFile('./maps.json', 'utf-8', function(err, data){
        json = JSON.parse(data);
        for(let i = 0; i < data.length; i++){
            let name = data[i].name;
            let link = data[i].link;
            let extra = data[i].extra;

        }
        const mapRot = new Discord.MessageEmbed()
            .setTitle("Map Details")
            .setAuthor(client.user.username)
            .setDescription("These are your maps for the night.")
            .addField("Maps", name)
            .addField("Link", link)
            .addField("Extra", extra);

        message.channel.send(mapRot);

Any help would be appreciated!

A: Welcome to StackOverflow! I'm not too familiar with the Discord API, however, it seems as though you can do something like this, where you pass to addFields a list of arguments.
So I would think you could first map through the array to transform the data, and then pass it in as it should be specified to addFields. Something along the lines of:
fs.readFile('./maps.json', 'utf-8')
.then(JSON.parse)
.then(data => data.map((entry) => {
   // here, 'entry' stores an object of the form:
   // {
   // "name": "2 Evil Eyes",
   // "link": "http://",
   // "extra": ""
   // }
   // and per the Discord documentation, needs to return
   // an object of the form:
   // {
   // "name": 'Inline field title',
   // "value": 'Some value here'
   // }

   // for example:
   return { name: entry.name, value: entry.value }
}))
.then((parsedEntries) => {
new Discord.MessageEmbed()
            .setTitle("Map Details")
            .setAuthor(client.user.username)
            .setDescription("These are your maps for the night.")
            .addFields(...parsedEntries)

// that last .addFields call is expecting parsedEntries to be of the form
// [{name: "field name", value: "field value"}, {name: "field2", value: "field2value"}]
})

Edit: essentially, you have a list of objects with properties that look like this:
{
   "name": "2 Evil Eyes",
   "link": "http://",
   "extra": ""
}

But addFields takes objects with properties that look like this:
{
   "name": "Field title"
   "value": "Field value"
}

So you can use the JavaScript map function to map over each entry in the list, converting objects from your original format as specified in your maps.json file to the one that the Discord API requires.
Here's an article that might help introduce the essential concept of JavaScript mapping if you aren't previously familiar with it.


text:
Q: Make sure crawlers don't 'click' on button I have the following code in my view:
= form_tag(new_demo_path, :method => "put", id: "demo-form") do
  = submit_tag "Try out demo", :name => nil

This will setup a demo environment which will be accessible for 7 days.  Of course I don't want search engines to click this.  Since it's a put request, will this be a problem?  Do I need to include something so they don't click this link?

A: Some time ago I found myself in a similar situation and I wrote a negative captcha plugin for Rails: https://github.com/markets/invisible_captcha. It's based on the honeypot strategy, the idea was to provide a better user experience.
More or less, you should add into your form:
<%= form_tag(new_demo_path, :method => "put", id: "demo-form") do %>
  <%= invisible_captcha %>
<% end %>

In your controller:
invisible_captcha only: [:new_demo] # assuming new_demo is the action that handles the form


text:
Q: How to filter by ReferenceProperty in Java's GAE? Assuming I have the following (simplified) models in a GAE Java application:
Entity project = new Entity("Project")
project.setProperty("name", "test");

and
Entity task = new Entity("Task");
task.setProperty("name", "test");
task.setProperty("project", project.getKey());

How do I get all Tasks that have a reference to a specific Project?
I've tried
    Query q = new Query("Task");
    Query.FilterPredicate projectFilter =
            new Query.FilterPredicate("project",
                    Query.FilterOperator.EQUAL,
                    project.getKey()
                    );
    q.setFilter(projectFilter);

But to no avail.
I've check the actual data with the Datastore viewer and everything is in place.
Tasks have a proper Key to a project and all of the properties are indexed.
The only thing that seems out of the ordinary, is the fact that (considering my app supports multi-tenancy), that Project key as a namespace prefix on the viewer.
Could that be the problem, and is there any solution?
Many thanks in advance.

A: try to use project.getKey().getId() instead,
or use the special key filter: Entity.KEY_RESERVED_PROPERTY
which is described here:
https://developers.google.com/appengine/docs/java/datastore/queries#Key_Filters


text:
Q: CentOS rsync directory contents but not directory? I'm trying to get the contents of /deploy/ to populate to /panda/ but it doesn't seem to work. I searched on here and found instruction to leave the trailing slashes; however each time I run it a blank-named directory is created within /panda/ (so /panda/ /) that contains the contents of /deploy/ but I am trying to get this to occur without it creating a new directory . I would like the contents of /deploy/ to override the contents of /panda/
This is the code I am currently using:
rsync -ahrvz /home/jellywhat/public_html/deploy/ /home/jellywhat/public_html/panda/

I do not get a 'deploy' directory inside of /panda, I simply get a directory with a blank name, containing the contents of /deploy/

I tried removing the trailing slash on the receiving directory...
rsync -ahrvz /home/jellywhat/public_html/deploy/ /home/jellywhat/public_html/panda

This seemingly does nothing. I get an email with the file list, which is correct, and includes FileA.php, a specific file I am using as a reference, but FileA.php which is located under /deploy/cfx_controllers/ is not being copied to /panda/cfx_controllers/ even though it is the most recent file modified and does not exist under /panda/cfx_controllers/
UPDATE: 1:51PM
It actually is 'working;' it is not updating the existing panda directory , it is making an entirely new one:

How can I get it to 'update' the 'existing' directory without this occurring?
UPDATE: 2:36PM
I tried the receiving directory with and without a slash. With a slash, it creates a duplicate directory in the parent directory. Without a slash, it places the contents of /deploy/ inside of a seemingly unnamed folder.

Does anyone have any guidance on where I am failing to get this deployment script to actually deploy the files?

A: This command will copy the contents of deploy (but not the directory name itself) into the existing target directory panda:
rsync -ahrvz /home/jellywhat/public_html/deploy/ /home/jellywhat/public_html/panda/

The trailing slash on the source directory tells rsync to copy the directory contents without the directory name itself. The trailing slash on the destination directory is irrelevant. If the copy doesn't work like this for you then you haven't entered the command exactly as you have written in your question.
Note that there's no point using -z as you cannot compress files during a local copy. Also, the -r is implied by -a so it can be omitted.

Um, this file that you now say you're creating to contain the command. If you created it on a Windows system please ensure you transferred it as a text file and not a binary file. Otherwise the file line endings will get badly in the way.

A: There are no "directories with empty names" (or files, for that matter) in Linux, you probably have some garbage (that prints as nothing) at the end of the command. Note that you can have a file named a file name<move back to beginning of line><erase to end of line> (here <...> is a sequence of characters that tell your terminal to do as directed). You don't see anything, but there is a name there. Infinite fun to be had of newbies ;-)
rsync is very picky on slashes at the end (there really isn't any other reasonable way to tell the program what it should do), read the manual carefully.


text:
Q: Regular expression matching repetitive strings I need to match files like the following
session1_******.php

Do I do something like this?
{session1_}^(.*).php

A: This regex will match what you seek:
^session1_.*\.php$

Note the escaped dot \. meaning a literal dot (not a regex "any character")

A: The most direct answer
^session1_.*\.php$

A carat (^) is used to indicate the beginning of a string or to negate a character class (e.g. [^abc] ... meaning not "a", "b", or "c"), it has no meaning in the middle of a regex.
Parenthesis are only needed if you need to capture the result.
A period (.) must be escaped.
Assuming this this is the entire string you are matching, the ^...$ require a full match from beginning to end.  If there could be text before the beginning remove the ^, or there could be text as the end remove the $.


text:
Q: Overwrite variable in function from another file 1. Summary
I don't find, how I can overwrite variable in function from another file.

2. Example
2.1. Configuration
I use logbook and pyfancy modules.
I have 2 files — config.py and first.py:
config.py:
import logbook
import sys

from pyfancy.pyfancy import pyfancy

log = logbook.Logger("config")

logbook.StreamHandler(sys.stdout,
                      level=logbook.DEBUG).push_application()

def green_foreground(coloredtext):
    log.debug(pyfancy().green().bold(coloredtext))

first.py:
import logbook

from config import green_foreground

log = logbook.Logger("first")

green_foreground("Sasha Champion!")

3. Steps to reproduce
I run in console:
python first.py

4. Expected behavior
I want, that log variable:

*

*log = logbook.Logger("first") — in first.py,

*log = logbook.Logger("second") — in second.py and so on.

D:\PyfancyRefactoring>python first.py
[2018-01-25 16:54:25.469005] DEBUG: first: Sasha Champion!

5. Actual behavior
Value of log variable from config.py file.
D:\PyfancyRefactoring>python first.py
[2018-01-25 16:54:25.469005] DEBUG: config: Sasha Champion!

6. Not helped
For example, I add to config.py:
if __name__ == 'config':
    log = logbook.Logger("config")
else:
    log = logbook.Logger("first")

I get actual behavior, not expected behavior.

7. Do not offer

*

*I know that I can define green_foreground function in each file, but it will be a lot of duplicate code and I think, that it a not a good practice.

A: The config file creates a logger, named config, and the function green_foreground logs to that logger. It is hard coded that way - at no point do you tell the green_foreground function to log anywhere else, it has no idea about the log created in first.py.
When you run first.py, python creates two different log instances. You can modify the green_foreground function to accept a log instance as an argument and default to the one creatd in config, or:
change config.py to log this instead:
log = logbook.Logger(__name__)


text:
Q: Display data attribute value with CSS I'm using a WordPress plugin to display events on a calendar. It has the following markup to display days:
Monday

Instead of displaying "Monday", I'd like it to display "Mon". Is it possible to output the data attribute (data-day-abbr) using CSS?
This would be a prefered workaround, otherwise, I'll need to create child template files.

A: You can do this by hiding the th content's visibility, and replacing it using CSS' content and attr:

[data-day-abbr]:before {
  content: attr(data-day-abbr);
  visibility: visible;
}

th {
  visibility: hidden;
}

    Monday

A: Access data-day-abbr in CSS and set its value on a pseudo element (before):
#tribe-events-monday:before {
     content: attr(data-day-abbr);
}

A: What you could do is "hide" the text in the th by setting it's font-size to zero.
Than add an :after element and fill it with the data attribute.
More information

th {
  border: 1px solid black;
  font-size: 0;
}
th:after {
  content: attr(data-day-abbr);
  font-size: 12px;
}

    Monday

A: You can use text-indent and ::before

[data-day-abbr] {
  text-indent: -100vw;/* at least enough to hide text */
}
[data-day-abbr]::after {
  content: attr(data-day-abbr);
  float:left;/* or display: block;*/
  text-indent: 0;
}

    Monday
    Tuesday
    Wednesda
    Thursday
    friday
    Saturday
    Sunday


text:
Q: Creating a complex pivot table in T-SQL I am using SQL Server 2008 R2 and T-SQL. These are abbreviated examples.
My table/view has the following fields
Table/View
    ReportID,
    UnitName,
    UnitID,
    CaseDefinitionID,
    CaseDefinition,
    DateOfDelivery,
    YEAR(DateOfDelivery) AS [Year],
    MONTH(DateOfDelivery) AS [Month],
    DATENAME(m,DateOfDelivery) AS [Month name]

and my target report is:
Unit    |   Case type 1|    Case type 2|    Case total|
Unit A  |            36|             40|            76|

    2013|            20|             18|            38|
     Jan|            10|
     Feb|            10|

    2014|            16|
     Mar|             8|
     Dec|             8|

Unit B  |            12|
    2013|            12|
     Jan|             6|
     May|             6|

Grand total|         48|

The month rows can be empty, NULL content is fine. The example report is incomplete to aid clarity.
Progress so far is the following query:
SELECT *
FROM
(
    SELECT
        PCT.[Year],
        PCT.UnitName AS [Unit],
        PCT.UnitID,
        PCT.CaseDefinition AS [Case definition]

    FROM
        PivotBase AS PCT
) AS P1

PIVOT
(
    COUNT(UnitID)
    FOR [Case definition] IN ([Case type 1],[Case type 2])
) AS P2

This produces the following table
Year|Unit   |Case type 1|Case type 2|
2013|Unit A |       20  |         18|
2014|Unit A |       16  |         22|
2013|Unit B |       6   |          8|
2014|Unit B |       6   |          8|

There is no need for dynamic SQL
My reading so far has covered many options but I still have no idea where to go next. How do I produce the required report.

A: It's doable with some fancy rollup (SQL Fiddle)
;WITH
    CTE1 AS
    (
        SELECT      UnitName,
                    [Year],
                    [Month],
                    CaseDefinition,
                    GROUPING_ID(UnitName,[Year],[Month],CaseDefinition)
                                        AS GroupingID,
                    CASE GROUPING_ID(CaseDefinition,UnitName,[Year],[Month])
                        WHEN 0 THEN UnitName + '-' + CAST(Year AS varchar(4)) + '-' + RIGHT('0' + CAST([Month] AS varchar(10)),2)
                        WHEN 1 THEN UnitName + '-' + CAST(Year AS varchar(4))
                        WHEN 3 THEN UnitName
                        WHEN 7 THEN 'zzz'  -- So that grand total appears at the bottom
                        ELSE NULL
                    END                 AS GroupingLevel,
                    CASE GROUPING_ID(CaseDefinition,UnitName,[Year],[Month])
                        WHEN 0 THEN '    ' + CASE [Month]
                                                WHEN 1 THEN 'Jan'
                                                WHEN 2 THEN 'Feb'
                                                WHEN 3 THEN 'Mar'
                                                WHEN 4 THEN 'Apr'
                                                WHEN 5 THEN 'May'
                                                WHEN 6 THEN 'Jun'
                                                WHEN 7 THEN 'Jul'
                                                WHEN 8 THEN 'Aug'
                                                WHEN 9 THEN 'Sep'
                                                WHEN 10 THEN 'Oct'
                                                WHEN 11 THEN 'Nov'
                                                WHEN 12 THEN 'Dec'
                                             END
                        WHEN 1 THEN '  '   + CAST([Year] AS varchar(4))
                        WHEN 3 THEN UnitName
                        WHEN 7 THEN 'Grand Total'
                    END                 AS DisplayName,
                    COUNT(UnitID)       AS UnitCount
        FROM        PivotBase
        GROUP BY    GROUPING SETS(
                        (CaseDefinition),
                        (UnitName,CaseDefinition),
                        (UnitName,[Year],[CaseDefinition]),
                        (UnitName,[Year],[Month],CaseDefinition)
                    )
    )

SELECT      pvt.GroupingLevel,
            pvt.DisplayName,
            pvt.[Case Type 1],
            pvt.[Case Type 2],
            ISNULL(pvt.[Case Type 1],0) + ISNULL(pvt.[Case Type 2],0) AS [Case Total]
FROM        CTE1
PIVOT       (
                SUM(UnitCount) FOR CaseDefinition IN ([Case Type 1],[Case Type 2])
            ) pvt
ORDER BY    GroupingLevel

Explanation:

*

*GROUPING SET( (set1), (set2), (set3) ) defines the roll up level. You will get a count of UnitID for each unique combination inside set1, then set2, then set3

*GROUPING_ID is the most obscure function in here. Think of it as a bit mask. If a column is aggregated, its bit value is set to 1. For example: GROUPING_ID(field3, field2, field1, field0). If all 4 are not aggregated, the bit mask is 0000 = 0. If field0 is aggregated away, the returned value is 0001 = 1, and so on.
You can replace the last SELECT with SELECT * FROM CTE1 to see the inner working of the query.

A: You can get there by pivoting on Month and Year and then using WITH ROLLUP
WITH data
     AS (SELECT *
         FROM   (SELECT Dateadd(month, Datediff(month, 0, PCT.dateofdelivery), 0
                        )
                        MonthYear,
                        PCT.unitid,
                        PCT.unitname
                        AS
                        [Unit],
                        PCT.casedefinition
                        AS
                                [Case definition]
                 FROM   pivotbase AS PCT) AS P1
                PIVOT ( Count(unitid)
                      FOR [case definition] IN ([Case type 1],
                                                [Case type 2]) ) AS p2),
     rollup
     AS (SELECT Month(monthyear)           Month,
                unit                       unitX,
                Year(monthyear)            Year,
                Sum([case type 1])         [case type 1],
                Sum([case type 2])         [case type 2],
                Grouping(unit)             GUnit,
                Grouping(Month(monthyear)) gm,
                Grouping(Year(monthyear))  gy
         FROM   data
         GROUP  BY unit,
                   Year(monthyear),
                   Month(monthyear) WITH rollup)
SELECT COALESCE(Cast(month AS VARCHAR), Cast(year AS VARCHAR), unitx,
       'Grand Total')
       Unit,
       [case type 1],
       [case type 2]
FROM   rollup
ORDER  BY gunit,
          unitx,
          year,
          gm DESC,
          month

SQLFiddle


text:
Q: Selenium Remote Webdriver gives JSONDecodeError My code:
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common import desired_capabilities

class test_mycode(unittest.TestCase):
    def setUp(self):
        desired_cap = {'browser': 'IE', 'browser_version': '8.0', 'os': 'Windows', 'os_version': '7', 'resolution': '1366x768'}
        self.driver = webdriver.Remote(command_executor='http://username:ACCESS_KEY@hub.browserstack.com:80/wd/hub', desired_capabilities=desired_cap)

    def test_website(self):
    .....

The error is:
Traceback (most recent call last):
File "C:\Workspace\Pumpkin Patch Website\test cases\_test_mycode.py", line 55, in setUp
    desired_capabilities=desired_cap)
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium-2.48.0-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 87, in __init__
    self.start_session(desired_capabilities, browser_profile)
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium-2.48.0-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 141, in start_session
    'desiredCapabilities': desired_capabilities,
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium-2.48.0-py3.5.egg\selenium\webdriver\remote\webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium-2.48.0-py3.5.egg\selenium\webdriver\remote\errorhandler.py", line 102, in check_response
    value = json.loads(value_json)
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\elton.tiong\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

selenium-server-standalone2.48.0 is installed and running.
Python is 3.5
This is the code I wrote to run Selenium on Browserstack. I followed the instructions given by Browserstack, however, when I run it, it raised JSONDecodeError.
I also changed the command_executor to http://127.0.0.1:4444/wd/hub but it failed. Then I changed the desire_capabilities=desired_cap to desired_capabilities.DesireCapabilities.FIREFOX but it also fail.
I googled everywhere but cannot find any answer. Can someone please help? Thank you very much.

A: I know this is 2 years old, but since no one answered, hopefully this will be helpful to someone else. The value in the desired_cap is basically an invalid json. To confirm, I ran it against https://jsonlint.com/.
The fix is simple - replace all the single quotes to double quotes:
desired_cap = {'browser': 'IE', 'browser_version': '8.0', 'os': 'Windows', 'os_version': '7', 'resolution': '1366x768'}
desired_cap = desired_cap.replace('\\'', '\\"')


text:
Q: Creating a grid for a table within a text.grid in Python I have created a file with different tables inside along with fields in each of the tables. When I use "db = sqlite3.connect('File')" it connects to the file but when I go to paste it in the text.grid, it doesn't appear to be organised. Is there a way to put it into a table so it looks more organised?
Here is some of the code I use, Thanks!!
def CustomerDetails():
    db = sqlite3.connect('File')
    cursor = db.cursor()
    sql1 = "select * FROM CustomerTable"
    cursor.execute(sql1)
    result = cursor.fetchall()
    count = (len(result))
    for each in result:
        out = each
        message = out
        text.insert(0.0, message)
        text.insert(0.0, '\n' )
    cursor.close()

and
# Frame 1 Heading buttons
labelspare=Label(f1, text =" ").grid(column=1, row=1, sticky=(W, E))
f1button1=Button(f1,  text="Current Orders").grid(column=2, row=2, sticky=(W,E), ipadx = 20, ipady = 10, padx = 5, pady = 5)
f1button2=Button(f1,  text="Order",command = CurrentOrders).grid(column=3, row=2, sticky=(W, E), ipadx = 20, ipady = 10, padx = 5, pady = 5)
f1button3=Button(f1,  text="Customer",command = CustomerDetails).grid(column=4, row=2, sticky=(W, E), ipadx = 20, ipady = 10, padx = 5, pady = 5)
f1button4=Button(f1,  text="Products",command = ProductDetails).grid(column=5, row=2, sticky=(W, E), ipadx = 20, ipady = 10, padx = 5, pady = 5)
labelspare=Label(f1, text =" ").grid(column=1, row=3, sticky=(W, E))
labelspare=Label(f1, text =" ").grid(column=1, row=4, sticky=(W, E))
text=Text(f1, width = 125, height = 42, wrap = WORD)
text.grid(row = 4,column=2,columnspan = 8, sticky =(W, E))

Basically, once the button is clicked the subroutine should run and paste the file into the text.grid but it just looks very unorganized, as though it literally just pasted the file in.
To resolve any confusion, I have added a picture of some fictitious data to show how "Unorganized" the data is. The fields don't align how I would like them too, similar to an excel spreadsheet. http://imgur.com/8MTPpAx


text:
Q: SQL Insert into XML datatype column truncates the characters I have a XML datatype column in table.
When I try to insert lengthy encrypted string (ex: "7L1dj23bdRz2nAD5D4QeguRB") with 3251148 characters into it, it just truncates and stores only a partial string with the first 2097154 characters, instead of full string.
What would cause these issue? Any Ideas?


text:
Q: Tensorflow print in function I have a function in a file neural_network.py that defines a loss function:
def loss(a, b):
    ...
    debug = tf.Print(a, [a], message = 'debug: ')
    debug.eval(session = ???)
    return tf.add(a, b)

To explain, somewhere in this function I want to print a tensor. However, I don't have any session declared in this function; my sessions are declared in another file called forecaster.py. Therefore, when I try to put tf.Print() in loss(), I can't because I don't know which session to eval with. Is there a way to solve this problem, either by using tf.Print() or other debug methods? Thanks!

A: tf.Print works as an identity function which returns the same tensor that you passed as the first parameter, having a side effect of printing the list of tensors specified as the second parameter.
So you should use as following:
def loss(a, b):
    ...
    a = tf.Print(a, [a], message = 'debug: ')
    return tf.add(a, b)

a will be printed each time tensor tf.add(a, b) is evaluated.


text:
Q: Error during deployment: Members, tuples or sets must use the same hierarchies in the function in SSAS I am creating a new calculation in SSAS, to calculate avg value.
I have already two measure created:

*

*Sum of Risk Score as [Measures].[Risk Score]

*Total Count as [Measures].[VM Result Table Count]
And in the expression tab I have written the following expression.
[Measures].[Risk Score] / [Measures].[VM Result Table Count]

Now, when I deploy the SSAS project, I get the following error:
   "MdxScript(VMCube) (10, 22) Members, tuples or sets must use the same hierarchies in the  function."
Please help.
Thanks

A: Calculated members belong to a measure group of your choice. Maybe the values belong to different measure groups and don't 'see' each other. But as Preet Sangha stated... without knowing more that is only a wild guess.


text:
Q: Prometheus for Tensorflow Serving What are the steps to use the Prometheus exporter for Tensorflow serving?
According to 1.11 TF serving supports prometheus metrics:
https://github.com/tensorflow/serving/releases/tag/1.11.0
I'm starting a docker from the example https://www.tensorflow.org/serving/docker and the following:
docker run -p 8501:8501 -p 8500:8500 \
--mount type=bind,\
source=/tmp/tfserving/serving/tensorflow_serving/servables/tensorflow/testdata/saved_model_half_plus_two_cpu,\
target=/models/half_plus_two \
-e MODEL_NAME=half_plus_two -t tensorflow/serving &
Prometheus configuration file:
global:
  scrape_interval:     10s
  evaluation_interval: 10s
  external_labels:
    monitor: 'tf-serving-monitor'
scrape_configs:
  - job_name: 'tensorflow'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8501']
But prometheus fails to find the metrics exposed by tf serving.
Is there a specific port I should open on docker or some parameter I should pass to TF serving?

A: According to the release notes you linked to TensorFlow exports Prometheus metrics at /monitoring/prometheus/metrics (as opposed to Prometheus' default /metrics). So at the very least you need to add a metrics_path to your config:
scrape_configs:
  - job_name: 'tensorflow'
    scrape_interval: 5s
    metrics_path: '/monitoring/prometheus/metrics'
    static_configs:
      - targets: ['localhost:8501']

But first make sure you can see the metrics exported at http://localhost:8501/monitoring/prometheus/metrics in your browser. Else poke around (with your browser) until you find the proper URL (and reflect that in your config).


text:
Q: Userform in Excel 2013 disappears while switching an active workbook behind I have faced one problem in Excel 2013. In my project, I have a userform that contains a listbox which lists names of all opened excel books.
When a user clicks on a particular name in the list, the appropriate book is activated. So the userform is always on top and while the user is clicking on the names in the list, he can see all opened workbooks getting activated one by one behind the active userform.
This is the way it used to work in Excel 2010.
Now, after upgrade from 2010 to 2013, if a user clicks on a name in the list, selected workbook gets activated but the userform disappears.
What exactly has been broken in Excel 2013 and what is the way to bypass this problem?

A: Yes, the default behavior has changed. In Pre Excel 2013, The different workbooks are shown within one main Excel window if opened in the same instance. But in Excel 2013, they are shown in their own window. And because of this a modeless userform will only be visible on top of the workbook that was active when the userform was loaded.
And I don't think this has a fix yet. It is by design and may not be fixed.

A: @Siddharth, based on what you said, I think I have a solution.  When you open a form, it will only show up on top of the ActiveWorkbook.  As long as all the code is in the same code thread (not sure if terminology is right) , you're stuck with the same workbook;  But if you use the Application.Run or Application.Ontime commands it seems to start it's own code thread, which is independent enough to work.  Just Activate the workbook/sheet first, and then Unload the form and remote call the macro that showed the form in the first place.
Unfortunately, you need to use Unload instead of Hide, because of the aforementioned issue;  which means you need to save any/all options selected.
Private Sub lstFiles_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    ThisWorkbook.Application.Workbooks(lstFiles.Text).Activate
    Unload Me
    Application.Run "USER_Macro1"
    'Application.OnTime Now(), "USER_Macro1"
End Sub

Private Sub USER_Macro1(Optional Control)    ' As IRibbonControl)
    ModelessForm.Show vbModeless
End Sub

I tested it in Excel 2013 and so far it even seems to work regardless of the Screenupdating = false issue seen elsewhere.


text:
Q: EmptyPage error on final page of paginated Wagtail site I've searched the site and none of the answers are different from what I've tried:
Example | Example | Example | Example
My aim is to display 5 posts per paginated page on my Wagtail site. It works except for the fact I am getting a persistent EmptyPage error on the last page. I currently have 25 live posts, so there should be exactly 5 on each of the 5 pages. It's just page 5 (currently last page) that comes up empty.
I am pretty sure the problem is with the template and not with the queryset/model itself, but everything I've seen online looks identical to what I have.
Here is my model:
class BlogIndexPage(Page):

    body = RichTextField(blank=True)

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        blog_pages = BlogPage.objects.live().public().order_by("-date")
        page = request.GET.get("page")
        paginator = Paginator(blog_pages, 5)

        try:
            blog_pages = paginator.page(page)
        except PageNotAnInteger:
            blog_pages = paginator.page(1)
        except EmptyPage:
            blog_pages = paginator.page(paginator.num_pages)

        context["blog_pages"] = blog_pages
        return context

Here is my template:
{% if blog_pages.paginator.num_pages > 1 %}

   {% if blog_pages.has_previous %}

          «

   {% endif %}

   {% for page_num in blog_pages.paginator.page_range %}

            {{ page_num }}

   {% endfor %}

   {% if blog_pages.has_next %}

         »

   {% endif %}

{% endif %}

Traceback:
EmptyPage at /blog/
That page contains no results
Request Method: GET
Request URL:    https://***/?page=5
Django Version: 3.1.12
Exception Type: EmptyPage
Exception Value:
That page contains no results
Exception Location: /***/venv/lib/python3.6/site-packages/django/core/paginator.py, line 55, in validate_number
Python Executable:  /***/venv/bin/python
Python Version: 3.6.9
Python Path:
['/***/mysite',
 '/***/venv/bin',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/***/venv/lib/python3.6/site-packages']
Server time:    Wed, 06 Oct 2021 07:34:39 +0200
Error during template rendering
In template /***/mysite/mysite/templates/base.html, error at line 0

That page contains no results
1   {% load static wagtailuserbar %}
2
3   <!DOCTYPE html>
4
5
6           <meta charset="utf-8" />
7           <title>
8               {% block title %}
9                   {% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %}
10              {% endblock %}
Traceback Switch to copy-and-paste view
/***/venv/lib/python3.6/site-packages/django/core/handlers/exception.py, line 47, in inner
                response = get_response(request) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/core/handlers/base.py, line 204, in _get_response
                response = response.render() …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/response.py, line 105, in render
            self.content = self.rendered_content …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/response.py, line 83, in rendered_content
        return template.render(context, self._request) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/backends/django.py, line 61, in render
            return self.template.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 170, in render
                    return self._render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 162, in _render
        return self.nodelist.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/loader_tags.py, line 150, in render
            return compiled_parent._render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 162, in _render
        return self.nodelist.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/loader_tags.py, line 62, in render
                result = block.nodelist.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/defaulttags.py, line 312, in render
                return nodelist.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/defaulttags.py, line 211, in render
                    nodelist.append(node.render_annotated(context)) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 988, in render
            output = self.filter_expression.resolve(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 671, in resolve
                obj = self.var.resolve(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 796, in resolve
            value = self._resolve_lookup(context) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/template/base.py, line 858, in _resolve_lookup
                            current = current() …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/core/paginator.py, line 167, in next_page_number
        return self.paginator.validate_number(self.number + 1) …
▶ Local vars
/***/venv/lib/python3.6/site-packages/django/core/paginator.py, line 55, in validate_number
                raise EmptyPage(_('That page contains no results')) …

A: In this bit of code:
{% for page_num in blog_pages.paginator.page_range %}

        {{ page_num }}

{% endfor %}

?page={{ blog_pages.next_page_number }} should be ?page={{ page_num }}.


text:
Q: Kotlin - assigning non-nullable type to nullable type I am assigning a value to val nullable type from null-able string. Getting un-expected results. The code is as follows:
val username3: String? = null       // null assigned to constant. can be re-assigned after a check.
    if (name2 != null) {
        val username3 = name2           // no error, statement execute and username3 remains null? is it a bug?
    }
    System.out.format("3) name2: %s, username3: %s%n", name2, username3)

Result is:
3) name2: Jamie Smith, username3: null

A: val username3 = name2 statement defines a new variable username3 and sets its value to name2. It's not the same username3 that you defined in the first line. New username3's scope is only within if condition.
1) If you want to assign value to a variable at later stage then define it with var not val.
2) when you put var/val before variable name you define a new variable. Don't do this when you want to assign value to already defined variable.


text:
Q: Convert double to string with more than 5 decimal digit precision At first I used boost's lexical_cast to do this. But due to the way C++ represents doubles/floats, when I converted 5.1 to a string it would give me 5.0999999 or something to that extent. So, I converted it this way:
stringstream ss;
ss << 3.14159265359;
cout << ss.str();

But this would only give me 3.14159, and I would like more precision than that. I think I saw something about printf() being able to do this, but I am actually working on a Windows GUI program, not outputting to a console. How can I get more than 5 decimal digits of precision? I am willing to settle for 8, but 10 or 11 would be nice. Is this too much to ask for given how C++ represents floats and doubles?

A: ss << setprecision(12) << 3.14159265359;

Also, the choice between using streams and the C printf/scanf family has nothing to do with GUI vs. console.  The C equivalent of ostringstream is sprintf.


text:
Q: Unable to cast object of type 'System.Windows.Controls.Grid' to type 'System.Windows.Shapes.Ellipse'? I'm implementing a drag and drop wpf application and i have created 3 ellipse, i'm using thumb control to drag and drop the ellipse in the map, and i wish to get the drop position for ellipse. However i get an error when drag ellipse as below:

Unable to cast object of type 'System.Windows.Controls.Grid' to type
  'System.Windows.Shapes.Ellipse'

My XAML:
 <Window x:Class="DragandDropMFP.MainWindow"
                xmlns:local="clr-namespace:DragandDropMFP"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
                Title="MainWindow" Height="350" Width="525">

    <Grid x:Name="maingrid" MouseMove="MainGrid_MouseMove">
        <Grid.Background>
            <ImageBrush ImageSource="/Map/Capture.Png" />
        </Grid.Background>

        <Canvas>
            <Thumb Canvas.Left="38" Canvas.Top="22" DragDelta="Thumb_DragDelta">
                <Thumb.Template>
                    <ControlTemplate>
                        <Viewbox Width="50" Height="50">
                            <Grid Width="20" Height="20">
                                <Ellipse
                                 Fill="Blue"
                                 MouseMove="DragMouseMove"/>
                                <TextBlock HorizontalAlignment="Center" Text="Printer1" FontSize="4" TextAlignment="Center" VerticalAlignment="Center"/>
                            </Grid>
                        </Viewbox>
                    </ControlTemplate>
                </Thumb.Template>
            </Thumb>

            <Thumb Canvas.Left="37" Canvas.Top="100" DragDelta="Thumb_DragDelta">
                <Thumb.Template>
                    <ControlTemplate>
                        <Viewbox Width="50" Height="50">
                            <Grid Width="20" Height="20">
                                <Ellipse Fill="Yellow"
                                 MouseMove="DragMouseMove"/>
                                <TextBlock HorizontalAlignment="Center" Text="Printer2" FontSize="4" TextAlignment="Center" VerticalAlignment="Center"/>
                            </Grid>
                        </Viewbox>
                    </ControlTemplate>
                </Thumb.Template>
            </Thumb>

            <Thumb Canvas.Left="37" Canvas.Top="174" DragDelta="Thumb_DragDelta">
                <Thumb.Template>
                    <ControlTemplate>
                        <Viewbox Width="50" Height="50">
                            <Grid Width="20" Height="20">
                                <Ellipse Fill="Red"
                                 MouseMove="DragMouseMove"/>
                                <TextBlock HorizontalAlignment="Center" Text="Printer3" FontSize="4" TextAlignment="Center" VerticalAlignment="Center"/>
                            </Grid>
                        </Viewbox>
                    </ControlTemplate>
                </Thumb.Template>
            </Thumb>
        </Canvas>

        <TextBlock x:Name="ctlStatus" HorizontalAlignment="Stretch" Height="30" TextWrapping="Wrap" Text="status" VerticalAlignment="Bottom" RenderTransformOrigin="0.495,-4.7" />

    </Grid>
</Window>

My xaml.cs :
  public MainWindow()
        {
            InitializeComponent();
        }

       private void MainGrid_MouseMove(object sender, MouseEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Arrow;
            objmoveposition(sender, e);
        }

        private void DragMouseMove(object sender, MouseEventArgs e)
        {

            Mouse.OverrideCursor = Cursors.Hand;
            objmoveposition(sender, e);
        }

        private void objmoveposition(object sender, MouseEventArgs e)
        {

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (Mouse.OverrideCursor == Cursors.Hand)
                {
                    Ellipse objTextbox = (Ellipse)sender; <--Error

                if (objTextbox != null)
                    {
                    //----< Move Control >----
                    Point mousePoint = e.GetPosition(this);

                    //< Vertical >
                    int posY = (int)mousePoint.Y;
                    int actHeight = (int)Application.Current.MainWindow.Height;
                    int margin_Bottom = actHeight - (posY + (int)objTextbox.Height + (int)SystemParameters.CaptionHeight + (int)SystemParameters.BorderWidth + 4);

                    //< Horizontal >
                    int posX = (int)mousePoint.X;
                    int actWidth = (int)Application.Current.MainWindow.Width;
                    int margin_Right = actWidth - (posX + (int)objTextbox.Width + (int)SystemParameters.BorderWidth);

                    ctlStatus.Text = "Top=" + posY + " margin_bottom=" + margin_Bottom + " WinHeigth=" + actHeight + Environment.NewLine + " Left=" + posX + " margin_Right=" + margin_Right + "WinWidth=" + actWidth;
                    //ctlStatus.Text = "position=" + objTextbox.ActualHeight;
                }
             }

            }

        }

        private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            UIElement thumb = e.Source as UIElement;

            Canvas.SetLeft(thumb, Canvas.GetLeft(thumb) + e.HorizontalChange);
            Canvas.SetTop(thumb, Canvas.GetTop(thumb) + e.VerticalChange);
        }

Output:

Your guidance is highly appreciated!
Thanks!

A: The sender is the ellipse that raised the event, so you can replace this:
Ellipse objTextbox = ellipse1;

with this;
Ellipse objTextbox = (Ellipse)sender;

As long as you only assign the event to ellipses this is safe. If it gets assigned to other object types you'll need to check the type of sender before casting.
You don't need the name of the object.

A: Just found out by changing the Ellipse to Grid and everything works like cham..
Ellipse objTextbox = (Ellipse)sender;

change to
Grid objTextbox = (Grid)sender;

Thanks!


text:
Q: Play Framework 2.0 schedules an Akka Actor at server launch I have an Akka actor that validates random data and makes some changes to it based on that data's show time and updates it. Currently what I'm doing is using this code inside a controller:
static ActorRef instance = Akka.system().actorOf(new Props(ValidateAndChangeIt.class));
static {
    Akka.system().scheduler().schedule(
        Duration.Zero(),
        Duration.create(5, TimeUnit.MINUTES),
        instance, "VALIDATE"
    );
}

The problem with using this inside a controller is that someone has to access a page processed by that controller for the actor to start, and if this doesn't happen, everything stays paused.
Is there a way to do this at server start? I actually don't know how it behaves if the actor generates an exception. Does it stop future schedules or does it continue? In case it doesn't, is there any way of making the actor re-schedule in case any crash or error?

A: For running your code at server startup, take a look at the Global object:  move the code from your controller to the onStart() method:
public class Global extends GlobalSettings {

  @Override
  public void onStart(Application app) {
    ActorRef instance = Akka.system().actorOf(new Props(ValidateAndChangeIt.class));
    Akka.system().scheduler().schedule(
        Duration.Zero(),
        Duration.create(5, TimeUnit.MINUTES),
        instance, "VALIDATE"
    );
  }

}

A: Play Framework provides a way by which scheduling of a job can be done in the Global.java without you explicitly invoking it.
public class Global extends GlobalSettings {

    private Cancellable scheduler;

    @Override
    public void onStart(Application app) {
        super.onStart(app);
        schedule();
    }

    @Override
    public void onStop(Application app) {
    //Stop the scheduler
        if (scheduler != null) {
            scheduler.cancel();
            this.scheduler = null;
        }
    }
    private void schedule() {
        try {
            ActorRef helloActor = Akka.system().actorOf(new Props(HelloActor.class));
            scheduler = Akka.system().scheduler().schedule(
                    Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds
                    Duration.create(30, TimeUnit.MINUTES),     //Frequency 30 minutes
                    helloActor,
                    "tick",
                    Akka.system().dispatcher(), null);
        }catch (IllegalStateException e){
            Logger.error("Error caused by reloading application", e);
        }catch (Exception e) {
            Logger.error("", e);
        }
    }
}

And create the Actor, HelloActor.java
In the on onReceive method, you can do the processing of data, sending emails, etc.
public class HelloActor extends UntypedActor {

    @Override
    public void onReceive(Object message) throws Exception {
        // Do the processing here. Or better call another class that does the processing.
        // This method will be called when ever the job runs.
        if (message.equals("tick")) {
            //Do something
            // controllers.Application.sendEmails();
        } else {
            unhandled(message);
        }
    }
}

Hope this helps.


text:
Q: Logstash: Limit the message batch size to 10MB The problem
I have a server with Logstash as a logging engine. The Logstash instance is configured to save its logs in an AWS Elasticsearch instance.
A few hours ago, I stopped seeing any logs in the ES cluster Kibana view:

The logstash log file has a lot of similar errors:
{:timestamp=>"2016-02-25T14:39:46.232000+0000",
 :message=>"Got error to send bulk of actions: [413]
 {\"Message\":\"Request size exceeded 10485760 bytes\"}",
 :level=>:error}

I've talked to the AWS support, and they confirmed that their ES machines limit request size to 10MB.
What have I tried

*

*Set flush_size => 50 in the configuration

The question
How can I limit the Logstash request size to the 10MB limit enforced by ES?

A: I have had same issue, to fix that I set flush_size => 100 in my output:elasticsearch configuration for logstash.
As a side note check "free storage space" in ES dashboard for your domain.
Edit:
for the first run after this change i run logstash from command line instead of as a demon:
/opt/logstash/bin/logstash -f /etc/logstash/conf.d/

A: bug in github side: https://github.com/awslabs/logstash-output-amazon_es/issues/55
I have also lowered the flush_size => 10, but sometimes still had problems. So i when to track the source, created several outputs, add IDs to them to help tracking and added a fallback size:  retry_max_items => 1
Then i used the logstash API, when logstash was not outputing any more events, to find the outputs that were locking up:
curl -XGET 'localhost:9600/_node/stats/pipeline?pretty' -s | jq . | awk 'BEGIN {FS="{|}|: |\," } /"in":/ { i=$2 ; next }; /"out":/ { o=$2 ; next } /"id":/ { id=$2 }; /name/ { print $0, i-o , id }  '
The output with in-out greater than zero are the ones that are unable to flush to amazon_es
With this i found the source of the problem and that i had events with almost 10MB. So my solution was to truncated them to a sane size and finally fix this.
So my setup is now something like this:
filter {
(...)
# truncate big fields events to ~1MB
# need the logstash-filter-truncate plugin
  truncate {
    length_bytes => "1048576"
    fields => [ "message", "error" , "error_orig" ]
  }
(...)
}
output {
(...)
      amazon_es {
        id => "producer"
        hosts => "${ES_HOSTNAME}"
        index => "logstash-%{+YYYY.MM.dd}-%{[type]}-%{[environment]}"
        document_type => "%{[type]}"
        flush_size => 10
        # if still fails, flush one by one until success
        retry_max_items => 1
      }
(...)
}

Hope this helps someone with the same problem


text:
Q: How to add Ember-Bootstrap to an EmberJS project created via Yeoman I've started working on an EmberJS application and used Yeoman to generate the skeleton structure. Now, I'd like to add Ember-Bootstrap to my project but am having trouble doing so. I downloaded the latest version from GitHub and unzipped it but I'm not sure what to include.
I see several .js files in the packages/ember-bootstrap/lib folder. Do I need to include all of these? If so, then in which order should I include them?
Someone mentioned in another answer that you needed to add it to the "assets" folder but I don't have one of these.
Does installing Ember-Bootstrap require having a Rails project? I'm not familiar with Rails so please forgive for the newbie questions.
Thanks.

A: I found a great project that supports Bootstrap 3.0 with many components,
you can find it here:
https://github.com/ember-addons/bootstrap-for-ember
you can see all components alive:
http://ember-addons.github.io/bootstrap-for-ember
GoodLuck.


text:
Q: How to run GNAT Community? I've installed Ada Community into desired directory and can't make it run.
There are lot of executable files in the bin directory, tried a lot of them.
Here is my GNAT directory.


text:
Q: JavaScript extending the eval() function? I'm trying to make my own eval function in JavaScript, which will execute a string in the surrounding context, like eval, plus add a few more things.
So, in general, when doing:
eval("var foo = 8");
foo; // === 8

No problem; however, when I want to extend eval with my own function, like so:
function myEval(str) {
    return eval(str);
}
myEval("var foo = 8");
foo; //error, "foo" is not defined etc.....

And the obvious reason is because in myEval, the eval function called is only executed in that function's scope, not the surrounding scope.
I was wondering if its possible to execute eval in the scope it's surrounding function was called, in order to extend the JavaScript function eval?

A: Figured it out, just wrap the eval function in another function, and call that other function in the surrounding scope, like so:

function g(str) {
    return {
        eval,
        go(){
            this.eval(`
              //some other cool stuff
              let test = 1000;
              ${this.str}
            `)
        },
        str
    }
}
g("var pp = 3 * test").go()
console.log(pp);

EDIT:
this actually accomplishes it:

function str(cod1,cod2) {
    return `
        ${cod1};
        (function(...args) {
            ${cod2}
        })
    `
}

function scope1() {
  eval(str(
    `
      var x,
          y,
          z
    `,
    `
      x = args[0];
      y = args[1];
      z = args[2];

    `
  ))(1, {test(){return "ing"}}, {ok:"string"})
  console.log(x,y.test(),z, "scope1");
}

scope1();

try {
  console.log(x, y, z);
} catch(e) {
  console.log(e.toString());
}


text:
Q: How to pass variable to Component received in props? In Layout.jsx I´ve the following structure, where children is a Component.
How can I pass 'name' to 'children' component?
const Home = () => {
    return
Hello world!
; {/* here I need the name */}
};

class App extends Component {
    render() {
        return (
        <Layout>
            <Switch>
                <Route path='/' component={Home}/>
                ...
            </Switch>
        </Layout>
        );
    }
}

class Layout extends Component {
    name = "John";
    render() {
        const { children } = this.props;
        return (

            { children }

        );
    }
}

A: React component has to be uppercase. If the child variable holds a React component, you can just store it inside some uppercase variable and then render as a tag.
const { child: Child } = this.props;

return (

    <Child name={this.name} />

);

A: Try const { children: Child } = this.props;


text:
Q: Get pixel dimensions of a PNG on my Mac? I have a random .PNG file on my Mac.  Actually I have about a hundred of them.  What is the easiest way to get the pixel dimensions?  (I.e, 100 pixels wide and 50 high, or whatever).

A: Find the file in a Finder window, and either:

*

*Highlight the file and press ⌘ Cmd + ⌥ Option + I, or

*Control-click the file and hold ⌥ Option so you can select "Show Inspector".
This will open an inspector which is similar to the Get Info window, but updates each time you select a file.
Now expand the "More info" section on the inspector. You will be able to see the PNG's dimensions and color depth, among other data. Select a new file to see its dimensions in the inspector.

A: This is an old question, but for current readers, there is now a readily available solution.  In Yosemite, you can turn on the "Show Preview Column" in Finder. Finder > View > Show View Options
Here's a screenshot.
.

A: In Terminal, you can use the following:
$ sips -g pixelWidth Pictures/238337225.png
/Users/danielbeck/Pictures/238337225.png
  pixelWidth: 1140
$ sips -g pixelHeight Pictures/238337225.png
/Users/danielbeck/Pictures/238337225.png
  pixelHeight: 900

To extract the value only, use e.g.
$ sips -g pixelHeight Pictures/238337225.png | tail -n1 | cut -d" " -f4
900

To embed that in AppleScript:

set h to do shell script "sips -g pixelHeight /Users/danielbeck/Pictures/238337225.png | tail -n1 | cut -d' ' -f4"
set w to do shell script "sips -g pixelWidth /Users/danielbeck/Pictures/238337225.png | tail -n1 | cut -d' ' -f4"
display alert "Height: " & (h as text) & "
Width: " & (w as text)

Result:

Alternatively, you can read the Spotlight metadata:
mdls Pictures/238337225.png | grep kMDItemPixel
kMDItemPixelCount              = 1026000
kMDItemPixelHeight             = 900
kMDItemPixelWidth              = 1140

To get the names and dimensions of all files in a directory:
$ mdls Pictures/* | grep "\(kMDItemDisplayName\|mMDItemPixel\)"
[...]
kMDItemDisplayName             = "url.png"
kMDItemPixelCount              = 16384
kMDItemPixelHeight             = 128
kMDItemPixelWidth              = 128
[...]

Or alternatively, using find and sips:

find /Users/danielbeck/Pictures -type f -name "*.png" -exec sips -g pixelWidth {} \; -exec sips -g pixelHeight {} \;

More more flexibility, wrap in a shell script:
$ cat dim.sh
#!/usr/bin/env bash

filename=$1

if [ ! -f "$filename" ] ; then
    echo "$filename not found!";
    exit 1
fi

h=$( mdls "$filename" | grep kMDItemPixelHeight | tail -n1 | cut -d= -f2 )
w=$( mdls "$filename" | grep kMDItemPixelWidth | tail -n1 | cut -d= -f2 )

osascript -e "tell application \"Finder\" to {activate, display alert \"$filename\\nWidth:$w\\nHeight:$h\"}"

Result after chmod +x dim/sh:
$ ./dim.sh Pictures/flying_cars.png

You could easily extend the script to display dimensions for multiple files at once, or e.g. all png files in a certain directory. Output is as Finder dialog, so you can embed it into an Automator service:
Open Automator and select to create a Service that receives image files as input in any application.
Add a Run Shell Script action that receives input as arguments and enter the following:
dlg=
for f in "$@"
do
    h=$( mdls "$f" | grep kMDItemPixelHeight | tail -n1 | cut -d= -f2 )
    w=$( mdls "$f" | grep kMDItemPixelWidth | tail -n1 | cut -d= -f2 )
    dlg="$dlg$f\nW:$w H:$h\n"
done
osascript -e "tell application \"Finder\" to {activate, display alert \"$dlg\"}"
exit 0

Save as Show Image Dimensions. Select a few image files in Finder and select Finder » Services » Show Image Dimensions or Right-click on one of the files and [Services »] Show Image Dimensions

A: The easiest way; open the images in Safari.
Select all the images. Then use Ctrl+Click context menu and choose Open With > Safari.
Optionally you can merge all the open Safari menus together into separate tabs using the Safari menu Window > Merge All Windows.
The top of the Safari window displays the image dimensions:

A: Here is how to use the Finder add a separate 'Dimensions' and 'Resolution' column to the list view of a folder.

*

*Open your Pictures folder. /Users/~/Pictures

*Create a new folder within the opened Pictures folder. Do not drag one in from elsewhere.

*In this new folder, in list view, right/option-click the column header row.

*Check both of the options available at the bottom of the contextual
menu, 'Dimensions' and 'Resolution'.

Now the nice part.

*

*Drag this new folder onto the desktop (or wherever) and open.

*Note that the modified header row retains the headers 'Dimensions'
and 'Resolution'.

*Add images files to the folder and in list view read the dimensions
and resolutions info for all the image files at once and not one at a
time with the various info panel methods.

Sometimes Resolution is not calculated or available and a dash will appear in the column. See attachment.
This still works as of macOS Sierra 10.12.6
I do not know if this folder setting sticks when the folder is moved to another user account, network folder, etc.
Screenshot: Folder in list view with Dimension and Resolution columns.

A: Open the image in preview then go to tools>Show Inspector(⌘S). This will bring up a window that displays the image dimensions with pixels as the unit.


text:
Q: SyntaxError while trying to launch a pynodered server I am trying to launch a simple python code as a node in node-red, I installed pynodered and made a .py file including the following code
from pynodered import node_red
@node_red(category="pyfuncs")
def lower_case(node, msg):
    msg['payload'] = str(msg['payload']).lower()
    return msg

I tried launching the pynodered server but I got a syntax error (I tried on windows10/Ubuntu16.04 still the same error)
C:\Users\omara\Downloads\Cyber Physical Systems>pynodered test.py
Traceback (most recent call last):
  File "c:\users\omara\appdata\local\programs\python\python35\lib\runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\omara\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\omara\AppData\Local\Programs\Python\Python35\Scripts\pynodered.exe\__main__.py", line 5, in <module>
  File "c:\users\omara\appdata\local\programs\python\python35\lib\site-packages\pynodered\server.py", line 93
    print(f"From {name} register {obj.name}")
                                           ^
SyntaxError: invalid syntax


text:
Q: Define priority for docker container with restart policy always On a Linux server, I've serveral Docker containers running. For example, some Compose-Stacks for Wordpress hosting. But also internal applications like Confluence. After a reboot, it seems that the internal containers were started first. So the hosting containers (like Wordpress) are down for several minutes.
That's not good, since the internal apps were used by a few persons, where the external ones have much more traffic. So I want to define some kind of priority: Like starting the Wordpress containers before the Confluence, to name a concret example.
How can this be done? All containers have the restart policy always. But it seems not possible to define in which orders the containers should start...

A: version 3+ : Version 3 no longer supports the condition form of running containers.
version 2 : depends_on will help your case if you do docker-compose up, but ignores when you run in swarm mode.
docker-compoopse.yml  (works after version 1.6.0 and before 2.1)
version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

DOCS :
depends_on
Controlling startup order in Compose


text:
Q: Threejs - Detect canvas limits in the camera world Is there a way to determine the max / min values for height and width in the threejs coordinate system?
I'm (kinda) aware of the Frustum / Projection matrix thing, but I can't quite see the whole picture, I'd be glad if someone could illuminate me on this, with some practical example, since I'm pretty new to all this and I'm struggling a little to get my head around it.
The first think that came to my head to solve this problem was to create a mesh and use it as a dummy to detect the boundaries of the canvas, but I was wondering if it would be a more convenient way to achieve this.
Just FYI I need this for a script that should draw a 2d grid of lines, with a fixed camera.


text:
Q: How to change a dataframe column from list value to multiple columns in r? This is my dataframe df:

    A                 B                            C
1   14      list('one'=1,'two'=3,'three'=98)     1.12
2   1       list('one'=8,'two'=87,'three'45)     0.98
3   81      list('one'=4,'two'=41,'three'19)     1.02
4   11      list('one'=4,'two'=0 ,'three'0 )     1.15
5   10      list('one'=1,'two'=1 ,'three'12)     0.80

I want the 'B' column which is a list to be splitted in different columns
and the new columns' names should contain the old column name + the lists' names.
The output should be like this:

    A     B.one  B.two  B.three  C
1   14      1     3       98     1.12
2   1       8     87      45     0.98
3   81      4     41      19     1.02
4   11      4     0       0      1.15
5   10      1     1       12     0.80
'

A: You should be able to use tidyr::unnest_wider. Example:
df = data.frame(a = 1:3)
df$b = list(list(x = 1, y = 2), list(x = 2, y = 5), list(x = 3, y = 4))
df
#   a    b
# 1 1 1, 2
# 2 2 2, 5
# 3 3 3, 4

tidyr::unnest_wider(df, b, names_sep = ".")
# # A tibble: 3 x 3
#       a   b.x   b.y
#   <int> <dbl> <dbl>
# 1     1     1     2
# 2     2     2     5
# 3     3     3     4


text:
Q: docker image build "context canceled" error on windows 10 i'm trying to build a simple r-base official docker image but it's giving me a strange "context cancelled" error on windows 10.
i've tried pulling the image (which was successful) and then building it but i'm getting the same error. i've also tried reinstalling docker or building any other image (R or not) from Docker Hub but i'm having no luck with it as well. the strange thing is when i reinstalled docker, it ran the getting-started tutorial on shell without problems.
what may be happening?
here's my dockerfile
FROM r-base:4.0.2
COPY . /usr/local/src/myscripts
WORKDIR /usr/local/src/myscripts
CMD ["Rscript", "main.R"]

and the shell output
C:\Users\jean\path>docker build -t my-image .
[+] Building 1.7s (5/7)
 => [internal] load build definition from Dockerfile                                                               0.1s
 => => transferring dockerfile: 31B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.1s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/r-base:4.0.2                                                    1.4s
 => CANCELED [internal] load build context                                                                         0.1s
 => => transferring context: 7.08kB                                                                                0.0s
 => CANCELED [1/3] FROM docker.io/library/r-base:4.0.2@sha256:837898ed6a0dc6f9cb0f3d1fa0e801f01673797cdfd3e21c8cd  0.1s
 => => resolve docker.io/library/r-base:4.0.2@sha256:837898ed6a0dc6f9cb0f3d1fa0e801f01673797cdfd3e21c8cd2ad60f2db  0.0s
 => => sha256:837898ed6a0dc6f9cb0f3d1fa0e801f01673797cdfd3e21c8cd2ad60f2dbe2da 765B / 765B                         0.0s
 => => sha256:1c4e181b5dbeef804a4bf1f2c6b888b0d2da333b1a5d99f0e1a3ced46b1cdaef 1.58kB / 1.58kB                     0.0s
 => => sha256:673e45d6ffe13b98601b5e19ec2bfbd4ec1b1c135ed9d9e911f6c83c7b9cef1e 5.35kB / 5.35kB                     0.0s
error from sender: context canceled

A: if you want to run docker build from Rstudio, please add a .dockerignore file containing :
.RData
.Rhistory
.git
.gitignore
manifest.json
rsconnect/
.Rproj.user

A: I ran across the same problem, and discovered the issue was with R/RStudio.  I was running the docker build through the terminal pane and it kept giving me the "error from sender: context canceled" comment.  I believe that R/RStudio locks up the files it is using, which throws a wrench into the docker machinery when it tries to copy the files.  Docker built the image with no problem after I closed RStudio and ran the build through a different terminal.

A: I had the same problem when I was building the image with DOCKER. The problem is shown in the following image.

After that I closed RStudio, it worked!

A: I had the same issue when running a Docker build from the RStudio Terminal. For me adding a Windows Firewall rule to allow the app "RStudio Session" fixed it.
You can change it by Control Panel

Control Panel\System and Security\Windows Defender Firewall\Allowed apps

A: Got same error when tried to run docker-compose in Visual Studio with Release build. Change to Debug solved the problem.

A: Try with sudo in case you are on mac.

A: for windows users, disable 'metered connection' for you network.

A: I had this issue with docker.
For me it was a problem with my Hard Disk Drive.
My project was in one of my drives and I repeatedly got this error.
So I've moved my project to another drive and the problem gone.
I had some bad sectors.
Maybe this happens to you.

A: Mine was a similar error, but supposedly with permission denied to some random file. It turned out to be an issue with my SSD. I ran windows tool for error checking on the drive, let it fix errors it found and it started working fine again.

A: It worked for me after adding .git in .dockerignore file


text:
Q: ECR - Ngnix image with multiple sites I'm working on the deployment of multiple websites with nginx. I want to use ECS for that and create Github actions for automatic deployment on commit. The problem is that I have multiple websites for the same company, and so on, multiple repositories. How can I automatically create an image (ngnix) from different repositories and push it into ECR?

For example, I have 3 repositories: simulator_1, simulator_2, and simulator_3, I want to automatically create a ngnix image that contains simulator_1, simulator_2, and simulator_3 and push it into ECR.

Thanks by advance

A: Finally, I chose to go to one image per repository / one ngnix server per repository, because it seems that ngnix doesn't take too much performance from the server.


text:
Q: AWS Java S3-Upload Error while Runing Applet in HTML I solved the problem upto certain extent by using the following command
$applettviewer -J-Djava.security.policy=java.policy.applet MyApplet.html

it does not show any error like before.
I came to know that my Applet has to be signed even im running in my Local System.
This is my test.html
File Name : test.HTML
<html>
<applet code="*MyApplet.class*"  archive="aws-java-sdk-1.2.12.jar,commons-codec-1.3.jar,commons-logging-1.1.1.jar,httpclient-4.1.1.jar,httpcore-4.1.jar,jackson-core-asl-1.4.3.jar,mail-1.4.3.jar,stax-1.2.0.jar,stax-api-1.0.1.jar" width="500" height="500"></applet>
</html>

my Folder structure is as follows:
bin/
|----------------- MyApplet.class
|----------------- AwsCredentials.properties
|----------------- mime.types
|----------------- required Jar Files
|----------------- java.policy.applet
|----------------- test.html ( HTML file to Load the Applet)

I dont know how to sign the Class file.
Please guide me.
Regards,
Ananthavel

A:
I dont know how to sign the Class file.

See Steps for the Code Signer in the Java tutorial.

A: You need to build your project as jar file. Then using keytool and jarsigner located in bin folder of jdk you need to sign your applet
and change your html as
<applet code="MyApplet.class"  archive="MyApplet.jar,aws-java-sdk-1.2.12.jar,commons-codec-1.3.jar,commons-logging-1.1.1.jar,httpclient-4.1.1.jar,httpcore-4.1.jar,jackson-core-asl-1.4.3.jar,mail-1.4.3.jar,stax-1.2.0.jar,stax-api-1.0.1.jar" width="500" height="500"></applet>


text:
Q: Sandboxed tests with Junit5 (Is Junit4 @RunWith more powerful compared to Junit5 @ExtendWith) So with Junit4 I was able to run tests with my own runner via @RunWith annotation.
This was super powerful and allowed me to use my own "special" class loader for each test.
This "special" class loader job was to reload a subset of classes when those were accessed (actually it could implement different reloading policies but that's beside the point).
What this effectively allowed me to achieve is running each test in a "sandbox".
I had multiple tests that were setting/requiring different values of static class variables running in parallel without stepping on each other toes.
My question is whether it's possible to achieve the same state of nirvana :) with a new Junit5?
Thank you very much for taking time to look and answer this.
My brute force attempt to use @ExtendWith along with custom implementation of TestInstanceFactory that was reloading class and returning instance of "reloaded" class failed miserably with the following exception:
org.junit.jupiter.api.extension.TestInstantiationException message: TestInstanceFactory [<my implementation of TestInstanceFactory class name>] failed to return an instance of [<my-test-class>@<hash as loaded by original loader>] and instead returned an instance of [<my-test-class>@<hash as loaded by my special loader>].

A: Apparently it's possible in Junit5.
See github discussion with proposed solution:
https://github.com/junit-team/junit5/issues/3028#issuecomment-1286880925


text:
Q: Unable to create account for installing Oracle Database So I was looking for installing an Oracle 12c database on my Windows 8 laptop, so that I could learn much of SQL(after posting my last question).
I have downloaded all the needed zips. obviously while trying I got error:
[INS-30131] Initial setup required for the execution of installer validations failed.

Additional Information:
 - Framework setup check failed on all the nodes
 - Cause: Cause Of Problem Not Available
 - Action: User Action Not Available
Summary of the failed nodes
hp
 - Version of exectask could not be retrieved from any node
 - Cause: Cause Of Problem Not Available
 - Action: User Action Not Available

Well after looking into many posts on SO, I figured out that it needs some hidden User account (C$). I got steps for setting up such a account but unfortunately they are not working for me.
Following the path as: Control Panel>Administrative Tools> Computer Management>Shared.
As mentioned in steps across internet, there is no option for me to create a new account.
Apart from that, I have tried changing my Username and also I have tried using default Administrator account but nothing seems working.
I am pretty sure this is not new so somebody out there must have a solution to this issue. Pls advice...

A: This is the description of the error, I saw it, but was trying to find an idea how to fix it.
Anyway, I solved it by renaming  the volume group and updating accordingly the fstab and the grub.conf.


text:
Q: RedirectToAction gets ignored I am using ASP.NET 5. Using the browser Chrome.
My Controller has the following Action Method
public async Task<IActionResult> Index()
{
    return View();
}

[HttpPost]
public IActionResult DoSomething()
{
    //do something
    return RedirectToAction("Index");
}

When I run

http://localhost:59693/MyArea/MyController/DoSomething

via a POST in Index
and have a breakpoint over the line
 return RedirectToAction("Index");

it just ignores the line and goes to the next line without calling the Index action method.
and displays in the browser

http://localhost:59693/MyArea/MyController/DoSomething

with a blank screen.
Surely if you have a return statement then it immediately returns from that method and doesn't jump to the next line. Really odd.
I even tried to the full
 return RedirectToAction("Index","MyController,new {area="MyArea"});

When I put a breakpoint on my Index Action Method it never gets hit.
I even tried
 return Redirect("http://www.google.com");

It still displays

http://localhost:59693/MyArea/MyController/DoSomething

Some bug in ASP.NET 5?
How to I call an action method from an action method in the same controller if the above doesn't work?

A: I changed my DoSomething action method to be asynchronous and added an await clause
[HttpPost]
public async Task<IActionResult> DoSomething()
{
    await _db.callsql();
    //do something start

    return RedirectToAction("Index");
}

The issue seems to be because the actionmethod Index was asynchronous but DoSomething not, combined with me stepping through the code.


text:
Q: suPHP and Apache DBD : change GID only (Note: if you're familiar with suPHP setups and want to skip the question's details, you'll find a quick explanation of what I'm trying to achieve at the end)
I am currently setting up a machine to host several websites, belonging to several users. For convenience purposes, these users are stored in a MySQL database. libnss-mysql and pam-mysql are used to connect this backend and Linux, therefore allowing these users to log-in and use the machine's services. Every user stored in the MySQL database belongs to the users group.
Each of these users is given a home directory under /home/users. For instance, user test' s files can be found under /home/users/test. This directory has the following ownership/permissions:
drwx--x--- test www-data /home/users/test

Similarly, the website index (and other files) display the following permissions:
-rw-r----- test www-data /home/users/test/index.php
-rw-r----- test www-data /home/users/test/robots.txt

In order to allow access to these websites, the following VirtualHost is configured in Apache, using DBD and relying on the MySQL backend.
<VirtualHost *:80>
    ServerName *

    DBDriver mysql
    DBDParams host=localhost,user=user,pass=pass,dbname=db
    DBDocRoot "SELECT document_root FROM users WHERE domain=%s" HOSTNAME
</VirtualHost>

If the domain associated with test is example.com, Apache will use DBD to match this domain with /home/users/test and provide its contents. For instance, example.com/index.php will pass the index to the PHP interpreter, while example.com/robots.txt will have Apache deliver the file as static content.
Now, in order to protect my users from each other, I would like to restrict the permissions of their PHP scripts. With the above setup, PHP scripts go through Apache, and are interpreted by mod_php. Thing is : the Apache process in run by www-data:www-data, which gives access to all homes to any script.
To prevent this, I decided to install suPHP, but here is my problem : suPHP and the DBD MySQL lookup don't actually cooperate well:

*

*If I compile suPHP in paranoid mode, I must set a static user and group for all requests. However, scripts in /home/users/test must be run as test:users, while those in /home/users/othertest must be run as othertest:users.

Here is where the problem happens in the configuration :
<VirtualHost *:80>
    ServerName *

    suPHP_Engine on

    # The user is stored in the database, it can't be set statically.
    suPHP_UserGroup ??user?? users

    DBDriver mysql
    DBDParams host=localhost,user=user,pass=pass,dbname=db
    DBDocRoot "SELECT document_root FROM users WHERE domain=%s" HOSTNAME
</VirtualHost>

*

*If I compile suPHP in owner mode, then all PHP scripts are executed as test:www-data instead of test:users. This will also provide privileges in all home directories.

*If I set all files to a test:users ownership in /home/users/test (and use owner mode), then the web server can no longer access it, even to deliver static contents.
All in all
Is there any way I could combine both DBD MySQL and suPHP, and achieve something between paranoid mode and owner mode? I need to change the executing group from www-data to users (paranoid mode), but the executing user must be the script owner (owner mode). In a simple way :
# The following script must be interpreted as test:users.
-rw-r----- test www-data /home/users/test/index.php

# The following script must be interpreted as othertest:users.
-rw-r----- othertest www-data /home/users/test/index.php

A: I am not sure if I understood your question, but if you are trying to restrict execution and access between different users while removing read permission from others and allowing www-data to access these files you may try to do the following:

*

*Compile suphp with paranoid setid-mode

*Use the virtual host configuration and permissions you already have

*Use extended acls to give read permission to www-data user on the specified folders (setfacL)

Suphp impersonate the script execution by using setuid, it will be based on filesystem permissions after comparing with the suPHP_UserGroup value. Using extended acls would allow www-data user to access all files, but will not permit execution of php scripts as it is not specified on suPHP_UserGroup directive.
You will need to add acl option on your /home filesystem (adding it to fstab and remounting the filesystem will be fine) before adding your extended acls on files and folders.
You can get more information about setfacl on it's manpage (http://linuxcommand.org/man_pages/setfacl1.html), it's fairly complete.


text:
Q: MATLAB: How to apply ifft correctly to bring a "filtered" signal back to the time doamin? I am trying to get the output of a Gaussian pulse going through a coax cable. I made a vector that represents a coax cable; I got attenuation and phase delay information online and used Euler's equation to create a complex array.
I FFTed my Gaussian vector and convoluted it with my cable. The issue is, I can't figure out how to properly iFFT the convolution. I read about iFFt in MathWorks and looked at other people's questions. Someone had a similar problem and in the answers, someone suggested to remove n = 2^nextpow2(L) and FFT over length(t) instead. I was able to get more reasonable plot from that and it made sense to why that is the case. I am confused about whether or not I should be using the symmetry option in iFFt. It is making a big difference in my plots. The main reason I added the symmetry it is because I was getting complex numbers in the iFFTed convolution (timeHF). I would truly appreciate some help, thanks!
clc, clear
Fs = 14E12;          %1 sample per pico seconds
tlim = 4000E-12;
t = -tlim:1/Fs:tlim; %in pico seconds
ag = 0.5;            %peak of guassian
bg = 0;              %peak location
wg = 50E-12;         %FWHM

x = ag.*exp(-4 .* log(2) .* (t-bg).^2 / (wg).^2); %Gauss. in terms of FWHM
Ly = x;

L = length(t);
%n = 2^nextpow2(L);  %test output in time domain with and without as suggested online
fNum = fft(Ly,L);

frange = Fs/L*(0:(L/2)); %half of the spectrum
fNumMag = abs(fNum/L);   %divide by n to normalize

% COAX modulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%phase data
mu = 4*pi*1E-7;
sigma_a = 2.9*1E7;
sigma_b = 5.8*1E6;
a = 0.42E-3;
b = 1.75E-3;
er = 1.508;
vf = 0.66;
c = 3E8;
l = 1;
Lso = sqrt(mu) /(4*pi^3/2) * (1/(sqrt(sigma_a)*a) + 1/(b*sqrt(sigma_b)));
Lo = mu/(2*pi) * log(b/a);
%to = l/(vf*c);
to = 12E-9; %measured
phase = -pi*to*(frange + 1/2 * Lso/Lo * sqrt(frange));

%attenuation Data
k1 = 0.34190;
k2 = 0.00377;
len = 1;
mldb = (k1 .* sqrt(frange) + k2 .* frange) ./ 100 .* len ./1E6;
mldb1 = mldb ./ 0.3048; %original eqaution is in inch
tfMag = 10.^(mldb1./-10);

% combine to make in complex form
 tfC = [];
     for ii = 1: L/2 + 1
        tfC(ii) = tfMag(ii) * (cosd(phase(ii)) + 1j*sind(phase(ii)));
     end

%END ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%convolute both h and signal
fNum = fNum(1:L/2+1);
convHF = tfC.*fNum;
convHFMag = abs(convHF/L);
timeHF = ifft(convHF, length(t), 'symmetric');  %this is the part im confused about

% Ignore,
% tfC(numel(fNum)) = 0;
% convHF = tfC.*fNum;
% convHFMag = abs(convHF/n);
% timeHF = ifft(convHF);

%% plotting

% subplot(2, 2, 1);
% plot(t, Ly)
% title('Gaussian input');
% xlabel('time in seconds')
% ylabel('V')
% grid

subplot(2, 2, 1)
plot(frange, abs(tfC(1: L/2 + 1)));
set(gca, 'Xscale', 'log')
title('coax cable model')
xlabel('Hz')
ylabel('|H(s)|V/V')
grid
ylim([0 1.1])

subplot(2, 2, 2);
plot(frange, convHFMag(1:L/2+1), '.-', frange, fNumMag(1:L/2+1)) %make both range and function the same lenght
title('The input signal Vs its convolution with coax');
xlabel('Hz')
ylabel('V')
legend('Convolution','Lorentzian in frequecuency domain');
xlim([0, 5E10])
grid

subplot(2, 2, [3, 4]);
plot(t, Ly, t, timeHF)
% plot(t, real(timeHF(1:length(t)))) %make both range and function the same lenght
legend('Input', 'Output')
title('Signal at the output')
xlabel('time in seconds')
ylabel('V')
grid

A: It's important to understand deeply the principles of the FFT to use it correctly.
When you apply Fourier transform to a real signal, the coefficients at negative frequencies are the conjugate of the ones at positive frequencies. When you apply FFT to a real numerical signal, you can show mathematically that the conjugates of the coefficients that should be at negative frequencies (-f) will now appear at (Fsampling-f) where Fsampling=1/dt is the sampling frequency and dt the sampling period. This behavior is called aliasing and is present when you apply fft to a discrete time signal and the sampling period should be chosen small enaough for those two spectra not to overlap Shannon criteria.
When you want to apply a frequency filter to a signal, we say that we keep the first half of the spectrum because the high frequencies (>Fsampling/2) are due to aliasing and are not characteristics of the original signal. To do so, we put zeros on the second half of the spectra before multiplying by the filter. However, by doing so you also lose half of the amplitude of the original signal that you will not recover with ifft. The option 'symmetric' enable to recover it by adding in high frequencis (>Fsampling/2) the conjugate of the coefficients at lower ones (<Fsampling/2).
I simplified the code to explain briefly what's happening and implemented for you at line 20 a hand-made symmetrisation. Note that I reduced the sampling period from one to 100 picoseconds for the spectrum to display correctly:
close all
clc, clear
Fs = 14E10;          %1 sample per pico seconds % CHANGED to 100ps
tlim = 4000E-12;
t = -tlim:1/Fs:tlim; %in pico seconds
ag = 0.5;            %peak of guassian
bg = 0;              %peak location
wg = 50E-12;         %FWHM
NT = length(t);

x_i = ag.*exp(-4 .* log(2) .* (t-bg).^2 / (wg).^2); %Gauss. in terms of FWHM
fftx_i = fft(x_i);
f = 1/(2*tlim)*(0:NT-1);

fftx_r = fftx_i;
fftx_r(floor(NT/2):end) = 0; % The removal of high frequencies due to aliasing leads to losing half the amplitude
% HER YOU APPLY FILTER
x_r1 = ifft(fftx_r); % without symmetrisation (half the amplitude lost)
x_r2 = ifft(fftx_r, 'symmetric'); % with symmetrisation
x_r3 = ifft(fftx_r+[0, conj(fftx_r(end:-1:2))]); % hand-made symmetrisation

figure();
subplot(211)
hold on
plot(t, x_i, 'r')
plot(t, x_r2, 'r-+')
plot(t, x_r3, 'r-o')
plot(t, x_r1, 'k--')
hold off
legend('Initial', 'Matlab sym', 'Hand made sym', 'No sym')
title('Time signals')
xlabel('time in seconds')
ylabel('V')
grid
subplot(212)
hold on
plot(f, abs(fft(x_i)), 'r')
plot(f, abs(fft(x_r2)), 'r-+')
plot(f, abs(fft(x_r3)), 'r-o')
plot(f, abs(fft(x_r1)), 'k--')
hold off
legend('Initial', 'Matlab sym', 'Hand made sym', 'No sym')
title('Power spectra')
xlabel('frequency in hertz')
ylabel('V')
grid

Plots the result:

Do not hesitate if you have further questions. Good luck!
---------- EDIT ----------
The amplitude of discrete Fourier transform is not the same as the continuous one. If you are interested in showing signal in frequency domain, you will need to apply a normalization based on the convention you have chosen. In general, you use the convention that the amplitude of the Fourier transform of a Dirac delta function has amplitude one everywhere.
A numerical Dirac delta function has an amplitude of one at an index and zeros elsewhere and leads to a power spectrum equal to one everywhere. However in your case, the time axis has sample period dt, the integral over time of a numerical Dirac in that case is not 1 but dt. You must normalize your frequency domain signal by multiplying it by a factor dt (=1picoseceond in your case) to respect the convention. You can also note that this makes the frequency domain signal homogeneous to [unit of the original multiplied by a time] which is the correct unit of a Fourier transform.


text:
Q: multidimensional Lists? Until now I used multidimensional arrays int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6}}; but now I need something dynamic like list. Is there such a thing as multidimensional lists? I want to create something like a table with 4 columns. The 4th column should be a 10sec timer and when the 10seconds pass and column 2 and 3 on the specific line are not filled the whole line should be deleted from the list.

A: In .NET 4 you could create a list of tuples.

A: Try
class Foo{
    public int Col1 { get;set; }
    public int Col2 { get;set; }
    public int Col3 { get;set; }
    public int Col4 { get;set; }
}

and List<Foo>

A: what you want is List< List< yourtype > >
this will give you what you want:
List< List<int> > lst = new List< List< int > >;
lst.Add( new List<int>() );
lst[0].Add( 23 );
lst[0][0] == 23;

A: I suggest you create a class that encapsulates what you said a single "line" in your list should do. It will give your code that much more expressiveness and be far more readable, which is the core trait of any good code.
So in the end you will have List<YourSpecificClass>

A: You can just use a list that contains list like:
var multiList = new List<List<int>>();

After reading through your question again I don't think this is what you want. My guess is that you want something like this:
public class Item
{
    public int? Col1 { get; set; }
    public int? Col2 { get; set; }
    public int? Col3 { get; set; }
    private Timer Timer { get; set; }
    public List<Item> ParentList { get; set; }

    public Item()
    {
        Timer = new Timer();
        Timer.Callback += TimerCallBack();
        // Set timer timeout
        // start timer
    }

    public void AddToList(List<Item> parentList)
    {
        parentList.Add(this);
        ParentList = parentList;
    }

    public void TimerCallBack()
    {
        if(!Col3.HasValue || !Col2.HasValue)
        {
            ParentList.Remove(this);
        }
    }
}
....
var list = new List<Item>();
var item = new Item { /*Set your properties */  };
item.AddToList(list);

That should get you started. You can read about the Timer here.

A: It really depends on your application.  You could use List<List<int>>, for instance, and add new items thusly:
myList.Add(new List<int> { 0, 0, 0, 0 });

It sounds from your last comment that you're going to be applying specific logic to the items in this list, which suggests the possibility that you should create a class for your items, e.g.
public class Item
{
   public int Col1 { get; set; }
   public int Col2 { get; set; }
   public int Col3 { get; set; }
   public int Col4 { get; set; }

   public bool CanRemove { get { return Col2==0 && Col3 == 0 && Col4 == 0; } }

and then create a List<Item>.  Then you can remove entries from it via:
var toRemove = myList.Where(x => x.CanRemove).ToList();
foreach (Item it in toRemove)
{
   myList.Remove(it);
}


text:
Q: How to split string based on delimiters in Java I would like to split string based on the delimiters.
The example string is: ["INESIS","13-ARTENGO-P1046","19"]
It should be divided into three string after splitting.
String data="[\"INESIS\",\"13-ARTENGO-P1046\",\"19\"]";
String[] values=data.split(",");

I have tried in the above way, but it isn't working.

A: try
String data="[\"INESIS\",\"13-ARTENGO-P1046\",\"19\"]";
you must put the escape character \ before each " otherwise java thinks that you ended your string
This way you tell java that you didn't mean to cut the string but that " is part of your string

A: First you need to provide String in valid form.
Eg:
String data="[\"INESIS\",\"13-ARTENGO-P1046\",\"19\"]"; // escape "

Then you need to remove [ and ]. You can use replaceAll("\\[|\\]","") for that.
Then split from ,
Eg:
String data="[\"INESIS\",\"13-ARTENGO-P1046\",\"19\"]";
String[] values=data.replaceAll("\\[|\\]","").split(",");
for(String i:values){ // just to print the values
   System.out.println(i);
}

Out put:
"INESIS"
"13-ARTENGO-P1046"
"19"

A: To split a string on the basis of other string, StringTokenizer class can be used.
Here is a code snippet for this
    String str = "Splitting, Using, Comma"
    System.out.println("---- Split by comma ',' ------");
    StringTokenizer st2 = new StringTokenizer(str, ",");

    while (st2.hasMoreElements()) {
        System.out.println(st2.nextElement());
    }