text:
Q: Json data stored in a string type column, how to interact with it I have a column of type String where json data is stored, I am not able to interact with this column.
    id                          active  indicators
0   617f27ad9df9b10b633d5850    True    [{'_id': '617abc32fe562a3281b4448d', 'column': 'created_at', 'indicatorId': '61088233be3a2e04a2d3d8f8', 'value': '00-00-00', 'key': '****'}, {'_id': '617abc32fe562a4441b2268e', 'column': 'hash', 'indicatorId': '61088233be3a2e04a2d3d8fc', 'value': '14fsdfsd44*', 'key': '****'}

The column types
df_raw_nps.dtypes
id                               string
active                           boolean
indicators                       string
dtype: object

I'm trying to access to create new columns according to the values of the fields "column" and "value" of this json.
d2 = pd.DataFrame([{n['column']:n['value'] for n in i}for i in df['indicators']])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----> 1 d2 = pd.DataFrame([{n['column']:n['value'] for n in i}for i in df['indicators']])

TypeError: string indices must be integers

The result was to be like this:
    id                          active  created_at  hash
0   617f27ad9df9b10b633d5850    True    00-00-00    14fsdfsd44*

Does anyone know what I'm doing wrong? I've tried to convert the column to a json object but without success.

A: As you have shown that the columns contains a string (which BTW is not a valid Json because it uses simple quotes...), you must literal_eval it:
d2 = pd.DataFrame([{n['column']:n['value'] for n in ast.literal_eval(i)}
                   for i in df['indicators']], index = df.index)

From there you have just to horizontaly concat it:
pd.concat((df.drop(columns='indicators'), d2), axis = 1).to_string()

to get as expected:
                         id  active created_at         hash
0  617f27ad9df9b10b633d5850    True   00-00-00  14fsdfsd44*


text:
Q: How to check internet connection in Phonegap periodically? I am working with Phonegap. I need to check the network connection periodically. Actually I am getting some data from a server. If there is no connection, I need to show an error alert.
I googled it and found the solution. But it is not ok. Because I need to check the connection periodically.

    <title>navigator.network.connection.type Example</title>

A dialog box will report the network state.

It check only the first time when the application launches. But I need to check it periodically, because I am doing socket programming. If there is a problem with internet, I need to show it. But this code only shows at launch time.

A: Perhaps you could use the 'online' and 'offline' event listeners on the document to notify your App when it becomes online or offline, as described in the docs eg. here: http://docs.phonegap.com/en/3.2.0/cordova_events_events.md.html#online

A: Unfortunately the answer is not stable on Chrome and Safari as well as several mobile browsers. It does not give you the "real Internet connection" state but rather the "network connection state". See:
https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.onLine
"In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. To learn more, see the HTML5 Rocks article, Working Off the Grid."
See this HTML5 Rocks article for a true stable solution - more work of course:
http://www.html5rocks.com/en/mobile/workingoffthegrid/

A: Working example: http://jsfiddle.net/Gajotres/d5XYR/
Use interval timer to check internet connection every predefined time. This solution requires HTML5 browser but this is not a problem because jQuery Mobile already requires HTML5 browser. In this case timer will check internet connection every 100 ms and set final result into a javascript global variable.
Everything depends on this line:
window.navigator.onLine -- it will be false if the user is offline.

Final solution:
var connectionStatus = false;

$(document).on('pagebeforeshow', '#index', function () {
    setInterval(function () {
        connectionStatus = navigator.onLine ? 'online' : 'offline';
    }, 100);
    $(document).on('click', '#check-connection', function () {
        alert(connectionStatus);
    });
});

Tested on:

*

*Windows Firefox

*Windows Google Chrome

*Windows IE9 and IE10

*Android 4.1.1 Chrome

*iPad 3 Safari

*iPad3 Chrome

A: Try this code,

For More Details Click Here..!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Three.js and Perlin.js terrain generation issues I am having issues with my perlin noise terrain generation in javascript. All the hills are pointing one way.
Another issue I have is that diagonally through the middle of my map my terrain gets screwed up.
https://i.stack.imgur.com/YPLSz.png
Here's my code:
//Generate terrain
var xoff = 0;
var zoff = 0;
var inc = 0.005;
var amplitude = 100;

for (var x = 0; x <= worldDiameter+1; x++) {
    xoff = 0;
    for (var z = 0; z <= worldDiameter+1; z++) {
        var heightValue = (noise.perlin2(xoff, zoff) * amplitude);

        mapGeometry.attributes.position.setZ(z*worldDiameter+x, heightValue);

        xoff = xoff + inc;
    }
    zoff = zoff + inc;
}```


text:
Q: CASE on Alias Column selected in SubQuery and Alias column in WHERE CLAUSE I have two questions.

*

*Remove the row WHERE difference_previous_level is 0 for the same time , which means I don't want to repeat the row with the same time. In the screenshot attached we shouldn't have row no 331 because it has same time as row 332 and difference_previous_level is 0 while row 332 should stay here. While difference_previous_level and previous_level are Alias columns.
Image where row 331 should delete

*Apply CASE on Alias Column selected in the sub query. I want to apply CASE on difference_previous_level WHEN VALUE not 0 THEN regenzähler column value, e.g in row no 332, difference_previous_level is 2 it should have value 2103 from Regenzähler.
Here is what I have:

SELECT DISTINCT time_time , col_2 AS Regenzähler,  LAG(col_2) OVER (ORDER BY time_time ) AS previous_level,  col_2-LAG(col_2) OVER (ORDER BY time_time ) AS difference_previous_level
FROM  raindata
Order by time_time, difference_previous_level

I tried both but error is alias column doesn't exit.

A: *

*You could add a column with LAG for column time_time and then filter out rows with difference_previous_level=0 AND time_time = previous_time_time.

SELECT t.* FROM
(
    SELECT
        DISTINCT time_time ,
        LAG(time_time) OVER (ORDER BY time_time )   AS previous_time_time,
        col_2                                       AS Regenzähler,
        LAG(col_2) OVER (ORDER BY time_time )       AS previous_level,
        col_2-LAG(col_2) OVER (ORDER BY time_time ) AS difference_previous_level
    FROM  raindata
) t
WHERE NOT (t.difference_previous_level = 0 AND t.previous_time_time = t.time_time)
ORDER BY t.time_time, t.difference_previous_level

*Try like below:

SELECT
    t.*,
    CASE
        WHEN difference_previous_level <> 0 THEN t.Regenzähler
        ELSE difference_previous_level
    END AS new_column
FROM
(
    SELECT
        DISTINCT time_time ,
        LAG(time_time) OVER (ORDER BY time_time )   AS previous_time_time,
        col_2                                       AS Regenzähler,
        LAG(col_2) OVER (ORDER BY time_time )       AS previous_level,
        col_2-LAG(col_2) OVER (ORDER BY time_time ) AS difference_previous_level
    FROM  raindata
) t
WHERE NOT (t.difference_previous_level = 0 AND t.previous_time_time = t.time_time)
ORDER BY t.time_time, t.difference_previous_level


text:
Q: estoy intentando extraer una imagen desde una ruta guardada en la base de datos :( y me sale este error estoy intentando extraer una imagen desde una ruta guardada en la base de datos :(  y me sale este error:
Fatal error: Uncaught TypeError: mysqli_query():
Argument #1 ($mysql) must be of type mysqli, string given in
C:\xampp\htdocs\mostrar img\index.php:10 Stack trace: #0
C:\xampp\htdocs\mostrar img\index.php(10):
mysqli_query('SELECT * FROM p...', Object(mysqli)) #1 {main} thrown in
C:\xampp\htdocs\mostrar img\index.php on line 10

conexion.php es aparte...
index

    <meta http-equiv="Content-Type" content="text/html" ; charset="iso-8859-1" />
    <title>Index</title>

    <?php
    include("conexion.php");
    mysqli_select_db($conexion, $base);
    $result = mysqli_query("SELECT * FROM productos", $conexion) or die("Error en: busqueda" . mysql_error());
    if ($row = mysql_fetch_array($result)) {
        do {
            $ruta = $row['url_imagen']
    ?>
            <img src="<?php echo $ruta; ?>" width="190" height="160">

    <?php
            echo "
";
            echo "" . $row["producto"] . "
";
            echo "
";
        } while ($row = mysql_fetch_array($result));
    } else {
        echo "No Se Ha Encontrado Ningun Registro";
    }
    ?>

Conexion.php (en un archivo aparte)
<?php
    $conexion = mysqli_connect('localhost','root','123');
    $base = "img";
?>


text:
Q: Allocating/initializing Swift object from Objective-C I am working on an app where I am getting an API response and need to create objects from this and put it in an Array to use later. The API call is made in Objective-C, but my new Object is made in Swift (it's an old app with mostly Objective-C code).
The API call itself is working fine, but when I try to convert this the object an object is not made.
This is the object code (Swift):
import Foundation

@objc
class GCBOKSProductInfo: NSObject, NSCoding {

var featureName: String = ""
var available: Bool = false

static let sharedInstance = GCBOKSProductInfo()

override init() {
    super.init()
}

init(featureName: String, available: Bool) {
    super.init()

    self.featureName = featureName
    self.available = available
}

convenience required init?(coder decoder: NSCoder) {
    guard let featureName = decoder.decodeObject(forKey: "featureName") as? String
        else { return nil }

    self.init(
        featureName: featureName,
        available: decoder.decodeBool(forKey: "available")
    )
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(featureName, forKey: "featureName")
    aCoder.encode(available, forKey: "available")
}

}

and here is where I am trying to make an object out of the API response:
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[responseObject count]];
for (NSDictionary *boksProductInfoDict in responseObject) {

    NSString *featureName = boksProductInfoDict[@"FeatureNaam"];
    NSString *available = boksProductInfoDict[@"Beschikbaar"];

    GCBOKSProductInfo *boksProductInfo = [[GCBOKSProductInfo alloc] initWithFeatureName:featureName available:available.boolValue];

    [result addObject:boksProductInfo];
}

The extracting of the featureName and available works (if I put a breakpoint in the object I see that it is made correctly), but the "boksProductInfo" never seems to be allocated/initialized correctly, so when I add it to the "result" array there is no information in the entry.
If I try to po the "boksProductInfo" I get this:
ProjectName.GCBOKSProductInfo: 0x60800005ee70
And if I try to po "boksProductInfo.featureName" I get this:
error: member reference type 'GCBOKSProductInfo *' is a pointer; did you mean to use '->'?
error: incomplete definition of type 'GCBOKSProductInfo'
forward declaration of 'GCBOKSProductInfo'
Any idea where I might have it wrong?


text:
Q: Ubuntu unattended upgrades to run at a certain time I'm trying to work out the best way to run unattended upgrades every Thursday at 3am but can only see a way to run this weekly but not a given time.
I thought of one way would be to have a script that is called by cron on Thursday at 3am
The below script would work just for security updates
#!/bin/sh
sh -c 'grep precise-security /etc/apt/sources.list > /etc/apt/secsrc.list'
sh -c 'apt-get -o Dir::Etc::sourcelist="secsrc.list" \
-o Dir::Etc::sourceparts="-" update && \
apt-get --assume-yes upgrade'

Any thoughts on another way?

A: What wrong with doing it this way? If you just add a cron rule 0 3 * * Thu USERNAME SCRIPT  it should work fine.

A: try using cron-apt, here is my config:
APTCOMMAND=/usr/bin/aptitude # or /usr/bin/apt-get
MAILON="always"
SYSLOGON="upgrade"
MAILTO="ruslanas.gzibovskis@ittc.vu.lt"
OPTIONS="-o quiet=2"

and actions.d/3-download i modified:
autoclean -y
dist-upgrade -d -y -o APT::Get::Show-Upgraded=true
upgrade -y -o APT::Install-Recommends=false -o APT::Install-Suggests=false
dist-upgrade -y -o APT::Install-Recommends=false -o APT::Install-Suggests=false
clean

hope that will help ;)


text:
Q: TSQL - Appending text to a datetime in the SELECT gives unwanted order of operations I have a query:
SELECT TOP 3
    Person.Name AS PersonName,
    YEAR(Person.DateBorn)/100 AS JustCenturyNumbers,
    Person.PersonNumber AS RestOfDateTimeNumbers,
    YEAR(Person.DateBorn)/100+Person.PersonNummer AS CompleteDateTimeNumber
FROM Person

What I want is to append the RestOfDateTimeNumbers to JustCenturyNumbers and get a complete datetime number representation like:
PersonName  JustCenturyNumbers  RestOfDateTimeNumbers   CompleteDateTimeNumber
Tim         20                  0003167012              200003160000
Fred        19                  0009272725              190009270000
Jenny       19                  0106207228              190106200000

But what I get is:
PersonName  JustCenturyNumbers  RestOfDateTimeNumbers   CompleteDateTimeNumber
Tim         20                  0003167012              3167032
Fred        19                  0009272725              9272744
Jenny       19                  0106207228              106207247

I guess that the /100-function is somehow applied to the rest of the string somehow rather than the date alone, but I've been unable to solve it as I'm new to TSQL-functions.
Any idea of how I can fix this and get the result I want?
I use TSQL and SQL-Server 2008 (rt).

A: in your query you are adding two int values
change it to string concat by casting values to varchar
SELECT TOP 3
    Person.Name AS PersonName,
    YEAR(Person.DateBorn)/100 AS JustCenturyNumbers,
    Person.PersonNumber AS RestOfDateTimeNumbers,
    cast(YEAR(Person.DateBorn)/100 as varchar(2))+cast(Person.PersonNummer as varchar(16)) AS CompleteDateTimeNumber
FROM Person

A: You're falling foul of Data Type Precedence when doing the concatenation. You need to CAST the first part of your formula to varchar if you want the final result to be treated as text rather than numeric:
SELECT TOP 3
    Person.Name AS PersonName,
    YEAR(Person.DateBorn)/100 AS JustCenturyNumbers,
    Person.PersonNumber AS RestOfDateTimeNumbers,
    CAST(YEAR(Person.DateBorn)/100 AS varchar(2)) +Person.PersonNumber AS CompleteDateTimeNumber
FROM Person

A: If you use a derived table (nested SELECT), it's real easy.
SELECT
t.*,
cast( JustCenturyNumbers as varchar(50) ) +
cast( RestOfDateTimeNumbers as varchar(50) )
as CompleteDateTimeNumber
FROM
(
    SELECT TOP 3
    Person.Name AS PersonName,
    YEAR(Person.DateBorn)/100 AS JustCenturyNumbers,
    Person.PersonNumber AS RestOfDateTimeNumbers,
    FROM Person
) t


text:
Q: Why in the following code, Father always goes below %mother? I want that "Father is over mother". Why in the following code, Father always goes below mother?
\documentclass{article}
\usepackage{calc}
\usepackage{tikz}
\usetikzlibrary{trees}

\begin{document}
\newlength\treeheight
\setlength{\treeheight}{\textheight-2cm}
\begin{tikzpicture}[grow=right,anchor=west,
  every node/.style={},
  level 1/.style={sibling distance=\treeheight/2},
  level 2/.style={sibling distance=\treeheight/4},
  level 3/.style={sibling distance=\treeheight/8}]
  % parents
  \node {My Family Tree}[edge from parent fork right]
    child { node {Father}
      child{ node {Paternal Gfather}
        child{ node {Paternal GGfather}}
        child{ node {Paternal GGmother}}
      }
      child{ node {Paternal Gmother}
        child{ node {Maternal GGfather}}
        child{ node {Maternal GGmother}}
      }
    }
    child { node {Mother}
      child{ node {Maternal Gfather}}
      child{ node {Maternal Gmother}}
    }

  ;
  \end{tikzpicture}
\end{document}

A: As suggested by Ignasi, you should use grow'=right instead of grow right. grow', when used, arranges the children in the opposite order. Further, you may like to add some inner separation to all nodes and split long nodes using align=left as I did. I have also adjusted the level distance in the code to adjust the distance between levels.
\documentclass{article}
\usepackage{calc}
\usepackage{tikz}
\usetikzlibrary{trees}

\begin{document}
\newlength\treeheight
\setlength{\treeheight}{\textheight-2cm}
\begin{tikzpicture}[grow'=right,anchor=west,
  every node/.style={align=left,inner sep=4pt},
  level 1/.style={sibling distance=\treeheight/2},
  level 2/.style={sibling distance=\treeheight/4},
  level 3/.style={sibling distance=\treeheight/8}]
  % parents
  \node[anchor=east] {My Family\\ Tree}[edge from parent fork right,level distance=1in]
    child { node {Father}
      child{ node {Paternal\\ Gfather}
        child{ node {Paternal\\ GGfather}}
        child{ node {Paternal\\ GGmother}}
      }
      child{ node {Paternal\\ Gmother}
        child{ node {Maternal\\ GGfather}}
        child{ node {Maternal\\ GGmother}}
      }
    }
    child { node {Mother}
      child{ node {Maternal\\ Gfather}}
      child{ node {Maternal\\ Gmother}}
    }

  ;
  \end{tikzpicture}
\end{document}


text:
Q: Maven, how to add additional libs not available in repo I have a maven project that has a set of library dependancies that are not available via any maven repository.  How can I add those libraries to the pom? I want to do this so when I run 'mvn eclipse:eclipse' it doesnt remove those libraries from the eclipse classpath.

A: You can declare it as a dependency with system scope.
<project>
...
 <dependencies>
   <dependency>
     <groupId>sun.jdk</groupId>
     <artifactId>tools</artifactId>
     <version>1.5.0</version>
     <scope>system</scope>
     <systemPath>${java.home}/../lib/tools.jar</systemPath>
   </dependency>
 </dependencies>
 ...
</project>

A: You have 3 options:

*

*Add your libraries to your local repository via install:install-file (obviously, this is not portable, you won't be able to build the project on another machine without doing the same).

*Install and run an "enterprise repository" like Nexus, Archiva, or Artifactory and add your libraries via deploy:deploy-file.

*Setup a file based repository as described in this previous answer and put your libraries in there.

Then, declare your libraries in your pom like any other dependency.

A: You can include them with your project in a sub-directory (perhaps lib/).  You can also provide .bat and/or .sh files containing all the appropriate calls to the maven-install-plugin necessary for each project member (or server env) to add these jars to the local repo.
This approach allows new project members to get up & running quickly, without having to invest several hours in setting up a new public repo for your project or team.

A: You can't 'add them to the pom'. You have to put them in some repo. You can put them in the local repo with the maven-install-plugin, as suggested by the error message. Or you can deploy them in a local copy of Nexus or something like it.

A: recently I created a small UI Util to install libraries to you local repository.
It works the same way as install:install-file.
https://github.com/escv/maven-install-ui


text:
Q: SaveFileDialog Menuclick Item Doesnt Work. If I set path = "C:\\MSREAD.txt";  and Click on SaveAs Menu Item ,it saves Filetext,But If I dont give the String path and save it from saveFD.FileName it doesnt work.Please help me with this issue.
Thanks a lot
public void SaveToFile()
{
    String SavedFile = "";
    saveFD.InitialDirectory = @"C:";
    saveFD.Title = "Save a Text File";
    saveFD.FileName = "";
    RichTextBox richTextBox1 = new RichTextBox();

    saveFD.Filter = "Text Files|*.txt|All Files|*.*";
    try
    {
        if (saveFD.ShowDialog() != DialogResult.Cancel)
        {
            SavedFile = saveFD.FileName;
            path = SavedFile.ToString();
            //path = "C:\\MSREAD.txt";
            MessageBox.Show(path);
            richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
            SaveMyTextBoxContents(path);
        }
    }
    catch(Exception e)
    {
     MessageBox.Show(e.ToString());
    }
}

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    SaveToFile();
}

public void SaveMyTextBoxContents(string path)
{
    if (listBoxItems.SelectedIndex == -1)
    {
        if (rdBtnSlow.Checked && rdBtnNo.Checked)
        {
            using (StreamWriter outputFile = new StreamWriter(path))
            {
                foreach (string item in listBoxItems.Items)
                {
                    saveAllText = slowNo + " " + item;
                    outputFile.WriteLine(saveAllText);
                }
            }
        }
    }
}

A: Here is your problem:
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);

You first save the richTextBox text to file, but then override the same file with SaveMyTextBoxContents, However  the file is empty because of SaveMyTextBoxContents method will only save something if some conditions are true "not selected item and both check boxes are checked", and the listBoxItems.Items.Count > 0 which apparently not the case


text:
Q: Performing a SHA256 Hash on RIPEMD160 Message Digest I am trying to perform a SHA256 hash on the message digest of a RIPEMD 160 hash. I am using the OpenSSL library on the Mac platform.
The issue I am having is the intermediary process of taking the message digest of the RIPEMD 160 and then performing another SHA256 hash on it. So far I have only been able to perform 1) a SHA256 Hash on a string, 2) a RIPEMD160 hash on a string in isolation. I need to perform a RIPEMD160 hash on a previous SHA256 message digest then perform a second SHA256 hash on the RIPEMD 160 digest......
SHA256 digest-> RIPEMD160 hash function-> RIPEMD160 digest -> 2nd SHA256 Hash function. I hope this makes sense....?
Code for SHA256 Hash function on just a String
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;

for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{

    ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();

}
Code for RIPEMD160 Hash on just a String
 int main()
 {

  unsigned char digest[RIPEMD160_DIGEST_LENGTH];

  char string[] = "hello world";

  RIPEMD160((unsigned char*)&string, strlen(string), (unsigned
  char*)&digest);

  char mdString[RIPEMD160_DIGEST_LENGTH*2+1];

     for(int i = 0; i < RIPEMD160_DIGEST_LENGTH; i++)
     sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

     printf("RIPEMD160 digest: %s\n", mdString);

  return 0;

}

A:
Code for SHA256 Hash function on just a String

SHA256 doesn't operate on strings.  SHA256 operates on bytes.  Unfortunately, in C, they are frequently the same data type.
Once you leave Caesar and Vigenere behind cryptography doesn't work on strings. This is very important to remember.

Assuming that your input data IS a text string, and it IS currently represented in the expected encoding (US-ASCII / ISO-8859-1 / UTF-8) then, after correcting some bad pointers, your code is fine:
unsigned char digest[RIPEMD160_DIGEST_LENGTH];
...
RIPEMD160((unsigned char*)string, strlen(string), (unsigned char*)digest);

Now digest contains your RIPEMD160 digest.  We recall that cryptography only operates on bytes, and that digest is bytes, and we get
unsigned char hash[SHA256_DIGEST_LENGTH];

SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, digest, RIPEMD160_DIGEST_LENGTH);
SHA256_Final(hash, &sha256);

Or the accelerator version, like you did with RIPEMD160:
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(digest, RIPEMD160_DIGEST_LENGTH, hash);


text:
Q: In Python, how to write back a stringIO text file to a zip archive, then back to bytea field in PostgreSQL? A relative noob to Python, I've successfully pulled a text file, out of a zip archive, contained in a PostgreSQL bytea field, using this code:
myzip = ZipFile(StringIO(rv[0]["archivefield"]), 'a')
data = myzip.read("content.txt",'a')

# *** WORK ON content.txt HAPPENS HERE ***

I've then done the work I need on that text file...  So far, so good!
Now, though, am a bit confused on syntax to get the content.txt zipped back into its correct place in the archive, then written back to 'archivefield'.
Could any of you experts here suggest the little bit of syntax I'd need? Almost there!
Well, thanks to help received here - we're now certainly writing back to 'archivefield' - this is great!
Issues now are:
1) I'm apparently doubling the size of the original field. Is this a function of 'append' mode? How to 'wind back to zero and rewrite over the field?
- and/or -
2) data I'm writing back doesn't encode back into hex(?) mode as the original data appeared to be - and would be standard for v9 of PostgreSQL.
- OR -
Is the problem that the data is not being zipped again, hence its large size?

A: Use ZipFile.writestr:
strf = StringIO(rv[0]["archivefield"])
zipf = ZipFile(strf, "a")
data = myzip.read("content.txt"')

# process data, changing its value

zipf.writestr("content.txt", data)
zipf.close()  # actually write contents out

then write str.getvalue() back to your PostgreSQL database, overwriting the previous value at rv[0]["archivefield"]. I can't help you with that, I'm afraid.


text:
Q: Writing XML RSS Friendly feeds function I'm trying to write a xml rss feed but noticed I'm getting problems with £ & etc...
Does anybody have a php function to strip / replace all bad characters?
Cheers

A: Found a bug in the code - sorted!


text:
Q: chrome.webRequest is undefined Not sure where I'm going wrong here:
content.js
chrome.webRequest.onBeforeRequest.addListener(
  function(info) {
    console.log("URL intercepted: " + info.url);
  },
  // filters
  {
    urls: [
      "<all_urls>"
    ]
  },
  // extraInfoSpec
  ["blocking"]
);

manifest.json
{
  "name": "Color Changer",
  "author": "Microsoft Edge Extension Developer",
  "description": "Change the color of the body on learn.microsoft.com",
  "version": "1.0",
  "manifest_version": 2,
  "icons": {
    "25": "images/color-changer25.png",
    "48": "images/color-changer48.png"
  },
    "permissions": [
    "webRequest",
    "webRequestBlocking",
        "tabs",
        "notifications",
        "http://*/",
        "https://*/"
    ],
  "browser_action": {
    "default_icon": {
      "20": "images/color-changer20.png",
      "40": "images/color-changer40.png"
    },
    "default_title": "Color Changer",
    "default_popup": "popup.html"
  },
  "content_scripts": [{
    "matches": [
        "<all_urls>"
    ],
    "js": [
      "js/jquery-3.5.1.min.js",
      "js/content.js"
    ],
    "run_at": "document_end"
  }],
  "background": {
    "scripts": ["js/background.js"],
    "persistent": true
  },
  "web_accessible_resources": [
    "css/*.css",
    "js/*.js",
    "html/*.html"
  ]
}

Error:
Uncaught TypeError: Cannot read property 'onBeforeRequest' of undefined

A: Content scripts operate within the context of the page they are injected into. chrome.* isn't available to pages.


text:
Q: Don't use default focus animation for UITableViewCell I have a very simple cell and I want the text to be 1.0 alpha when focused and 0.5 when unfocused. This works by overriding didUpdateFocusInContext
import Foundation

class SettingsTableViewCell: UITableViewCell {

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)

    var textColor:UIColor?

    if self.focused == true {
        textColor = UIColor.blackColor().colorWithAlphaComponent(1.0)
    } else {
        textColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
    }

    let attributedTitle = self.textLabel?.attributedText?.mutableCopy() as! NSMutableAttributedString
    let range =  NSMakeRange(0, attributedTitle.length)
    attributedTitle.addAttribute(NSForegroundColorAttributeName, value: textColor!, range: range)
    self.textLabel?.attributedText = attributedTitle

}

}
HOWEVER, I don't want the white background when focused... how to get rid of it?

A: Set your cells' focusStyle to UITableViewCellFocusStyleCustom and UIKit won't do any default focus appearance at all on the cells: it'll be entirely up to you.


text:
Q: AttributeError: module 'seaborn' has no attribute 'tsplot' I am trying to use seaborn's tsplot function but it is not showing an output. Instead I'm getting an error:
gammas = sns.load_dataset('gammas')
sns.tsplot(time='timepoint',  # 时间数据, x轴
           value='BOLD signal',  # y轴value
           unit='subject',  # 拆分,默认参数
           condition='ROI',  # 分类
           data=gammas
           )
sns.plt.show()

The error:
    "C:\Program Files\Python37\python.exe" C:/Users/42021/PycharmProjects/klyprojects/venv/plt_loss_acc.py
Traceback (most recent call last):
  File "C:/Users/42021/PycharmProjects/klyprojects/venv/plt_loss_acc.py", line 137, in <module>
    plot_loss_acc_seaborn()
  File "C:/Users/42021/PycharmProjects/klyprojects/venv/plt_loss_acc.py", line 43, in plot_loss_acc_seaborn
    sns.tsplot(time='timepoint',  # 时间数据, x轴
AttributeError: module 'seaborn' has no attribute 'tsplot'

seaborn version 0.10.0 python37
Please help.

A: This release also removes a few previously-deprecated features:
The tsplot function and seaborn.timeseries module have been removed. Recall that tsplot was replaced with lineplot().
The seaborn.apionly entry-point has been removed.
The seaborn.linearmodels module (previously renamed to seaborn.regression) has been removed.
refer to:https://seaborn.pydata.org/whatsnew.html

A: seaborn-0.9.0 still has this interface.


text:
Q: Answering questions with truth tables "With every dinner I have three rules":

*

*If I don't drink wine, then I eat soup

*If I eat soup and drink wine, then I'll have some pudding

*If I have pudding or don't drink wine, then I'll skip the soup

I have to answer these questions:

*

*Do I drink wine with every dinner?

*Do I eat soup with every dinner?

I have to figure out the solution with the help of truth tables.
I have the following translation keys:

*

*Drink wine = w

*Eat soup = s

*Eat pudding = p

The propositions then, are translated as follows:

*

*~w -> s

*(s ^ w) -> p

*(p v ~w) -> ~s

I have one truth table with only the proposition letters w en s, and two with w, p, and s.
Now, here's where I can't really decide what I should do. Should I just look at the truth tables? The ones for 2 and 3 are not easy to figure out just by looking at them. Should I extend the truth tables, and include e.g. for the first question a column for w, and check which models of w are also models for the propositional sentences?

A: First of all you must "model" your problem in the correct way.
I think that the translations of the three assumptions (call the three sentences $\sigma_1$, $\sigma_2$ and $\sigma_3$) are correct.
But you must model also the answer to the two questions :
Do I drink wine with every dinner?
Do I eat soup with every dinner?
in terms of the propositional variables : $w, s$ and $p$; call the supposed answers $\alpha_1$ and $\alpha_2$.
Then we must work with a logical relation between these sentences; I imagine that your problem is about tautological implication :

$\Gamma \vDash_{TAUT} \varphi$

where : $\Gamma = \{ \sigma_1, \sigma_2, \sigma_3 \}$ and $\varphi$ must be in turn each of the proposed answer to the two above question, i.e. $\alpha_1$ and $\alpha_2$.
Only at this point you will introduce truth-table, building a tt for the three propositional variables $w, s$ and $p$ and the calculations for the three formulas $\sigma_i$ and for $\alpha_1$ and $\alpha_2$.
In order to show that there is a relation of tautological implication between $\Gamma$ and $\alpha_i$, you must check that for each row in the tt such that all three formulas $\sigma_i \in \Gamma$ have the value true, also $\alpha_i$ has true (in that row).


text:
Q: How to delete all the lines in a UNIX file except first and last line? I want to keep only header and trailer records in a UNIX file.

A: Use head and tail, one after another:
head -n 1 file.txt; tail -n 1 file.txt

Running tail if head succeeds:
head -n 1 file.txt && tail -n 1 file.txt

Example:
% cat file.txt
foo
spam
egg
bar

% head -n 1 file.txt; tail -n 1 file.txt
foo
bar

% head -n 1 file.txt && tail -n 1 file.txt
foo
bar

A: With sed:
sed -n '1p;$p' file

Suppress automatic printing of pattern space (-n) but print first (1p) and last line ($p) of pattern space.
If you want to edit your file "in place" use sed's option -i.


text:
Q: A paper by Elashvili (translation request) I would like to know if there is an English version of a paper by Elashvili called "Centralizers of nilpotent elements in semisimple Lie algebras".
If not, is there atleast an online version of the original paper that can be accessed (preferably freely) ?
[added] Here is a more elaborate reference to the paper, which I suspect has appeared in a publication/collection with multiple names :
A. G Elashvili, Centralizers of nilpotent elements in semi-simple Lie algebras, Sakarth. SSR Mecn. Akad. Math. Inst. Srom (= Akad. Nauk Gruzin. SSR Trusy Tbiliss. Mat Inst. Ramazde = Publ. Math. Inst. Tbilisi) 46 (1975), pgs 109-132.


text:
Q: facebook-php-sdk vs facebook-php-sdk-v4 I am using facebook-php-sdk v 3.0.0.
Checked that facebook-php-sdk-v4 have changed totally.
I have requirements of Register,Login & Sharing from this API.
My question is :
Which is more suits for me?
Do I require to update version to 4.0.0?
1) facebook-php-sdk
https://github.com/facebook/facebook-php-sdk
2) facebook-php-sdk-v4
https://github.com/facebook/facebook-php-sdk-v4
Please Guide
Thanks,
Niko

A: You should work with the latest version - 4.4 of the PHP SDK. This SDK is compatible with the Facebook v2 APIs and methods. This new version of SDK has been completely rebuilt.
The older SDK uses the v1.0 of the facebook API that will be supported until April 30th, 2015.
See here: Facebook Platform Changelog


text:
Q: Wine, but for mac .apps? Is there such a program like wine, but one that runs Mac / OSX .app(s)? I would find it very interesting to run mac .apps and see the result on such a program.

A: Sadly no, although people are trying. See www.darlinghq.org
Similar Question
You could always run virtualized though...


text:
Q: What is the word that we use to call a father who is the main earner in the family? In Asian families, usually the father is the person who goes to work and earns money in order to feed the family, and the mother is a housewife who usually cooks meals, cleans the house, and washes the clothes.
I wonder if there is a word in English that I can use to call that father?

A: You can also use the idiomatic expression: he who brings home the bacon:

*

*to earn money to live on:

*

*If Jo is at home looking after the children, someone needs to bring home the bacon.

(Cambridge Dictionary of American Idioms)

A: You could use the word Provider, since it's not slang and is gender-neutral.

A: If you want a word that emphasizes masculinity, I would recommend
Patriarch:
  a man who heads a family, group, or government
(merriam-webster)
Though this doesn't necessarily imply they are the primary money-earner typically they will be.

A: You can call such a person (m/f) a breadwinner:

a person who earns money to support a family

(source: Merriam-Webster)

A: Paterfamilias is a word that means exactly this:

*

*the male head of a household

(Merriam-Webster)
Although given that you've tagged this question with 'Slang' it may be too formal, or obscure.


text:
Q: How to manage .env configuration in continous integration I develop an application with nodejs and react. I use dotenv for configuration in my different environment.
I use TFS 2017 for build and release my application.
What is the best practise for add my .env file of production environment?

A: Production configs can be difficult to maintain. You can use any module or even write your own custom module to load environment variable in to your application.
However, maintaining production .env files locally for each product (i.e. committing them or putting them inside your docker image is a bad idea. If you ever happen to change some of those configs, you will have to manually change in the code for each application, build docker image (if required) and redeploy. If there are just a couple of applications, it might be easy. But if the number of related applications grow in size (as usually happens in case of microservice based architecture) - all of them sharing credentials, ips for database connections etc. it becomes a hectic task to manually change code and redeploy all the applications.
Usually, developers tend to keep a central repository of all credentials and environment variables. For examples, AWS offers parameter store and MS Azure offers Azure Key vault. In such a case, all the parameters are fetched during start time, and all we have to do is restart the application.
So usually people set only one global varibale NODE_ENV (as prod or dev), dynamically fetch all environment variables based on NODE_ENV running something like env $(node read-env-variables.js) node app.js.


text:
Q: requirejs with angular - not resolving controller dependency with nested route The RequireJS is not resolving dependency properly when the routes is of multiple levels as in http://www.example.com/profile/view. If I just have http://www.example.com/view, the controller dependency is resolved properly.
My bootstrap.js
require.config({
    baseUrl : 'res/js',
    paths: {
        routeResolve: 'routeResolve',
        'domReady': 'lib/domReady',
        angular: 'lib/angular',
        angularRoute: 'lib/angular-route',
        angularResource: 'lib/angular-resource',
        angularSanitize: 'lib/angular-sanitize',
        cssPath : '../css'
    },
    map: {
      '*': {
        css: 'lib/require-css/css.min'
      }
    },
    shim: {
        'angular': {'exports': 'angular'},
        'angularRoute': {deps : ['angular']},
        'angularResource': {deps : ['angular']},
        'angularSanitize': {deps : ['angular']}
    },
    priority: ['angular']
});

Folder structure:
-rootdir
    - public
          - res
              - js
              - css

When I use this route http://www.example.com/profile/view, all the dependency modules are resolved with base url as http://www.example.com/profile/res/js/controller.js, which does not exist in this path http://www.example.com/profile.
If I change the route to http://www.example.com/view (just one level), dependencies are resolved with this base url http://www.example.com/res/js/controller.js
There should be a configuration issue which I am missing, but I could not find a solution for this.

A: I created working plunker here. It is based on the answer to angular-ui-router with requirejs, lazy loading of controller. I would exepct that the issue will be related to HTML setting <base href...
There is an example of the state, which in resolve loads lazily controller via requireJS:
$stateProvider
  .state("first", {
    url: "/firstr",
    template: "
The message from ctrl: {{message}}
",
    controller: "FirstCtrl",
    resolve: {
      loadOtherCtrl: ["$q", function($q) {
        var deferred = $q.defer();
        require(["FirstCtrl"], function() { deferred.resolve(); });
        return deferred.promise;
      }],
    },
  });

There is the main.js for that example:
var cfg = {

    baseUrl: "res/js/",

    // alias libraries paths
    paths: {

        // here we define path to NAMES
        // to make controllers and their lazy-file-names independent

        "TopMenuCtrl": "Controller_TopMenu",
        "ContentCtrl": "Controller_Content",
        "OtherCtrl"  : "Controller_Other",
        "FirstCtrl"  : "Controller_First",
        "app"  : "../../app",
    },

    deps: ['app']
}

require.config(cfg);

The most important think here, because of the:
$locationProvider.html5Mode({enabled: true});

is the setting of the base in the index.html:

Because I need here to be sure that this will work in plunker I do generate that dynamically, but in your case it could be just <base href="/" /> or some other setting, which will "teach" all the web where to search for resources
Check it here in action. Read more here


text:
Q: How we may can use Cambria and Verdana fonts on Overleaf I want to use Cambria fonts on the overleaf template! How I can do this? I referred to overleaf faqs but I did not get a clear idea any once can help me to do it in a simple way? Thanks

A: Cambria is not generally available but the Chrome core font Caladea is metric compatible
\documentclass{article}
\usepackage{fontspec}

\newfontfamily\cfont{Caladea}
\newfontfamily\vfont{Verdana}

\begin{document}

One two three

{\cfont One two three}

{\vfont One two three}

\end{document}


text:
Q: Python: how to update GeoJSONDataSource? Bokeh nowadays support GeoJSONDataSource that makes it much easier to work and plot data from GeoDataFrame as described here.
However I am not able to update. Let's suppose we have two shapefiles shape1.shp and shape2.shp. This what I am doing but I am not able to update the shape
import geopandas as gpd
from bokeh.plotting import save, figure
from bokeh.models import GeoJSONDataSource
from bokeh.models import Select
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox,layout, gridplot

f1  = gpd.read_file('shape1.shp')
f1g  = GeoJSONDataSource(geojson=f1.to_json())

f2  = gpd.read_file('shape2.shp')
f2g  = GeoJSONDataSource(geojson=f2.to_json())

select =  Select(title="Shape",  options = ['F1','F2'], value, ='F1')
geo_source1 = f1g ### first shape
p = figure(plot_width=600,plot_height=500)
p.patches('xs', 'ys', source = geo_source1, fill_color='white')

def update_plot(attrname, old, new):
    if select.value == 'F2':
        geo_source1.geojson = f1g.geojson   #first shape
    if select.value == 'F2':
        geo_source1.geojson = f2g.geojson   #second shape

select.on_change('value', update_plot)

controls = widgetbox(select1)
first_row = row(controls,p)
curdoc().add_root(first_row)


text:
Q: How do I get a String from a loop which runs in a thread? I started converting my code to a more object oriented style and now I'm having some problems. I'm running a while loop which returns messages received from a socket.
public void run(){

    try {

        while(IrcMessage != null){

        IrcMessage = in.readLine();
        System.out.println(IrcMessage);
        ....
        ....

I want those messages to be displayed in my jframe. I do have an idea how this could work but I dont know how to execute it. How do I access a variable declared in a thread?
public class socketRead extends Thread{

    String IrcMessage = "";

Where I start my thread:
public static void main(String[] args) throws IOException {

    NewJFrame frame = new NewJFrame();
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.read.start();
}

I hope you get my question.
Thank you in advance!

A: You could pass a reference to your JFrame to the thread which needs to update it.


text:
Q: Multiple values in lawnchair I'm using Lawnchair, and I've managed to store a value locally. Something like this:
var Users = new Lawnchair({table:'Users', adaptor:'dom'});

function save_prompt()
{
    var UserName = prompt("Your Username","John Doe");
    if (UserName!=null && UserName!="")
    {
        Users.save
        ({key:'UserData', SavedUserName:UserName});
    }
}

function recall_prompt()
{
    Users.get
    ('UserData',function(r)
        {
            document.getElementById('Message').innerHTML = r.SavedUserName;
        }
    );
}

I call both functions save_prompt & recall_prompt using buttons binded with onclick.
Basically this script will pop up a textfield to enter your username (John Doe is default) and saves it.
With recall_prompt, it worked fine by showing the saved username in the html div id="Message".
My question is, how to save a second, third, and beyond usernames? And how to retrieve them all to show in the html div? I've tried numerous methods that can be found on the 'net but I just can't get it to work. It seems the new username always overwrites the old ones.

A: Lawnchair saves data as Key:value pairs. So if u save another username with the same key, (UserData), it'll always get overridden. To save more usernames u'll have to change the keys. Make it UserData_1, UserData_2, like that.

Or you could store an array of usernames with the key 'UserData', so each time u need to save a username, get the array from DB, then add the new username to it and resave it.


text:
Q: Modal content don't show in dropdown I'm calling Bootstrap 5 modal from dropdown but instead of showing content it shows only grey background. What I'm missing?
Here is jsfiddle and here is code:

        <button type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="true" class="btn btn-primary">Dropdown</button>

            <button type="button" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#test">
              Launch demo modal
            </button>

Modal title

                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                    ...

                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

A: The modal code should be outside the
 tag

        <button type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="true" class="btn btn-primary">Dropdown</button>

            <button type="button" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#test">
                Launch demo modal
              </button>

Modal title

          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

          ...

          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: Proof orthogonal complement of symmetric matrices
Prove that $\{ A \in \mathbb{R}^{n \times n} \mid A \text{ is symmetric}\}^{\bot} = \{ A \in \mathbb{R}^{n \times n} \mid  A \ \text{is skew-symmetric}\}$ with $\langle A, B \rangle = \operatorname{Tr}(A^\top B)$.

(Note: I am aware of the other 3 questions posted about this problem on this forum, this one too.)
Proof.
Let $\{A\in\mathbf{R}^{n\times n}\mid A\text{ symmetric}\}=W$ and $\{A\in\mathbf{R}^{n\times n}\mid A\text{ antisymmetric}\}=V$.
We first prove the inclusion $\supseteq$. Let $A\in V$, then we have to show that $A\in W^\perp$, or equivalently $A\perp B$ for all $B\in\mathbf{R}^{n\times n}$ symmetric. We have
$$\langle A,B\rangle=\operatorname{Tr}(A^\top B)=\operatorname{Tr}(-AB)=-\operatorname{Tr}(AB^\top)=-\operatorname{Tr}(B^\top A)=-\langle B,A\rangle=-\langle A,B\rangle$$
so $\langle A,B\rangle=0$, therefore $A\in W^\top$.
Now we prove the inclusion $\subseteq$. Let $A\in W^\perp$, then we have to show that $A\in V$.
Consider the inner product $\langle A,A+A^\top \rangle$. Since $(A+A^\top)^\top=A+A^\top$, we have that $A+A^\top$ is symmetric for all $A\in \mathbf{R}^{n\times n}$ and because $A$ is orthogonal to all symmetric matrices, this inner product is equal to $0$. But we also have
$$0=\langle A,A+A^\top\rangle=\langle A,A\rangle+\langle A,A^\top\rangle \iff \langle A,A\rangle=\langle A,-A^\top\rangle$$
Here comes the problem: I want to deduce from this step that $A=-A^\top$, but I realise that this is not allowed.
How should I prove the second inclusion? I know that otherwise I can use something that uses the unique decomposition of $A\in\mathbf{R}^{n\times n}$ as sum of a symmetric and an antisymmetric matrix $A=\frac{A+A^\top}{2}+\frac{A-A^\top}{2}$, but I don't see how this would help.

A: If you already know that $\langle\,\cdot\,,\,\cdot\,\rangle$ is an inner product (in particular, that it is positive definite), then you're essentially done after your first display equation: The equations implies that $V$ and $W$ are orthogonal and transverse to one another, but since $\dim V + \dim W = n^2 = \dim {\bf R}^2$, they are in fact orthogonal complements.

A: You wish to show that for $A\in W^\bot$ you have $A+A^T = 0$. We have
$$\begin{aligned} \langle A + A^T, A + A^T\rangle &=\langle A, A+A^T\rangle +\langle A^T, A+A^T\rangle\\ &=0+\langle A^T, A+A^T\rangle \end{aligned}$$ since $A + A^T$ is symmetric and $A\in W^\bot$. If you expand the second term you obtain $$\langle A^T, A+A^T\rangle = \text{Tr}\left(A(A+A^T)\right) = \text{Tr}\left((A+A^T) A\right) =\langle A+A^T, A\rangle = 0 $$ as well, where we used that $\text{Tr}(BC) = \text{Tr}(CB)$ for all matrices $B$ and $C$.
This shows that $\langle A + A^T, A + A^T\rangle=0$ and since $\langle\cdot,\cdot\rangle$ is an inner product this implies that $A + A^T=0$, which gives $A^T = -A$ as desired.

A: If the trace of $XA$ is  $0$ for all symmetric matrices $X$ then one can consider an $X$ with all entries zero apart from $1$s in positions $(i,j)$ and $(j,i)$. In this way one shows that each $a_{ij}+a_{ji}=0$ and  each $a_{ii}=0$.


text:
Q: Zend Framework: Zend_Form in layout How do I add a Zend_Form to my layout? The layout has no "controller" in which to initiate the form. How do I do this?

A: You can add a form to the layout using action helpers.
So your action helper should look like:
class Application_Controller_Helper_AddMyForm extends Zend_Controller_Action_Helper_Abstract
{
    public function preDispatch()
    {
        $view = $this->getActionController()->view;
        $form = new Application_Form_MyForm();
        $view->myForm = $form;
    }
}

And this helper should be registered in the Bootstrap:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initMyActionHelpers()
    {
        $this->bootstrap('frontController');
        $addMyForm = Zend_Controller_Action_HelperBroker::getStaticHelper('AddMyForm');
        Zend_Controller_Action_HelperBroker::addHelper($addMyForm);
    }
}

Now you should be able to access myForm from the layout:
echo $this->myForm;

Please see more info on implementing re-usable widgets with action helpers in Weier O'Phinney's blog and Rob Allen's blog

A: In response to Phil Brown's comment:
class My_View_Helper_AddMyForm extend Zend_View_Helper_Abstract()
{
    public function addMyForm() {
        return new My_Form_MyForm();
    }

}

Now in your layout:
echo $this->addMyForm();

I have not tested it, but it should work assuming you have registered My/View/Helper helper path. Less code, and you only call it when you need it.


text:
Q: How to use teamcity for android application deployment How can i sue TeamCity for android application deployment.
Currently i am trying to use Gradle for this and not getting any success.
Is there any other way or any other build runner in TeamCity for android applications deployment ?


text:
Q: Inconsistent Differential Equation Result I'm doing a review problem right now that has gotten me to the equation (which I know to be correct):
$\frac{1}{s}ds = -\frac{1}{200}dt$
Which I then use to solve for $s$. My method is as follows:
$\int \frac{1}{s}ds = \int -\frac{1}{200}dt$
$\int \frac{1}{s}ds =  -\frac{1}{200} \int dt$
$ln(s) = \frac{-t}{200} + C$
$ln(s) =C - \frac{t}{200}$
$e^{ln(s)} = e^{(C - \frac{t}{200})}$
$s = e^{(C - \frac{t}{200})}$
These are all what I'd consider to be fairly straightforward operations...except that I'm going wrong somewhere, because the correct result should actually be:
$s =C e^{(-\frac{t}{200})}$
But I can't for the life of me figure out what step I'm getting incorrect. Is anyone else able to spot it?

A: Notice that
$$e^{\left(C-\frac{t}{200}\right)}=e^C\cdot e^{-\frac{t}{200}}=\widetilde{C} e^{-\frac{t}{200}}$$


text:
Q: Using ZMQ on iOS I am trying to build an iOS app that is exposed to a fairly extensive Rust project, but I am having issues with one of the dependencies in the project.  The Rust project has a ZMQ dependency, and while I am able to build the project on my Mac, when I try to incorporate the Rust project I get the following error:

error: failed to run custom build command for `zmq-sys v0.8.3`

Caused by:
  process didn't exit successfully: `/Users/lisa/company/project/project_detail/target/debug/build/zmq-sys-16dfc88dff84d855/build-script-build` (exit status: 101)
  --- stdout
  cargo:rerun-if-env-changed=LIBZMQ_NO_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG_ALLOW_CROSS_aarch64-apple-ios
  cargo:rerun-if-env-changed=PKG_CONFIG_ALLOW_CROSS_aarch64_apple_ios
  cargo:rerun-if-env-changed=TARGET_PKG_CONFIG_ALLOW_CROSS
  cargo:rerun-if-env-changed=PKG_CONFIG_ALLOW_CROSS
  cargo:rerun-if-env-changed=PKG_CONFIG_aarch64-apple-ios
  cargo:rerun-if-env-changed=PKG_CONFIG_aarch64_apple_ios
  cargo:rerun-if-env-changed=TARGET_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_aarch64-apple-ios
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_aarch64_apple_ios
  cargo:rerun-if-env-changed=TARGET_PKG_CONFIG_SYSROOT_DIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR

  --- stderr
  thread 'main' panicked at 'Unable to locate libzmq:
  pkg-config has not been configured to support cross-compilation.

  Install a sysroot for the target platform and configure it via
  PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a
  cross-compiling wrapper for pkg-config and set it via
  PKG_CONFIG environment variable.', /Users/lisa/.cargo/registry/src/github.com-1ecc6299db9ec823/zmq-sys-0.8.3/build.rs:31:17
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...

I am trying to build the appropriate library for the iOS and iOS simulator architectures without relying on pkg-config, but if someone can provide useful instructions for configuring pkg-config for cross-compilation, I am not opposed to it, I just don't know how and can't find any up to date resources.
I have cloned the libzmq project from this github: https://github.com/zeromq/libzmq.git, then navigate into libzmq.
Inside libzmq, I run ./autogen.sh followed by ./configure --prefix [directory location] --target "aarch64-apple-ios", then make and make install.
The above procedure without the --target flag is how I got the project to compile on my Mac in the first place, and with the target flag in place make and make install both complete successfully, but when I try to build the project using PROJECT_DIR="${PWD}/ProjectName" ./ProjectName/build-rust.sh,
I get the previously posted error.
I am following the Swift-Bridge Book (https://chinedufn.github.io/swift-bridge/building/xcode-and-cargo/index.html) to try to load the Rust libraries into Xcode.
One thing to note: In the libzmq git hub, there is a folder called builds/ios/ and inside this folder is what looks to be a build file for all of the iOS archs, but I haven't been able to get the repo to build with that file.  I think figuring out how to use the build_ios.sh build file as opposed to the standard build.sh provided might be the answer, but I've tried dropping build_ios.sh where build.sh is, and ./autogen.sh doesn't work, because it complains that it can't find configure.ac, even though this file does exist.


text:
Q: How do I diagnose missing rows on a MySQL slave? I'm running traditional master/slave replication on MySQL 5.1.52, my master is set for statement based replication.  A few tables are missing rows on the slave (differing row counts), these tables are insert only on the master using "load data infile ...", with auto-increment Pks.  It is strange that the missing rows on the slave have gaps in the PK values where the rows should be.  Slave is marked read-only so there are no accidental deletes.

A: The traditional way would be to use pt-table-checksum and pt-table-sync
I like doing things a little different. I immediately run pt-table-sync with the --sync-to-master --print options.
Here is the --sync-to-master option

--sync-to-master
Treat the DSN as a slave and sync it to its master.
Treat the server you specified as a slave. Inspect SHOW SLAVE STATUS,
  connect to the server's master, and treat the master as the source and
  the slave as the destination. Causes changes to be made on the master.
  Sets --wait to 60 by default, sets --lock to 1 by default, and
  disables --[no]transaction by default. See also --replicate, which
  changes this option's behavior.

Here is the --print option

--print
Print queries that will resolve differences.
If you don't trust pt-table-sync, or just want to see what it will do, this is a good way to be safe. These queries are valid SQL and you can run them yourself if you want to sync the tables manually.

This, if you do something like this:
echo "SET SQL_LOG_BIN=0;" > /root/SQLChanges.sql
pt-table-sync --print --sync-to-master h=10.1.2.30,u=username,p=password >> /root/SQLChanges.sql

The file /root/SQLChanges.sql will contain every change you need to execute on the Slave. Once you are satisfied with its contents, just execute the script on the Slave.
With regard to using LOAD DATA INFILE in Replication, @DTest answered this question about that. I further explained how mysql replicates LOAD DATA INFILE.


text:
Q: Is it possible in Unity Mirror to connect and sync not spawned objects? I have an object what I use only in one scene, so I do not want to make it prefab. This object has network identity, and a script which is increasing a syncvar integer in the update method. When the game starts this object got disable because the server is not running. When I start hosting the server this object got enabled. Everything fine is this point but when a client is joining this object is still disabled in the client and not synchronized.
If I am right it is because the objects are not connected to each other. how and I solve it without making this object a prefab and just spawn it?
How can I spawn objects without a player prefab with authority on the server (it would be a singleton service object)?

A: NetworkIdentities have to be spawned.
If it is already in your scene you can enforce it to be spawned by using
NetworkServer.SpawnObjects();

NetworkServer.SpawnObjects
Also you can spawn any prefab you defined in the NetworkManager. Look for the Registered Spawnable Prefabs Array.
To spawn a registered prefab you can use
NetworkServer.Spawn();

NetworkServer.Spawn
For example spawn a registered prefab on the server using a Command:
[Command]
public void CmdSpawnGameObject()
{
   var spawnObject = Instantiate(prefab, Vector3.zero, Quaternion.identity);
   NetworkServer.Spawn(spawnObject, connectionToClient);
}

How can I spawn objects without a player prefab with authority on the
server (it would be a singleton service object)?

You can't. You have to have a playerPrefab spawned and you have to have authority. But you can also hand over authority using
identity.AssignClientAuthority(conn);

Authority with Mirror


text:
Q: How to trim string from one specific character to another in VB .NET Already used the trim() function, it needs to define the position but in my case
I want to fetch the value of character from first underscore(_) to second underscore(_) .
fileName = EBGI_13641689_1653559001438_EBAOGIPA_PDOC_PL_GPT
Output should be like this
13641689


text:
Q: Библиотеки для работы с видео в Java Существуют ли какие-нибудь библиотеки (помимо JMF и Xuggle) для работы в видео файлами на Java?
A: Посмотрите в сторону FMJ (не путать с JMF) и Theora-Java.
Можно посмотреть на разные байндинги к Java: ffmpeg-java, VLCJ, посмотрте на QuickTime.. раньше там был байндинг к Java, но теперь вроде как нет, но всё ещё есть нативное API


text:
Q: Preserve file ownership while copying [tcl] I am trying to copy a file to a destination using tcl.
file copy $filename $destination

However, I want the file ownership to be preserved while copying the file.
Eg: file copy file1.txt file2.txt
ls -l
total 0
-rw-r--r-- 1 reshma root 0 Jan 10 08:34 file1.txt
-rw-r--r-- 1 root   root 0 Jan 10 08:34 file2.txt

How do I preserve the file ownership while copying?


text:
Q: Accessing 3 tables in Laravel using foreign key (laravel 6) I want to show data from a database(sql) that is from a specific user.
I have 3 tables:
Users
Stores
Areas
These are the following relationship between tables:
User hasOne Area
Area hasMany Stores
Basically what I wanted to show is that every user has their own area that has many stores.
User model
function area() {
    return $this->hasOne('App\Area');
}

Area model
 function user() {
    return $this->belongsTo('App\User');
}

function stores() {
    return $this->hasMany('App\Store');
}

Store Model
function area() {
    return $this->belongsTo('App\Area');
}

My database looks like this:
user table
id name role_id area_id
area table
id name user_id
store table
id name area_id
How can I access user->area->store?
This is what I got so far
function show() {
    $id= Auth::user()->id;
    $user = User::find($id);
    echo($user->area->stores);
}

Thank you

A: you can use the hasManyThrough for get sotres of an area:
define stores function in User model
public function stores()
{
    return $this->hasManyThrough(Store::class, Area::class);
}

and use it :
$stores = auth()->user()->stores;

I hope be useful.


text:
Q: C++ Generic Data Type Whats the best approach to a fast generic data type in C++. I have an event system that needs to be able to pass event information around the program.
sendEvent(123, "a String", aFloat, aVec3, etc); // sendEvent(EventID, EventArg, EventArg ...);

eventData.at(0).asFloat();
eventData.at(1).asInt(); // etc.

Until now I only needed float/int/ptr, and I handled this inside a union. but now I've got a few most structures and this is becoming a little more complex, so I'm revisiting it.
I had a dig through boost::any but this is too slow, there could be alot of data flying around, but this idea seems like the right direction.
I had a rather naive shot with using void* data hold but that got very ugly quickly.

A: If you have a limited set of supported types, you can try boost::variant. It's more or less a better union. It avoids the heap allocations that boost::any is using and should give maximum performance.
http://www.boost.org/doc/libs/1_56_0/doc/html/variant.html
Example:
// create a variant capable of storing int, float and string
boost::variant<int, float, std::string> eventData;
eventData = 42.f; // store a float
float f = boost::get<float>(eventData); // get the float


text:
Q: Adding vertices to graph using ArrayList I am trying to add create two ArrayList of vertices (setA, setB) which will store the stores for comparing  them late how ever I am unable to add vertices to the arraylist.
here is the code
import java.util.*;

public class BipartiteGraph<Vertex> {

    private String strName;
    ArrayList<Vertex>[] vertexList;

    public BipartiteGraph(){

        vertexList = new ArrayList[2];
        vertexList[0] = new ArrayList<Vertex>();
        vertexList[1] = new ArrayList<Vertex>();
        Scanner vertexInput = new Scanner(System.in);
        int vertex;
        vertex = vertexInput.nextInt();
        for(int i = 0; i < 10; i++){
            vertexList[0].add(vertexInput.nextInt());
        }
    }
}

Also if someone could guide me if I am in the right direction.

A: You are trying to add int variable into the container of Vertex objects. Assuming, that your Vertex has a constructor accepting int you should rather use:
vertexList[0].add(new Vertex(vertexInput.nextInt()));


text:
Q: Load External Libraries in Symfony 3 I have Service directory in my symfony application like below

src/SwipeBundle/Service

Inside of this directory I have class called.

RSA.php

This class has
namespace SwipeBundle\Service;

require_once __DIR__ . 'RSA/Crypt/RSA.php';
require_once __DIR__ . 'RSA/File/X509.php';

class RSA
{
    public function privateKey() {
        require_once __DIR__ . 'RSA/Certificates/private.txt';
    }

    public function certificates() {
        return require_once __DIR__ . 'RSA/Certificates/pinew.cer';
    }
}

and the files directory are

src/SwipeBundle/Service/RSA/Certificates/pinew.cer
  src/SwipeBundle/Service/RSA/Certificates/private.txt
  src/SwipeBundle/Service/RSA/Crypt/RSA.php
src/SwipeBundle/Service/RSA/File/X509.php

I want to load the classes of this service class to my Controller, like so.
Controller
    use SwipeBundle\Service;

    class BillsPayController extends Controller
    {
        public function indexAction() {

            $rsa = new \Crypt_RSA();
            $hash = new \Crypt_Hash('sha1');
            $x509 = new \File_X509();

            $privatekey = file_get_contents(RSA()->privateKey());
            $x509->loadX509(file_get_contents(RSA()->certificates()));

        }
}

I tried also using this one.

use SwipeBundle\Service\RSA;

    class BillsPayController extends Controller
    {
        public function indexAction() {

            $a = new RSA();
            $a->privateKey();

        }
}

Error I encountered.
    Attempt result 1: Attempted to load class "Crypt_RSA" from the global namespace.
    Did you forget a "use" statement?

   Attempt result 2: Compile Error: main(): Failed opening required '/Users/jaysonlacson/Sites/contactless/src/SwipeBundle/ServiceRSA/Crypt/RSA.php' (include_path='.:')

A: I think you are missing a forward slash like this:
require_once __DIR__ . '/RSA/Crypt/RSA.php';
require_once __DIR__ . '/RSA/File/X509.php';

I'm just guessing, but can you try that?


text:
Q: Is there any way to make an OptionMenu more navigable in tkinter? So I´m doing a GUI app on Python with tkinter and my dropdown list (alphabetically ordered) is too long (+600 options). Currently the dropdown is created with OptionMenu, but it only has an arrow to go down on the list one by one.
Is there any way to make it more easy to navigate?
I´m thinking of something like common dropdowns where you type a letter and it takes you to the options that start with that letter. Or even a simple bar on the side to scroll down quickly, but any ideas are welcome.
root = Tk()
clicked = StringVar(root)
options = df['name'].tolist()
clicked.set(options[0])
dropdown = OptionMenu(root, clicked, *options)
dropdown.pack()

Thanks!


text:
Q: how to call a command from a bash script in Linux I am trying to call a command from a script (defined as functions inside .bashrc) as following
the first function hooks the rm command by deleting any file except a file named "forensicfile1"
#hooking rm command
function rm(){
if [[ $1 = "forensicfile1" ]]; then
echo "$1 file is deleted by user ">forensicaudit
else
rm $1
fi
}

the second hooking function is trying to hook the ls command by listing all files except the forensicfile1
#hooking ls command
function ls(){
if [[ $PWD = "/home/waleed/forensicdata" ]]
then
alias myls='ls "/home/waleed/forensicdata" -1 "forensicfile1" '
myls
else
ls $PWD
fi
}

however the following lines are not working
rm $1 // within the first function

alias myls='ls "/home/waleed/forensicdata" -1 "forensicfile1" '
myls
ls $PWD

can anyone help?


text:
Q: How to open Google maps application using the "maps:" scheme? Firstly, I'm making a web application, not an iPhone application.

How do you open the Google maps application with a location passed to it so you can view it on the app?
I put this as a link:
Open in Google Maps

It does open the Google Maps application but it doesn't zoom into the place with a marker as requested, how do I do this?

A: Based on the Apple docs, I believe what you are looking for is:
Open in Google Maps

A: The following code will open google maps with a marker on the requested location.
[someUIApplication openURL:[NSURL URLWithString:@"http://maps.google.com/maps?q=58.09423,67.97662"]]

A: You no longer use the maps: protocol, just link directly to google. I believe maps: predates the phone, possibly a Symbian convention in origin.
Developer reference.
https://developer.apple.com/library/ios/#featuredarticles/iPhoneURLScheme_Reference/Articles/MapLinks.html


text:
Q: Is there case for closed paragraphs tags  I'm reading HTML Paragraphs documentation here: http://www.w3schools.com/html/html_paragraphs.asp
but there is nothing about
 usage
But I was trying it and it works as new line. Is there difference between p and br in this case?
If I can use
 as
 then why do I need
 ?

A:
 elements are paragraphs, they are not empty elements and cannot be self-closed (i.e.
 is not valid). They must contain some other nodes, and should be correctly closed using
, for example:

This is my paragraph

A
 tag is an empty element (i.e. it cannot contain child elements).
Empty
 elements are strongly discouraged in the specification, for example:

The P element represents a paragraph. It cannot contain block-level
  elements (including P itself).
We discourage authors from using empty P elements. User agents
  should ignore empty P elements.

What is actually happening is that your browser is converting your invalid
 to

, and then displaying an empty paragraph. Browsers have some default CSS rules for elements defined, and since
 elements are block-level elements with a default margin defined, this explains why you seem to see a 'new line' when using
.
If you use a CSS reset, such as:
p {
    margin: 0
}

You will see the 'new line' disappear. This is why
 exists. It allows you to force a line break within HTML.

A:
 stands for Line break and it sends your text to the next line.

 stands for paragraph. It creates a blank line and then move to a new line.

A: You don't need
 it's a relic from the old web, generally you should avoid using it unless you're building something like an email.
 tags makes responsive styling on websites harder, you can do everything with CSS instead nowadays.
The closing  tag acts in a similar way since it breaks the following content on to the next line.


text:
Q: Change time slider to 30 min slots instead of 1 hour I am using the code below to use a time slider which allows the div to slide from 9am - 8pm in 1 hour slots.
I need to edit the code so that the time slider goes up in 30 mins (half hour) slots instead.

A: Add a step option.
Ex:
min: 1,
max: 12,
range: "min",
value: 1,
step: .5,

Here's a jsFiddle example that shows how you can use the step and handle the ":30" time change.


text:
Q: NLP Lemmatizer removes 's' from 'us' I'm trying to use the following lemmatize function, but when inputting text with "us", the function removes the "s". How to prevent that?
lemmatizer = nltk.stem.WordNetLemmatizer()
w_tokenizer = TweetTokenizer()
def lemmatize_text(text):
    return [(lemmatizer.lemmatize(w)) for w in \
                                     w_tokenizer.tokenize((text))]
lemmatize_text('us')


text:
Q: Apache Nifi: How to convert string (text/plain) to JSON type using Nifi processor? Please guide me the right component for converting string to json
using appropriate Nifi processor component.
Input is a string of content type text/plain
{ productName : "tv", locationName: " chennai"}

Output of EvaluateJsonPath is still the same as I am unable to evaluate json property based on json path due to wrong content type sent as input.
{
 productName : "tv",
 locationName: " chennai"
}

Note: Tried SplitText, AttirtubesToJson processors not able to achieve desired conversion.

A: This is because the input data is not valid JSON. I recreated this flow locally and the error from EvaluateJsonPath is
2017-08-22 10:20:21,079 ERROR [Timer-Driven Process Thread-5] o.a.n.p.standard.EvaluateJsonPath EvaluateJsonPath[id=0aec27af-015e-1000-fac5-4e0f455a10fe] FlowFile StandardFlowFileRecord[uuid=b903eeb0-8985-4517-910f-5e3bbbccb8dc,claim=StandardContentClaim [resourceClaim=StandardResourceClaim[id=1503421928125-1, container=default, section=1], offset=376, length=47],offset=0,name=91708717370829,size=47] did not have valid JSON content.

Which condenses to [flowfile] did not have valid JSON content. The processor uses a strict validator and the input you're providing is not valid JSON. You'll need to use text manipulation or regexes to update this content to the following:
{"productName":"tv", "locationName":"chennai"}

Once you have accomplished this (via ReplaceText, etc.), the EvaluateJsonPath processor will work properly.
Also, to be clear, EvaluateJsonPath is designed to execute JSONPath expressions to extract JSON values to flowfile attributes. It is not designed to manipulate arbitrary text into JSON format.
Update
There is no universal process to convert arbitrary data to JSON. Given the specific input you provided, the following values for ReplaceText will convert this to valid JSON:

*

*Search Value: (?<!\")(\w+)(?=[\s:])

*Replacement Value: "$1"

*Replacement Strategy: Regex Replace

*Evaluation Mode: Entire text
If you get incoming data that is invalid in some other way, you'll have to modify this process. You may be interested in something like JSONLint to validate and format your incoming data.


text:
Q: How does return work for a function local variable? I'm confused regrading the return of a local variable: the variable, its address and returning address using pointers.
First:
#include <stdio.h>

int returner(void);

int main(void)
{
    printf("The value I got is = %d\n", returner());
    return 0;
}

int returner(void)
{
    int a = 10;
    return a;
}

Output:
The value I got is = 10

The local variable is returned although it should go out of scope after the function returns, how does that work?
Second:
#include <stdio.h>

int *returner(void);

int main(void)
{
    int *pointer = returner();
    printf("The value I got is = %d\n", *pointer);
    return 0;
}

int *returner(void)
{
    int a = 10;
    return &a;
}

Output:
Test.c: In function 'returner':
Test.c:15:12: warning: function returns address of local variable [-Wreturn-local-addr]
   15 |     return &a;

Why is the address is not returned, although the value is returned as in First sample?
Third:
#include <stdio.h>

int *returner(void);

int main(void)
{
    int *pointer = returner();
    printf("The value I got is = %d\n", *pointer);
    return 0;
}

int *returner(void)
{
    int a = 10;
    int *ptr = &a;
    return ptr;
}

Output:
The value I got is = 10

Now, how is this method returning the address of the local variable and also prints its correct value, although the variable should go out of scope / be destroyed after the function returns?
Please explain the three cases that how the methods are working.

A: In C the return is by value.
The first code returns the value of a, which is 10, and that's fine, it's a mere copy of the local variable a.
The second code returns the value of a pointer to a, which is its address. It just so happens that that address will not be valid after the function goes out of scope, and the lifetime of the local variable stored in that address ends. The compiler is smart enough to detect this and warn you.
The third code is different, there is an assignment of an address coming from another pointer, the compiler doesn't check further to see if the assigned address is valid or not, that extra layer of indirection throws the compiler off.
The output continues to be 10 but this is by chance, it's undefined behavior, and as such, that is one of the possible outcomes. There is no standardized behavior for this kind of construct and to demonstrate it I tweaked things a bit. As you can see here https://godbolt.org/z/eKerdM, with optimizations -O3 enabled.
With clang the program outputs some random value:

The value I got is = -1313555320

And no warnings are produced.
Whereas gcc verifies further and detects a problematic assignment:

<source>: In function 'returner':
<source>:16:12: warning: function returns address of local variable
[-Wreturn-local-addr]
  16 |     return ptr;
     |            ^~~
<source>:14:9: note: declared here
  14 |     int a = 10;
     |         ^

And the program outputs 0:

The value I got is = 0

In both cases the value is no longer correct, and clang behaves differently from gcc.

A: *

*Output First: the value (which has no scope) is returned.

*Output Second: You are trying to return the address of something which does go out of scope.

*Output Third: Although you are trying to do the same thing as previously, the compiler doesn't detect the problem.  The pointer being returned, however, is just as problematic.

A: int returner(void)
{
    int a = 10;
    return a;
}

The above function returns an int by value, as far as the return goes, it's equivalent to having written return 10;
int *returner(void)
{
    int a = 10;
    return &a;
}

The above is an example of what they call "undefined behavior" - it might work, sometimes, but it's not sound. The address that's returned refers to a position on the function call stack used to provide storage to function local variables. That memory is no longer retained for holding int a after returner returns, although it might not have been reused, and may still have the value 10 at that address, for some time afterward, there is no guarantee.
The third example is not very different from the 2nd. The behavior could differ from the 2nd, as the stack allocation is different, but neither should be expected to work consistently, or to be portable.

A: What's being returned from the function is the value of a, just like what's passed to functions is the value of its parameters.
The only time you would need to worry about going out of scope is when you're returning a pointer to a local function variable with automatic storage duration, i.e.:
int *badFunction ()
{
   int ret[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   return ret;
}

In this case the value being returned is a pointer to the array ret, however, since ret goes out of scope when badFunction exits, the returned pointer is obviously invalid. Workarounds would be using a variable with static storage duration or the heap.
In your case, with a plain old int, you don't need to worry about scope.


text:
Q: take variable in outer function in php I need help getting the $total variable into return $seed = ( rand('1','10') * $seed + 5) % $this->total;. Can anyone help me?
public function index()
{
    $total = $this->m_soal->count_soal();

    function lcm_rand($seed) {
        return function() use (& $seed ) {

            return $seed = ( rand('1','10') * $seed + 5) % $this->total;
        };
    }

}

A: Not sure why you would need the inner function, but perhaps something like this would help you.
private int $total = 5; // for testing purposes

public function lcm_rand($seed)
{
    return ((random_int(1, 10) * $seed) + 5) % $this->total;
}


text:
Q: Getting "java.lang.NoSuchMethodError" when trying to include Twilio API in android app I am trying to include Twilio API in my android app, But when I try to send sms from it, I am getting java.lang.NoSuchMethodError. I tried to resolve it by adding httpclient-4.2.2.jar file , but no success.
Below is my Error Log:
12-06 10:32:26.497: E/AndroidRuntime(12901): FATAL EXCEPTION: main
12-06 10:32:26.497: E/AndroidRuntime(12901): java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager.<init>
12-06 10:32:26.497: E/AndroidRuntime(12901):    at com.twilio.sdk.TwilioRestClient.<init>(TwilioRestClient.java:137)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at com.example.twiliodemo.TwilioDemo.sendMessageByTwilio(TwilioDemo.java:40)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at com.example.twiliodemo.TwilioDemo.onCreate(TwilioDemo.java:23)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.Activity.performCreate(Activity.java:5008)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.os.Looper.loop(Looper.java:137)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at android.app.ActivityThread.main(ActivityThread.java:4745)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at java.lang.reflect.Method.invokeNative(Native Method)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at java.lang.reflect.Method.invoke(Method.java:511)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-06 10:32:26.497: E/AndroidRuntime(12901):    at dalvik.system.NativeStart.main(Native Method)

This is my activity.
package com.example.twiliodemo;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.resource.factory.SmsFactory;
import com.twilio.sdk.resource.instance.Account;
import com.twilio.sdk.resource.instance.Sms;

public class TwilioDemo extends Activity {

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

        sendMessageByTwilio();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void sendMessageByTwilio(){
         /* Find your sid and token at twilio.com/user/account */
        try {
            String ACCOUNT_SID = "AC15b63878d56d436af26cfd6f0e94c706";
            String AUTH_TOKEN = "2c870b5aa3c5f4d1bcacbe747d6808f6";
            String TWILIO_URL="http://api.twilio.com";

            TwilioRestClient clientTwilio=new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN,TWILIO_URL);
                Account account = clientTwilio.getAccount();

                SmsFactory smsFactory = account.getSmsFactory();
                Map<String, String> smsParams = new HashMap<String, String>();
                smsParams.put("To", "+919423872793");
                smsParams.put("From", "+12403486854"); // Replace with a valid phone
                // number in your account
                smsParams.put("Body", "Hi..");

                Sms sms = smsFactory.create(smsParams);
                Log.d("SMS -", ""+sms);

        } catch (Exception e) {
            Log.e("**************", String.valueOf(e));
        }
    }

}

I have also added 'twilio-java-sdk-3.3.10.jar' in libs folder.

A: Try cleaning your project and if you have a separate project you use make sure you have set it as a library project!


text:
Q: How to map pojo class's field to string object returning from API I am working on an application where I want to convert string object coming from data api to json object.Now, I converted string object to json but there is a problem.
My pojo class has multiple fields with corresponding getters and setters one of them is "filterName" and it looks like
   @SerializedName(value="cellFilter", alternate="tissueFilter")
    private String filterName;

What it does is it extracts the value associated with "cellFilter" and "tissueFilter". I am not sure if its an optimized way to retire the data using the same field. Also, I want to use that same field to retrieve another value and I don't know how to do that ( i.e I want to use filterName to get the values of tissueFilter, cellFilter and applicationFilter ).
data object looks like as following
Note - there are 3 strings for tissueFilter, cellFilter and applicationFilter which comes from data api. After converting them in java objects they look like this,
tissufilter

 {
    "url": "xyz",
    "sortOrder": 8,
    "imageId": "1111",
    "tissueFilter": "Heart"
  }

cellFilter
{
    "url": "xyz",
    "sortOrder": 6,
    "imageId": "2222",
    "cellFilter": "Pancreas"
  }

and applicationFilter
 {
    "applicationFilter": "c56",
    "url": "xyz",
    "sortOrder": 1,
    "imageId": "3333",
  }

Thank you

A: If Jackson JSON library is used for serializing/deserialing JSON data, @JsonAlias annotation should be applied to deserialize the field which may have different names:
@Data
class Pojo {
    private String url;
    private int orderId;
    private String imageId;

    @JsonAlias({"applicationFilter", "cellFilter", "tissueFilter"})
    private String filter;
}

After deserialization of the mentioned JSON snippets, the field filter should be set to appropriate value defined as "applicationFilter", etc.

However, it seems that Gson is used in the question, and its @SerializedName also allows for multiple versions in alternate parameter:
@Data
class PojoForGson {
    private String url;
    private int orderId;
    private String imageId;

    @SerializedName(value = "cellFilter" alternate = {"applicationFilter",  "tissueFilter"})
    private String filter;
}


text:
Q: Share image from resources How can I share an image from the drawable folder with ShareActionProvider?
I have proved a lot of things but it doesn´t work.
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);

What is the uri in this case? Uri uri = Uri.parse("android.resource://com.android.example/" + R.drawable.photo); does not work.
Thank you

A: You can't get path of the drawable like this as the resource folder is compiled into the apk, but you can grab the resource like this:
Resources res= getResources();
Drawable drawable= res.getDrawable(R.drawable.photo);
Bitmap bm = BitmapFactory.decodeResource(res, drawable, opts);

Then write this in memory then can get the uri of that resource.


text:
Q: what is the point of heterogenous arrays? I know that more-dynamic-than-Java languages, like Python and Ruby, often allow you to place objects of mixed types in arrays, like so:
["hello", 120, ["world"]]

What I don't understand is why you would ever use a feature like this. If I want to store heterogenous data in Java, I'll usually create an object for it.
For example, say a User has int ID and String name. While I see that in Python/Ruby/PHP you could do something like this:
[["John Smith", 000], ["Smith John", 001], ...]

this seems a bit less safe/OO than creating a class User with attributes ID and name and then having your array:
[<User: name="John Smith", id=000>, <User: name="Smith John", id=001>, ...]

where those <User ...> things represent User objects.
Is there reason to use the former over the latter in languages that support it? Or is there some bigger reason to use heterogenous arrays?
N.B. I am not talking about arrays that include different objects that all implement the same interface or inherit from the same parent, e.g.:
class Square extends Shape
class Triangle extends Shape
[new Square(), new Triangle()]

because that is, to the programmer at least, still a homogenous array as you'll be doing the same thing with each shape (e.g., calling the draw() method), only the methods commonly defined between the two.

A: Applying a multimethod to the array might make some sense. You switch the strategy to a more functional style in which you focus on a discrete piece of logic (i.e. the multimethod) instead of a discrete piece of data (i.e. the array objects).
In your shapes example, this prevents you from having to define and implement the Shape interface. (Yes, it's not a big deal here, but what if shape was one of several superclasses you wanted to extend? In Java, you're SOL at this point.) Instead, you implement a smart draw() multimethod that first examines the argument and then dispatches to the proper drawing functionality or error handling if the object isn't drawable.
Comparisons between functional and object-oriented styles are all over the place; here are a couple relevant questions that should provide a good start: Functional programming vs Object Oriented programming and Explaining functional programming to object-oriented programmers and less technical people.

A: As katrielalex wrote: There is no reason not to support heterogeneous lists. In fact, disallowing it would require static typing, and we're back to that old debate. But let's refrain from doing so and instead answer the "why would you use that" part...
To be honest, it is not used that much -- if we make use of the exception in your last paragraph and choose a more liberal definition of "implement the same interface" than e.g. Java or C#. Nearly all of my iterable-crunching code expects all items to implement some interface. Of course it does, otheriwise it could do very little to it!
Don't get me wrong, there are absolutely valid use cases - there's rarely a good reason to write a whole class for containing some data (and even if you add some callables, functional programming sometimes comes to the rescue). A dict would be a more common choice though, and namedtuple is very neat as well. But they are less common than you seem to think, and they are used with thought and discipline, not for cowboy coding.
(Also, you "User as nested list" example is not a good one - since the inner lists are fixed-sized, you better use tuples and that makes it valid even in Haskell (type would be [(String, Integer)]))

A:
Is there reason to use the former over
  the latter in languages that support
  it?

Yes, there is a very simple reason why you can do this in Python (and i assume the same reason in Ruby):
How would you check that a list is heterogenous?

*

*It can't just compare the types directly because Python has duck typing.

*If all the object have some common typeclass Python has no way to guess that either. Everything supports being represented anyways, so you should be able to put them in a list together too.

*It wouldn't make any sense to turn lists into the only type that needs a type declaration either.

There is simply no way to prevent you from creating a heterogenous list!

Or is there some bigger reason to use
  heterogenous arrays?

No, I can't think of any. As you already mentioned in your question, if you use a heterogenous arrays you're just making things harder than they have to be.

A: There is no reason not to support heterogeneous lists. It's a limitation for technical reasons, and we don't like those.
Not everything needs to be a class!
In Python, a class is basically a souped up dictionary with some extra stuff anyway. So making a class User is not necessarily any clearer than a dictionary {"name": ..., "id": ...}.

A: There is nothing to stop you having a heterogeneous array in Java. It is considered poor programming style and using proper POJOs will be faster/more efficient than heterogeneous arrays in Java or any other language as the types of the "fields" are statically known and primitives can be used.
In Java you can
Object[][] array = {{"John Smith", 000}, {"Smith John", 001}, ...};

A: Eterogenous lists are very useful. For instance, to make the game of snake, I can have a list of blocks like this:
[[x, y, 'down'], [x1, y1, 'down']]
instead of a class for the blocks, and I can access faster to every element.

A: In Lua an object and an array are the same thing so the reason is more clear. Let's say that Lua takes the weak typing to the extreme
Apart from that, I had a Google Map object and I needed to delete all markers created so far in that map. So I ended up creating an array for markers, an array for circles and an array for places. Then I made a function to iterate over those three arrays and call .remove() on each of them. I then realized that I could just have a single non homogeneous array and insert into them all the objects and iterate once over that array

A: Here is a simple answer:

N.B. I am not talking about arrays that include different objects that
    all implement the same interface or inherit from the same parent, e.g.:

Everything extends java.lang.Object... and that's plenty. There is no reason not to have Object[] and put anything you like in. Object[] are exceptionally useful in any middleware like persistence layer.


text:
Q: Need a SQL Server query to eliminate the Highlighted Rows ( Returning Routes in Flight) I have a requirement where I need to eliminate all the rows which have returning flight routes.
I have highlighted the routes in the orange color which depicts this behavior.
For example, row 1 has one route BKI - MYY and row 4 has MYY - BKI. I need a flag (Boolean 1/0) that checks the entire row and sees if it's a returning flight or not.
Note: there are a few scenarios where the flight started at 10:00 PM night today and returned the next day early morning. if it is a consecutive day then we need to eliminate that rows as well.
Any thought on how to solve this?
Gsheet link : Sample Data : https://docs.google.com/spreadsheets/d/1ibrUfOTMEx4i-erDQnIfszdcEvJKU_oFcnMBFcGbvyM/edit?usp=sharing
Definition: Return flight is a two-way journey by air. If a flight is starting from the source and after certain hop/route returns backs to the same source (Departure Station)
std_utc = Departure Time
Sta_utc = Arival Time

with AllFlight as
(
select row_number()over(order by std_utc)rn, aoc,hub,flight ,departure,arrival,std_utc,sta_utc
from TABLENAME01
),
returnFlight as
(
select * from AllFlight s
where exists
(
    select * from AllFlight s2
    where s2.rn<s.rn and s2.arrival=s.departure and s2.departure=s.arrival
    and
    (date_diff(EXTRACT(DATE FROM s.sta_utc),EXTRACT(DATE FROM s2.std_utc), DAY))<=1
)
)

select aoc,hub,flight ,departure ,arrival,std_utc  ,sta_utc from AllFlight where rn not in (select rn from returnFlight)

This query is kept on running and not giving me the desired output.
Note: I am using Bigquery

A: I have created a table named S65828793 with your provided data. First I have numbered the rows in ascending sequence of departure time. Then from that I have identified the flights that have been another flight within two consecutive days from opposite direction and marked those as returning flight.
Then at last I have excluded all the returning flight from the total flight list.
with AllFlight as (
select row_number()over(order by departuretime)rn, aoc  ,hub    ,flight ,departure  ,arrival    ,DepartureTime  ,ArrivalTime from S65828793
),
returnFlight as (select * from AllFlight s
where exists (select * from AllFlight s2 where s2.rn<s.rn and s2.arrival=s.departure and s2.departure=s.arrival and datediff(day,cast(s.ArrivalTime as date),cast(s2.departuretime as date))<=1))
select aoc  ,hub    ,flight ,departure  ,arrival    ,DepartureTime  ,ArrivalTime from AllFlight where rn not in (select rn from returnFlight)

Result:


text:
Q: React Native TouchableHighlight Font Color Text Change how do TouchableHighlight handles the color of the text when tap. I already did it on the backgroundColor using underLayColor. Here's my code:
<TouchableHighlight
                        style={{ borderRadius: 5}}
                        underlayColor="#ffffff"
                        onPress={this.onLoadPress}>
                            <View style={[styles.buttonBox, styles.btnEditProfile]}>
                                <Text style={styles.btnEditProfileText}>
                                    Edit Profile
                                </Text>
                            </View>
                    </TouchableHighlight>

A: I've been struggling with this myself. And using onPressIn and onPressOut props of TouchableWithoutFeedback causes a little delay that becomes glitchy if you use that on a component that receives frequent taps. However, that delay doesn't occur when you use onShowUnderlay and onHideUnderlay props of TouchableHighlight itself.
P.S. your TouchableHighlight component should have an onPress property for this to work.

A: The TouchableHighlight has all the props of TouchableWithoutFeedback. TouchableWithoutFeedback has the onPressIn and onPressOut props which can receive a function (basically like onMouseDown and onMouseUp). You can use those methods to change a state which will change the style of the text. Here is a working example.


text:
Q: Getting error `object has no attribute LAYER_ID_COUNT' in KiCad PCBNEW trying to add track in Python script I am trying to programatically add a new track to a KiCad board using the Python API. My code fails when trying to assign the layer to the new track.
My code is modeled off this example...
https://github.com/mmccoo/kicad_mmccoo/blob/master/basics/basics.py#L141
...which builds a dictionary of available layers, and then uses that dictionary to look up the desired layer by name.
Unfortunately the field pcbnew.LAYER_ID_COUNT doe snot seem to exist in the latest version of KiCad (5.1.2). To confirm, I typed the following into the Python command prompt...
import pcbnew
pcbnew.LAYER_ID_COUNT
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'module' object has no attribute 'LAYER_ID_COUNT'

How can I work around this issue?

A: The following code will create the layertable table used by the above example (and many other examples)...
layertable = {}

for i in range(1000):
    name = board.GetLayerName(i)
    if name != "BAD INDEX!":
        layertable[name]=i

It is a horrible hack, but it works. It makes the reasonable assumption that there will never be more than 1000 layers.
Once the above code as set up the layertable dictionary, you can assign a layer to a track like this...
track.SetLayer(layertable["F.Cu"])