text:
Q: How to create a custom grid filter I have added a custom grid column using the field URL in a custom database:
$this->addColumn('url', array(
    'header'   => Mage::helper('companymodule')->__('Has Website'),
    'align'    => 'left',
    'index'    => 'url',
    'renderer' => new Company_Module_Block_Adminhtml_Module_Grid_Renderer_HasUrl(),
    'type'      => 'options',
    'options'   => Mage::getSingleton('companymodule/hasurl')->getOptionArray(),
));

And created this custom rendered:
class Company_Module_Block_Adminhtml_Module_Grid_Renderer_HasUrl extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        $value = trim((string)$row->getData($this->getColumn()->getIndex()));
        if (empty($value)) {
            return 'No';
        } else {
            return 'Yes';
        }
    }
}

As well as a custom model for the filter dropdwon:
class Company_Module_Model_Hasurl extends Varien_Object
{
    static public function getOptionArray()
    {
        return array(
            'Yes'   => Mage::helper('companymodule')->__('Yes'),
            'No'    => Mage::helper('companymodule')->__('No')
        );
    }
}

This works fine unless you try to filter. I think it's trying to match the value 'Yes' to the value of $row->getData($this->getColumn()->getIndex()) (the URL field in the database table.) But instead of matching the URL field value itself, I am basically trying to filter by ((bool)empty($url)) so that the user can filter by whether or not this database entry has a URL or not.
How can I create custom logic for a filter like this?

A: try adding a custom filter callback: Here we add new Role Name column to admin user grid.
in your grid:
$this->addColumn('role_name', array(
    'header' => Mage::helper('adminhtml')->__('Role Name'),
    'index' => 'role_name',
    'type' => 'options',
    'options' => $this->getRoleName(),
    //'filter' => false,
    'renderer' =>  'Company_Module_Block_Adminhtml_Permissions_User_Grid_Renderer_Role',
    'filter_condition_callback' => array($this, '_roleFilter'),
));

and add a 2 method like this:
protected function _roleFilter($collection, $column) {
    $filterroleid = $column->getFilter()->getValue();
    if (!$value = $column->getFilter()->getValue()) {
        return $this;
    }
    $this->getCollection()->addFieldToFilter('parent_id', array('eq' => $filterroleid));
    return ;
}

Add This method for Role Filter with drop-down
public function getRoleName() {
    $rolename = array();
    $roles = Mage::getModel('admin/roles')->getCollection();
    foreach ($roles as $role):
        $rolename[$role->getId()] = $role->getRoleName();
    endforeach;
    return $rolename;
}

A: try adding a custom filter callback:
in your grid:
$this->addColumn('url', array(
    'header'   => Mage::helper('companymodule')->__('Has Website'),
    'align'    => 'left',
    'index'    => 'url',
    'renderer' => new Company_Module_Block_Adminhtml_Module_Grid_Renderer_HasUrl(),
    'type'      => 'options',
    'options'   => Mage::getSingleton('companymodule/hasurl')->getOptionArray(),
    'filter_condition_callback' => array($this, '_filterHasUrlConditionCallback')
));

and add a method like this:
protected function _filterHasUrlConditionCallback($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return $this;
    }
    if (empty($value)) {
        $this->getCollection()->getSelect()->where(
             "main_table.url IS NULL");
    }
    else {
        $this->getCollection()->getSelect()->where(
             "main_table.url IS NOT NULL");
    }

    return $this;
}

note it's not tested; you may have to check for empty rather than null on the database; also make sure you have the correct table alias (if URL is not on the main_table).


text:
Q: CONCAT multiple fields which may have NULLS, set the delimiter once: SQL Server 2008 R2 I would like to concatenate many columns in SQL Server 2008 R2, and have them delimited by a TAB. So far, I have only been able to come up with a primitive solution:
select
   isnull(col1,'')
   + CHAR(9)
   + isnull(col2,'')
   + CHAR(9)
   + isnull(col3,'')
   + CHAR(9)
   + isnull(col4,'')
   + CHAR(9)
   + isnull(col5,'')
from TBL_A

For the sake of brevity, I only included 5 columns, however I need to concatenate about 20 columns.

Since any of the columns could be NULL, I need to wrap each columns in the isnull statement. I also need to add the char(9) after every column. CONCAT_WS would take care of both of these issues very simply however this is only available in SQL Server 2017.
Does anyone have a more eloquent way of doing this?

A: I feel like a STUFF() in combination with FOR XML PATH() and an UNPIVOT should get this done for you. I don't think there's a way around the multiple null checks.
Here is a working fiddle of how you might accomplish this.
-- schema
create table t1 (
    id int
    ,col1 char(1)
    ,col2 char(1)
    ,col3 char(1)
);

create table t2
(
    id int,
    colVal char(1)
);

-- some sample data
insert into t1
select 1, 'a', 'b', 'c'
union all
select 2, 'd', 'e', 'f';

insert into t2
select
    id
    ,colVal
from t1
unpivot
(
    colVal
    for cols in (col1, col2, col3)
) u
order by
    id;

-- the actual query
select
    id
    ,stuff((
        select
            '-'
            + isnull(colVal,'')
        from
            t2 as innerTable
        where
            innerTable.id = outerTable.id
        for xml path (''))
    ,1 , 1, '')
from
    t2 as outerTable
group by
    id;

drop table t1;
drop table t2;

The process here is as follows:

*

*"Verticalize" the data using UNPIVOT and the row identifier to allow us to aggregate it back into row groups later on.

*Use a correlated subquery to query against the vertical data per group.

*Using FOR XML PATH('') to combine the record values into a delimited string and STUFF to chop off the leading separator.

Note that I've used dashes in my example to make it clearer how the separators are coming into play. I also made the presumption that your records have some form of unique identifier (id int in the example).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Child object binding is null I have this Person entity and it has a child field which is the Parent Person and join to itself via parent_id.  When I tried to hit Update, why is the person.getParentPerson() is always null?
@javax.persistence.Table(name = "person")
@Entity
public class Person implements Serializable {

    // Fields
    @Column(name = "id", nullable = false, insertable = true, updatable = true, length = 20, precision = 0, unique =
        true)
    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private ParentPerson parentPerson;

    @Column(name = "name", nullable = true, insertable = true, updatable = true, length = 10)
    private String name;

    //some other fields, setters and getters
    ....
}

@Controller
@RequestMapping("/person")
public class PersonController {

    @RequestMapping("/add.htm")
    private ModelAndView personEdit() {
        Person person = new Person();
        Person parentPerson = new ParentPerson();
        if (checkIsParent()) {
           parentPerson.setId(-1);
        }
        person.setParentPerson(parentPerson);
        mav.addObject("person", person)
        return mav;
    }

    @RequestMapping("/update.htm")
    @ModelAttribute("person") @Valid Person person
    private ModelAndView personUpdate() {
        //person.getParentPerson() is null
    }
}

HTML snippet:
   <form id="uForm" action="update.htm" method="post" accept-charset="UTF-8" autocomplete="off">
       <@global.spring.formInput path="person.id" attributes='size="40"'/>
       <@global.spring.formInput path="person.name" attributes='size="40"'/>
   </form>


text:
Q: How to set up a React development environment to work on Draftail extension? I would like to set up a React development environment so I can test making extensions to editor provided by https://www.draftail.org/.  It's primarily to work on this project.  https://github.com/getuptree/wagtailcolourpicker.  I plan to do this development on a Laptop running a Ubuntu variant.
If I am allowed to ask this here (does not fit strictly into a Q&A format) is for any good online tutorials to get me started on what I might need to know to undertake this.  I know Javascript fairly well but not really Reactjs although I have watched some video tutorials on it.  I won't say too much about that in case the moderators delete this paragraph.
I am afraid I can't really tell you what I've tried to far as my problem is not knowing how to get started.
Thanks for your consideration.


text:
Q: ECG QRS detection using python Problem:
ECG QRS detection using python
Code:
self.signal_frequency = 250  # Set ECG device frequency in samples per second here.
self.filter_lowcut = 0.0
self.filter_highcut = 15.0
self.filter_order = 1

def bandpass_filter(self, data, lowcut, highcut, signal_freq, filter_order=5):
    """
    Method responsible for creating and applying Butterworth filter.
    :param deque data: raw data
    :param float lowcut: filter lowcut frequency value
    :param float highcut: filter highcut frequency value
    :param int signal_freq: signal frequency in samples per second (Hz)
    :param int filter_order: filter order
    :return array: filtered data
    """
    nyquist_freq = 0.5 * signal_freq
    low = lowcut / nyquist_freq
    high = highcut / nyquist_freq
    #N, Wn = signal.buttord([20, 50], [14, 60], 3, 40, True)
    #b, a = signal.butter(N, Wn, 'band', True)
    b, a = signal.butter(filter_order, [low, high], btype="band",analog=False)
    y = lfilter(b, a, data)
    return y

I receive the following error:
ValueError: Digital filter critical frequencies must be 0 < Wn < 1


text:
Q: Function App outbound public IPs altough VNet injection enabled I've configured VNet injection for my Function App and have set the Route All optio to Enabled. However, what I don't understand why there's a bunch of public IP addresses displayed in Outbound addresses. Looking at MS documentation, enabling VNet injection brings the service inside the VNet forcing all traffic to the VNet. What am I missing ?
Func App VNet integration
Route all enabled


text:
Q: RxJS - Same without Subscription / BehaviorSubject? I am looking for an alternate way to do :
import { interval, BehaviorSubject } from 'rxjs';

const source$ = interval(1000);
const store$ = new BehaviorSubject<number[]>([]);
source$.subscribe((point) => store$.next([...store$.value].concat(point)));

// result
store$.subscribe(console.log);

I indeed would like not to use subscription at all, and so I guess no BehaviorSubject.
Thanks for any hint.

A: You can use a scan operator.
const source$ = interval(1000);
const store$ = source$.pipe( // or simply interval(1000).pipe(
    scan((result, value) => [...result, value], []),
);

// result
store$.subscribe(console.log); // [0], [0, 1], ...


text:
Q: Base change of trace for Gorenstein or Cohen-Macaulay morphisms  This is basically a question of functoriality for base change of CM morphisms.
EDIT: $\text{ }$ Brian Conrad sent me an email explaining the that this is indeed true, and follows from his book.  I'll explain this in my case a little later.  First I will state the question.
Suppose that $f : X \to V$ is an equidimensional (dimension $d$) finite type  (reduced, if it helps) Cohen-Macaulay morphism (flat with Cohen-Macaulay fibers).  I'm also happy to assume that $V$ is integral, excellent and has a dualizing complex.  Additionally suppose that we have $f' : X' \to V$ another equidimensional (dimension $d$) finite-type (reduced)  Cohen-Macaulay morphism that factors through $f$ as below.
$$f' : X' \xrightarrow{\phi} X \to V.$$
Further suppose that $\phi$ is finite (although the question could be asked more generally for proper $\phi$, I'll phrase it for finite $\phi$).  If it helps at any point, please feel free to assume that $f$ and $f'$ are Gorenstein morphisms.
Recall that $\omega_{f}[d] = f^! \mathcal{O}_V$ and that by Brian Conrad's book [LINK: Google books][1] we know that both $\omega_f$ and $\omega_{f'}$ are compatible with base change.
I'd like to conclude that the following natural map is also compatible with base change:
$$\phi_* \omega_{f'} \cong R \mathcal{H}om_{O_X}(\phi_* O_{X'}, \omega_f ) \cong \mathcal{H}om_{O_X}(\phi_* O_{X'}, \omega_f ) \to \omega_f$$.
The map can be interpreted as evaluation at 1.
In other words, I'd like to know that the trace map of $\phi$ is compatible with base change.  Furthermore, it would be even good enough to prove this in the $f, f'$ Gorenstein morphisms case.
One way to do this would be as follows.  If $g : T \to V$ is any other morphism and $f_T : X_T \to T$ and $f_T': X_T' \to T$ are the base changes and $g_X : X_T \to X$ is the projection, is it true that the natural map (denoted [*] below)
$$g_X^* \phi_* \omega_{f'} \cong g_X^* \mathcal{H}om_{O_X}(\phi_* O_{X'}, \omega_f ) \to \mathcal{H}om_{O_{X_T}}(\phi_* O_{X_T'}, \omega_{f_T} ) \cong (\phi_T)_* \omega_{f_T'}$$
between abstractly isomorphic sheaves is an isomorphism?

Edit: Brian Conrad pointed out to me that this is already a special case of what is in his Theorem 3.6.1 (assuming I understand everything right).  Essentially the point is that in my case everything is finite type, which makes it all much easier.

A: A short answer, if you are willing to upgrade your discussion to a derived category situation. The natural base-change isomorphism of duality
$$
{g'}^* f^! \cong {f'}^! g^*
$$
holds under the hypothesis of a "Tor-independent" square. In other words, you may not have $g$ flat, but if $f$ is, it holds. This is the case always if you work with varieties over a field  and the map $f$ is the structural morphism. All this is explained in Lipman's Notes on derived functors and Grothendieck duality in SLN 1960. See Theorem 4.4.1 and its corollaries.
Of course, the problem of unravelling the isomorphism and making it explicit in terms of differentials, say, might not be completely trivial.


text:
Q: ETCS set theory: Are empty sets isomorphic? Just a quick question about ETCS: Are any two empty sets isomorphic? Here, a set $X$ is empty if there exists no $x \in X$, i.e. no functions $x: 1 \to X$.
The reason I'm asking is that I need this to show that empty sets are initial sets.
Thank you!

A: In the case of the theory of sets as a well-pointed topos, if an object is empty it will be initial. Take $i:0\to A$ and $id_A:A\to A$. Assuming $A$ non-initial, $0$ will not be isomorphic with $A$, so $\chi_i:A\to\Omega\neq\chi_{id_A}:A\to\Omega$. By well-pointedness, there must be a point $x:1\to A$ that distingushes them. Hence from $\neg(A\cong 0)$ we have derived that $A$ must have a point.
EDIT:
Forgot an important extra piece of information: Initial objects must be empty in a Cartesian closed category, on pain of triviality. So all non-initial objects are non-empty, and all initial objects (by assumption in most topoi) are empty.

A: Let $\mathcal{S}$ be an externally two-valued elementary topos with the axiom of finite choice, i.e. there are only two subobjects of $1$ in $\mathcal{S}$ (up to isomorphism) and any epimorphism with codomain $1$ is a split epimorphism. If $X$ is an object in $\mathcal{S}$ such that there do not exist any morphism $1 \to X$, then $X$ is an initial object in $\mathcal{S}$. Indeed, let $U \rightarrowtail 1$ be the image of the unique morphism $X \to 1$. If $U$ is a terminal object then the unique morphism $X \to 1$ is an epimorphism, in which case the axiom of finite choice implies it has a section, i.e. there exists a morphism $1 \to X$. Thus $U$ is not a terminal object – so it must be an initial object, by two-valuedness. But initial objects in cartesian closed categories are strict, so $X \to U$ must be an isomorphism, and so $X$ must itself be an initial object.
Note that $\mathcal{S}$ need not be well-pointed for the above proof to work: for example, $\mathcal{S}$ could be the topos of simplicial sets. Conversely, any non-degenerate elementary topos with the property that "empty objects are initial" must be externally two-valued and have the axiom of finite choice.


text:
Q: Moment is showing wrong date in React Native I'm using moment to convert my JSON date into normal date format but I got 13 days previous date from correct date.
var dt = Moment.utc('2020-01-15T00:00:00').format('d MMM YYYY');
console.log(dt); // console value: 3 Jan 2020

A: d is the format for day of week (0-6). You want D or DD for day of month.
Moment docs for format options

A: Acc to https://momentjs.com/docs/#/displaying/format/  d while formatting in moment is for day of the week that is (0-6)
so in your case it is showing as 3rd day of the week


text:
Q: Data structure keeping the order of ManyToMany items For example,
There are two lines and a few stations.
Line X
Station A - Station B - Station C - Station D

Line Y
Station E - Station F - Station B - Station G

Line X and Y are crossing at Station B
So my tables are like this below
Line Table
1 X  "LineX"
2 Y  "LineY"

Station Table
1 A X
2 B X,Y
3 C X
4 D X
5 E Y
6 F Y
7 G Y

Models are like this (This is django but using doctrine are almost same.)
class Line(models.Model):
    name = models.CharField(unique=True,max_length=255)
    def __str__(self):
        return self.name

class Station(models.Model):
    name = models.CharField(unique=True,max_length=255)
    lines = models.ManyToManyField(Line)
    def __str__(self):
        return self.name

In this case, you can get the stations of LineX easily.
SELECT from station table where line (which include) Y
return A,B,C,D
However for LineY
it returns B,E,F,G
but B is not the top.
It's third station.
I think I should add some column to maintain the order of each lines.
What is the best practice for structure keeping the order of manytomany items?
I am familliar with Doctorine2 and django models.
I would appreciate any help of you.

A: Warning: this answer considers the data structure in the DB only, and does not address django.
Perhaps you could implement a Line_Order table with foreign keys to the line, and the stations. I'd also have a direction tag (as I assume your lines are bi-directional and not circular)
E.g.
    Line_id    Station_id    Direction
1   1          1             Line X Eastbound
2   1          2             Line X Eastbound
...
5   1          4             Line X Westbound
...
10  2          5             Line Y Northbound
11  2          6             Line Y Northbound
12  2          2             Line Y Northbound
13  2          7             Line Y Northbound
...

And then to be honest, I'd drop the Line column entirely from the stations table.
The above structure is brittle to changes. If your train lines are likely to be modified, then you may alternatively wish to consider a "Next station" table analogous to a linked list. Your table could list the line_id, the station_id, the next station_id and the previous station_id. The direction of travel may or may not be required depending on your implementation.


text:
Q: Using Imagemagick to convert PDFs having rasters in them results in white backgrounds behind the sections covered by the rasters I tried to use ImageMagick (v6.8.9-9 Q16) to convert a PDF containing a PNG file embedded in it to a PNG file.
The original PNG file had a transparent background. In the PDF too it appears fine. But in the PNG obtained after conversion, the area originally occupied by the PNG in the PDF has a white background. Please see the links for more clarity.
The command I ran is as follows:
convert -colorspace sRGB dice.pdf converted_dice.png
I also tried setting the -transparent white switch but it ends up taking out whites that were actually required in the final image.
Are there any extra switches or parameters to pass to convert in order to get rid of just this white background?

A: Kurt already explains the whole thing in great detail. So here is just how to assemble an image with ImageMagick after running it through pdfimages -png
pdfimages -png my.pdf my

This resluts in two files
identify my-0*png
  my-000.png PNG 360x310 360x310+0+0 8-bit sRGB 256c 3.3KB 0.000u 0:00.000
  my-001.png PNG 360x310 360x310+0+0 8-bit sRGB 256c 9.44KB 0.000u 0:00.000

my-001.png is the image labeled smask in pdfimages -list. To reassemble the image back to it's original form use -compose CopyOpacity with the ImageMagick command composite
composite -compose CopyOpacity my-001.png my-000.png my-reassembled.png

See also http://www.imagemagick.org/Usage/masking/#masks for more information.

A: Your approach to this task cannot work.
The command you used will convert the complete letter-sized PDF page (612 x 792 pt) into a PNG image.
However, the original size of the image embedded in the PDF page (612 x 792 pt) is 800 x 600 pixels. This can be seen by running pdfimages -list:
pdfimages -list dice.pdf
 page num  type width height color comp bpc  enc interp object ID x-ppi y-ppi  size ratio
 ----------------------------------------------------------------------------------------
    1   0 image   800   600   rgb     3   8  image   no     12  0    72    72  277K   20%
    1   1 smask   800   600  gray     1   8  image   no     12  0    72    72 50.1K   11%

So this is the first problem when converting the PDF page: it does not give your the correct size of the contained images.
The second, more fundamental problem however is: any image you get from converting a PDF page is the combination of all PDF objects overlayed on each other as they are from the page area. (Of course you could crop only part of the page -- but this gives you likewise the combination of all PDF objects from the cropped area...). The results of this you've encountered when you tried to convert all white pixels into transparent ones: since the originally different objects are merged into one representation of pixels, you can no longer discriminate between them as required.
You should take a different approach and use a different tool to extract the image: use pdfimages (the tool used above with the -list parameter to display image properties from the PDF's pages). As you can see, there are two images list: one is an RGB raster image, the other is a grayscale raster image, dubbed as type smask (softmask).
Here is a command to extract both images as PNG:
 pdfimages -png dice.pdf dice-images

This will extract the two:

*

*dice-images-0000.png (a color image)

*dice-images-0001.png (a grayscale image)

(Note: Only very recent versions of pdfimages, the Poppler version, will let your extract the images as PNG. Within the PDF there is no such thing as PNG. There are only raster data, compressed with different methods. Older versions will only be able to extract images as PPM or PNM. This does not have any influence on what I describe below. Even if you extract PPM/PNM images, these two files can still be processed as described below...)
Below is a side-by-side, scaled-down montage of the two:

As you can see, the image itself does not have a transparent background, but a white one. (It does not have an Alpha channel.) Within the PDF format, these two images are used in combination to create transparent areas:

*

*what appears completely black in the softmask (right) means: this pixel of the real image (left) is meant to be fully transparent.

*what appears completely white in the softmask (right) means: this pixel of the real image (left) is meant to be fully opaque.

*what appears in a shade of gray in the softmask (right) means: this pixel of the real image (left) is meant to be partially transparent (in line with its level of gray/black).

To combine these two files (color image and grayscale softmask) back into one PNG with transparency, you can employ ImageMagick now...


text:
Q: How to correctly instantiate a PixelBuffer for VLCJ mediaPlayer I am currently having issues getting VLCJ 4 to spin up a video. I can get the application to run, but seem to running into an issue with the videoPixelBuffer not being instantiated. The below code is from the pixelbuffer tutorial on the main page. I have been trying to understand how it is function but cannot see how the function that instantiates the videoPixelBuffer is ever called. I have tried to manually call it up that has not work either. I believe the issue is with videoPixelBuffer, but cannot see a way to fix this.
Any ideas?
Below you will see the code I am using and the error messages I have gotten.
Here is the link to the Github repo for the demo as well. (https://github.com/caprica/vlcj-javafx/blob/pixelbuffer-test/src/test/java/uk/co/caprica/vlcj/javafx/test/WritableImageDemo.java)
Versions:

*

*VLCJ 4.1.0

*VLC 3.0.8

*Openjdk 13

*Openjfx 13

Code:
package player;

import java.nio.ByteBuffer;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelBuffer;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.player.embedded.videosurface.CallbackVideoSurface;
import uk.co.caprica.vlcj.player.embedded.videosurface.VideoSurfaceAdapters;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.BufferFormat;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.BufferFormatCallback;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.RenderCallback;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.format.RV32BufferFormat;

public class Test extends Application {

    private MediaPlayerFactory mediaPlayerFactory;

    private EmbeddedMediaPlayer embeddedMediaPlayer;

    private WritableImage videoImage;

    private PixelBuffer<ByteBuffer> videoPixelBuffer;

    private ImageView videoImageView;

    @Override
    public void init() {
        mediaPlayerFactory = new MediaPlayerFactory();
        embeddedMediaPlayer = mediaPlayerFactory.mediaPlayers().newEmbeddedMediaPlayer();
        embeddedMediaPlayer.videoSurface().set(new FXCallbackVideoSurface());
    }

    @Override
    public final void start(Stage primaryStage) throws Exception {
        StackPane root = new StackPane();
        root.setStyle("-fx-background-color: black;");
        videoImageView = new ImageView();
        videoImageView.setPreserveRatio(true);
        videoImageView.fitWidthProperty().bind(root.widthProperty());
        videoImageView.fitHeightProperty().bind(root.heightProperty());
        root.getChildren().add(videoImageView);

        Scene scene = new Scene(root, 1200, 675);
        primaryStage.setScene(scene);
        primaryStage.show();

        String mrl = getParameters().getRaw().get(0);

        embeddedMediaPlayer.media().play(mrl);
    }

    @Override
    public final void stop() throws Exception {
        embeddedMediaPlayer.controls().stop();
        embeddedMediaPlayer.release();
        mediaPlayerFactory.release();
    }

    private class FXCallbackVideoSurface extends CallbackVideoSurface {
        FXCallbackVideoSurface() {
            super(new FXBufferFormatCallback(), new FXRenderCallback(), true, VideoSurfaceAdapters.getVideoSurfaceAdapter());
        }
    }

    private class FXBufferFormatCallback implements BufferFormatCallback {
        private int sourceWidth;
        private int sourceHeight;

        @Override
        public BufferFormat getBufferFormat(int sourceWidth, int sourceHeight) {
            this.sourceWidth = sourceWidth;
            this.sourceHeight = sourceHeight;
            return new RV32BufferFormat(sourceWidth, sourceHeight);
        }

        public void allocatedBuffers(ByteBuffer[] buffers) {
            assert buffers[0].capacity() == sourceWidth * sourceHeight * 4;
            PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteBgraPreInstance();
            videoPixelBuffer = new PixelBuffer<>(sourceWidth, sourceHeight, buffers[0], pixelFormat);
            videoImage = new WritableImage(videoPixelBuffer);
            videoImageView.setImage(videoImage);
        }
    }

    private class FXRenderCallback implements RenderCallback {
        @Override
        public void display(MediaPlayer mediaPlayer, ByteBuffer[] nativeBuffers, BufferFormat bufferFormat) {
            Platform.runLater(() -> {
                videoPixelBuffer.updateBuffer(pb -> null);
            });
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class WritableImageDemoLauncher {public static void main(String[] args) {Test.main(args);}}

Error Messages:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at player.Test$FXRenderCallback.lambda$0(Test.java:110)
at javafx.graphix/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AcessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:92)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:830)

Test.java:110 is the following line:
videoPixelBuffer.updateBuffer(pb -> null);


text:
Q: renaming array group name I want to change numbers in arrays [0], [1] etc
I don't know their names aswell to be honest but I have made arrows after them
Array
(
    [user_id] => 1
    [0] => Array  # <----- this [0]
        (
            [prod] =>
        )

    [1] => Array # <----- this [1]
        (
            [item] => 1
            [place] => 2
            [holder] => 2
            [type] => 1
            [amount] => 1
            [sellprice] => 13000.00
            [buyprice] => 12000.00
            [notification] => 16
        )
)

wanted result :
Array
(
    [user_id] => 1
    ['Some Title'] => Array  # <----- this [0]
        (
            [prod] =>
        )

    ['Title'] => Array # <----- this [1]
        (
            [item] => 1
            [place] => 2
            [holder] => 2
            [type] => 1
            [amount] => 1
            [sellprice] => 13000.00
            [buyprice] => 12000.00
            [notification] => 16
        )
)

I want to replace those [0] and [1] with some titles
this code is being generated with array_push

A: $arr = array(); // your array
// your array push code goes here
    $arr['Title'] = $arr[0];
    $arr['Title 2'] = $arr[1];
    unset($arr[0]);
    unset($arr[1]);


text:
Q: How to create histogram with "zoom-in" feature I was impressed by the Reputation histogram on the SE sites allowing one to zoom in to any time interval.  How was it created?

A: This is a barplot rather than histogram... Anyway, judging from the page source, it is made with Highcharts JS.


text:
Q: Rails nested resources and routing - how to break up controllers? I have the following models:

*

*Post

*Tag

*TaggedPost (from which Post and Tag derive their associations by has_many :through)

And I have the following routes.rb file:
resources :tags

resources :posts do
  resources :tags
end

So when I navigate to, say, /posts/4/tags, that will shoot me into the index action for the Tag controller with the post_id value set in the parameters array.  Cool.
My question is though, now that I'm accessing the nested tags resource under posts, should I be hitting the Tags controller still?  Or should I setup some other controller to handle the nested nature of tags at this point?  Otherwise I have to build additional logic into the Tags controller.  This can be done of course, but is this the common way of handling nested routes and resources?  The code I have in the index action for the Tags controller is as follows:
TagsController.rb
def index
  if params[:post_id] && @post = Post.find_by_id(params[:post_id])
    @tags = Post.find_by_id(params[:post_id]).tags
  else
    @tags = Tag.order(:name)
  end
  respond_to do |format|
    format.html
    format.json {render json: @tags.tokens(params[:q]) }
  end
end

I can see the code in this controller growing increasingly large, as I plan for many additional resources to be associated with tag resources.  Thoughts on how to break this out?
Summary of questions:

*

*If a resource is nested, should the nested resource be going through a different controller representing the nested nature of the resource?  This is opposed to going through the normal controller as I am in the code example that I provided.

*If so, how should these controllers be named and setup?

Let me know if you need more information.

A: All you are doing with nested resources is changing the routing URL. Only thing you would have to do is make sure you are passing the proper id (in your case post)to the tag controller. Most common error is the Can't Find *** ID.
If you don't nest a profile route into a user route it would look like this

domain.com/user/1
domain.com/profile/2

When you nest the routes it would be

domain.com/user/1/profile/2

That is all that it is doing and nothing else. You don't need additional controllers. Doing nested routing is just for looks. allowing your user to follow the association. The most important thing about nesting routes is that you make sure you make the link_to's to the right path.
When not nested: it would be
 user_path

and
 profile_path

when it is nested you would need to use
user_profile_path

rake routes is your friend to find out how the routes have changed.
Hope it helps.

A: I think the best solution is to split up controllers:
    resources :tags

    resources :posts do
      resources :tags, controller: 'post_tags'
    end

And then you have 3 controllers. Optionally, you can inherit
PostTagsController from TagsController to do something like:
    class PostTagsController < TagsController
        def index
            @tags = Post.find(params[:post_id]).tags
            super
        end
    end

If the difference is only the retrieval of tags, you can:
    class TagsController < ApplicationController
        def tags
            Tag.all
        end

        def tag
            tags.find params[:id]
        end

        def index
            @tags = tags
            # ...
        end
        # ...
    end

    class PostTagsController < TagsController
        def tags
            Product.find(params[:product_id]).tags
        end
    end

Use that methods and simply override tags in the inheriting controllers ;)


text:
Q: iOS new image type HEIC can't be used, must get JPEG I am using
navigator.camera.getPicture

to get the picture from the camera roll on iOS.
If I add the option:
navigator.camera.DestinationType.FILE_URI

it gives me a JPG which is great, but I can't get the geolocation EXIF information from it. To get the location I need to use:
navigator.camera.DestinationType.NATIVE_URI

However that gives me a HEIC file. That cannot be used in an img tag or in any real way.
The end goal is to get the EXIF location information from the image as well as a usable JPG.


text:
Q: Python: stopping gravity I have tried to create realistic gravity using tkinter in python. The gravity works, but the ball I am animating does not stop. Here is my code:
import tkinter as tk
import time

xv=0
yv=0
x=0
y=0
def move(event=None):
    global xv,yv, direction

    if event.char == 'w':
        yv-=15
    elif event.char == 'a':
        xv-=1
    elif event.char == 'd':
        xv+=1
    elif event.char == 's':
        yv+=1

m = tk.Tk()

canvas = tk.Canvas(m)
canvas.pack(expand=2, fill='both')
oval_id = canvas.create_oval(0,0,10,10,fill='red')

canvas.bind_all('<w>', move)
canvas.bind_all('<a>', move)
canvas.bind_all('<d>', move)
canvas.bind_all('<s>', move)

while 0==0:
    yv*=0.9
    xv*=0.9
    x+=xv
    y+=yv
    yv+=1
    if y > 170:
        yv=0
    time.sleep(0.05)
    canvas.move(oval_id,xv,yv)
    canvas.update()

The ball does stop, but when you press w to jump, it sinks down and is lower on the screen. can I get it to go back up to 170px without using too much code?

A: Use absolute coordinates and constant downward acceleration:
yv = 0
xv = 1
while True:
    yv += .5 # .5 is the acceleration
    x+=xv
    y+=yv
    if y > 170: # check that didn't move past the floor
        y=170        # reset to the floor
        yv = -yv*.9  # reverse velocity and lose some energy from the bounce
    time.sleep(0.05)
    canvas.coords(oval_id,x,y,x+10,y+10) # use absolute coordinates
    canvas.update()


text:
Q: ExecuteExcel4Macro , Is there any way to reference worksheet by index instead of its name in Application.ExecuteExcel4Macro I would like to reference worksheet by index method for the worksheet without open the workbook. However, I don't know how to do it for this. Many example from online is using "Sheet1", which is not my case. For my case, each workbook has its worksheetname, They are all named differently.
Sub excelfor_macro()
Dim p As String, f As String
Dim s As String, a As String
Dim my_array(1 To 8) As String
Dim r As Integer

Application.ScreenUpdating = False
p = "C:\Users\puntek\Desktop\"
f = "490XXZMAV31002S84D6A_002S84D68.xlsx"
s = SHEETNAME(1).Name  **'This is where, i want to reference by index, not worksheet name**

For r = 1 To 8
    a = Cells(r + 8, 3).Address 'start from row 9 the info
    my_array(r) = GetValue(p, f, s, a)
Next r
End Sub

Private Function GetValue(path, file, sheet, ref) 'This is getvalue function, the worksheetname will pass to sheet
Dim arg As String
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
    GetValue = "File Not Found"
    Exit Function
End If
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Address(, , xlR1C1)
GetValue = ExecuteExcel4Macro(arg)
End Function

A: Open the workbook to get the name:
Dim wb as Workbook
p = "C:\Users\puntek\Desktop\"
f = "490XXZMAV31002S84D6A_002S84D68.xlsx"
Set wb = Workbooks.Open(p & f) ' or Set wb = Workbooks.Add(p & f)
s = wb.Worksheets(1).Name
' optionally close the workbook
wb.Close


text:
Q: How to prove convergence for the following series let $$s(x)=\sum_{k=0}^{\infty}\ x^k$$
I have to show that the series converges to $$\frac{1}{1-x}$$ for $$|x|<1$$
I can easily show the series converges for $|x|<1$ using the Ratio test. But how do I show it converges to $1/1-x$?
After that, I have to show that $s^2(x)=\sum_{k=0}^{\infty}\ (ak) x^k$ using the cauchy product. so what I wanted to do is multiply $\sum_{k=0}^{\infty}\ x^k$ by $\sum_{k=0}^{\infty}\ x^k$ which should give me the result $\sum_{k=0}^{\infty}\ ck$ which is equal to $\sum_{k=0}^{\infty}\ \sum_{m=0}^{k}\ x^m.x^k-^m)$
What should I do next? or am I completely wrong?

A: Take sequence of partial sums:
$$s_n=\sum_{k=0}^nx^k=\frac{1-x^n}{1-x}\xrightarrow[n\to\infty]{}\frac1{1-x}\;,\;\;\text{since}\;\; |x|<1\implies x^n\to 0$$


text:
Q: How can I create link with Twig in label for form How can I create a link / path in label in this case:

    {{ form_widget(form.gdpr, { 'label': 'Terms' }) }}

Something like that:

    {{ form_widget(form.gdpr, { 'label': 'Terms' }) }}

A: Twig has a function, form_label() that allows you to specify a label for a form element. Nothing stops you to wrap this label into a  tag :

    {{ form_label(form.gdpr, 'Terms') }}
    {{ form_widget(form.gdpr) }}

For more informations, see the documentation


text:
Q: how to do image scaling with window size Seems so simple, but ...
scale image size with window size?
1)create a container for the image = entire window width, so container grows with window width
2)slap image inside the container
3)scale image based on % of the width of the container

HTML

CSS
.imgEnclosure {
    width: 100%;
}

.validatedImage {
    /* original size (w,h) = 220px by 108px */

    /*
        1.0em = font-size: 24px from html Selector
        so ... original size = 9.167em by 4.500em
    */

    max-width: 30%;
    min-width: 10%;

    height: auto;
}

The image shows the same size no matter how I change the browser window width.

A: Good Grief ...
Instead of:
max-width: 30%;
min-width: 10%;

Use
width: 30%;

Honestly, I could not ask for a simpler answer ... even though I do not understand why the max-, min-width response does not work?

A: I am not sure as to why it didn't work , I believe it could be an error in styling in the parent element or forced styling from parent elements that transferred to the child element .
Did you try placing the
max-width: 30%; min-width: 10%;
in your .imgEnclosure and not the img class itself? Maybe that would have worked too. I normally place positional styles in parent elements so that child elements would easily inherit the styling properties.
Regardless: do check out this as it might answer your question! hope this helped :)


text:
Q: How to parse JSON Array to Webview Android I have this JSON data
"posts":[{
"date":"2016-02-10 10:28:42",
"categories":[{}],
"tags":[],
"author":{"name":"admin"},
"custom_fields":{
                 "ref_number":["ITB NUMBER: ITB\/002\/2016"],
                 "deadline":["26 February, 2016"],
                 "entity":["Refugees (xxx)"]
                }

I want to pass entitywith the code below in my JSONParser.java
            Post post = new Post();
            // Configure the Post object
            post.setTitle(postObject.optString("title"));

            post.setDate(postObject.optString("date", "N/A"));
            post.setContent(postObject.optString("content", "N/A"));
post.setCfs(postObject.getJSONObject("custom_fields").optJSONArray("entity").getString(0));

to my Webview. using the code below in my PostFragment.java
id = args.getInt("id");

                //Title and date pass successfully
                title = args.getString("title");
                String date = args.getString("date");

               //but the entity displays null
                entity = args.getString("entity");

                //author is passed and it displays well/successfully
                String author = args.getString("author");

                 // Construct HTML content

                // html for entity to webview
                html += "
" + entity + "
";

                html += "
" + title + "
";
                // The actual content
                html += content;

am able to pass and display title and content, however when i try entity it shows null in webview
Where am i going wrong

A: Try:
entity = args.getString("custom_fields.entity");

Hope it helps!

A: Your question is not clear , as per my understanding you need Refugee element
The JSON you have posted is not valid.
As per my understanding  elements of entity is also an JSONObject , so the parser should be like this
.optJSONArray("entity").getJSONObject(i); // i is poistion

This will give you ith element of entity array


text:
Q: If $A$ is a linear map, then $A(\alpha(t))'=A(\alpha'(t))$ Let $A:\mathbb R^3\to \mathbb R^3$ be a linear map. I need the following technical result to solve a problem I'm solving:
$$A(\alpha(t))'=A(\alpha'(t))$$
Where $\alpha:I\to \mathbb R^3$ is a parametric curve.
Intuitively, I know this is true, but I would like to prove it formally.

A: Let $T$ be the derivative of $A \circ \alpha$, evaluated at a given $t \in I$.  Then $T$ is the unique linear map $\mathbb{R} \rightarrow \mathbb{R}^3$ such that
$$\frac{||A \circ \alpha(t + h) - A \circ \alpha(t) - T(h)||}{|h|}$$
goes to zero as $h$ goes to $0$.  Let $S: \mathbb{R} \rightarrow \mathbb{R}^3$ be the linear map $S(h) = A(\alpha'(t)h)$.  Then
$$\frac{||A \circ \alpha(t + h) - A \circ \alpha(t) - S(h)||}{|h|} = \frac{||A[ \alpha(t + h) -  \alpha(t) - \alpha'(t)h]||}{|h|}$$
where $|| \cdot ||$ is a fixed norm on $\mathbb{R}^3$.
The numerator is bounded by $||A|| \cdot ||\alpha(t+h) - \alpha(t) - \alpha'(t)h||$, where $||A||$ is the norm of the linear transformation $A$, and by definition of $\alpha'(t)$,
$$\frac{||\alpha(t+h)-\alpha(t) -\alpha'(t)h||}{|h|}$$
goes to zero as $h$ goes to $0$.  So $S$ satisfies the same property as $T$.  By uniqueness, $S = T$.
Another way using the chain rule:
The chain rule says that the derivative of $A \circ \alpha$, evaluated at $t$, is the composition of the linear transformation $\alpha'(t): \mathbb{R} \rightarrow \mathbb{R}^3$ (the derivative of $\alpha$ evaluated at $t$), followed by the linear transformation $A'(\alpha(t)): \mathbb{R}^3 \rightarrow \mathbb{R}^3$ (the derivative of $A$ evaluated at $\alpha(t)$).  So
$$(A \circ \alpha)'(t) = A'(\alpha(t)) \circ \alpha'(t)$$
Since $A$ is a linear transformation, its derivative at every point of $\mathbb{R}^3$ is constant and equal to $A$.  Thus
$$(A \circ \alpha)(t) = A \circ \alpha'(t)$$
as linear maps $\mathbb{R} \rightarrow \mathbb{R}^3$.


text:
Q: Laravel own variable in scope I'm using the haversine formula to calculate a distance, this is working fine.

But I would like to hide results where the distance is greater then the max_radius field on that result.

This is my database scheme.

This is the query I'm using.
You can see I hard coded the distance (50)
public function scopeFitsDistance($query, $lat, $lng)
{
    return $query->select(\DB::raw("*,
                      ( 3959 * acos( cos( radians(?) ) *
                        cos( radians( lat ) )
                        * cos( radians( lng ) - radians(?)
                        ) + sin( radians(?) ) *
                        sin( radians( lat ) ) )
                      ) AS distance"))
            ->addBinding($lat, 'select')
            ->addBinding($lng, 'select')
            ->addBinding($lat, 'select')
            ->having('distance', '<', 50); <----------
}

But now I'm wondering how I can hide results where that distance < max_radius, which is a field inside the table.
The following returns no results
->having('distance', '<', 'max_radius');

Thank you!

A: HAVING only works with GROUP BY
You can do a sub-select and then use a WHERE clause instead.


text:
Q: CreateProcessWithLogonW : unable to start process Hi I am completely new to programming. And please someone help me.
I am trying to start a pocess from a service.
I need to start the new process by prompting user to enter admin credentials.
I was trying to use CreateProcessWithLogonW().
Am I using the right function.
I tried to give input username, password, domain as localhost. I gave full pathe to the .exe file that i need to start.
Here is the piece of code.
CreateProcessWithLogonW(L"Administrator",
                        L"localhost",
                        L"password",
                        0,
                        NULL,
                        L"c:\myupdates\myapp.exe",
                        NORMAL_PRIORITY_CLASS | CREATE_CONSOLE,
                        NULL,
                        NULL,
                        &si,
                        &pi);

Si.cb = sizeof(si);
Si.lpDesktop = L"winsta0\\default";

But the process never started. Can you guys tell me what I am doing wrong.
And what do I need to do to promt user to enter credentials of administrator instead of hardcoding it.

A: One problem is passing a string literal as the command-line argument, as that argument must be modifiable. From CreateProcessWithLogon() in relation to the command-line argument:

The function can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.

You also need to escape the backslashes. Change to:
WCHAR cmdLine[] = L"c:\\myupdates\\myapp.exe"; /* 'cmdLine' is a
                                                  copy of the string
                                                  literal. */

and pass cmdLine instead.
After any WINAPI function failure check GetLastError() as it will inform you of the reason for failure.

A: You may want to escape the program string properly as well:
L"c:\myupdates\myapp.exe"

should at least be:
L"c:\\myupdates\\myapp.exe"

Frankly, there are a multitude of things wrong with this code, from improper setup of SI, to the parameters passed to the API itself. I suggest you read up more.

A: None of CreateProcess* functions will do any promting. They are low level APIs and know nothing about GUI.
If you want user to be prompted, use ShellExecuteEx with runas command. Windows will first ask a permission to elevate and then prompt for credentials.

A: Maybe it's too late to help you. But it might be helpful for others, though. If you use the CreateProcessWithLogonW function and you are using the Default desktop just keep lpDesktop as NULL.
If lpDesktop is not Null you have to enter the user's sid (getting with LookupAccountNamean) as a ACE in desktops and winstation's DACL
So here are the steps you have to do to add an ACE for a desktop:

*

*get Desktop handle with OpenDesktop, use the right dwDesiredAccess

*get the Security Descriptor with GetSecurityInfo and DACL_SECURITY_INFORMATIONas securityinfo

*get the DACL from your Security Descriptor

*Add AddAccessAllowedAcewith the sid of your User's sid

*Set the modified DACL to your Desktop handle

now repeat those steps for winsta0 winstation
The commantary of Mr. Furious in the documantary helped me alot to solve this problem.

A: The access violation is down to the lpCommandLine parameter. That is meant to a editable memory, LPWSTR and the API function does modify the buffer. But you pass a pointer to non-modifiable memory.
But there's a more fundamental problem. You say you want to prompt for credentials from a service. Services should not show UI and in modern versions of Windows, a service simply cannot show UI. Your design is flawed and you need to re-consider it.


text:
Q: Реализация методоа в шаблонных класах Как для класса:
template <class T>
class cFunction {
public:
    cFunction(cArguments* args, int _n);
    T getFunc(int num);
private:
    T* func;
};

сделать реализацию метода(конструктора например)
Такая конструкция не работает:
template <class T>
cFunction <T>::cFunction(cArguments* args, int _n)
{
    for(int i = 0; i < _n; i++) {
        func[i] = new T(args->getA(), args->getB(), args->getX());
    }
}

Зато работает инлайн вставка:
template <class T>
class cFunction {
public:
    cFunction(cArguments* args, int _n) {
        for(int i = 0; i < _n; i++) {
            func[i] = T(args->getA(), args->getB(), args->getX());
        }
    }
    T getFunc(int num);
private:
    T* func;
};

Как правильно писать реализацию без использования инлайн вставок?
A: C++ (gcc-4.3.4), с присваиванием возиться не стал http://ideone.com/FxVNKd
#include <iostream>

class cArguments
{
    public:

    cArguments(int,int,int)    {}
    int getA(){return 0;}
    int getB(){return 0;}
    int getX(){return 0;}

};

template <typename T>
class cFunction {
public:
    cFunction(){}
    cFunction(cArguments* args, int _n);
    T getFunc(int num);
private:
    T* func;
};

template <typename  T>
cFunction<T>::cFunction(cArguments* args, int _n)
{
    for(int i = 0; i < _n; i++) {
        /*func[i] =*/ new T(args->getA(), args->getB(), args->getX());
    }
}

using namespace std;

int main() {

    cArguments arg(10,10,10);

    cFunction<cArguments> a(&arg, 10);

    return 0;
}


text:
Q: VirtualBox Error - VTx is disabled in the BIOS (VERR_VMX_NO_VMX) this error keeps showing to me when I try to launch a VM, I saw that other people had this issue but I can't find a way to fix it.
I went to the BIOS to check is the virtualization was enabled already, I even disabled it and enabled it again as another guy said on a different topic.
In the error it says that "VT-x is disabled", but I couldn't find it on my BIOS, only the Intel Virtualization, could this be the error?
Here is the images of the error and my BIOS.
PS: Sorry if there is any mistakes on my english, english is not my native language.


text:
Q: Angular-Route and the ng-view div hide the page I'm trying to use angular-route, but when I change the div tag from

 to

 that tag is suddenly empty.
The app.js code I have is:
angular .module('testApp', ['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateURL:'views/main.html',
                controller: 'MainCtrl'
            })
            .when('/adoption', {
        templateURL: 'views/foo.html',
        controller: 'fooCtrl'
        })
        .otherwise({
        redirectTo: '/'
        });
    });

and the html pages and controllers are made, but pretty much empty, save some placeholder stuff.
I'm not 100% sure how I'm supposed to include the angular-route code, but what I have seems to be working.

A: you app.js should be like this:
angular .module('testApp', ['ngRoute'])
.config(function ($routeProvider) {
    $routeProvider
        .when('/main', {
            templateURL:'views/main.html',
            controller: 'MainCtrl'
        })
        .when('/adoption', {
    templateURL: 'views/foo.html',
    controller: 'fooCtrl'
    })
    .otherwise({
    redirectTo: '/main'
    });
});


text:
Q: Else condition always works There is a bug in my code which I'm not able to identify. This code should return True if the list contains [3,3].
But, if I write an else condition, it always shows False. If I skip the else condition, the code works fine.
def has_33(nums):
    for i in range(0,len(nums)-1):
        if nums[i]==3 and nums[i+1]==3:
            return True
        else:
            return False
    pass

The above code returns :
# Check
has_33([1, 3, 3]) . -- > False

# Check
has_33([1, 3, 1, 3]) --> False.

But, if I change the code to this :
def has_33(nums):
    for i in range(0,len(nums)-1):
        if nums[i]==3 and nums[i+1]==3:
            return True
    pass

The code works fine :
# Check
has_33([1, 3, 3]) --> True

# Check
has_33([1, 3, 1, 3]) -- > Returns nothing , False.

Why is this happening?

A: It's because the else condition is satisfied first.
You have a for loop which goes over all the numbers in your list [1,3,3], first it check's the first number which is 1 and then the second number which is 3;
if nums[i]==3 and nums[i+1]==3:

In this case nums[i] is 1 which means nums[i]==3 is not True , which means your code will go straight to the Else
And the solution to your problem is simple:
def has_33(nums):
    for i in range(len(nums)):
        if nums[i]==3 and nums[i+1]==3:return True
    return False

A: The other answers explain the bug pretty well. I did want to point out two things though.

*

*A best practice in Python is to avoid iterating over a set of indices if possible, instead preferring to iterate over the object (e.g. for n in nums).

*There are library functions that make your life substantially easier.

Consider the following code using the any() and zip() built-in functions.
def has_33(nums):
    return any(x==y==3 for x, y in zip(nums, nums[1:]))

If you wanted, you could make this more general so that it might be applicable in other projects. The use of a default value preserves the original behavior.
def has_duplicate(nums, val=3):
    return any(x==y==val for x, y in zip(nums, nums[1:]))

A: Try like this , The error occurring in your code because it will return and exit from code in the first loop itself. So you can give a flag and whenever the condition meets change the flag to true, then return the flag last:
def has_33(nums):
    flag = False
    for i in range(0,len(nums)-1):
        if nums[i]==3 and nums[i+1]==3:
            flag = True

    return flag

A: You can also make small adjustment in your function and decrease an indentation of "else" statement this way:
def has_33(nums):
    for i in range(0,len(nums)-1):
        if nums[i]==3 and nums[i+1]==3:
            return True
    else:
        return False
    pass

This is standard structure of "for" loop in Python - if your loop completes correctly without interruption (in your case - without finding two subsequent "3" on your list), it executes "else" statement.


text:
Q: How to get parameters using "/:params" in Angular 2 I want to get parameters from a link similar to this "sample.com/product/45" using "product/:id",
Here is my route declaration :
export const routes: Routes = [
  { path: 'product/:id', component: Product }
];

Here is the component class
export class Product implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id'];

       console.log(this.id); //I get undefined here
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

when i tried to console.log() the id , i got undefined

A: Try this ,
ngOnInit() {
    this.id = this.activatedRoute.snapshot.params["id"];
}


text:
Q: How to get the list of products launched in the latest quarter if product gets launched at different time in different regions I have a table
/---------------------------------------\
|Region | Product | 1 |  2  |  3  |  4  |
|-------|---------|---|-----|-----|-----|
|   A   |   ABC   | 0 | 120 | 421 | 520 |
|   B   |   ABC   | 0 |   0 |   0 | 670 |
|   C   |   DEF   | 0 |   0 |   0 | 125 |
|   D   |   PQR   | 0 |   0 | 780 | 560 |
|   E   |   PQR   | 0 |   0 |   0 | 340 |
|   F   |   XYZ   | 0 |   0 |   0 | 780 |
|   G   |   XYZ   | 0 |   0 |   0 | 900 |
\---------------------------------------/

In this table, I need to find the name of products that were launched in quarter 4.
The result that query should give is DEF and XYZ
I will be grateful if someone could help

A: try this
select *
from yourTableName a
where a.field4 > 0
     and a.field3 = 0
     and a.field2 = 0
     and a.field1 = 0
     and a.product not in (select b.product
                           from yourTableName b
                           where b.field3 >0
                                 or b.field2>0
                                 or b.field1>0)

and if you just want the product use below
select a.product
    from yourTableName a
    where a.field4 > 0
         and a.field3 = 0
         and a.field2 = 0
         and a.field1 = 0
         and a.product not in (select b.product
                               from yourTableName b
                               where b.field3 >0
                                     or b.field2>0
                                     or b.field1>0)

here field4 as quarter 4
     field3 as quarter 3 and so on.

A: You need to group by product and aggregate (sum) the values for each quarter per product, regardless of region:
select
    Product
from #table
group by Product
having sum([4]) > 0
and sum([3]) = 0
and sum([2]) = 0
and sum([1]) = 0

With sample data to illustrate:
create table #table
(
    Region varchar(1),
    Product varchar(3),
    [1] int,
    [2] int,
    [3] int,
    [4] int
)

insert into #table
values
    ('A','ABC',0,120,421,520),
    ('B','ABC',0,0,0,670),
    ('C','DEF',0,0,0,125),
    ('D','PQR',0,0,780,560),
    ('E','PQR',0,0,0,340),
    ('F','XYZ',0,0,0,780),
    ('G','XYZ',0,0,0,900)

select
    Product
from #table
group by Product
having sum([4]) > 0
and sum([3]) = 0
and sum([2]) = 0
and sum([1]) = 0

drop table #table

Output:
/---------\
| Product |
|---------|
|   DEF   |
|   XYZ   |
\---------/


text:
Q: Is Higgs mechanism necessary in QCD? As we know, the Higgs mechanism is introduced in the Standard model in order to explain the masses of the gauge bosons, the leptons and the neutrinos (maybe?). The Higgs mechanism is necessary to introduce masses in electroweak theory because of gauge symmetry and chiral symmetry.
But is the Higgs mechanism still necessary in QCD? It seems there is no chiral symmetry in QCD so that mass of the quark does not have to be zero. And on the other hand, the gluon seems to be massless(maybe I am wrong? mass of proton). It seems like Higgs mechanism is not necessary in QCD.
Is my understanding right? Thanks a lot!

A: That really depends on what you call necessary.
If you completely forget all about $SU(2)_L$ (say, in an alternate universe with no Weak Interactions). Then mass terms in the Lagrangian for quarks and leptons are not forbidden by any symmetry and you would not need the Higgs field to generate the mass of the quarks or of the electron.
Now, in OUR universe, all those particles interact weakly and then mass terms are forbidden and you need the Higgs to give masses to quarks and leptons.
The mass of the proton, on the other side, has very little to do with the Higgs. Consider that the light quarks that compose the proton have a pole mass of a few MeV (2 to 4 MeV), while the proton itself masses ~900 MeV. Where does the extra mass comes from?
The answer is binding energy. The quarks interact very strongly and the mass of the proton is the combination of the three real quarks plus a whole lot of virtual quarks and gluons. Even if we had no Higgs and the masses of all those guys were zero, the proton mass would not change much.
Since most of the visible mass in the universe is made of protons and neutrons, it is a bit of a fallacy to say that the Higgs field "is responsible for all mass". It is certainly responsible for the mass of elementary particles, but QCD is what generates "our mass". If anyone wants to check what would change if we did not have the Higgs, there is a good paper by Chris Quigg (http://arxiv.org/pdf/0901.3958v2.pdf), which also has a deeper discussion on mass generation by QCD.


text:
Q: How to show only (src) files not (target) files by Eclipse shortcut (cntrl + alt + R)? By using Eclipse shortcut (CTRL+Shift+R)
Will show both (src) files and also (target) files.
Like that

The problem is that
Some times by mistake
I select the target file then i update my changes
After build i will NOT see the new changes !!
Thats because i update the wrong files (target)
So any idea
How to show only (src) files not (target) files by Eclipse shortcut (CTRL+Shift+R) ?

A: The quick and (dirty way) :
Right click on a target folder(s)
Go to folder(s) properties,
Mark folder as Derived like that.

Derived entities are excluded from searching by default like that.

The (safe way) :
By create a working set

That include only those entities you want searched and search only within that working set.
In our case will include ALL without target folder(s).
Note : This answer is related to
Exclude folders from Eclipse search

A: In the project-settings on java build-path you'll find on source a checkbox like this:

Disable it, for not getting files which are in the target folder to your view.
So you will not find it by Eclipse shortcut (CTRL+Shift+R)


text:
Q: Why is C# code partially greyed out in the Visual Studio 2015 editor? This is how sample C# code looks in my VS 2015 configuration:

The statements in the rectangles are greyed-out.  What is the meaning for this?  Per this SO answer, I know that there are rules under References->Analyzers, but I cannot tell which active rule produces this result.
EDIT:
Per Hans Passant's guidance:

A: The analyzer is suggesting that your code should be functioning also without those lines.
I assume it is able to determine that Tick and Finished are never null. Variables you introduced are superfluous, too.


text:
Q: distinct in query repeating values I wonder if anyone can spot the problem with this 'view' query to show only 'company' and 'materials'.  The problem is that it shows each entry a separate time for each material and company.  I'm using this view to populate a dropdown box in a form but I would only like it to show the distinct values for each column (company/materials) - as of now if, for example, end result is the company 'Anderson' twice but with different materials for each...it shows 'Anderson' twice.  I've tried using DISTINCT after the select statement for each of the two, but I don't achieve what I want.
select `b`.`company` AS `company`, `bp`.`material` AS `material`
from (((`caseys_wrdp4`.`windows_brands_products` `bp`
        left join `caseys_wrdp4`.`windows_brands` `b` on((`bp`.`brand_id` = `b`.`id`)))
       join `caseys_wrdp4`.`Windows_last_submissions` `ls`)
      join `caseys_wrdp4`.`windows_materials` `wm`)
where ((`bp`.`width` = round(`ls`.`width`,0))
       and (`bp`.`height` = round(`ls`.`height`,0))
       and (`bp`.`material` = `wm`.`name`)
       and (`bp`.`type` = `ls`.`type`)
       and if ((`ls`.`minimumbid` <> '0.00'),
               (`bp`.`cost` between `ls`.`minimumbid` and `ls`.`maximumbid`),
               (`bp`.`cost` <= `ls`.`maximumbid`)))

A: Possible answer:
Add GROUP_CONCAT and GROUP BY to your query:
select `b`.`company` AS `company`, GROUP_CONCAT(`bp`.`material`) AS `materials`
from (((`caseys_wrdp4`.`windows_brands_products` `bp`
    left join `caseys_wrdp4`.`windows_brands` `b` on((`bp`.`brand_id` = `b`.`id`)))
  join `caseys_wrdp4`.`Windows_last_submissions` `ls`)
  join `caseys_wrdp4`.`windows_materials` `wm`)
where ((`bp`.`width` = round(`ls`.`width`,0))
   and (`bp`.`height` = round(`ls`.`height`,0))
   and (`bp`.`material` = `wm`.`name`)
   and (`bp`.`type` = `ls`.`type`)
   and if ((`ls`.`minimumbid` <> '0.00'),
           (`bp`.`cost` between `ls`.`minimumbid` and `ls`.`maximumbid`),
           (`bp`.`cost` <= `ls`.`maximumbid`)))
GROUP BY(`b`.`company`);

This will give you back a single row for each company w/ company and materials. materials will be a comma-separated list (@Barmar). You could then parse that field for the 2nd drop down.
Example Rows:
'Anderson' 'Wood,Vinyl'
'WM' 'Metal','Plastic'
Assuming you're building a webpage, depending on how you're building the DOM, you can either use javascript str.split(), https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split, or on the server side, any language should work.


text:
Q: How do I detect a view that I have created programmatically in espresso I have this line of Espresso test code:
    onView(withId(R.id.rvWorkDaySchedule)).perform(swipeDown());

And rvWorkDaySchedule is shown in red in the editor of Android Studio because there is no such XML view id in the layouts - I create this RecyclerView programmatically.
So how do I detect views that have been inflated programmatically with Espresso?

A: First of all, Espresso allows you to use Hamcrest matchers in tests.
Hamcrest 1.3 Quick Reference.
The most useful for catching the programmatically added views are withChild, withParent, hasSibling, and hasDescendant.
To make it more clear, I would give a simple example from my app:
onView(withId(R.id.action_bar_details))
        .check(matches(withChild(withChild(withText("Details")))));

Secondly, for RecyclerView tests in Espresso use onData methods instead onView.
Espresso  2.1. Espresso Cheat Sheet Master
Another example from my app - using onData method
onData(anything()).inAdapterView(withId(R.id.listView)).atPosition(getRandomPosition()).
                onChildView(withId(R.id.item)).check(matches(isDisplayed()));

Finally, check these great Googles repository for get more examples

*

*GoogleSample

*GoogleCodeLabs


text:
Q: PHP file_put_contents - How to organize the output? I have this code below:
file_put_contents("ceontent.txt", "Account: " . $_POST['callcenteragent'] . " Pass: " . $_POST['agentpassword'] . " IP: " . $ipaddress . " User-agent: " . $browser . " \n", FILE_APPEND);

The output going to be:
Account: Michael Pass: Michaelpwd122@@ IP: 197.210.55.69
 User-agent: Mozilla/5.0 (Linux; Android 6.0; TECNO W5 Lite Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 Instagram 150.0.0.33.120 Android (23/6.0; 320dpi; 720x1280; TECNO; TECNO W5 Lite; W5Lite; mt6580; en_US; 230877674)

It's kinda a mess and i can't read.
How to make it look like this:
    ====================================================================================
    ====================================================================================
    Account: Michael
    Password: Michaelpwd122@@
    IP: 197.210.55.69
    User-Agent: Mozilla/5.0 (Linux; Android 6.0; TECNO W5 Lite Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 Instagram 150.0.0.33.120 Android (23/6.0; 320dpi; 720x1280; TECNO; TECNO W5 Lite; W5Lite; mt6580; en_US; 230877674)
    ===================================================================================
    ===================================================================================

I've tried to add "=====================" but somehow its not put content.
Any help please? Thank you in advance.

A: $separator = '===============================================';
$data = [
    $separator,
    $separator,
    "Account: " . $_POST['callcenteragent'],
    "Pass: " . $_POST['agentpassword'],
    "IP: " . $ipaddress,
    "User-agent: " . $browser,
    $separator,
    $separator,
];

file_put_contents("ceontent.txt", implode("\n", $data), FILE_APPEND);

A: for writing new lines in html, you should use BR tag or tags that make own new line after closing them such as h(1|2|3|4|5|6), p and ...
but for writing new line character in files you can use \n that maked for creating new lines in texts
in php you can use new line character by 3 way:
1: Put your texts in double quotation and use \n character (such as another languages):
$text = "amirali esteki answered the user:\npra sar";
echo('
' . $text . '\
');

2: use chr function that is for generate a single-byte string from a number. the single-byte number of new line character is ten (10):
$text = 'amirali esteki answered the user:' . chr(10) . 'pra sar';
echo('
' . $text . '\
');

3: use PHP_EOL constant that defined for new character by PHP:
$text = 'amirali esteki answered the user:' . PHP_EOL . 'pra sar';
echo('
' . $text . '\
');

and about your code:
$text = '====================================================================================' . PHP_EOL;
$text .= '====================================================================================' . PHP_EOL;
$text .= 'Account: ' . $_POST['callcenteragent'] . PHP_EOL;
$text .= 'Password: ' . $_POST['agentpassword'] . PHP_EOL;
$text .= 'IP: ' . $ipaddress . PHP_EOL;
$text .= 'User-agent: ' . $browser . PHP_EOL;
$text .= '====================================================================================' . PHP_EOL;
$text .= '====================================================================================' . PHP_EOL;
file_put_contents('ceontent.txt', $text, FILE_APPEND);

Note: please make sure your codes be safe against hackers attacks. certainly you should use a XSS clean method or function for safing received data from clients and methods


text:
Q: SoapServer sends text/html header instead of text/xml My soap server sends Content-Type: text/html in the response header. I need Content-type: text/xml.
public function index()
{
    $this->layout = 'soap';
    ini_set("soap.wsdl_cache_enabled", "0");
    $this->server = new SoapServer('wsdl/tur.wsdl', array(
            'soap_version' => SOAP_1_2,
    ));
    $this->server->setObject($this);
    $this->server->handle();
}

Here is server's response:
HTTP/1.1 200 OK
Date: Mon, 19 Mar 2012 12:17:10 GMT
Server: Apache/2.2.20 (Ubuntu)
X-Powered-By: PHP/5.3.6-13ubuntu3.6
Set-Cookie: CAKEPHP=msmid2fijgrj1efjs0otl8qfj1; expires=Mon, 19-Mar-2012 16:17:10 GMT; path=/
P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 877
Content-Type: text/html; charset=UTF-8
I've tried to call header() with text/xml conent type
public function index()
{
    $this->layout = 'soap';
    ini_set("soap.wsdl_cache_enabled", "0");

    header("Content-Type: text/xml");

    $this->server = new SoapServer('wsdl/tur.wsdl', array(
        'soap_version' => SOAP_1_2,
    ));
    $this->server->setObject($this);
    $this->server->handle();
}

before and after constructing SoapServer, but no result.

A: (Answered in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:

Solved, it was a сakephp feature. Thanks to How to write content type in cakephp?
public function index()
{
    $this->layout = 'soap';
    ini_set("soap.wsdl_cache_enabled", "0");
    $this->server = new SoapServer('wsdl/tur.wsdl', array(
        'soap_version' => SOAP_1_2,
    ));
    $this->server->setObject($this);
    $this->server->handle();

    $this->RequestHandler->respondAs('text/xml');
}


text:
Q: What does principal end of an association means in 1:1 relationship in Entity framework public class Foo
{
    public string FooId{get;set;}
    public Boo Boo{get;set;}
}

public class Boo
{
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

I was trying to do this in Entity Framework when I got the error:

Unable to determine the principal end of an association between the types
  'ConsoleApplication5.Boo' and 'ConsoleApplication5.Foo'.
  The principal end of this association must be explicitly configured using either the
  relationship fluent API or data annotations.

I have seen questions on StackOverflow with a solution for this error, but I want to understand what the term "principal end" means.

A: This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.
Had a situation where having FK of dependent must be it's PK was not feasible.
E.g., Foo already has one-to-many relationship with Bar.
public class Foo {
   public Guid FooId;
   public virtual ICollection<> Bars;
}
public class Bar {
   //PK
   public Guid BarId;
   //FK to Foo
   public Guid FooId;
   public virtual Foo Foo;
}

Now, we had to add another one-to-one relationship between Foo and Bar.
public class Foo {
   public Guid FooId;
   public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
   public virtual Bar PrimaryBar;
   public virtual ICollection<> Bars;
}
public class Bar {
   public Guid BarId;
   public Guid FooId;
   public virtual Foo PrimaryBarOfFoo;
   public virtual Foo Foo;
}

Here is how to specify one-to-one relationship using fluent api:
modelBuilder.Entity<Bar>()
            .HasOptional(p => p.PrimaryBarOfFoo)
            .WithOptionalPrincipal(o => o.PrimaryBar)
            .Map(x => x.MapKey("PrimaryBarId"));

Note that while adding PrimaryBarId needs to be removed, as we specifying it through fluent api.
Also note that method name [WithOptionalPrincipal()][1] is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.

A: In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.
In case of entity framework FK in dependent must also be its PK so in your case you should use:
public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping
modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

A: You can also use the [Required] data annotation attribute to solve this:
public class Foo
{
    public string FooId { get; set; }

    public Boo Boo { get; set; }
}

public class Boo
{
    public string BooId { get; set; }

    [Required]
    public Foo Foo {get; set; }
}

Foo is required for Boo.


text:
Q: Use common class to hold static data I need to do something quit simple - I would like to do a one time http request to a static data - I would like to do it either when the application starts or as "lazy-loading", when needed. I would like to send the http request one time and set a variable (member -> property) with the returning results, so I can use that property later on instead of doing another http request.
Below is my code - is it the best practice solution ?
Any remark\improvement\another way of doing it - would be appreciated.
The "lut" is for "lookup table" dat -> the static data.
@Injectable({providedIn: 'root'})
export class lutData
  {
    _someData : somedataType[] = null;
    constructor(private lutService : LutService){} //The service is a simple http service
    public get SomeData() : somedataType[] {
      if (this._someData){
        return this._someData;
      }
      else {
        this.lutService.getSomeLutData().subscribe(result =>{
          this._someData = result;
          return this._someData;
        });
      }
    }
}

This is the component that should use the data: I'm using injection, but maybe there's a better way doing it.
export class XXX_Component {
  someData : somedataType[];
  constructor(private lookUpData : lutData) { }
  ngOnInit() {
    this.setLutData();
  }
  setLutData() {
    this.someData = this.lookUpData.SomeData;
  }
}

A: What I would do is take the best of Observable:
@Injectable({providedIn: 'root'})
export class LutData
  {
    _someData : somedataType[] = null;
    constructor(private lutService : LutService){} //The service is a simple http service
    public someData() : Observable<somedataType[]> {
      if (this._someData){
        return of(this._someData);
      }
      else {
        const req = this.lutService.getSomeLutData();
        req.subscribe(data=> this._someData = data);
        return req;
      }
    }
}

Component
export class XXX_Component {
  someData$ : Observable<somedataType[]> = this.lookUpData.someData();
  constructor(private lookUpData : LutData) { }
}

Then in your component template use the async pipe:
<div *ngFor="let item of (someData$ | async)">
  {{item}}
</div>

A: Store data in a service is very good way of making data available for all the components and also maintain the consistency. But calling the http request whenever your project is start or app is render on the device, depend on the use case.
It's good, If you need updated data at least once whenever user land on your page like, user_details, user jwt keys etc.
Consider an example, suppose you have a page where you listing pricing/packages details of your services. And these information are not changing very frequently. For this example calling http service at the time of start your project is unnecessary.
For this type of application, where your data are not changing very frequently you can call http once and after that store the response in your native storage with some validation roles. So whenever your page is open
1. Look into native storage for the data.
2. If found and  pass the validation role.
3. Then store in a service for future use.
4. If not found or not able to pass validation role.
5. Call http request again.
6. Save the response to native storage with same validation role.
7. And also set the response in your service for future use.


text:
Q: batch script to parse txt file with delimiter as semicolon my text file is as shown below:
H;SEQUENCENUMMER;TIMESTAMP;VERSION;VALIDITY_FLAG;SID
D;1077;1383519656;"20.0.8-2";1;;
D;1079;1383519657;"20.0.8-2";2;;

i want to parse this using windows batch program and output file will look like as beloW:
H  SEQUENCENUMMER  TIMESTAMP  VERSION  VALIDITY_FLAG  SID
D  1077  1383519656  "20.0.8-2"  1
D  1078  1383519657  "20.0.8-3"  2

something like a tab delimited
pls suggest

A: @echo off
    setlocal enableextensions enabledelayedexpansion

    rem Get a tab character
    for /f tokens^=^*^ delims^= %%t in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do set "tab=%%t"

    rem For each line in text file, replace ; with a tab
    (for /f "tokens=*" %%l in (plaintext.txt) do (
        set "line=%%l"
        echo !line:;=%tab%!
    )) > output.txt

    endlocal

A: @echo off
setlocal enabledelayedexpansion
if exist output.txt del output.txt
for /f "delims=" %%a in ('type "Your Text File.txt"') do (set $line=%%a
                                               echo !$line:;=   !>>output.txt)

A: You can use nested for-loops as follows:
@echo off
echo.|set a=>outfile.txt
for /f %%A in (infile.txt) do (
    for %%B in (%%A) do (
        echo.|set /P ="%%B    ">>outfile.txt
    )
    echo.>>outfile.txt
)

A: You don't really seem to be parsing anything, you are just replacing semicolons with tabs. You can use VBScript to do this. Save the following as "process.vbs"
Option Explicit
Dim Line,Regex

Set RegEx = new RegExp
Regex.Pattern = ";"
Regex.Global=True

Do While Not WScript.StdIn.AtEndOfStream
   Line = WScript.StdIn.ReadLine()
   Line = Regex.Replace(Line,VBTab)
   WScript.Echo Line
Loop

Then you can run it like this:
vbscript /nologo process.vbs < yourfile > newfile


text:
Q: Angular 8 datatables search not working as expected I'm trying to use angular datatables to  filter through data received from the server and I've encountered a problem. Search doesn't work (no error messages) when iterating through objects in a subscribe, but works when simply assigning values to my array of objects.
I've tried several different implementations I found online but none have seemed to work or weren't specific enough.
So this is the working code (credit.component.ts):
        getCreditList() {
        this.creditService.getCreditList().subscribe(credits => {
            this.credits = credits;
            console.log(this.credits); //outputs all credits as array of objects
            this.dtTrigger.next();
        });
    }

But when trying to filter the data in the promise, even tho the data displayed is correct, the search functionality of angular datatables is broken:
        this.creditService.getCreditList().subscribe(credits => {
            credits.forEach((obj, index) => {
                if (obj.deleted_at == null) {
                    this.credits.push(credits[index]);
                }
            });
            console.log(this.credits); // outputs all credits as array of objects where objects deleted_at property equals null
            this.dtTrigger.next();
        });
    }

In case there's a need for additional code here's related credit.component.html:

            ID
            credit

            {{ credit.userid }}

            {{ credit.credit }}

Related credit.service.ts:
getCreditList() {
    return this.http.get<Credit[]>(this.url + 'credit');
}

Credit class:
export class Credit {
    id: number;
    credit: number;

    deleted_at: Date;
}

I expect to be able to preform a search with pre filtered data like in the working example.
If anyone could shine some light on this mystery it would be greatly appreciated.
Thank you!
Edit:
Pagination doesn't seem to work either, regardless of the aforementioned codes. I'm beginning to wonder maybe the problem is with async call, as in the data gets rendered too late or something? How would I go about solving this? Any help would be appreciated.

A: I know its a bad practice but for me it works if I put the trigger in a timeout like this:
setTimeout(() => {
   this.dtTrigger.next()
}, 1);


text:
Q: How can I show the information of a specific element vue js Hello good morning, I am having this problem, I have 2 tables, a main table that has a button that opens a popup with the second table.
What is the idea? That if I click on the button of the first table and first option it would have to show me only the information of that element, in the popup I make a console.log(item.id) and it shows me the data of that element well , but when I open the popup it shows me all the data.. it must be something that I am overlooking, thank you very much

<template>
 <v-card>
  <v-card-title>
  Control Modificaciones
  </v-card-title>
  <v-card-text>
  <v-row>
    <v-col cols="12" md="3" class="ml-3">
      <v-text-field
        v-model="fechaDesde"
        type="date"
        label="Fecha Desde"
        :rules="[(v) => !!v || 'Este campo es requiredo']"
        required
      ></v-text-field>
    </v-col>
    <v-col cols="12" md="3" class="ml-3">
      <v-text-field
        v-model="fechaHasta"
        type="date"
        label="Fecha Hasta"
        :rules="[(v) => !!v || 'Este campo es requiredo']"
        required
      ></v-text-field>
    </v-col>
    <v-btn color="info" title="Crear" class="mt-6 ml-8" @click="buscar()">
      Buscar
    </v-btn>
  </v-row>
   </v-card-text>
  <v-row>
  <v-col cols="8" md="8" class="ml-3">
    <v-card-text>
      <v-simple-table>
        <template>

              Nro Orden
              Cliente
              Tipo
              Fecha Creacion
              Fecha Ult Modificacion
              Cant Modificada
              Acciones

              {{ item.numero }}
              {{ item.cliente.nombre }}
              {{ item.tipoPresupuestoString }}
              {{ formatDate(item.fechaAlta) }}
              {{ formatDate(item.fechaModificacion) }}
              {{ item.numero }}

                <v-icon
                  title="Historial del presupuesto"
                  @click="abrirPopupListadoPresupuestoHistorial(item)"
                  >mdi-clipboard-text-clock-outline</v-icon
                >

        </template>
      </v-simple-table>
    </v-card-text>
  </v-col>
</v-row>

<v-row>
  <v-col cols="12" md="12" class="ml-3">
    <v-dialog
      v-model="popupPresupuestoHistorial"
      class="ml-10"
      max-width="800px"
      max-height="700px"
    >
      <v-card>
        <v-card-title class="text-h3 dark lighten-2">
          Listado de Presupuesto Historial.
        </v-card-title>
        <v-card-text>
          <v-simple-table>
            <template>

                  Fecha
                  Comentario
                  Usuario
                  Datos Generales
                  Articulos Nuevos
                  Articulos Modifados
                  Articulos Eliminados
                  Acciones

                  {{ formatDate(item.fecha) }}
                  {{ item.observacion }}
                  {{ item.usuario.name }}
                  {{ item.datosCabecera }}
                  {{ item.articulosNuevos }}

                    {{ item.articulosModificados }}

                    {{ item.articulosEliminados }}

            </template>
          </v-simple-table>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            color="primary"
            @click="popupPresupuestoHistorial = false"
          >
            Cancelar
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-col>
</v-row>
</v-card>
</template>

A: It seems that in your popup, you are rendering the same thing as in the main table. Please look at the following line in your popup:

This line basically loops over the entire list of items and is not at all using the item you selected.
Add a new property to your data function to store the selected item. Assign your selected item to that property and use it in your popup to render out any details you need.

A: Observations :

*

*In v-dialog, Instead of iterating the whole list. You have to just filtered out the object from the list array based on the item id you passed in abrirPopupListadoPresupuestoHistorial method and then use that object inside the <v-dialog> to show the data based on the selected record only.

*As you are going to show only selected item details inside the dialog. You can directly bind the filtered object instead of using v-for as it will always contain the selected item.id details. You can use Array.find() method to just get the object based on the id passed.

Demo (Just for a demo purpose I am passing item ID as 3) :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      popupPresupuestoHistorial: false,
      list: [{
        id: 1,
        observacion: 'observacion 1',
        name: 'name 1'
      }, {
        id: 2,
        observacion: 'observacion 2',
        name: 'name 2'
      }, {
        id: 3,
        observacion: 'observacion 3',
        name: 'name 3'
      }, {
        id: 4,
        observacion: 'observacion 4',
        name: 'name 4'
      }, {
        id: 5,
        observacion: 'observacion 5',
        name: 'name 5'
      }],
      dialogList: []
    }
  },
  methods: {
    openDialog(itemID) {
     this.popupPresupuestoHistorial = true;
     this.dialogList = this.list.find(({ id }) => id === itemID)
    }
  }
})

<link rel="stylesheet" href="https://unpkg.com/vuetify@2.6.7/dist/vuetify.min.css"/>

  <v-app id="inspire">
    <v-btn @click="openDialog(3)">Open Item 1 Details</v-btn>

    <v-dialog
      v-model="popupPresupuestoHistorial"
      class="ml-10"
      max-width="800px"
      max-height="700px"
    >
      <v-card>
        <v-card-title class="text-h3 dark lighten-2">
          Listado de Presupuesto Historial.
        </v-card-title>
        <v-card-text>
          <v-simple-table>
            <template>

                  Comentario
                  Usuario

                  {{ dialogList.observacion }}
                  {{ dialogList.name }}

            </template>
          </v-simple-table>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            color="primary"
            @click="popupPresupuestoHistorial = false"
          >
            Cancelar
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </v-app>


text:
Q: PyQt file browsing - setting a default option? I've been trying to implement a file browsing widget in the GUI I'm designing. I am using the QFileDialog module, which works great - I can browse and save a file with the following line of code:
filenames = QFileDialog.getOpenFileName()

My widget is set up with a QLineEdit, which I would like to display the name of the file selected, and a QPushButton, which I would like to initiate the above line of code. However, I'd like to know if there's a way I can set a "default" option. If the browse push button is not clicked, I would like the file to be the following:
filenames = str(glob.glob('*.npy')[0])

Which would be saved as the filename in question and show up in my LineEdit. My problem is coming from trying to display a different file name in the LineEdit, depending on whether or not the browse push button has been clicked. If it has been clicked, I would like the LineEdit to show the user-selected file instead of the default option. Here are the applicable lines of code in my retranslate function:
def retranslateUi(self, ROIGUI):
    self.lineEdit.setText(_translate("ROIGUI", self.fileSelect(False), None))
    self.Browse.setText(_translate("ROIGUI", "Browse...", None))
    self.Browse.clicked.connect(self.fileSelect(True))

Which link to the following function. As you can see, this is currently not working correctly because in the LineEdit, tripped is always False. Very silly.
def fileSelect(self,tripped):
    filenames = str(glob.glob('*.npy')[0])
    if tripped==True:
        filenames = QFileDialog.getOpenFileName()
        self.lineEdit.setText(_translate("ROIGUI", filenames, None))
    return filenames

I've been trying different ways of getting this to work, but everything I tried either (a) never updates my LineEdit after file browsing, or (b) runs file browsing immediately without ever using the default option. Thoughts? I'm sure there's a way of doing this that I'm just not seeing.
Thank you in advance.
Edited To Add
I think I have fixed most of my problem - my Browse button is now connected via buttonGroup to an integer, so my fileSelect looks like this:
def fileSelect(self):
    signal = self.buttonGroup2.checkedId()
    if signal==-1:
        filenames = str(glob.glob('*.npy')[0])
    elif signal==1:
        filenames = QFileDialog.getOpenFileName()
        if (filenames.isNull()):
            filenames = str(glob.glob('*.npy')[0])
    return filenames

And my "retranslate" browse button and lineEdit look like this:
self.lineEdit.setText(_translate("ROIGUI", str(self.fileSelect()), None))

self.Browse.clicked.connect(self.fileSelect)

My only problem is getting the text of my lineEdit to update; although the file in use itself updates after it's selected with Browse, the text itself doesn't update. Help?

A: If the cancel button is selected from the QFileDialog filenames variable will be a null QString so, you could:
filenames = QFileDialog.getOpenFileName()
if (filenames.isNull()):
    self.lineEdit.setText(_translate("ROIGUI", filenames, None))
else:
    # The alternative code. Set the default value here to the QLineEdit.

Reference: QFileDialog.getOpenFileName()


text:
Q: How to retrieve data from a Query instead of from Tables with Jackcess I have an Access DB, to make the job easier, I did the queries into DB. How I can take data from the query instead of from tables?
To take data from tables I used this code:
Table table = db.getTable("matchTable");
Cursor cursor = CursorBuilder.createCursor(table);

while (cursor.findNextRow(Collections.singletonMap("idMatch", 15))) {
       Row row = cursor.getCurrentRow();
       ...
}

A: According to the Jackcess FAQ (specifically, here):

Can Jackcess execute SQL queries?
As of the 1.1.19 release, Jackcess has the ability to read the Queries saved in an Access database (i.e. interpret the data stored in the system Queries table). However, Jackcess does not have the ability to execute these Queries.

It means that Jackcess can retrieve the SQL code associated with a saved query in Access, but Jackcess cannot execute that SQL code (or return its results).
In other words, if we have a saved query in Access named [MySavedQuery] then Jackcess can retrieve a String that contains the SQL command, e.g.,
SELECT * FROM Customers WHERE City='wherever'

but Jackcess cannot execute that command to actually return the results of that query. Also, the Jackcess method db.getTable() can open an Access table, but it cannot open a saved query as if it was a table.
However, UCanAccess can execute saved Access queries and return their results. That is, UCanAccess can do
SELECT * FROM MySavedQuery


text:
Q: Unable to install SonarQube Scanner CLI for java project in TFS I have downloaded the extension but unable to install it on my TFS 2015.Does anyone have any suggestions or solutions please?
enter image description here

A: Please make sure you have the permission to install the extension. Project collection administrators with Edit collection-level information permissions can install extensions.If you don't have the permission,please request it first, then try install the extension again.
If you already have the permission, just try to clean caches, close browser and reopen it,then try it again.
Please refer to Get extensions for Team Foundation Server (TFS) for more information.


text:
Q: How to show numeric keyboard (tab from simple text keyboard) on an EditText I am implementing an Android app in which I have an EditText which I want to fill with text. The values that the users will enter are like this : "12bread","45drink", etc.
I want to make it easier for the user and when he focuses on the EditText I first show him the numeric tab of the standard text keyboard.

The problem is that I want to do that without obligating the user to press on 123 first:

Using inputType="number" or other programatically methods just result in showing the numeric keypad but I can't return to text keypad within a single click after so that he can use chars also for the value.

Can anyone tell me if there is a solution to solve this? I have searched and searched and no Q/A matched my case and till now nobody said it is impossible. So I am still hoping for a miracle.
The images presented above are just to show the types of keyboards.

A: Ok this might work. Use a "onTextChangeListener" in your EditText so when the lenght or some determinative string has been recorded the keyboard will switch. I Have a project where I do something like this:
yourEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }
        //Check after user finished writting
        @Override
        public void afterTextChanged(Editable s) {
            //if the lenght of the editText is > 3...
            if (s.length()>=3){
                yourTextView.setInputType(InputType.TYPE_CLASS_NUMBER);
                    }

                }

    });


text:
Q: How to express symmetric polynomials in terms of elementary symmetric polynomials? Firstly, I know there are very similar questions (How to express a symmetric polynomial in terms of elementary symmetric polynomials and Expressing a symmetric polynomial in terms of elementary symmetric polynomials using computer? ) already. Unfortunately they didn't help me that much.
The task is to express some symmetric polynomials in terms of elementary symmetric polynomials. Which is always possible by a theorem which also says that if the initial polynomial is homogeneous of degree d, the resulting polynomial is isobaric of weight d.
For example
$\sum_{i=1}^n x_i=S_1 $
$\sum_{i=1}^n x_i^2=S_1^2-2S_2$ because $\left(\sum_{i=1}^n x_i\right)^2=\sum_{i=1}^n x_i^2 + 2 \sum_{1\leq k < l \leq n}x_{k}x_l=S_1^2 +2S_2$
The case $\sum_{i=1}^n x_i^3$ is already significantly more complicated:
One sees that $$S_1(S_1^2-2S_2)=\sum_{i=1}^n x_i^3+\sum_{r \neq s} x_{r} x_s^2$$ then $$S_1S_2=\sum_{i}x_i \cdot \sum_{r<s}x_r x_s=\sum_{r<s}x_r^2x_s+\sum_{r<s}x_r x_s^2+ \sum_{r<s \\ i \neq r,s}x_i x_r x_s=\sum_{r \neq s} x_{r} x_s^2+3S_3$$
Which gives us $\sum_{i=1}^n x_i^3=S_1^3-3S_1S_2+3S_3$
In the exercises it is asked to reshape other polynomials such as $\sum_{i \neq j } x_i^3 x_j$ and $\sum_{i=1}^n x_i^4$. The solutions of the exercises give the solutions after the first step, as if it was trivial. Personally I'm struggling a lot handling these expressions, am I missing something?
I would like to get some suggestions on how to learn solving these exercises. The theorem above gives some hints on how to choose the possible symmetric elementary polynomials, since they have to satisfy that relation. But how to find the coefficients in general?
Any suggestion is very much welcome.

A: Hint:

*

*A method to systematically transform a symmetric polynomial into a polynomial representation by elementary symmetric polynomials is presented in Paul Garrets algebra course section $15$ Symmetric polynomials.

*Examples of this method are given in this answer.