text:
Q: Pagination doesn't work with loop I'm trying to implement pagination inside my theme. I want to use understrap theme pagination. So, I downloaded this file, add require code inside my functions.php. Next I added code inside my loop and... it's not working. What's wrong with my code?
    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 2,
        'paged' => $paged,
        'cat' => '-6'
    );
    $query = new WP_Query($args);

    if ($query->have_posts()) :
        while ($query->have_posts()) :
            $query->the_post();
            $background = get_the_post_thumbnail_url(get_the_ID(), 'medium');

            $category = get_the_category();
            $category_class = $category[0]->slug;
            ?>

                    <a href="<?php the_permalink(); ?>">
                        <div class="post-listing__image <?php if ( has_post_thumbnail() ) {} else {echo "post-listing__image-default";}; ?>" style="background: url('<?php echo $background; ?>');">

                        dodano: <?php echo get_the_date(); ?>
                        <span class="badge badge-pill mm-badge <?php echo $category_class; ?>"><?php the_category(' '); ?>

<?php the_title(); ?>

                    <?php the_excerpt(); ?>
                    <a href="<?php the_permalink(); ?>" class="btn btn-default btn-mm btn-mm--green">Więcej

        <?php
        endwhile;

        wp_reset_postdata();
        else:
        ?>

Brak wyników spełniających kryteria wyszukiwania

        <?php
    endif;
?>

        <?php mmtemplate_pagination(); ?>

A: There seems to be some issues with your WP query. Try this code instead and let me know.
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'post',
    'posts_per_page' => 2,
    'paged' => $paged,
    'cat' => '-6'
);
$wp_query=new WP_Query($args);
if ( $wp_query->have_posts() ) :
    while ( $wp_query->have_posts() ) : $wp_query->the_post();
        $background = get_the_post_thumbnail_url(get_the_ID(), 'medium');

        $category = get_the_category();
        $category_class = $category[0]->slug;
        ?>

                <a href="<?php the_permalink(); ?>">
                    <div class="post-listing__image <?php if ( has_post_thumbnail() ) {} else {echo "post-listing__image-default";}; ?>" style="background: url('<?php echo $background; ?>');">

                    dodano: <?php echo get_the_date(); ?>
                    <span class="badge badge-pill mm-badge <?php echo $category_class; ?>"><?php the_category(' '); ?>

<?php the_title(); ?>

                <?php the_excerpt(); ?>
                <a href="<?php the_permalink(); ?>" class="btn btn-default btn-mm btn-mm--green">Więcej

    <?php endwhile; ?>

            <?php mmtemplate_pagination(); ?>

    <?php
    wp_reset_postdata();
    else:
    ?>

Brak wyników spełniających kryteria wyszukiwania

    <?php
endif;
?>

UPDATE:
You should not call the loop inside your 'template_part' file. It should be in the main file, see below code.

        <?php
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 2,
            'paged' => $paged,
            'cat' => '-6'
        );
        $wp_query=new WP_Query($args);
        if ( $wp_query->have_posts() ) :
            while ( $wp_query->have_posts() ) : $wp_query->the_post();

            get_template_part('template-parts/loop/loop', 'post-listing');

        endwhile;
        ?>

                <?php mmtemplate_pagination(); ?>

        <?php
        wp_reset_postdata();
        else:
        ?>

Brak wyników spełniających kryteria wyszukiwania

        <?php
    endif;
    ?>


text:
Q: SQLCE: Why I get "duplicate value" error? The field is identity enabled? In my query I don't use primary key field because identity setting is enabled.
   string sql = @"
                  INSERT INTO [tblTemplates] (personID, hash, data)
                      VALUES (@personID, @hash, @data)";

   cmd = new SqlCeCommand(sql, cn);
   cmd.Parameters.AddWithValue("@personID", newTemplate.personID);
   cmd.Parameters.AddWithValue("@hash", newTemplate.templateHash);
   cmd.Parameters.AddWithValue("@data", newTemplate.templateData);

   cmd.ExecuteNonQuery();

Randomly I can or cannot insert a record then an exception thrown:

A duplicate value cannot be inserted into a unique index.
  [ Table name = tblTemplates,Constraint name = PK_tblTemplates_templateID
  ]

This is the table schema:
-- Script Date: 26.08.2011 10:37  - Generated by ExportSqlCe version 3.5.1.5
CREATE TABLE [tblTemplates] (
  [templateID] int NOT NULL  IDENTITY (1,1)
, [hash] nvarchar(100) NOT NULL
, [data] image NOT NULL
, [personID] int NOT NULL
);
GO
ALTER TABLE [tblTemplates] ADD CONSTRAINT [PK__tblTemplates__templateID] PRIMARY KEY ([templateID]);
GO
CREATE INDEX [IDX_tblTemplates_personID] ON [tblTemplates] ([personID] ASC);
GO
CREATE UNIQUE INDEX [UQ__tblTemplates__templateID] ON [tblTemplates] ([templateID] ASC);
GO

Why I get this error?

A: It seems like a bug!
Workaround: Converting field data type from int to uniqueidentifier works.
My workaround attempts:
Attempt #1: Same connection
        bool executed = false;
        int counter = 0;

        while (!executed)
        {
            try
            {
                cmd.ExecuteNonQuery();
                succes = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("SERVER> (Error) Exception in AddTemplate() {0},{1}", ex.Source, ex.Message);
                System.Threading.Thread.Sleep(100);
            }

            counter++;

        }

Result: This seems like an endless loop.
Attempt #2: New connection
            try
            {
                cmd.ExecuteNonQuery();
                succes = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("SERVER> (Error) Exception in AddTemplate() {0},{1}", ex.Source, ex.Message);
                System.Threading.Thread.Sleep(100);
                AddTemplate(newTemplate); //Warning: Recursive call!
            }

Result: This try helped after a few recursive calls.

A: I had similar problem. I used IDENTITY_INSERT on my table like

SET IDENTITY_INSERT MyTable ON;
-- some identity insert on MyTable
SET IDENTITY_INSERT MyTable OFF;

After this, all inserts on MyTable throw "duplicate value" error.
Solution to this problem was

var cmd = Connection.CreateCommand();
cmd.CommandText = "SELECT MAX([Id] ) + 1 from [MyTable]";
object i = cmd.ExecuteScalar();
if (i != null && i is int)
{
    cmd.CommandText = "ALTER TABLE [MyTable] ALTER COLUMN [Id] IDENTITY (" + i + ",1)";
    cmd.ExecuteNonQuery();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: References homotopy groups of maps and diagrams In the following extract taken from the appendix of Wall's book on Differential Topology the author mentions the groups $\pi_n(j)$ associated to a map and the groups $\pi_n(\Phi)$ associated to a diagram, but he does not really define them.

I'm looking for references (textbooks or similar) where I can find a precise definition of these groups, and more about the exact sequences.


text:
Q: LaTeX code not working after processing the data from a PHP file I have a WordPress website and it supports LaTeX code via the LaTeX plugin (Simple Mathjax). When I use code like $\vec{V}$ it responds very well in the WordPress editor and prints my LaTeX code.
But when I process my data in a calculator from an external PHP file (hosted on my server) it only processes the data and doesn't show the LaTeX formatting code.
Already Tried Things

*

*I tried - echo "$\vec{V}$"; in the PHP file, but it doesn't print the latex formatted code.

*I also tried to do this -> $   <?PHP ...code file...?>  $ it also doesn't work.
My PHP File
<?php

$dateFrom = $_GET['v1'];
$dateTo = $_GET['v2'];

echo "$\vec{V}$
  ";

echo "Date From: ".$dateFrom."
";
echo "Date To: ".$dateTo."
";

?>


text:
Q: What is the Java translation to this@NameOfTheClass::open from Kotlin? I'm working on a Java project, having as reference a Kotlin project. This code uses this expression, which I would guess comes from functional programming:
this@MarkdownWorkspace::open

This is used in a constructor's parameter, which needs a "java.util.function.Consumer" object.
Thanks a lot!

A: Java equivalent of this@MarkdownWorkspace::open would be MarkdownWorkspace.this::open


text:
Q: Change syslog log file's owner/group? Is there a way to have syslog create a log file that's not owned by root?
I've got several jboss application servers that I've got logging to a server. Everyone's running CentOS. Right now, all of the logs are going to 'somelog.log' and it's owned by root:root. Can I make that instead be another user?

A: If possible for you, migrate to syslog-ng. It allows you to specify file modes per-file basis and is much more granular in every way.


text:
Q: How to efficiently cover a set of points with circles when you can't access point coordinates? Suppose I have a finite set of points distributed in a unit square. I can't access the point coordinates; instead, I can only specify a (point, radius) pair and see how many points fall inside that circle. I want to find a set of circles such that each point is in at least one circle, and no circle contains more than 1000 points. What's an efficient way to do this? E.g. a way that minimizes the expected number of (point, radius) searches?
I tried a recursive approach. E.g. f(point, radius) takes a circle and returns a set of smaller circles that cover it. Then recurse until each circle contains fewer than 1000 points. But there's not a straightforward (to me) way to choose the smaller circles in the recursive step.
Edit: Circles are allowed to overlap with each other / with the outside of the square.

A: Not having a strict partition ("strict" - where the circles in the solution may not overlap and points must appear in exactly 1 circle) simplifies the problem.
The straight-forward way to subdivide a circle under those circumstances is to form a set of child circles that circumscribe the four quadrants of the parent...

Here's a (cursorily tested) demo using that approach

class Circle {
  constructor(x,y,radius) {
    Object.assign(this, { x, y, radius })
    this.rSquared = radius*radius
  }

  contains(point) {
    let dx = point.x - this.x
    let dy = point.y - this.y
    return dx*dx + dy*dy < this.rSquared
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
    ctx.stroke();
  }

  subdivide() {
    const halfR = this.radius / 2.0
    const smallR = this.radius * Math.SQRT2 / 2.0

    return [
      new Circle(this.x-halfR, this.y-halfR, smallR),
      new Circle(this.x-halfR, this.y+halfR, smallR),
      new Circle(this.x+halfR, this.y-halfR, smallR),
      new Circle(this.x+halfR, this.y+halfR, smallR),
    ]
  }

}

// this class keeps a set of random points and answers countInCircle()
// solutions may only call countInCircle()
class Puzzler {
  constructor(count) {
    this.points = []

    for (let i=0; i<count; i++) {
      let point = { x: Math.random()*width, y: Math.random()*height}
      this.points.push(point)
    }
  }

  // answer how many points fall inside circle
  countInCircle(circle) {
    return this.points.reduce((total, p) => total += circle.contains(p) ? 1 : 0, 0);
  }

  drawSolution(circles) {
    // draw the random points
    this.points.map(p => ctx.fillRect(p.x,p.y,2,2))

    // draw the circles in the solution
    ctx.strokeStyle =  'lightgray'
    circles.forEach(circle => circle.draw())

    // log some stats - commented a few of these out for snippet brevity
    const counts = circles.map(circle => this.countInCircle(circle));
    console.log('circles:', circles.length)
    // console.log('counts:', counts.join(', '))
    // console.log('counts above 100:', counts.filter(c => c > 100).length)

    const averageCount = counts.reduce((a, b) => a + b) / counts.length
    console.log('average count:', averageCount.toFixed(2))

    const uncovered = this.points.reduce((total, point) => {
      return total + (circles.some(circle => circle.contains(point)) ? 0 : 1)
    }, 0)
    console.log('uncovered points:', uncovered)
  }

}

// setup canvas
const canvas = document.getElementById('canvas')
const { width, height } = canvas
const ctx = canvas.getContext('2d')

// setup puzzle
const count = 1000
const maxCountPer = 100
const puzzler = new Puzzler(count, maxCountPer)

// begin with an encompasing circle, subdivide and solve recursively
// until all subdivided circles meet the count criterion
let r = width*Math.SQRT2/2
let c = new Circle(width/2.0, width/2.0, r)
let solution = solve(c);

function solve(circle) {
  let result = []
  let count = puzzler.countInCircle(circle)
  if (count > 0 && count <= maxCountPer) {
    result.push(circle);
  } else if (count > maxCountPer) {
    circle.subdivide().forEach(c => {
      result.push(...solve(c))
    })
  }
  return result
}

requestAnimationFrame(() => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  puzzler.drawSolution(solution)
});

Circles Puzzle

 <canvas style="border: 1px solid gray;" id="canvas" height="800" width="800"></canvas>

A: Assumption: When you pick a point and a radius, you get back a list of points that are in the containing circle. I.e., you know which points are covered by which circles.
If that's correct,then you can map out the approximate relative location of all points, after which answers to this similar question should carry you over the finish line.
To map out the relative location of all points:
Note that you can find the distance between any pair of points by centering your circle on one and using binary search on your radius to find the distance to the other within whatever precision you want to use.
Next choose three arbitrary points that aren't too close together. Pick an arbitrary point. Grow the radius, say to 1/4. Pick an arbitrary point close to that radius (by incrementing radius a bit to get another point, or using binary search on radius). Say the distance between these first two points is d. Pick a third point at distance >= d from the first two points but ideally close to d, again by incrementing the two radii or binary search on the same.
Now you have a roughly equilateral triangle. It isn't important that it's equilateral, but it is important that the points aren't very close, and aren't co-linear.
Next, give these three points coordinates. Say the first point is at (0,0), the second point is at (0, dist to first point). The third point will have two possible locations based on its distance from the first two. Choose the one in the first quadrant (arbitrarily).
All other points can now be positioned relative to this triangle by finding their distance two the points of the triangle.
For purposes of your problem, it doesn't matter that the cloud of points is rotated relative to the input, or that we don't know where the unit square is relative to the points. You have a cloud of points with (approximately) known coordinates, and can proceed accordingly.


text:
Q: Sharepoint Development URL (Visual Studio) I'm trying to create a SharePoint app, but am having a hard time getting my Visual Studio to communicate properly so I can run my code.
I am using an Office 365 subscription and Visual Studio 2015 Community Edition.
If I look at the properties for my solution, in the SharePoint section active deployment configuration is set to "deploy app for SharePoint", server connection is "online", and site url is "http://myname.sharepoint.com/sites/MyDevSite" (with myname and MyDevSite replaced with the appropriate names for my site).
If I try to hit the debug button, I get a prompt saying "do you want to switch the project to offline mode?". If I hit no, I get a prompt saying "there were deployment errors. continue?". Saying yes asks about switching to offline mode again, and then saying no there again brings up a "communication with the SharePoint server is cancelled" error.
If right at the beginning I allow it to go into offline mode, I get the same prompt about deployment errors and then an error saying "connections to SharePoint server are currently disabled because the project is in offline mode. to connect to the SharePoint server, switch to online mode".
Things I have tried:

*

*using https instead of http on the server url

*using http://mysite.sharepoint.com (so dropping the /sites/MyDevSite portion of the url)

*building a deployment package and trying to add the zip file that visual studio created to my sharepoint dev site

I've come across guides for how to set up Visual Studio to work with SharePoint Online, however none of them give any insight into what I should be putting for my server url.
I can get functional projects through the Napa interface, however unfortunately I have been explicitly instructed that this isn't acceptable and I MUST do an MVC project in Visual Studio.
Until I at least have an environment where I can execute code, I can't do much with the various code examples that are out there. I suspect the problem is the url I'm putting into Visual Studio, however I suppose there could be a setting in Office 365's SharePoint configuration that I missed to enable remote debugging.
Any suggestions?

A: Are you using a SharePoint template? Which one? Do you see SharePoint templates when you create a new project?
https://connect.microsoft.com/VisualStudio/feedback/details/1294152/no-sharepoint-development-in-vs2015-community
The link above talks about templates not being available in Community Edition. It seemed like you may have to install some component to get it working.
I would be surprised if SharePoint templates were included in a free version of VS. I am more familiar with older versions so I could easily be wrong, but you had to have professional version or higher in 2010/2012.


text:
Q: Split table to sheet by column - don't work with numeric value I have this macro to split table into sheets by column:

Dim DR As Range
Sheets("Budget").Select
Set DR = Range("DR")

For Each cell In DR
Sheets("Budget").Copy after:=Worksheets(Sheets.Count)
ActiveSheet.Name = cell.Value

With ActiveWorkbook.Sheets(cell.Value).Range("MasterData")
.AutoFilter field:=9, Criteria1:="<>" & cell.Value, Operator:=xlFilterValues
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With

ActiveSheet.AutoFilter.ShowAllData
Next cell

End Sub

It works when there are text values in column like for example names of regional directiors (column 9 is DR - regional director) and range DR is a list of all directors without duplicates. But when I tried the same with column number 10 which is regional director number I doesn't work... I checked it many times with other columns and it olny works when there's a text value in a column. How to fix it? Why it doesn't work when there's a number in a column? It doesn't work even when I converted this number to text (number as text value).


text:
Q: null pointer exception on getNodeValue() when parsing XML web page - android I looked over several of the answers posted here, but I can't find the answer I need. It may have to do with the web site itself, but I don't think it is.
I'm trying to parse an XML on a web site and I'm getting a null pointer exception error.
I run the parsing is a separate thread following Google demand when reading from the web.
please see my code and try to help.
class BackgroundTask1 extends AsyncTask<String, Void, String[]> {

protected String[] doInBackground(String... url) {
    new HttpGet();
    new StringBuffer();
    InputStream is = null;
    HttpURLConnection con = null;

    try {
        //Log.d("eyal", "URL: " + boiUrl);
        URL url1 = new URL("http://www.boi.org.il/currency.xml");
        con = (HttpURLConnection)url1.openConnection();
        con.setRequestMethod("GET");
        con.connect();
        is = con.getInputStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        NodeList lastVld = doc.getElementsByTagName("LAST_UPDATE");
        String lastV = lastVld.item(0).getFirstChild().getNodeValue();
        }

        catch (Exception e) {
           e.printStackTrace();
        }

I get the error on the last line.
Thanks for your help.

A: You only have one LAST_UPDATE tag in your xml and it has an inner value, so try just using the node value from the Node Class you get from item(0)
 String lastV = lastVld.item(0).getNodeValue();

HTHs

A: There is no node returned for that tag name.  You may want to first check the size of the lastVld and then try to access the items in there.

A: This code worked for me
InputStream is = null;
HttpURLConnection con = null;

try {
    URL url1 = new URL("http://www.boi.org.il/currency.xml");
    con = (HttpURLConnection)url1.openConnection();
    con.setRequestMethod("GET");
    con.connect();
    is = con.getInputStream();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(is);
    NodeList lastVld = doc.getElementsByTagName("LAST_UPDATE");

    Element elem = (Element) lastVld.item(0);
    String lastV = elem.getTextContent();
    System.out.println(lastV);
} catch (Exception e) {
    e.printStackTrace();
}

I verified I was getting good content by adding a transformer to print out the results to the console.
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer xform = tFactory.newTransformer();

xform.transform(new DOMSource(doc), new StreamResult(System.out));

There was a couple times I tried running where elem came out null, which I think had something to do with some bad content being retrieved from the URL. This was the content that was printed by the transformer.
<html>
<body>
<script>document.cookie='iiiiiii=11a887d6iiiiiii_11a887d6; path=/';window.location.href=window.location.href;</script>
</body>
</html>

I noticed that if I had this file open in my browser, the code would all of a sudden quit working until I refreshed the page, then it started giving me the right output.
I suspect there's an issue with something at this URL, because when it works properly, this code works fine.
Good luck...


text:
Q: Tail bound of sum less than sum of tail bounds
Problem: Suppose we have a probability space $(\Omega, \mathcal{M}, P)$, a random variable $X$ on this space, and two nonnegative measurable functions $f,g:\mathbb{R}\to[0, \infty)$. Choose some $\epsilon > 0$. Prove that
  $$P(f(X)+g(X)>\epsilon) \le P(f(X)>\epsilon/2) + P(g(X)>\epsilon/2)$$

Attempt: by definition we know $P(f(X)+g(X)>\epsilon) = P(\{\nu \vert f(X)(\nu)+g(X)(\nu)))>\epsilon\})$, and it seems like a basic real analysis exercise, however I'm having trouble splitting this term into the two desired terms. Any help is appreciated!

A: Observe that
$$ \{ \nu \in \Omega \mid f(X)(\nu) + g(X)(\nu) > \epsilon \} \subset \{ \nu \in \Omega \mid f(X) (\nu) > \tfrac \epsilon 2\} \ \cup \ \{ \nu \in \Omega \mid g(X) (\nu) > \tfrac \epsilon 2\}. $$
So
\begin{align*} P\left( \{ \nu \in \Omega \mid f(X)(\nu) + g(X)(\nu) > \epsilon \}\right) & \leq P \left( \{ \nu \in \Omega \mid f(X) (\nu) > \tfrac \epsilon 2\} \ \cup \ \{ \nu \in \Omega \mid g(X) (\nu) > \tfrac \epsilon 2\} \right) \\ & \leq P \left( \{ \nu \in \Omega \mid f(X) (\nu) > \tfrac \epsilon 2\} \right) + P \left( \{ \nu \in \Omega \mid g(X) (\nu) > \tfrac \epsilon 2\} \right). \end{align*}


text:
Q: Plotting pandas dataframe and multiprocessing in Python I have a pandas dataframe and I want to plot slices of it, in a function using multiprocessing. Even though the function "process_expression" works when I call it independently, when I use the "multiprocessing" option it is not giving any plots.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy
import seaborn as sns
import sys
from multiprocessing import Pool
import os
os.system("taskset -p 0xff %d" % os.getpid())

pool = Pool()
gn = pool.map(process_expression, gene_ids)
pool.close()
pool.join()

def process_expression(gn_name, df_gn=df_coding):
    df_part = df_gn.loc[df_gn['Gene_id'] == gn_name]
    df_part = df_part.drop('Gene_id', 1)
    df_part = df_part.drop('Transcript_biotype', 1)

    COUNT100 = df_part[df_part >100 ].count()
    COUNT10 = (df_part[df_part >10 ].count()) - COUNT100
    COUNT1 = (df_part[df_part >1].count())- COUNT100 - COUNT10
    COUNT0 = (df_part[df_part >0].count())- COUNT100-COUNT10- COUNT1
    result = pd.concat([COUNT0,COUNT1,COUNT10,COUNT100], axis=1)
    result.columns = [ '0 TO 1', '1 TO 10','10 TO 100', '>100']
    result.plot( kind='bar', figsize=(50, 20), fontsize=7, stacked=True)
    plt.savefig('./expression_levels/all_genes/'+gn_name+'.png')#,bbox_inches='tight')
    plt.close()

the df_coding table is something like (it has more columns, I erased some):
 Isoform_name,heart,heart.1,lung.3,Gene_id,Transcript_biotype
 ENST00000296782,0.14546900000000001,0.161245,0.09479889999999999,ENSG00000164327,protein_coding
 ENST00000357387,6.53902,5.86969,7.057689999999999,ENSG00000164327,protein_coding
 ENST00000514735,0.0,0.0,0.0,ENSG00000164327,protein_coding

The input dataframe df_coding is a dataframe with a column Gene_id. In this column I have a list of gn_name. What I want is to take each time only the parts of the dataframe which have the name gn_name[i] in the Gene_id column and plot a barplot based on this dataframe.
For example if I call the 'process_expression('ENSG00000164327')', which is a specific gn_name, the output is something like this:

What am I doing wrong? I know that the process stops at the plotting command when I run it with multiprocessing.

A: The problem is between multiprocessing and matplotlib.  With multiprocessing you create a completely new context with each process.  The new context does not (and can not) successfully initialize the context because it is already initialized in the parent process.
If you are trying to overcome a performance issue then you may be on the right track.  However, plotting back to the correctly initialized context of the parent process will require you to go a lot deeper into the structure of the underlying matplotlib guts. Here is an example of setting a data pipe back to the original application.  Really this is only going to help if you are dealing with a lot of processing of the data before it is plotted.  It doesn't look like that is what you are doing here.
If you are trying to get a visual effect like stacked / overlayed results then you probably want to look into repeating the plot function or modifying the data structure to better represent what you want to visualize.
So.  What problem are you trying to solve?  A performance problem, or a visualization problem?  If it is a visualization problem then you do NOT want to use multiprocessing.


text:
Q: How to train data of different lengths in machine learning? I am analyzing the text of some literary works and I want to look at the distance between certain words in the text. Specifically, I am looking for parallelism.
Since I can't know the specific number of tokens in a text I can't simply put all words in the text in the training data because it would not be uniform across all training data.
For example, the text:
"I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. I have a dream today."
Is not the same text length as
"My fellow Americans, ask not what your country can do for you, ask what you can do for your country."
So therefore I could not columns out of each word and then assign the distance in a row because the lengths would be different.
How could I go about representing this in training data?  I was under the assumption that training data had to be the same type and length.

A: In order to solve this problem you can use something called pad_sequence,so follow this process, sure you are going to transform the data throught some word embedding techniques like TF-IDF or any other algorithm, and after finishing the process of converting the textual data into vectors and by using the shape method you can figure the maximum length you have and than use that maximum in the pad-sequence method, and here is a how you implement this method:
'''
from keras.preprocessing.sequence import pad_sequences
padded_data= pad_sequences(name-of-your-data, maxlen=your-maximum-shape, padding='post', truncating='post')
'''


text:
Q: How was the following Integral identity calculated? $$\frac{1}{2\pi} \int_{0}^{2\cdot\pi}\left |1+e^{j\cdot k\cdot d\cdot \cos(\theta )}  \right |^{2}d\theta =2(1+ J_{0}\left ( k d \right ))$$
Where:
$$j=\sqrt{-1}$$
and $J_{0}$
is the Bessel function of the first kind of order zero.
k,d are constants.

A: Here is my idea despite the fact that I didn't finish the calculation (yet)... I also don't promise to do so. I hope this helps though somehow ... Maybe you can continue from where I stopped my reasoning.
Let $ I = (\frac{1}{2\cdot\pi})\cdot \int_{0}^{2\cdot\pi}\left (1+e^{j\cdot k\cdot d\cdot cos(\theta )}  \right )^{2}d\theta $
Prove that $ I = 2 (1+ J_{0} ( 2 k d  ))$
Let $x=cos \theta $ which means that $d\theta = \frac{-dx}{sin x}$
Therefore $I = -\frac{1}{2 \pi} \int_{0}^{2 \pi} (1 + e^{jkdx})². \frac{1}{sin x}dx$ : (1)
On the other hand (source: https://en.wikipedia.org/wiki/Bessel_function)
$J_0(2kd) = \frac{1}{2 \pi} \int_{- \pi}^{\pi} e^{2jkdsin \alpha}d \alpha = \frac{1}{\pi} \int_{0}^{\pi} cos(-2kdsin(\beta)) d \beta$ :(2)
Now back to (1): $I = -\frac{1}{2 \pi}( \int_{0}^{2 \pi} \frac{1}{sin x} dx + 2 \int_{0}^{2 \pi} e^{jkdx}. \frac{1}{sin x}dx + \int_{0}^{2 \pi}e^{2jkdx}. \frac{1}{sin x} dx)$
Can you continue from here? Or did you do this kind of reasoning already?

A: Hint.\begin{align}
\left|1+e^{j\cdot k\cdot d\cdot \cos(\theta )}  \right|^{2}&=
\big(1+e^{j\cdot k\cdot d\cdot \cos(\theta )}\big)
\big(1+e^{-j\cdot k\cdot d\cdot \cos(\theta )}\big)
\\
&=  e^{-j\cdot k\cdot d\cdot \cos(\theta )} + 2 + e^{j\cdot k\cdot d\cdot \cos(\theta )}
\end{align}
$$=2+2\cdot \cos(k\cdot d\cdot \cos(\theta))=2\cdot(1+\cos(k\cdot d\cdot \cos(\theta))$$

A: $$\frac{1}{2\pi}\int_{0}^{2\cdot\pi}|1+e^{j\cdot k\cdot d\cdot \cos(\theta )}|^{2}d\theta =
\frac{1}{2\pi}\int_{0}^{2\cdot\pi}(1+e^{j\cdot k\cdot d\cdot \cos(\theta )})(1+e^{-j\cdot k\cdot d\cdot \cos(\theta )})d\theta $$
$$=\frac{1}{2\pi}\int_{0}^{2\cdot\pi}(2(1+cos(cos(k\cdot d\cdot cos(\theta)))d\theta
$$
Using the following identity:
$$\frac{1}{2\pi}\int_{0}^{2\cdot\pi}cos(a\cdot cos(\theta)d\theta =J_{0}(a)$$
We get:
$$\frac{1}{2\pi}\int_{0}^{2\cdot\pi}(2(1+cos(cos(k\cdot d\cdot cos(\theta)))d\theta=2(1+J_{0}(k\cdot d))$$


text:
Q: Where should I put original image like `psd` and `xcf` in rails project? Is there conventional place for original images like psd or xcf files in rails project?
I want to follow the convention if it exists.

A: There's no convention for where you place your project sources and other files.
But I too see why it's important to keep them together, and versioned in git.
I created a resources folder under my rails projects' root folder and place them there, i.e. your_app_root_folder/resources.

A: Per my comment above, we find very helpful to keep everything in one centralized place, so  all resources get branched at the same time. We usually add these additional folders to each Rails app:

myapp/resources/
----------------
   |___/creative = all creative resources for the site (i.e. PSDs, AIs, PNGs, etc.)
   |___/docs     = all documentation related to the project
   |___/ux       = UX designs and US related stuff

I've explained our approach in Where to store additional Rails project files? blog post


text:
Q: Problem in understanding division into groups and division among persons. My book describes these methods as under:

The number of ways in which $m.n$ different things can be equally divided into $m$ groups is $$ \frac{(mn)!}{(n!)^{m} . m!}$$ .

And the number of ways $m.n$ different things can be equally distributed among $m$ distinct persons is $$ \frac{(mn)!}{(n!)^m}$$ .
My question is : Why does the formula later doesn't contain $m!$ but the former contain so? What is the reason?? The book reasons that

In case of distribution of things among the persons, the thing which has gone to one person shalln't go to the other unlike in case of division into groups and so is the formula.

I really couldn't understand this. Please explain me lucidly why these formulas are different and what the book wanted to tell. Please help.

A: The groups are the same set of groups is the groups are permuted. There are $m$ groups and their permutations are $m!$. Permuting what each of $m$ persons will own is not the same distribution of good.
Visually: $\{A,B\}=\{B,A\}$. But $\text{Person }1\mapsto A$, $\text{Person }2\mapsto B$ is not the same as $\text{Person }1\mapsto B$, $\text{Person }2\mapsto A$.


text:
Q: Why is uploading to S3 so slow? I am using s3cmd to upload to S3:
# s3cmd put 1gb.bin s3://my-bucket/1gb.bin
1gb.bin -> s3://my-bucket/1gb.bin  [1 of 1]
  366706688 of 1073741824    34% in  371s   963.22 kB/s

I am uploading from Linode, which has an outgoing bandwidth cap of 50 Mb/s according to support (roughly 6 MB/s).
Why am I getting such slow upload speeds to S3, and how can I improve them?

Update:
Uploading the same file via SCP to an m1.medium EC2 instance (SCP from my Linode to the instance's EBS drive) gives about 44 Mb/s according to iftop (any compression done by the cipher is not a factor).

Traceroute:
Here's a traceroute to the server it's uploading to (according to tcpdump).
# traceroute s3-1-w.amazonaws.com.
traceroute to s3-1-w.amazonaws.com. (72.21.194.32), 30 hops max, 60 byte packets
 1  207.99.1.13 (207.99.1.13)  0.635 ms  0.743 ms  0.723 ms
 2  207.99.53.41 (207.99.53.41)  0.683 ms  0.865 ms  0.915 ms
 3  vlan801.tbr1.mmu.nac.net (209.123.10.9)  0.397 ms  0.541 ms  0.527 ms
 4  0.e1-1.tbr1.tl9.nac.net (209.123.10.102)  1.400 ms  1.481 ms  1.508 ms
 5  0.gi-0-0-0.pr1.tl9.nac.net (209.123.11.62)  1.602 ms  1.677 ms  1.699 ms
 6  equinix02-iad2.amazon.com (206.223.115.35)  9.393 ms  8.925 ms  8.900 ms
 7  72.21.220.41 (72.21.220.41)  32.610 ms  9.812 ms  9.789 ms
 8  72.21.222.141 (72.21.222.141)  9.519 ms  9.439 ms  9.443 ms
 9  72.21.218.3 (72.21.218.3)  10.245 ms  10.202 ms  10.154 ms
10  * * *
11  * * *
12  * * *
13  * * *
14  * * *
15  * * *
16  * * *
17  * * *
18  * * *
19  * * *
20  * * *
21  * * *
22  * * *
23  * * *
24  * * *
25  * * *
26  * * *
27  * * *
28  * * *
29  * * *
30  * * *
The latency looks reasonable, at least until the server stopped responding to ping requests.

A: I have seen many threads in a forum about slow upload to S3 using various clients, such as the free command line tools (written in Python, btw) and commercial ones.
Although I have no hard evidence for you, switching the S3 client (e.g. Cloud Berry Explorer) might solve your problem. Try it! :)

A: Just because you can go up to 50mbps does not mean you will always get 50mbps; The network path to S3 as well as the latency are also important.
If you are able to use multi-part upload, you will be able to break a file down into multiple pieces and upload it using multiple threads, possibly increasing the upload speed.

A: Just in case anyone stumbles upon this....
I had an issue where it was really slow to upload from an ec2 instance to an s3 bucket, turned out to be really simple, the region of the bucket!  I was using ec2 instances in north california, when the bucket was created as us standard it was really slow to transfer, with the bucket set to north california it was heaps faster.


text:
Q: Quickly enumerate domain users in remote trusted domain We have a situation where application code running on a server in one domain needs to list the users in another domain. Let's call the domains "PRODUCTION" and "CORPORATE" -- this code needs to run in PRODUCTION and interact with PRODUCTION resources, but there is a particular flow in which it needs to allow the user to select a member of CORPORATE\Domain Users (well, technically a more specific group, but that's a technicality). CORPORATE's domain controllers are all located remotely from the PRODUCTION servers, accessible over a VPN that is reasonably fast but a far cry from local. I have been having difficulty finding a way to efficiently list the members of the CORPORATE group.
I have tried various APIs, most recently the PowerShell ActiveDirectory module, which I suspect is built on top of System.DirectoryServices in the .NET Framework. The following command runs on a machine in the CORPORATE domain and on the CORPORATE LAN directly in several seconds:
Get-ADGroup "Domain Users" | Get-ADGroupMember

However, if I go to a machine in PRODUCTION, for which the CORPORATE DC is remote, the equivalent command:
Get-ADGroup -Server CORPORATEDC "Domain Users" | Get-ADGroupMember

...takes over 10 minutes to complete.
The result set has 1288 elements in it.
Is there some faster way to get the group members? The performance characteristics feel like it is setting up a remote iterator and then incurring a separate network round-trip (or perhaps several) for each individual element. Is there an API that can return the results in a single round-trip?
I ultimately want to do this from C# code and was just using PowerShell to proof out concepts. I am not opposed to using a native P/Invoke or COM API if it offers the functionality I need.


text:
Q: Komodo IDE 7 crashes on Ubuntu 11.10 Starting Komodo IDE 7 on Ubuntu 11.10 crashes in libcrypto.so during startup (see this forum discussion):
#0  0xb121ffbc in EVP_PKEY_CTX_dup () from /lib/i386-linux-gnu/libcrypto.so.1.0.0
#1  0xb12121f6 in EVP_MD_CTX_copy_ex () from /lib/i386-linux-gnu/libcrypto.so.1.0.0
#2  0xb1212362 in EVP_MD_CTX_copy () from /lib/i386-linux-gnu/libcrypto.so.1.0.0
#3  0xb0e93c4d in ?? () from .../Komodo-IDE-7/lib/python/lib/python2.6/lib-dynload/_hashlib.so
#4  0xb0e93fc9 in ?? () from .../Komodo-IDE-7/lib/python/lib/python2.6/lib-dynload/_hashlib.so
#5  0xb549ba2d in PyCFunction_Call () from .../Komodo-IDE-7/lib/mozilla/libpython2.6.so

How can I get it to run successfully?

A: On investigation, this happens when calling a function in the _hashlib module. This module is a builtin module in the standard Ubuntu python install (see sys.builtin_module_names), so the _hashlib.so that exists under lib/python/lib/python2.6/lib-dynload/_hashlib.so is not part of the Ubuntu python build.
You can fix this by recompiling that module from the standard Python sources:
export KOMODO_DIR=/home/davidf/Applications/Komodo-IDE-7
hg clone http://hg.python.org/cpython
cd cpython
hg checkout v2.6.5
(
    cd $KOMODO_DIR/lib/python/lib
    # handle no libssl.so
    ln -s /lib/libssl.so.0.9.8
    ln -s ./libssl.so.0.9.8 libssl.so
    # save the original _hashlib library
    cd python2.6/lib-dynload/
    mv _hashlib.so _hashlib.so.orig
)
# cd to python src for python 2.6.5
./configure --prefix $KOMODO_DIR/lib/python/

# step here to patch setup.py as @jalefkowit describes
# ...

# build and copy result to komodo's lib-dynload directory
$KOMODO_DIR/lib/python/bin/python setup.py build_ext
cp build/lib.linux-i686-2.6/_hashlib.so $KOMODO_DIR/lib/python/lib/python2.6/lib-dynload/

Caveats:

*

*I didn't actually use the above script; it's a recreation. There may be mistakes :)

*You need the CPython 2.6.5 sources; you can get these some other way if you like

*There is probably a shorter, and simpler way to do this

*This will build all the Python extension modules, not just the one you need

*On my Ubuntu 11.10, there's a libssl.so.0.9.8, but no libssl.so. The above linking allows the Python build to find them.

*This actually works on my machine, but for 64-bit / another release, you may need some adjustments


text:
Q: C++: an input validator function I have written the following function:
void check(int* input){

do{
    std::cout<<"Enter integer!";
    std::cin>>*input;
}while(!std::cin);
}

And I am using it in the main function as follows:
int main()
{
    int *k;
    k=new int;
    check(k);
    std::cout<<"Value of the k is:"<<*k<<"in address"<<k;
    return 0;
}

The problem is when user input some characters, the compiler keep printing "Enter integer!",  non-stop, and I have to stop the compiler manually.

A: What is happening is the stream is breaking. Basically, the program sees a character going into something that isn't a character and freaks out, which is UB. It is a simple fix you can find in just about any beginning level books that include data validation:
#include <limits>

if(cin.fail())
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

This tests if the stream is broken, clear the flag and ignore the rest of the input on the line.


text:
Q: Vim folding: how to map  to recursively open/close? In vim, it is often recommended to map <space> key in normal mode to za -- toggle current fold open/close. But I personally find this not enough. In particular, I'd like to map <space> to recursively open/close current fold, i.e.
If currently folded, map <space> to zO
If currently unfolded, map <space> to zC

How can I achieve that in my .vimrc?

A: zA is same as za, just toggle fold recursively depending on the current fold. It should fit your requirement.


text:
Q: How can we access NetworkMapCache in Contract-States library of CordApp I am trying to implement an Validator class in Contract-States library of CordApp, which have several validation methods that are inherited by Model classes in their init() fun, so that each time a Model class is called/initialized the validation happens on the spot.
Now I'm stuck at a point, where I need to validate whether the incoming member name(through a Model class) matches with Organisation name of the node, I need to access the NetworkMap for that. How can I do that?
In Work-Flow library each flow extends FlowLogic class that implements ServiceHub interface and through that we can access the NetworkMap, but how to do that in Contract-States library?
P.S. - I'm trying to avoid any circular dependency (Contract-States lib should not depend on Work-Flow lib)

A: The short answer, you can't.
The long answer:

*

*The difference between flow validations and contract validation is that the latter (contracts) must be deterministic meaning for the same input they must always give the same output whether it's now or after 100 years, in the current node or any other node.

*The reason for that is because any time (even in the future) when a node receives a transaction it must validate that transaction which includes validating the inputs which in return requires validating the transaction that created those inputs and so on, until you get a fully validated graph of all the inputs that lead to the outputs that were used as inputs and so on.

*That's why the contract should return the same result any time, and that's why it should be deterministic, and that's why contracts (unlike flows) don't have access to external resources (like HTTP calls, or even the node's database).

*Imagine if the contract was relying on the node's database for some validation rule, as you know, states are distributed on a need to know basis (i.e. only to participants of the state); so one node might have the state that you're using as validation source and another node won't, so the contract's output (transaction valid/invalid) will differ between nodes, and that breaks the deterministic concept.

*Contracts only have access to the transaction components: inputs, outputs, attachments, signatures, time-windows, reference states.

Good news, there are other ways to implement your requirement:

*

*Using an attachment that has the list of nodes that are allowed to be part of the transaction, this method should be used if the blacklist is not updated frequently and you can see the example here.

*Using reference states, where you can create a state that has the allowed parties and require the existence of that reference state in your transaction; this method should be used when the blacklist is more frequently updated. You can read about reference states here.

*Using Oracles, this option is in case there is a world organization (or for instance Ministry of Trade of some country) that provides an Oracle which returns the list of blacklisted parties; and you use that Oracle in your transaction. You can read about Oracles here.


text:
Q: Disable Angular Reactive form input based on selection value I have a form (using Angular Material), and I want to disable some of the input fields based on selection values. My code looks as below:
HTML
<mat-form-field class="someclass">
   <mat-select placeholder="Select payment method" formControlName="paymentMethod">
      <mat-option *ngFor="let payment of paymentMethodOptions" [value]="payment.value">
         {{payment.viewValue}}
      </mat-option>
   </mat-select>
</mat-form-field>

<mat-form-field class="someclass">
   <input matInput placeholder="Some input" formControlName="testInput">
</mat-form-field>

TS
paymentMethodOptions: payment[] = [
   { value: "opt-1", viewValue: "somevalue" },
   { value: "opt-2", viewValue: "anothervalue" }
];

paymentForm = new FormGroup({
   paymentMethod: new FormControl("", Validators.required),
   testInput: new FormControl({ value: "", disabled: true }, [
      Validators.required
   ])
});

I want to disable testInput if the value of the selection is equal to "opt-1". I've tried several options, but got different errors and couldn't solve it. Is there any working solution to this? Thanks in advance!

A: You'll can listen to the valueChanges event of the form :
this.paymentForm.valueChanges.subscribe((value) => {
  if(value.paymentMethod == 'opt-1'){
   this.paymentForm.controls['testInput'].disable();
  }else{
   this.paymentForm.controls['testInput'].enable();
  }
});

So everytime the select changes , the valueChanges event is called , the conditions kick in and it will enable or disable the formControl.

A: You can leverage the selectionChange @Output property on MatSelect and react accordingly:
onSelectionChanged({value}) {
  console.log(value);
  if(value === 'opt-1') {
    this.paymentForm.get('testInput').disable();
  } else {
    this.paymentForm.get('testInput').enable();
  }
}

And in template
<mat-select ... (selectionChange)="onSelectionChanged($event)">

Here's a Sample StackBlitz for your ref.
NOTE: In case there are more controls in your form than just mat-select, listening to valueChanges on the whole form could be expensive as this will get triggered every time there is a change in any of the form control. All we are concerned about is the change in the mat-select selection change.

A: Though there are already answers provided, If any had stumbled with the same issue. You can directly disable a form field by directly accessing its control
Had created a Stackblitz demo link
  <!-- INPUT FIELD -->
  <mat-form-field formControlName="testInput">
    <input matInput
           placeholder="Some input"
           [disabled]="paymentForm.get('paymentMethod').value === 'opt-1'">   // Disables the input once paymentMethod's formControlName value is opt-1
  </mat-form-field>


text:
Q: How to align a website to the center of the screen top/bottom and right/left? I want to have the effect like dropbox:https://www.dropbox.com/ where my website is centered in the exact middle of the page.

A: If you want to achieve this:

Here are different methods, with the pros/cons of each one, for centering a page vertically. Choose which one you prefer:

http://blog.themeforest.net/tutorials/vertical-centering-with-css/

EDIT. As suggested, I will proceed to explain one of the methods. It only works if you already know the height/width of the element to center (the link includes more methods). Assuming all your content is within , and that your content is 900px x 600px, you can do in your css:
html {
  width: 100%;
  height: 100%;
  }
body {
  width: 900px;
  height: 600px;
  position: absolute;
  top: 50%;
  margin-top: -300px; /* Half of the height of your body */
  }

However, this falls short for dynamically generated content, since you don't know the height of it. I've used it succesfully on log-in box pop-up and settings pop-up.
Another method I've used in the past for the whole page is the Method 1 from the link. It makes a set of divs to behave as a table, which can vertical-align to the middle.

A: Achieving this effect is way more complicated than it should be. Here's a bare-bones working example: http://jsfiddle.net/JakobJingleheimer/UEsYM/
html, body { height: 100%; } // needed for vertical centre

html { width: 100%; } // needed for horizontal centre

body {
    display: table; // needed for vertical centre
    margin: 0 auto; // needed for horizontal centre
    width: 50%; // needed for horizontal centre
}

.main-container {
    background-color: #eee;
    display: table-cell; // needed for vertical centre
    height: 100%; // needed for vertical centre
    // overflow: auto; // <- probably a good idea
    vertical-align: middle; // needed for vertical centre
    width: 100%; // needed for horizontal centre
}

.container {
    background-color: #ccc;
    padding: 20px;
}

A: If you want to align it vertically center, please check this web page: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

A: If you know the width and height of your page
then wrap your contents in following div css
.center
{
position:absolute;
top:50%;
left:50%;
margin-left: -(yourPageWidth/2);
margin-top: -(YourPageHeight/2);
}

A: On your topmost div give margin:0 auto 0 auto; Also define some width to that div.

A: First create a main container of the desired width and then put all your code inside the main container. For Eg.

     ......... your code

And in the css
#container{
  width: 700px ;
  margin-left: auto ;
  margin-right: auto ;
}

You can change the width as per your needs

A:

     ......... your code

#container{
  width: 700px ;
  margin:0 auto ;
  padding:0px;
}

A: Try this:
html

Hello this is some text. Hello this is some text. Hello this is some text.

CSS
html {
    height: 100%;
    background: #eee;
 }
 body {
   margin: 0;
   height: 100%;
   /*important*/
   text-align: center;
 }
 #centerMiddleWrap {
  /*important*/
    display: inline-block;
    vertical-align: middle;
 }
 #forceValign {
   /*important*/
    height: 100%;
    display: inline-block;
    vertical-align: middle;
 }
#centered {
    background: #000;
    color: #fff;
    font-size: 34px;
    padding: 15px;
    max-width: 50%;
    /*important*/
    display: inline-block;
}

Here is an demo

A: Wrap a div and define its width, use margin:0 auto for centering the div.
You can check a site's CSS by using Firebug or browser extensions.


text:
Q: What is YYYYPPP format I am working on a export functionality and one of the requirments is to display accounting period in YYYYPPP format.
Can anyone please explain what is YYYYPPP format

A: It is about time information where YYYY is the fiscal year and PPP is the period of that fiscal year. For example, 2017001 represents the first period in fiscal year 2017.
Often used in Analysis Budget Management tools like SAP. The standard format for entering periods is YYYYPPP or YYYY then PPP.


text:
Q: Cannot extract the embedded font - Code Igniter and dompdf Following the instruction in this link ( https://github.com/EllisLab/CodeIgniter/wiki/PDF-generation-using-dompdf ), I always encounter an error when opening the pdf file created. The error message is:"Cannot extract embedded font 'TradeGothicLT-CondEighteen'.Some characters may not display or print correctly. " and when i click  OK, the pdf displays black background and when i start highlighting the body, it captures the text but text are in black font-color. what should I do to get rid of this error?

A: There may be something wrong with your font cache, located at dompdf/lib/fonts/dompdf_font_family_cache.php (though the exact file name depends on your release and whether you have loaded fonts). This file tells dompdf what fonts are available for use in the PDF. If this file references a font that isn't actually available you can run into major issues on viewing. You may need to re-load your font files. Take a look at the Unicode how-to for an overview of using embedded fonts. This document hasn't been updated to reflect changes implemented in dompdf 0.6.0 beta 3, but the information is still pertinent.


text:
Q: How to assign labels to the x-axis using drupal module chart? I am trying to create a bar chart using chart, a drupal module using google chart tools.
I can't figure out how to put labels under the bars. The labels should be 'a', 'b', and so on. For some reason, only the first label, 'a' is showing up on the x-axis and its straight in the center of the graph.
Here is my code:
$chart = array(
  '#chart_id' => 'test_chart2',
  '#title' => chart_title(t('Bar Chart'), '0000ee', 15),
  '#type' => CHART_TYPE_BAR_V_GROUPED,
  '#size' => chart_size(400, 200),
  '#grid_lines' => chart_grid_lines(10, 10),
  '#bar_size' => chart_bar_size(25, 5),

 );

  $chart['#data'][] = array(10);
  $chart['#data'][] = array(20);
  $chart['#data'][] = array(30);
  $chart['#data'][] = array(40);
  $chart['#data'][] = array(50);
  $chart['#data'][] = array(60);
  $chart['#data'][] = array(70);
  $chart['#data'][] = array(80);

  $chart['#data_colors'][] = chart_unique_color('test_a');
  $chart['#data_colors'][] = chart_unique_color('test_b');
  $chart['#data_colors'][] = chart_unique_color('test_c');

  $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][0][] =   chart_mixed_axis_range_label(0, 200);
  $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][3][] = chart_mixed_axis_label(t('Hours'), 95);

  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][4][] = chart_mixed_axis_label(t('a'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][5][] = chart_mixed_axis_label(t('b'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][6][] = chart_mixed_axis_label(t('c'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][7][] = chart_mixed_axis_label(t('d'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][8][] = chart_mixed_axis_label(t('e'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][9][] = chart_mixed_axis_label(t('f'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][10][] = chart_mixed_axis_label(t('g'));
  $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][11][] = chart_mixed_axis_label(t('h'));

  return chart_render($chart);

A: chart_mixed_axis_label() method takes a second param in percentage to position the value.
Try giving percentage values.
chart_mixed_axis_label(t('a'), 10)
chart_mixed_axis_label(t('a'), 20)
chart_mixed_axis_label(t('a'), 30)

and so on.

A: In Drupal 6, I used CHART_TYPE_BAR_V instead of CHART_TYPE_BAR_V_GROUPED after applying this patch http://drupal.org/files/issues/chart.module-1169430.patch for the chart module,
$chart = array(
    '#chart_id' => $chart_id,
    '#title' => $title,
    '#type' => CHART_TYPE_BAR_V,
    '#size' => chart_size(700, 400),
    '#grid_lines' => chart_grid_lines(10, 10),
    '#bar_size' => chart_bar_size(55, 15),
  );
$chart['#data'][] = 10;
$chart['#data'][] = 20;
$chart['#data_colors'][] = C1;
$chart['#data_colors'][] = C2;
$chart['#mixed_axis_labels'][CHART_AXIS_X_TOP][1][] = chart_mixed_axis_label('a');
$chart['#mixed_axis_labels'][CHART_AXIS_X_TOP][1][] = chart_mixed_axis_label('b');

For more details about this patch, refer to chart issue https://www.drupal.org/node/1169430


text:
Q: I want to push my branch in git in a other branch in remote . I tried git push origin@ .it hasn't worked for me.Could anyone help me? I want to push my branch in git in a other branch in remote . I tried git push origin@ .it hasn't worked for me.Could anyone help me?
git push origin @ i expect to a push in a remote branch


text:
Q: PHP - format special characters and display I can see that htmlspecialchars() or htmlentities() convert special characters like & " to & " which isn't quite I am looking for.
My database table stores text articles that when I fetch and display,
anything that contains special characters do not display in a readable format.
Any PHP (Codeigniter) function that accomplishes this?
Added
Sorry for not being so clear about my question.
My case is that I have a word it's and this displays as it's

A: Perhaps you should check the charset of your output. For example use <meta charset="UTF-8">
in your html-document. [reference].

A: Try base64_encode() it.
$newStr = base64_encode("some texrt");

And by read, use base64_decode().
Set your mysql database to utf8:
SET NAMES utf8


text:
Q: How to get rid of ActivityManagerWrapper Error Google Login with Firebase com.miui.home? I am getting the following error on android Xiaomi phones with firebase google login. How do I fix this error ?
ActivityManagerWrapper  com.miui.home E
getRecentTasks: taskId=165   userId=0
baseIntent=Intent {
act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
flg=0x10000000
cmp=com.firmname.MainActivity
}

SHA-1 and SHA-256 finger prints added.


text:
Q: How to "overwrite" many columns base on column name without new columns being generated? I'm calculating weekly detection sex ratios by year for a study species across different sites. The goal is to create a set of tables (different tables for each site) with the row names as year and col names as week number.
As it currently stands, when using a loop to generate capture tables by sex, not all sexes were detected at each site every week, so instead of generating a column with NAs it just doesn't create a column for that week, so when I attempt to create a new table by division it doesn't work due to unequal dimensions of the male and female tables.
I've generated a 'dummy table' that is the correct dimensions with the correct labels for weeks and years, populated with NAs, but I don't know how to take a another table and overwrite only those columns which have the same name so that the NA columns are preserved as placeholders. Every join, anitjoin, bind list, or merge I've tried returns the two tables combined with new column names and all values present.
I've tried by first subsetting the data by sex and then site, as the plan is for each site to get its own table. Then aggregating the data such that the columns are week, year, and count (the number detected of that sex at that site, that week of that year). After that it gets cast/dcast to show the years as rows and weeks as columns.
I'm not sure how to maintain the same dimensions and column names for all data frames, which is I think necessary to create a table of the male:female ratio.
dat_male <- subset(dat, dat$Sex == "1")
dat_fem <- subset(dat, dat$Sex == "2")

The main data table has a separate line for every time a specimen was detected, so I subset out the sexes
df1<-as.data.frame(lapply(dat_week_total_table, function(x) rep.int(NA, length(x)))) #data frame with NAs of correct dimensions and col names.

for( k in 1:site_number){

  fem1<-subset(dat_fem, dat_fem$site == unique(dat_fem$site)[k])
  fem2<-aggregate(fem1$Count, by = list(fem1$jweek, fem1$YEAR), FUN = sum)
  colnames(fem2) = c("week", "YEAR", "Count")

  fem3<-dcast(fem2, YEAR~week, value.var = 'Count')
  fem3[is.na(fem3)] <- 0

fem_df<-df1 #here I've tried many functions but nothing has worked
# to overwrite only columns of the same name in fem_df with columns from fem3
#the same issue is occurs with the males

  assign(paste("fem_week_", unique(dat_fem$site)[k],"_table", sep = ""), fem3) #then the same process for the males  (same as female code but with male subset)

  temp <- male_df/fem_df #this is to create the ratios, but assumes equal dimensions

  assign(paste("dat_m:f_weekly_", unique(dat_male$site)[k],"_table", sep = ""), temp) #to name data frame by site
}

The error is the dimensions don't always match, or the dimensions exclude/include mismatching columns, throwing off the ratio. I am unsure how to populate the df1 table correctly by overwriting its NAs with values from the male and female tables.


text:
Q: Convert between cv::mat and Qimage would make the program crash #include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <QtGui>

//make QImage point to the contents of cv::Mat
inline QImage const mat_to_qimage_ref(cv::Mat &mat)
{
  return QImage((unsigned char*)(mat.data), mat.cols, mat.rows, mat.step1(), QImage::Format_RGB32);
}

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  QImage img("lena2.jpg");
  cv::Mat mat(img.height(), img.width(), CV_8UC4, img.bits(), img.bytesPerLine());
  QImage img = mat_to_qimage_ref(mat); //#1
  //QImage img2((unsigned char*)(mat.data), mat.cols, mat.rows, mat.step, QImage::Format_RGB32); #2

  QLabel label;
  label.setPixmap(QPixmap::fromImage(img)); //crash at here
  label.show();

  return a.exec();
}

(#2) is ok, but #1 will occur undefined behavior?(my case is crash)
Besides, if you use it as the codes below, It is okay
 cv::Mat img = cv::imread("lena2.jpg");
 QLabel label;
 label.setPixmap(QPixmap::fromImage(mat_to_qimage_ref(img)));
 label.show();

Don't know what is happening, something related to cycle dependency?

A: your function should be like this:
    QImage mat_to_qimage_ref(const cv::Mat3b &src) {
        QImage dest(src.cols, src.rows, QImage::Format_ARGB32);
        for (int y = 0; y < src.rows; ++y) {
                const cv::Vec3b *srcrow = src[y];
                QRgb *destrow = (QRgb*)dest.scanLine(y);
                for (int x = 0; x < src.cols; ++x) {
                        destrow[x] = qRgba(srcrow[x][2], srcrow[x][1], srcrow[x][0], 255);
                }
        }
        return dest;
    }

A: If you don't want to copy the image data, but just create a new QImage header for your data, try this:
Mat mat = Mat(...);

QImage qImage = QImage(
    (const uchar*)(mat.data),
    mat.cols,
    mat.rows,
    mat.step1(),
    QImage::Format_ARGB32); // if you have no alpha channel (CV_8UC3),
                            // you can use Format_RGB888

Also note, that OpenCV normally uses BGR channel order, you can use rgbSwapped() to solve this problem, but I don't know whether data gets copied with this function call.


text:
Q: Shell scripting:Extract data from table I need to extract the data under "Cell Name" Column knowing that there are different formats before and after the table that I want to extract data from.
%%/*4627363 MML Session=1497784916*/lst gtrx:;%%
RETCODE = 0  Execution succeeded.

List TRX
--------

 TRX ID  TRX Name           Cell Index        Cell Name  Frequency  Is Main
 0       Model-3900L-60            1        Model-3900L-6520        Yes
 1       Model-3900L-10            0           Model-3900L-1975     Yes
 2       GCAI6008_60081_I_H_DS-10  2       GCAI6008_60081_I_H_DS-1  Yes

4627363 MML Session=1497784916*/lst gtrx:;%%
    RETCODE = 0  Execution succeeded

A: sed -n '/Cell Name/,/MML/p' file | awk '{print $4}' | head -n -2 | tail -n +2

How it works:
sed -n '/Cell Name/,/MML/p': extract the table based on beginning and end.
awk '{print $4}': select the 4 column, that is "Cell Name".
head -n -2: strip the last 2 invalid end line.
tail -n +2: strip the first invalid beginning line.

A: awk '($1 ~ /^[0-9]+/ && ! /%%/){print $4}' file

A: You can set a flag to 1 when the line with "Cell Name" is found and to 0 when a blank line is found. When the flag is equal to 1, print the 4th field:
awk '!$0{c=0}c{print $4}/Cell Name/{c=1}' file

(note that !$0 returns 1 with an empty line but may also return 1 with for example a line that contains only 0 but it isn't the case with target lines of your file. You can change it to $0=="" that is more explicit if you want.)


text:
Q: Get MongoDB embedded collection docs Given this DB collection structure:
{
        "_id" : ObjectId("59ba5bf6fa12aa446c097793"),
        "tab" : "tab1",
        "tabfeeds" : [
                {
                        "url" : "//url1",
                        "limit" : 4,
                        "type" : "text"
                },
                {
                        "url" : "//url2",
                        "limit" : 8,
                        "type" : "normal"
                }
        ]
}
{
        "_id" : ObjectId("59ba73a6fa12aa446c097794"),
        "tab" : "tab2",
        "tabfeeds" : [
                {
                        "url" : "//url5",
                        "limit" : 4,
                        "type" : "normal"
                }
        ]
}

I can get all the "tabs" collection like this:
router.get('/tabs', function(req, res) {
    var db = req.db;
    var collection = db.get('tabs');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

And then:
$.getJSON( '/feeds/tabs', function( data ) {
    $.each(data, function(){
        tablistcontent += '' + this.tab + '	';
    });
});

But how can I list every element of tabfeeds for each tab?

A: So what you have to do is create a parameter in the anonymous function you're creating in your $.each call. That will be the index of the current item you're at in the array. Then you'll use that index to get the data corresponding to that index in the array called data.
Then you'll look into the object you're on and get the tabfeeds attribute, which will be an array. Then you loop through the tabfeeds array for every tab object and do whatever you want to do with that data.
// outside up here you'll have a variable to hold tab feed data
// i'll call it tabfeedData for example
var tabfeedData = '';

// loop through all the data
$.each(data, function(tab) {

    var tabfeeds = data[tab]["tabfeeds"]; // get array of tabfeeds from data variable

    tablistcontent += '' + this.tab + '	';

    // loop through tabfeeds and do whatever you need to (like construct a string with attributes from the tabfeed object)
    $.each(tabfeeds, function(tabfeed) {
        tabfeedData += "
";
    });

});


text:
Q: Blank/grey folium map when rendering in Jupyter Notebooks everyone. It's my first time here.
I'm trying to create a choropleth map that shows San Francisco's crime rate. I think that the code was just correct but for some reason, the map is not rendering. I can see the zoom buttons, the gauge, and the legend but not the map. I am only seeing a blank grey background. I had this problem with Jupyter Notebooks, Google Colab, and IBM Watson Studio.
Here's the screenshot of the rendered map and the code that I wrote. Behind the image, it tells me to make the notebook Trusted. But I think that the notebook is trusted because I created it (and Jupyter tells it). Some references said that it's because of the browser but the same thing happens in Chrome and Firefox. I tried creating a simple world map (using world_map = folium.map(); world_map) but it successfully rendered the world map.
I'm not sure what to do next. Any suggestions will be much appreciated. Thanks.
rendered map - grey screen
#create pandas dataframe
crime = pd.read_csv('https://cocl.us/sanfran_crime_dataset')
crime.rename({'PdDistrict':'Neighborhood'}, axis=1, inplace=True)
crime_neighborhood = crime['Neighborhood'].value_counts().to_frame()
crime_neighborhood.reset_index(level=0, inplace=True)
crime_neighborhood.rename({'Neighborhood':'Count', 'index':'Neighborhood'}, inplace=True, axis=1)

#import json
!wget --quiet https://cocl.us/sanfran_geojson/san-francisco.geojson -o san-francisco.geo.json
sanfran_json = r'https://cocl.us/sanfran_geojson/san-francisco.geojson'

#create San Francisco map
sanfran_map = fl.Map(location=[38, 122], zoom_start=12, tiles='Mapbox Bright')

#create Choropleth map
fl.Choropleth(
    geo_data=sanfran_json,
    data=crime_neighborhood,
    columns=['Neighborhood', 'Count'],
    key_on='feature.properties.DISTRICT',
    fill_color='YlOrRd',
    fill_opacity=0.7,
    line_opacity=0.2,
    legend_name='San Francisco Crime Rate').add_to(sanfran_map)

#show map
sanfran_map

A: Based from the forums I've read, the issue was because of the Mapbox Bright tile. I don't know the technical explanation but this tile seems to be no longer working in some cases. I'm glad that it's fixed now.

A: A possible solution could be the lack of internet connection to the map tile server.
I encountered a gray/blank map because jupyter was using an obsolete version of Chrome, which was blocked by the company internet security policy.  The notebook showed no error message, it's only when trying to access the tiles directly in another tab (after seeing some hints in Chrome's developer tools) that I was able to see the internet security policy message.
In my case, switching to a newer version of Chrome fixed the issue.


text:
Q: How to handle (on the server side) ampersand while inserting text into MySQL using PHP? When we insert a string with ampersand character into mysql, the string is inserted only till & character is encountered.
Example: when inserting "one & two"... only "one " is inserted.
Tried a few things like... htmlentities OR htmlspecialchars... nothing working for me.
Current PHP code:
$sms = htmlentities($_POST["sms"]);

$query = "INSERT INTO sms (detail,catID,deviceID) VALUES ('".$sms."',".$_POST["catID"].",'".$_POST["deviceID"]."')";

And as the app is live... I need to resolve it by editing the PHP files only, on the server. (I hope it can be done)

A: Here is a secure (against SQL injection) query:
$query = sprintf("INSERT INTO sms (detail,catID,deviceID) VALUES ('%s', '%s', '%s')",
                 mysql_real_escape_string($_POST['sms']),
                 mysql_real_escape_string($_POST['catID']),
                 mysql_real_escape_string($_POST['deviceID']));

I am escaping everything as a string, because I don't know your table schema.
However, if catID and deviceID are INTEGER types, then it should be:
$query = sprintf("INSERT INTO sms (detail,catID,deviceID) VALUES ('%s', %d, %d)",
                 mysql_real_escape_string($_POST['sms']),
                 ((int) $_POST['catID']),
                 ((int) $_POST['deviceID']));

A: htmlentities(); function is best used when displaying data from the database or a POST to protect the user and page form XSS
When inserting into the database sanitize to protect the database from abuse, using mysql_real_escape_string():
if(isset($_POST)){
    foreach($_POST as $key=>$value){
        if(get_magic_quotes_gpc()) {
            $value=stripslashes($value);
        }
        $_POST[$key]=mysql_real_escape_string($value);
    }
}

$query = "INSERT INTO sms (detail,catID,deviceID) VALUES ('".$sms."',".$_POST["catID"].",'".$_POST["deviceID"]."')";

A: Ok, well to complete the discussion, couldn't found a server side only solution... requires modification at both client & server side.
Here's how I needed to pass the upload text (as newStr):
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setHTTPMethod:@"POST"];

NSString *newStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                               NULL,
                                                                               (CFStringRef)uploadText.text,
                                                                               NULL,
                                                                               (CFStringRef)@"&",
                                                                               kCFStringEncodingUTF8 );

NSString *parameters = [[NSString alloc] initWithFormat:@"sms=%@&catID=%d&deviceID=%@",newStr,webCatID,[[UIDevice currentDevice] uniqueIdentifier]];

[newStr release];

And this modification on the server side:
    if ( get_magic_quotes_gpc() )
{
    $_POST['sms'] = stripslashes($_POST['sms'] );
}

$query = sprintf("INSERT INTO sms (detail,catID,deviceID) VALUES ('%s', '%d', '%s')",
                 mysql_real_escape_string($_POST['sms']),
                 ((int) $_POST['catID']),
                 mysql_real_escape_string($_POST['deviceID']));

Special thx to @PhpMyCoder & @Shef
& LOL on the urgency!


text:
Q: Find first number greater than x and return another value in that row I have created an investment spreadsheet. In one column I have the ending balance each year. In another column I have the years.
 A    B
2000 500K
2001 450K
2003 1.2M
2004 1.5M

How can I display the year I hit a certain arbitrary threshold (say $1M) in a single cell somewhere else on the sheet (say E32), without knowing how long it may take to reach the amount?

A: If we can make the assumption (as presented) that years are in column A and amounts are in column B, this array formula will work in any cell that's not in column A or B (such as E32).
=INDEX(A:A,MATCH(INDEX(B:B,MATCH(TRUE,B:B>=1000000,0)),B:B,0))

For array formulas, type it in and CSE - press Ctrl+Shft+Enter. This will display the formula with curly brackets around it.
On OSX, an array formula is input like this-

Select the range, press CONTROL+U and then press ⌘+RETURN.

source


text:
Q: Why can we chain flatMap to UserDefaults.standard.data In an article about UserDefaults in iOS development, I saw a code snippet where flatMap is chained to UserDefaults.standard.data like below:
self.isReadStatuses = UserDefaults.standard.data(forKey: "isReadStatuses")
      .flatMap { try? JSONDecoder().decode([URL: Bool].self, from: $0) } ?? [:]

Does anyone know Why can we use .flatMap here?

A: Because UserDefaults.standard.data(forKey:) returns Data? - an Optional<Data>, and Optional has a .flatMap method.
Specifically here, the flatMap closure gets a non-optional Data, and attempts to decode it returning another [URL:Bool]? (also, an optional because of try?).

A: I can guess why are you confused, although im not sure. I think you think that .map (and it's brothers, .flatMap and .compactMap) can only be used on Collections (e.g. an Array). That is completely wrong. .map (and the other 2) have a meaning of transformation, not iterating through an collection/array. So while they can be used on arrays, they have many more use-cases as well.
You can read more about differences between those 3 kinds of map here.
In the code you showed, the author of that blog post has used .flatMap with intention of transforming an Optional<Data> value (aka Data?) to [URL: Bool] which is the value he wants.
let udData = UserDefaults.standard.data(forKey: "isReadStatuses")

// Short way:
let isReadStatuses1 = udData.flatMap {
    try? JSONDecoder().decode([URL: Bool].self, from: $0)
} ?? [:]

// Long way:
let isReadStatuses2: [URL: Bool]
if let data = udData {
    isReadStatuses2 = (try? JSONDecoder().decode([URL: Bool].self, from: data)) ?? [:]
} else {
    isReadStatuses2 = [:]
}


text:
Q: How to run c++ in vscode I cannot for the life of me figure out how to run and debug a c++ file in vscode. There are always at least one or two things wrong.
I've already used the basic tutorials, but they don't seem to work for me.
Can someone explain it to me like I am 5 years old? Or point me in the direction of a place that will? I am totally burnt out and feel like a total dunce. I can't get a hello world program running and it is driving me crazy. Any help would be appreciated.

A: Is it on Windows or Linux ?
If on windows, first download and install the mingw setup. You can find it here :
https://sourceforge.net/projects/mingw/
After installation, add the location of th bin of g++ to PATH so that you can access it via the command line.
You can also add some extensions to your VS Code to make debugging C++ code easier, then in VS Code, open the terminal, and , while in the directory where you have your cpp file, simply do a g++ filename.cpp to compile, then run the executable, a.exe, unless otherwise specified in the previous command .
Hope this helps

A:

*Make sure that you have c++ compiler I prefer mingw.

*Open vscode and go to Extensions or by keyboard shortcut ctrl + shift + x.

*Search for .run and install

*Search for C/C++ and install.

*Go to settings ctrl + ,
By GUI

*In the search bar, search for code runner and Code-runner: Run In Terminal will be unticked by default. You tick it and close settings tab. Refer the pic for better understanding.

*Finally create a C++ file and save. Go to Terminal and select Run Build Task then click ctrl + alt + n to run the code. Again refer image for better understanding.

This should work, but if still didn't work let me know. Else refer any youtube video , you might have committed small mistake.
Let me know if this didn't work my dear 5 years old guy ;)


text:
Q: install jdk 6 or higher on a mac osx 10 If I run javac -version on my mac (osx 10.11.3), I get this output
javac 1.8.0_73

According to this android dev page, I need JDK 6 or higher. I downloaded jdk 7 and 8 from here and clicked on the dmg but I'm getting the same output javac 1.8.0_73 when running javac -version
Question: how can I install jdk 6 or higher on a mac?

A: Versions of the JDK have a naming convention of 1.x, 1.x.0_##, etc. The "x" is the product version number. This means that your return of "javac 1.8.0_73" means you already have JDK 8u73.


text:
Q: System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=2.1.3.0' I'm receiving the following warning on my ASP.NET Core 2.1 MVC project.

C:\Program
  Files\dotnet\sdk\2.2.102\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets(153,5):
  warning NETSDK1071: A PackageReference to 'Microsoft.AspNetCore.App'
  specified a Version of 2.1.7. Specifying the version of this package
  is not recommended. For more information, see
  https://aka.ms/sdkimplicitrefs

It appears to be referencing this line in my .csproj file:
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.7" />

If I remove the version from the PackageReference the warning goes away, but then I get this error when I try to start my project:

System.IO.FileLoadException: Could not load file or assembly
  'Microsoft.AspNetCore.Mvc.Core, Version=2.1.3.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60'. The located assembly's manifest
  definition does not match the assembly reference. (Exception from
  HRESULT: 0x80131040)
File name: 'Microsoft.AspNetCore.Mvc.Core, Version=2.1.3.0,
  Culture=neutral, PublicKeyToken=adb9793829ddae60'
at MyProject.Web.Startup.ConfigureServices(IServiceCollection
  services)
--- End of stack trace from previous location where exception was thrown ---
at
  Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection
  services)
at
  Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

I'm not sure where Microsoft.AspNetCore.Mvc.Core, Version=2.1.3.0 is even coming from. Anyone else run into the same problem?

A: I'm still not sure what caused the problem, but to fix it I went ahead and updated from ASP.NET Core 2.1 to 2.2 by following this article.
Here's the relevant part of my .csproj after the update:
<PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

<ItemGroup>
    <!-- Other Unrelated Packages Here -->

    <PackageReference Include="Microsoft.AspNetCore.App" />

    <!-- Other Unrelated  Packages Here -->
</ItemGroup>

Then, I updated all of my NuGet packages to the latest version.
I imagine there's a solution without having to upgrade versions of ASP.NET Core, but since I don't have any reason not to upgrade, this is what I did to fix it.

A: Add this
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.AspNetCore.Mvc.Core" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.1.7.0" newVersion="2.1.7.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>


text:
Q: How can I modify this algorithm which reorders a
*? Background:
I asked this question yesterday:
How to modify the orientation of a
 spanning multiple columns?
asking how to convert a list like this:
a  b  c

d  e  f

g  h  i

j  k  l

into a list like this:
a  e  i

b  f  j

c  g  k

d  h  l

and I got this awesome response by beeflavor: http://jsfiddle.net/H4FPw/12/
Problem:
Unfortunately I didn't specify that there could be any number of list items, so his response is hard-coded to 4 rows, and uses a tricky matrices algorithm (read: black magic) that I can't wrap my head around.
I'm poking and prodding at this, trying to add variability but unfortunately it's not coming together for me and today's the deadline for this stuff.
This is an updated example of the problem I'm having: http://jsfiddle.net/H4FPw/13/
Is there anyone out there with a better head for this stuff who can give me a steer in the right direction?

A: I know it's not as "elegant" as your accepted answer in that question, but the code I linked to in my answer yesterday does work perfectly for you:
http://jsfiddle.net/AcdcD/
If you don't need to handle resizing, it can be simplified slightly:
http://jsfiddle.net/AcdcD/1/
Maybe you can use this if you run out of time?

A: jQuery plugin .transpose()
Exactly what you want it to do. I needed the same thing so I've written a general jQuery plugin that transposes any floated or inline-blocked elements that seem to be in columns but their order goes in rows.
Check out my detailed blog post with an example for transposing US states, and then head over to GitHub where the plugin is maintained and you can get a minified version (915 bytes as of version 1.2) of it as well.
All you need to do is:
$("yourSelector").transpose();

In your case that would be
$("li").transpose();

The good thing is that plugin checks how many columns are there originally (before transposition) and transposes to the same amount of columns afterwards. It doesn't add any additional HTML elements into DOM (like floated column wrappers or similar) it just rearranges existing elements. This is very good when it comes to CSS settings of the page because it doesn't interfere with them in any way shape or form.
And it also distinguishes between different lists of elements (items that are contained within different containers) as if you'd have two UL elements that need transposition. You don't have to call .transpose() on each because plugin will do that for you. You'd still just use the same selector as previously written.

A: What about this code:
jsfiddle
// I add a number of new elements to the
, in this case, 'm', 'n', 'o' &'p'

var rowcount = 6; // I increase rowcount from 4 to 6 to accommodate the new elements
var colcount = 3;
var ichild=$('.directory-result-list-bottom').children();
var wf= "
";
var wb= "
"
var k="";
var u;
var v;
var carryover=0;

$('.directory-result-list-bottom').empty();

for(var i = 0; i<rowcount; i++){
    carryover=0;
    for(var j=0; j<colcount; j ++){
        k=k+wf+(ichild[(j*rowcount)+i].innerHTML)+wb;
    }
}
document.getElementById('place').innerHTML=k;

A: I believe empty LI's are needed to fill the empty space.
This should work:
for(var i = 0; i<rowcount; i++){
    for(var j=0; j<colcount; j ++){
        var n = (j*rowcount)+i;
        if (ichild[n])
            k=k+wf+(ichild[n].innerHTML)+wb;
        else
           k = k + wf + wb
    }
}

A: I think it's simpler to represent the items as a 1-D list (a,b,c...) and think about how to 1) get that from the original array and 2) transform it into the output array.
Step 1 is easy, because the 1-D list is the same order as the
 elements in the HTML source.
So, suppose we have n elements and we want to put them into R rows and C columns but filling columns first.  The element that goes in position (r,c) (0 based) is just element #R*c + r.  And, as stated before, the order in the source file is the row-first order, or (0,0), (0,1), (0,2), ...
If the # of elements doesn't fill the RxC grid exactly, then you have to add checks that the computed element number doesn't exceed n (easiest way is to pad the list with empty elements beforehand).
Depending on the design requirements, you can also adapt this to minimize the number of blank elements given a fixed number of rows or columns.


text:
Q: Twitter API 1.1 Hashtag Count I am having an issue figuring out how to return a total count for the number of times a hashtag was used on Twitter.  In the past I used the following code which did work but the "http://search.twitter.com/search.json" address has since been retired by Twitter.  The old code was:
<?php
   global $total, $hashtag;
   //$hashtag = '#supportvisitbogor2011';
   $hashtag = '#MyHashtag';
   $total = 0;
   function getTweets($hash_tag, $page) {
      global $total, $hashtag;
      $url = 'http://search.twitter.com/search.json?q='.urlencode($hash_tag).'&';
      $url .= 'page='.$page;
      $ch = curl_init($url);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
      $json = curl_exec ($ch);
      curl_close ($ch);
      //echo "<pre>";
      //$json_decode = json_decode($json);
      //print_r($json_decode->results);

      $json_decode = json_decode($json);
      $total += count($json_decode->results);
      if($json_decode->next_page){
         $temp = explode("&",$json_decode->next_page);
         $p = explode("=",$temp[0]);
         getTweets($hashtag,$p[1]);
      }
   }

   getTweets($hashtag,1);

   echo $total;
?>

I know that you know have to use a authorized twitter application and have access to be able to pull data.  I was able to set up the app and I can pull a list of data using the following code but I'm not sure how to use that data to come up with a total count.  Can someone help me to get a total by either changing the code I have or helping me with how I should go about it.  Here's the code I have that pulls the hashtag data:
<?php
session_start();
require_once("twitteroauth.php"); //Path to twitteroauth library

$hashtag = "MyHashtag";
$consumerkey = "MYINFOWOULDBEHERE";
$consumersecret = "MYINFOWOULDBEHERE";
$accesstoken = "MYINFOWOULDBEHERE";
$accesstokensecret = "MYINFOWOULDBEHERE";

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$hashtag);

echo json_encode($tweets);
?>

A: Here is one example for Twitter 1.1 API made from this. Keep this in mind:

Please note that Twitter's search service and, by extension, the
  Search API is not meant to be an exhaustive source of Tweets. Not all
  Tweets will be indexed or made available via the search interface.

https://dev.twitter.com/docs/api/1.1/get/search/tweets

*

*Download twitter-api-php and extract it to your folder at your server

*Create a Developer Account  and an Application

*Create a file twitter_search.php (in the same folder where you have twitter-api-php)

*Add your tokens and keys to twitter_search.php
twitter_search.php:
<?php
require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$hashtag = 'twitterapi';
$getfield = '?q=%23'.$hashtag.'&result_type=recent&include_entities=true&count=100';

// Perform the request
$twitter = new TwitterAPIExchange($settings);
$json_output = $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();

// Let's calculate how many results we got
$json = json_decode($json_output);
$n = count($json->statuses);
echo $n;
?>

Using the Twitter Search API
I posted originally this example in here.


text:
Q: Can I enable/disable mobile data from my iOS app? I want to make a today extension for iOS. In the storyboard I want a switch that turns on or off my mobile data on my iOS device. Does anyone know if that is possible?

A: No you cannot. However, you can use an alert view that  takes the user to the device settings:
UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)


text:
Q: ES6 lexical scoping issue The below example works fine and Lexical scoping is available in inner scope.
var fn =function(){

  this.no = 0;

  this.addNo = () => {

      setTimeout( ()=> {
        // ES6 lexical scope is available
        this.no =++this.no;
        console.log(this.no);
      }, 2000);

  }

}

var f1 = new fn();
f1.addNo();
f1.addNo();

Where as the below example does not work.
var fn =() =>{

  this.no = 0;

  this.addNo = () => {

      setTimeout( ()=> {
        // ES6 lexical scope is not available
        this.no =++this.no;
        console.log(this.no);
      }, 2000);

  }

}

var f1 = new fn();
f1.addNo();
f1.addNo();

Error
"TypeError: Cannot set property 'no' of undefined

A: es5 translate add function like this:
"use strict";

var fn = function fn() {
undefined.no = 0;

undefined.addNo = function () {

    setTimeout(function () {
        // ES6 lexical scope is not available
        undefined.no = ++undefined.no;
        console.log(undefined.no);
    }, 2000);
};

};
and es6 translate code like that so you can see the different.
var _this = this;

var fn = () => {
_this.no = 0;

_this.addNo = () => {

    setTimeout(() => {
        // ES6 lexical scope is not available
        _this.no = ++_this.no;
        console.log(_this.no);
    }, 2000);
};

};
because function with no default scope,then in es5 this is undefined.in es6 complier use this in function bind to the top scope.


text:
Q: How to pipe the result of 'date' command to 'mv' command I want to rename my file to the current timestamp.I know how to get the current timestamp("date +%s") but how can I pipe it to 'mv' command?

A: Use something like this (bash):
mv myfile myfile.$(date +%s)

Or alternatively:
mv myfile myfile.`date +%s`

if your shell doesn't do the $(command) thing.


text:
Q: Emberjs without ember data Im following this example Ember without Ember data
And tested to get my Teambox tasks, ( for make this work you need a teambox account and be logged in cause in this example I didnt add authenticacion);
http://jsbin.com/aZIXaYo/65/edit

If you are loggged in, the tasks appear correctly on the console.log
App.RedditLink = Ember.Object.extend({});

App.RedditLink.reopenClass({

  todooo: function(){
    $.ajax({
     url:"https://teambox.com/api/2/tasks",
     type: "GET",
     dataType: 'jsonp',
     success:function(json){
        var links = Em.A();
        json.forEach(function (child) {
    links.pushObject(App.RedditLink.create(child));
         //console.log(chilppld.name);
        });
        console.log(links);
        return links;
     },
     error:function(){
         alert("Error");
     }
    });
  }

});

This is what appears on the console
[Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, Class, _super: undefined, nextObject: function, firstObject: undefined, lastObject: undefined, contains: function…]

But on the template the data dont appears, check Jsbin

A: I don't get results from your url, but your todoo method doesn't return the array. Your current implementation is returning the array from ajax success callback. This is the updated version:
App.RedditLink.reopenClass({

  todooo: function() {
    var links = Em.A();

    $.ajax({
     url:"https://teambox.com/api/2/tasks",
     type: "GET",
     dataType: 'jsonp',
     success:function(json){
        json.forEach(function (child) {
          links.pushObject(App.RedditLink.create(child));
        });
     },
     error:function(){
         alert("Error");
     }
    });

    return links;
  }

});

I hope it helps


text:
Q: How to remove the undefined object from array using angular? let myArr=[{
    "name": "",
    "columns": [
      {

        "data": "test1",
        "type": "",

      },
      undefined,
      {
        "data": "test1",
        "type": "",
      }
    ],
    "info": "value",

  }]

Above array of object having undefined or null values, I have to remove the undefined values.

A: This can be done by combining Array.map(), Object.keys(), Array.reduce(), Array.isArray() and Array.filter() (the core piece) as shown in the runnable code below:

let myArr=[{
    "name": "",
    "columns": [
      {
        "data": "test1",
        "type": "",
      },
      undefined,
      {
        "data": "test1",
        "type": "",
      }
    ],
    "info": "value",
  }]

myArr = myArr.map(o => Object.keys(o).reduce((acc, key) => {
  let value = o[key];
  if (Array.isArray(value)) {
    value = value.filter(o2 => o2);
  }
  acc[key] = value;
  return acc;
}, {}));

console.log(myArr);

A: Try this
myArr[0].columns = myArr[0].columns.filter((data)=>data!==undefined);

This will filter out all the undefined values inside of columns


text:
Q: Что лучше. Фасад db (сырой, конструктор), модель или объект модели? Начинаю познавать фреймворк laravel и возникают вопросы.
Одни из них: Что лучше использовать при работе с бд? Фасад DB (сырой запрос или конструктор), модель или объект модели? Или их нужно как-то грамотно использовать все?
Это если что про MySQL, ну и к PostgreSQL тоже думаю относится.


text:
Q: A Mathematica program to output planar partitions I'd like to have a Mathematica program to output planar partitions for small values.  I seem to remember once writing such a program years ago using a program that appeared in an IEEE journal from the 1960's, but I can't locate the article and can't find the program.  Does anyone have any ideas?
By planar partition I mean exactly what is  given in the first answer to my question, namely:  "a two-dimensional array of integers that are non-increasing both from left to right and top to bottom
          and that add up to a given number n."

A: I believe this software suite is the answer to your prayers (and then some). (to give credit: Axel Riese's Omega package).

A: The unadorned term "planar partition" does not have an unambiguous meaning. One
possible meaning is described in an article in Mathworld entitled Plane partition:

"...a two-dimensional array of integers $n_{i,j}$ that are nonincreasing both from left to right and top to bottom

and that add up to a given number $n$."

The OP seeks

to output planar partitions for small values

If you could specify (1) what is the input, (2) what is a "planar partition,"
and (3) for small values of what parameter, then perhaps someone can help.


text:
Q: Chrome Android resizing some elements I am working on a web app and when I load it up in Chrome for android it shows some very weird text re scaling. Now when I load up the same page in for example DuckDuckGo privacy browser everything is normal. Why does this trigger and how can I prevent it?
images

A: To all that have the same issue, I found a way to fix it.
I still don't have a clue what caused it but it can be resolved by giving an element a max-width and max-height.
Something like this:
* {
    max-width: 999999px;
    max-height: 999999px;
}


text:
Q: Do I have to use Thread-safe Collections? Do I have to use concurrent types in MethodTwo.
if I don't, can my list (anotherList) is completely saved with true values?
public void MethodOne(List<int> idList)
{
    foreach (int id in IdList)
    {
         var Item = GetById(id);
         System.Threading.Tasks.Task.Run(() => MethodTwo(item.PropOne));
    }
}

public void MethodTwo(int prop)
{
    List<string> anotherList = new List<string>();
    anotherList.Add("AAA");

    if (prop>20)
        anotherList.Add("BBB");
    else
        anotherList.Add("CCC");

    //some other operations

    SaveList(anotherList);
}

There is a bug but I can not catch it. I am suspicious about this method. I tried load test on this method and I could not get any information.

A: No
Thread safety is a concern whenever multiple threads may write to the same data, or reading and writing, at the same time.
If your list is only accessed by a single thread it is perfectly safe to use a regular list.
This is often used when writing asynchronous code, a typical pattern might look something like:
int[] data = new int[]{1, 2, 3};
var result = await Task.Run(MyMethod);
// Use result
...

int[] MyMethod(int[] data ){
    // Do some processing
    return new int[]{4, 5, 6};
}

While the data-array is shared, it is perfectly safe as long as it is not modified.
If we change the example to do concurrent reading and writing we would be in trouble:
int[] data = new int[]{1, 2, 3};
var task = Task.Run(MyMethod);
data[0] = 42; // Writing shared data concurrently with reading. Unsafe!
var result = await task;
// Use result
...

int[] MyMethod(int[] data ){
    var d = data[0]; // Reading shared data concurrently with writing. Unsafe!
    // Do some processing
    return new int[]{d, 5, 6};
}

Since we now have both reading and writing that may be done at the same time, the code is unsafe. This could be fixed by a lock, but it is typically a better idea to try to avoid shared mutable state as much as possible in the first place.