text: Q: How to pre-load View Controllers? So I have a TabBarController with 3 children VCs. My problem is that ViewControllers 2 and 3 take a second to load which kind of ruins the experience for me. To remedy this, I want to pre-load VCs 2 and 3 at the same time as 1. Is this possible? :)


text:
Q: Servlet @WebServlet urlPatterns This is a quick question but I couldn't find a quick answer.
Now I have a servlet BaseServlet,
when user request any of the url below:
host
host/
host/BaseServlet

It should always refer to the same servlet and redirect to the homepage.
When I set
@WebServlet({"/BaseServlet", ""})

Only
host/
host/BaseServlet

works
If I set
@WebServlet({"/BaseServlet", "", "/"})

The BaseServlet will be requested constantly in loop ...
Why?
Edit:
BaseServlet does a forward to the index.html hid in WEB-INF folder and that's it.
getServletContext().getRequestDispatcher("/WEB-INF/index.html").forward(request,response);

The servlet spec says "A string containing only the / character indicates the "default" servlet of the application." So I want the BaseServlet to be my default. Why it doesn't work?

A: Edit:
If you want to pre-process then you can use Filter with url-pattern "/*" and dispatcher set to REQUEST that way it will ignore forward.
Last value "/" means all request.
Checkout discussion at: http://www.coderanch.com/t/366340/Servlets/java/servlet-mapping-url-pattern
And inside Servlet another forward request for index.html is generated which is also intercepted by servlet.
If you try @WebServlet({"/BaseServlet", "/"}) which is same as @WebServlet({"/BaseServlet", "", "/"}) will result in same error.
You can check this by typing following output statement in servlet:
System.out.println(req.getRequestURL());

A: *

*As you state in your Q, if you want the following:
host/
host/BaseServlet

Use
@WebServlet({"/BaseServlet", ""})

*If you want the following:
host

Add this to your welcome file (you can't specifiy welcome files using annotations)
<welcome-file-list>
    <welcome-file>/BaseServlet</welcome-file>
</welcome-file-list>

*
The servlet spec says "A string containing only the '/' character indicates the "default" servlet of the application."

But it says straight afterwards

In this case the servlet path is the request URI minus the context path
  and the path info is null.

In other words, if your URL is
host

then the servlet path will be
"" (empty string)

so you will need a welcome file list (but index.htm[l] and index.jsp in the webapp directory, not WEB-INF, are included implicitly as a starting welcome file list)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom "cellfilter" in Angular js I am working with the ng-grid in Angular js.
I have this line of code which defines the type of filter added.
  columnDefs: [{field:'date', displayName:'Birth Date', cellFilter:'date:\"dd MMM yyyy\"'},
                    {field:'pre', displayName:'Prev', cellFilter:'number'},
                    {field:'fct', displayName:'Fct', cellFilter:'number'},
                    {field:'act', displayName:'Act', cellFilter:'number'}
                    {field:'imp', displayName:'Important', cellFilter:'number'}]
    };

the Important column has values "H" "L" and "M". By normal(alphabetical) sorting I can achieve a sort of H-L-M but is there a way to define a filter that sorts as "H-M-L".
Any help is appreciated!! Thanks :)

A: Use a custom sort function:
    var result = 1;
    var test="HML";
    function impSortFn(a, b) {
    a=test.indexOf(a);
    b=test.indexOf(b);
    if (a == b) return 0;
    if (a < b) return -1;
    return result;
    }

    $scope.gridOptions = {
    data: 'myData',

    columnDefs: [{
      field: 'name',
      displayName: 'Name'
    }, {
      field: 'age',
      displayName: 'Age'
    }, {
      field: 'imp',
      displayName: 'Important',
      sortFn: impSortFn
    }]

See this Plunker


text:
Q: Use OpenLayers 4 with Angular 5 I'm trying to use OpenLayers 4 in Angular 5.
Basically I just want to implement the QuickStart example from the official OpenLayers Site.
What I have done so far:

*

*npm install ol --save to download the ol package

*angular-cli.json added those lines to the angular-cli.json. Saw that this has to be done on another example on Stackoverflow. The ol.css file exists. The ol.js file doesnt. So I don't know if this is the right or the wrong way but it can clearly not work.

My angular project consists of 3 components:
 -app
 --console
 --map
 --sidebar

 app.component.css
 app.compinent.html
 app.component.spec.ts
 app.component.ts
 app.module.ts

map.component.html
import { Component, OnInit } from '@angular/core';
import * as ol from '../../../node_modules/ol';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
  mapId: string;
  map: ol.Map = undefined;

  constructor() { }

  ngOnInit() {
    this.map = new ol.Map({
      target: this.mapId,
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM(),
        }),
      ],
      view: new ol.View({
        center: ol.proj.fromLonLat([6.661594, 50.433237]),
        zoom: 3,
      })
    });
  }
}

Can anyone tell how to get this working correctly?

A: If you do not want to start from zero with Angular5 and OpenLayers4, there is a mature project called IGO2-lib which is based on Angular 5.x, NodeJS, OpenLayers 4.x and Material Design. IGO2 is also a complete framework.

*

*Clone repository using: git clone https://github.com/infra-geo-ouverte/igo2-lib.git

*Deploy in cd igo2-lib/ and install from: npm install

*Start form: npm start

*Open your browser at http://localhost:4200/
Here it is a live demo from IGO2: https://geoegl.msp.gouv.qc.ca/igo2/apercu-qc/

A: Updated to Angular 8.x and OpenLayers 6.x:
Install ol and do the following changes:
1.) Add the accordant CSS in the html.index (make sure that the version of the CSS matches the installed version of ol) :
<link rel="stylesheet" href="https://openlayers.org/en/v6.1.1/css/ol.css" type="text/css">

Another way is to reference the CSS in the styles object within the angular.json:
"styles": [
  "./node_modules/ol/ol.css",
  "src/styles.scss"
],

2.) Create a map in app.component.ts:
import { AfterViewInit, Component } from '@angular/core';
import { defaults as defaultControls } from 'ol/control';

import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import ZoomToExtent from 'ol/control/ZoomToExtent';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements AfterViewInit {

  map: Map;

  ngAfterViewInit() {
    this.map = new Map({
      target: 'map',
      layers: [
        new TileLayer({
          source: new XYZ({
            url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
          })
        })
      ],
      view: new View({
        center: [813079.7791264898, 5929220.284081122],
        zoom: 7
      }),
      controls: defaultControls().extend([
        new ZoomToExtent({
          extent: [
            813079.7791264898, 5929220.284081122,
            848966.9639063801, 5936863.986909639
          ]
        })
      ])
    });
  }
}

3.) Some style in app.component.css:
.map {
  width: 100%;
  height: 100vh;
}

4.) And finally the markup in app.component.html:

Feel also free to take a look at my GitHub repo.
Edit:
As stated by Bhalchandra Bhosale it might be even better to set the target of the map within ngAfterViewInit:
export class MapComponent implements OnInit, AfterViewInit {

  ...

  ngAfterViewInit() {
    this.map.setTarget('map');
  }
}

Old answer for version 5.2 of ol:
ol is the right package for OpenLayers. However, you do not need to add anything in the angular-cli.json.
With the recent update ("ol": "^5.2.0") the way of importing classes and functions of OpenLayers changed a bit.
map.component.ts:
import { Component, OnInit } from '@angular/core';

import OlMap from 'ol/Map';
import OlXYZ from 'ol/source/XYZ';
import OlTileLayer from 'ol/layer/Tile';
import OlView from 'ol/View';

import { fromLonLat } from 'ol/proj';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})

export class MapComponent implements OnInit {

  map: OlMap;
  source: OlXYZ;
  layer: OlTileLayer;
  view: OlView;

  ngOnInit() {
    this.source = new OlXYZ({
      url: 'http://tile.osm.org/{z}/{x}/{y}.png'
    });

    this.layer = new OlTileLayer({
      source: this.source
    });

    this.view = new OlView({
      center: fromLonLat([6.661594, 50.433237]),
      zoom: 3
    });

    this.map = new OlMap({
      target: 'map',
      layers: [this.layer],
      view: this.view
    });
  }
}

map.component.html:

map.component.css:
.map {
  width: 100%;
  height: 100vh;
}

Add the CSS of OpenLayers within the header-tag of index.html:
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.1.3/css/ol.css" type="text/css">

Even older answer:
Your component might look like the following:
import {Component, OnInit} from '@angular/core';

import OlMap from 'ol/map';
import OlXYZ from 'ol/source/xyz';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/view';
import OlProj from 'ol/proj';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})

export class MapComponent implements OnInit {

  map: OlMap;
  source: OlXYZ;
  layer: OlTileLayer;
  view: OlView;

  constructor() {
  }

  ngOnInit() {
    this.source = new OlXYZ({
      url: 'http://tile.osm.org/{z}/{x}/{y}.png'
    });

    this.layer = new OlTileLayer({
      source: this.source
    });

    this.view = new OlView({
      center: OlProj.fromLonLat([6.661594, 50.433237]),
      zoom: 3
    });

    this.map = new OlMap({
      target: 'map',
      layers: [this.layer],
      view: this.view
    });
  }
}

CSS:
.map {
  width: 100%;
  height: 100vh;
}

HTML:

Let me know if this solution works for you.

A: Use this code into ngAfterViewInit() instead of ngOnInit()


text:
Q: Base constructor in base class instead of derived class in C# I'm learning how to properly apply OO principles in C#. I came across a little problem and I can't figure out how to solve it. I run into the following problem:
The current situation:
public abstract class Foo
{
    protected Foo()
    {
        //does nothing
    }
}

public class Bar : Foo
{
    public BarX ( int a, int b, int c) : base()
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public Bar( int a, int b, int c) : base()
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public doStuff()
    {
        //does stuff
    }
}

The point is that I hafe different types of Foo. In this case it would be circles and rectangles. I want them to have the same constructors as each type has the same attributes. They only have a different doStuff() method. I have tried many combinations but every time I try to move the arguments to the base class's constructor it tells me that 'some class does not contain a constructor that takes 0 arguments' (or 3 arguments) depending how I move around my code.
My question is how I can move the assignment of a, b and c's values to the abstract class's constructor?

A: The following will work:
public abstract class Foo
{
    protected Foo(int a, int b, int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public abstract void doStuff();
}

public class Bar : Foo
{
    public Bar(int a, int b, int c) : base(a, b, c)
    {
    }

    public override void doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public BarY(int a, int b, int c) : base(a, b, c)
    {
    }

    public override void doStuff()
    {
        //does stuff
    }
}

A: That's because BarY and BarX are calling a default constructor (base()) which doesn't exist in your base class when you only have a parameterised constructor.  You need to pass the arguments through as well (base(a, b, c)):
public abstract class Foo
{
    protected Foo(int a, int b, int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public abstract void doStuff();
}

public class Bar : Foo
{
    public BarX (int a, int b, int c) : base(a, b, c)
    {

    }

    public override void doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public Bar(int a, int b, int c) : base(a, b, c)
    {

    }

    public override void doStuff()
    {
        //does stuff
    }
}


text:
Q: Getting Started With SharePoint and InfoPath 2010 I am a .Net developer and I need to get started with SharePoint 2010 and InfoPath 2010 for a new project.
I believe I don't want too much SharePoint just the basic configuration and how to host an InfoPath form there. For InfoPath I need to know how to design forms and program it using VS2010.
I appreciate if you can provide me with some links/books to get started with SharePoint and InfoPath (with more emphasis on InfoPath development).
Edit
I really need some personalized advice instead of an entire website to surf. I will be totally lost like this.

A: As John alluded to - the path to learning really depends on your project needs.
My recommendation would be to learn InfoPath first. You don't need SharePoint and you don't even need Visual Studio to utilize the majority of InfoPath. You might be able to accomplish your goals right there without even delving into anything else.
If that is not enough start looking at the other things. You will need advanced programming (Visual Studio) if you are trying to customize the form experience for the user, adding functionality that is not available directly in InfoPath. Start looking down this path if you run into roadblocks with how you want your InfoPath form to work.
You will need SharePoint if you need a delivery mechanism, forms storage, tracking for the users. Start looking down this path if the forms start being complicated to manage on a file share (or if you need extra functionality like change tracking etc).
In general - start with Infopath and progress to the other things based on your needs. Programming is for the form (singular) experience, SharePoint is for the forms (plural) experience. Note also that they are not mutually exclusive - usually you end up needing both.


text:
Q: @react-three/drei Html element is not bubbling up the scroll event I have a <Html><svg /></Html> element in my react-three-fiber project. This element is grouped with the camera to keep element in front of the camera. When mouse pointer is on this element scroll i not working for ScrollControl and not scrolling. Is there a way to keep scrolling on the background ?

A: It is because your HTML elements didn't be in canvas.
You can do the following.
Add props 'fullpage' and 'zIndexRange={[-100, -2]}'
ex: <Html fullscreen zIndexRange={[-100, -2]}>
Then you can use your scrolling

A: I saw the answer at discourse threejs, but i could not find it right now, here is the solution for people here.
function App() {
    const html = useCallback((element) => {
        if (element) element.parentElement.style.pointerEvents = 'none';
    }, []);
    return (
        <Html ref={html} as="div" >
            Hello World
        </Html>
      )
}


text:
Q: Move Foo and Foo with ReSharper to matching files Code
I would like to use the ReSharper Move Types Into Matching Files functionality to move the code below which is written in a single .cs'. file:
public abstract class Foo
{

}

public abstract class Foo<T> : Foo
{

}

Executing the ReSharper refactoring causes this exception:

Can not move class Foo because there is another declaration that
  will be moved into file 'Foo.cs'.

Question
I can think of two outcomes of which either are ok by me:

*

*Move both Foo and Too<T> into Foo.cs

*Move Foo into Foo.cs and move Foo<T> into FooOfT.cs
So, the question remains:

*

*Is there another best naming practise that does not conflict with resharper?, or

*Is there a way to configure ReSharper to support this naming?

Note

*

*Because Generics are unique for each possible combination of constraints,  the Foo class is my interface class.  Therefore I won't rename Foo<T> to Bar<T>.

*I do not wish to rename Foo to FooBase as it is already an abstract class which makes the explicit 'Base' suffix redundant.

*I cannot refactor Foo to IFoo as Foo is my conceptual interface (because of a required basic implementation.

A: As far as I know, there is no way to tell Resharper to append the generic parameters of the filename. It will just use the class name, i.e. Foo, Foo<T> and Foo<A, B, C> all have Foo.cs as the filename, but - and that's the problem - ReSharper doesn't seem to know that this possibility exists and will show you an error in this scenario. Really nothing you can do about it except logging a bug or feature request.

A: You may consider these options:

*

*Use AbstractFoo

*Change Foo to an interface, if possible, and use IFoo

*Use GenericFoo

*Use different namespaces for Foo and Foo<T> and put them in different folders.


text:
Q: How do I continue a text over multiple SVG paths? (text behavior on paths) I would like to build a site where the text is not displayed in straight lines but on curved lines instead. I work with a single SVG path at the moment, that spans over multiple rows and put the text on that path with the textPath-element. I then scale the fontsize with JavaScript, to make it "responsive".
Here is what I have so far:

$(function() {
  var myFontsize = window.innerWidth * 0.015 + ((window.innerWidth - 1300) / -30);
  $( "text" ).css("font-size", myFontsize)
});

$( window ).resize(function() {
  var myFontsize = window.innerWidth * 0.015 + ((window.innerWidth - 1300) / -30);
  $( "text" ).css("font-size", myFontsize)
});
body {
    margin: 1vw;
}
path {
  fill: none;
}
#line-box {
  position: fixed;
  left: 1vw;
  top: 0;
  width: 101vw;
}
text {
  fill: black;
  font-size: 1.3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="line-box" viewBox="0 -30 1200 1200" preserveAspectRatio="none">
            <path vector-effect="non-scaling-stroke" id="curve" d="M0 0C449.6667 0 857 0 1160 0M0 35C292 35 584 35 876 55 953.6667 55 1031.3333 55 1160 35"/>
          <text text-anchor="start">
            <textPath xlink:href="#curve">
          Are you a human being? We apologize for the confusion, but we can't quite tell if you're a person or a script. Please don't take this personally. Bots and scripts can be remarkably lifelike these days!
                </textPath>
            </text>
        </svg>

(Change the width of the view box to see the behavior I am talking about)
Now the rendered text on the path of course doesn't behave like a text in a p-element for example, so where there is a "line-break" it wraps around the edges in the middle of the words (which are not words but single rendered letters).
I thought about putting each word into a tspan-element, thinking I could get a grip on each word this way, but the rows of text are put on one consecutive path, so I don't really know how to calculate or detect wether a word is leaving or entering a specific row of the path.
Is there a way to continue a text over multiple paths instead of having one path drawing multiple rows? Maybe this way it could be somehow calculated when a tspan-element is leaving a path and must enter the next?
I basically want the text and it's "line-breaks" to work similarly to a normal paragraph without hyphenation, just that the lines move on paths. That idea doesn't sound so complicated to me, but I don't really know what the best way is to make it work.
Maybe SVG-paths are just not the right tool for this. In that case, does anyone have a better Idea where I should look? I am not hesitant to look into some js-libraries for example.
Thank you so much :)

A: You'll definitely need Javascript to implement this. SVG is a relatively low-level format for describing vector graphics, not a text layout format. Responsive line breaks is a feature in the pipeline, but not fully implemented yet AFAIK. Responsive line breaks on text paths? That is far too specialised.

That idea doesn't sound so complicated to me

Well, it is for various reasons. Here is a somewhat naive implementation:

const nssvg = "http://www.w3.org/2000/svg";
const nsxlink = "http://www.w3.org/1999/xlink";

const text = document.querySelector('text');
const originalText = text.textContent.trim();

function nextCurve(curves) {
    const currentCurve = curves.shift();
    const currentLength = currentCurve.getTotalLength();

    return [currentCurve, currentLength, /\s+/g, 0];
}

function makeTextPath(content, id) {
    const textPath = document.createElementNS(nssvg, 'textPath');
    textPath.setAttributeNS(nsxlink, 'xlink:href', '#' + id);
    textPath.textContent = content;
    text.appendChild(textPath);
}

function onResize() {
    text.style.fontSize = (window.innerWidth * 0.015 + ((window.innerWidth - 1300) / -30)) + 'px';
    // flush old layout
    text.innerHTML = "";

    let currentText = originalText;
    // set text in a provisorial tspan so it can be measured
    const tspan = document.createElementNS(nssvg, 'tspan');
    tspan.textContent = currentText;
    text.appendChild(tspan);

    const curves = [...document.querySelectorAll('.curve')];
    let [currentCurve, currentLength, re, previousIndex] = nextCurve(curves);

    // search for spaces
    while (re.exec(currentText)) {
        // measure the position of the space
        const length = tspan.getSubStringLength(0, re.lastIndex)
        if ( (length < currentLength) ) {
            previousIndex = re.lastIndex;
        } else {
            // if the space is beyond the end, add a textPath with one word less,
            // provided there is still a curve left to use
            if (currentCurve) {
                makeTextPath(currentText.substring(0, previousIndex), currentCurve.id);
            }

            // remove the already used part from the tspan
            // and initialize for next line
            tspan.textContent = currentText = currentText.substring(previousIndex).trim();
            [currentCurve, currentLength, re, previousIndex] = nextCurve(curves);
        }
    }

    // there is a rest that still needs to be layed out
    if (currentCurve) {
        makeTextPath(currentText, currentCurve.id);
    }
    //the provisorial tspan can be removed now
    tspan.remove();
}

onResize();
window.addEventListener('resize', onResize);
#line-box {
  left: 1vw;
  width: 98vw;
}
text {
  text-anchor: start;
  fill: black;
  font-size: 1.3rem;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="line-box" viewBox="0 -30 1200 1200" preserveAspectRatio="none">
  <defs>
    <path class="curve" id="c1" d="M0 0C449.6667 0 857 0 1160 0"/>
    <path class="curve" id="c2" d="M0 35C292 35 584 35 876 55 953.6667 55 1031.3333 55 1160 35"/>
    <path class="curve" id="c3" d="M 0,70 C 292,70 584,90 876,110 953.67,110 1031.3,90 1160,70"/>
  </defs>
  <text>
    Are you a human being? We apologize for the confusion, but we can't quite tell if you're a person or a script. Please don't take this personally. Bots and scripts can be remarkably lifelike these days!
  </text>
</svg>

One simplification about this you mentioned yourself: the potential line breaks are found with the regular expression /\s+/g, which will identify various space characters. This is even less sophisticated than the algorithms used for line breaks in HTML (with the default hyphens: none).
The big problem is identifying what is fitting on the path used in <textPath>. There are a few interfaces defined for SVGTextContentElement that look like they could be helpful. But in practice, they fall short. The algorithm for describing how to position glyphs is quite longish, but it doesn't say much about glyphs that cannot be positioned:

*

*Glyphs whose midpoint-on-the-path are off the path are not rendered.

*Continue rendering glyphs until there are no more glyphs (or no more space on path).

Suppose the nth character is not rendered. The quote above doesn't say anything about the return values of textPath.getSubStringLength(0, n) or textPath.getStartPositionOfChar(n). Firefox, for example, returns values as if they were all lumped up somewhere near the end of the path. Other browsers may return something completely different, there is no guarantee what.
I decided to circumvent this problem by first laying out the string in a straight line, then measuring where the spaces end up, and break at the last space whose position is still smaller than the length of the path it will be laid out with. But this is only a rough estimate. In reality the character spacing differs between straight and curved layout. Especially for narrow curves the results will be wrong, and when the text is positioned on its inside, some letters may disappear.
Another problem arises from the concept of "addressable characters" used for producing character indices in SVG:

A character that is addressable by text positioning attributes and SVG DOM text methods. Characters discarded during layout such as collapsed white space characters are not addressable, neither are characters within an element with a value of none for the display property. Addressable characters are addressed by their index measured in UTF-16 code units (thus, a single Unicode code point above U+FFFF will map to two addressable characters as a UTF-16 code unit consists of 16 bits).

If you have a string as returned from the textContent property, and apply methods of the Javascript String prototype, the same indices may point to completely different characters.
To completely solve both problems, a lot more code will be needed, and all the special cases to be considered are quite beyond the scope of this answer. Maybe there is a library out there somewhere that attempts this, but I am not aware of it.


text:
Q: Package version and AssemblyInfo version I'd like to ask, what is the difference between package version and assemblyinfo version? Should it be the same? So if version in package.manifest is 2.0.5, so assemblyinfo version should be the same?
Thank you

A: AssemblyInfo works just for assembly - exe or dlls inside the appx.
Package version is used to identify version of the packaged app (appx). It's used when you update the app - the new version have to be higher in order to be able to update the application.
These two versions are completely unrelated and you don't need to set AssemblyInfo attributes according to package manifest.


text:
Q: relationship between entities in c#, necessary? Regarding the topic, some entities have multiplicity relationship
I learned all of these in my studies, however, is it necessary to maintain in c# programming such as using Entity framework in this example ? :
http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-1
this is because I am confused on how the updating of entities works, such as cascading and why it's important.
I find it easier to just code the entity being independent with each other despite the fact they are actually related in real life such as category-product.
can anyone briefly show how CRUD works with this relationship in questions?

A: Entity Framework with its entities and their associations between each others gives you the advantage that the framework itself - the OR - Mapper - takes care of all the updates, deletes and inserts for you. It takes care of maintaining the relationships between the entities and the entities itself. You 'just' need to define the model.
You can always go the manual road and code all that yourself. But in most cases defining the entities with their properties and relations between them and having Entity Framework or any other OR-Mapper (like nHibernater) take care of all that, is a huge plus in terms of development speed, maintainability and consistency.
If you define your entities separate from each other - with other words, you do not work with associations between them - you can not navigate from one object to the other. See the example:
Example a) with associations defined:
2 entities: order and orderitem
One order can have up to n order items. You can traverse/navigate from the specific order to all associated order items, e.g.
var myOrder = Repository.FindOrderById(15);
var orderItems = myorder.OrderItems;

Example b) without associations defined:
2 entities: order and orderitem
Without associations defined, you can not navigate from one entity to another. You would need to query for all order items separately, e.g.
var myOrder = Respository.FindOrderById(15);
var orderItems = Repository.FindOrderItemsByOrder(15);

This is not saying how the entities are loaded. In example b, to query the order and the related order items, the OR-Mapper executes 2 queries against the database. In example a, you could define whether to lazy load the entities in 2 queries or to eager load in 1 query. Having defined associations give you the option to choose whether to load related entities eagerly or lazy.
This is a good starting point for Entity Framework in general:
http://msdn.microsoft.com/en-us/library/bb386876.aspx
That is a good overview how relationships between entities work and what options you have:
http://msdn.microsoft.com/en-us/library/ee373856.aspx


text:
Q: Kerberos authentication stops after the AS-REP stage I'm running a Tomcat 8 web server. I wanted to force the users to use Kerberos SSO authentication. so I disabled all NTLM communication on the server.
On my debug environment, everything runs smoothly using this guide.
When moving to my production, using a different domain and server, the authentication fails.
While comparing the wireshark results on clients of the two environments, I noticed that successfully connecting to the server contains the following packets:
HTTP GET (client -> sever)
HTTP 401 Unauthorized (server -> client) (WW-Authenticate: Negotiate)
AS-REQ (client -> DC)
KRB Error: KRB5KDC_ERR_PREAUTH_REQUIRED (DC -> client) (I understand that this is normal?)
AS-REQ (client -> DC)
AS-REP (DC -> client)
TGS-REQ (client -> DC)
TGS-REP (DC -> client)

On my production environment, using similar client-side and server-side configurations (as far as I know), the client stops after the AS-REP packet, and instead of requesting a ticket with a TGS-REQ packet, immediately sending a HTTP GET NTLMSSP_NEGOTIATE packet
I can't find the reason for this to happen. I've compared the similar packets between the two clients and I can't find any differences. It looks like the client just gives up after receiving the AS-REP from the server and instead of requesting a kerberos ticket, just decides to use NTLM authentication.
I turned on kerberos logging and I receive no errors, and there are no packets between the AS-REP and the NTLM request (except for a TCP FIN packet to the DC)
Does anyone know what could cause such a problem? I've been looking everywhere and can't seem to find much information about this issue.

A: KRB Error: KRB5KDC_ERR_PREAUTH_REQUIRED (DC -> client) - this is normal. It's because preauthentication is turned on, by default, to increase security. Client first sends AS-REQ without preauth, and if such request is rejected, sends AS-REQ again, with preauth.
When you're modifying configuration, for example to troubleshoot Kerberos issues, remember to always clean Kerberos cache before running another test. Otherwise you'll be frustrated that you're changing configuration, but can't see effects - all because cached Kerberos tickets will be used. You can use KerbTray to purge cache.
Why NTLM? Because AD can't find user with requested SPN. For http servers it should look like: HTTP/@REALM. AD must find exactly one user, because it needs his/her password to generate TGS.


text:
Q: Linux bash, getting getopt default parameters I'm trying to write a moderately difficult bash program, but somehow I cannot parse command line parameters and set default parameters with getopt.
Getopt is somehow ignoring optional parameters, setting them after the --, which denotes end of parameters.
Simple test, where l(list) is required:
getopt -s bash -o l: -l list: -- -l test

Produces:
-l 'test' --
If I were to define l(list) as optional, then output is:
getopt -s bash -o l:: -l list:: -- -l test
-l '' -- 'test'
I used this example as a base, but as of my testing, even this script does not work as intended(setting arga value to something produces always default value).
OS: Linux, getopt -V=getopt from util-linux 2.27
Any help appreciated :)

A: Check the man page:

A simple short option is a '-' followed by a short option character.  If the option has  a  required
         argument, it may be written directly after the option character or as the next parameter (i.e. separated by whitespace on the command line).  If the option has an optional argument, it must be  written directly after the option character if present.

So you want
$ getopt -s bash -o l:: -l list:: -- -ltest
 -l 'test' --

Similarly, for optional long args, you must provide the argument in a specific way:
required
$ getopt -s bash -o l: -l list: -- --list foo
 --list 'foo' --
$ getopt -s bash -o l: -l list: -- --list=foo
 --list 'foo' --

optional
$ getopt -s bash -o l:: -l list:: -- --list foo
 --list '' -- 'foo'
$ getopt -s bash -o l:: -l list:: -- --list=foo
 --list 'foo' --


text:
Q: Phonegap iOS app using PHP and MySQL. How to setup? Right now I'm building my first iOS app using Phonegap. This is because I wanna use PHP and MySQL databases. I got started and it kind of works.
But now, I got a really basic question...
Is it possible to just use the jQuery function .load() to load the first page of a PHP-application, that is located on my web server, and then use and post go thru a login process. I tried, and it seems to be working.
But I imagine there will be a lot of downsides?
Like, would I be able to access the deviceid and geolocation plugins?

A: Yes, if you develop your application using PhoneGap as a wrapper you can be able to access a wide range of device features such as camera, accelerometer, geolocation etc. PhoneGap comes with JavaScript module that you can use to query device features and use them.


text:
Q: Hide a file extension by editing the file name in High Sierra Before upgrading to High Sierra (i.e. when using Yosemite/El Capitan/Sierra) I constantly hid file extensions by hitting enter and manually removing the file extension from the file name. After upgrading to High Sierra, I noticed this no longer applies. Instead, I have to go to the file info via cmd+I and manually check Hide extension.
As for Finder preferences, Show all filename extensions is de-selected.
How can I restore the previous behavior, which is very comfortable to me?

A: As others have commented, you weren't hiding the file extensions, you were deleting them from the file name itself.  This will impact how the file functions.  But, if you haven't had a problem so far, great.  Just avoid doing it from now on.
As you've noticed, there is an option in the information pane to hide the extension.  Oddly, I can't explain why you've only noticed this now.  It has been there in earlier versions for quite some time.
The only way I'm aware of to get rid of file extensions is to make sure the Finder Preferences option you mentioned is unchecked, then batch select all the files of concern to you and hit ⌘+Alt+I to bring up a single information pane summarising all the selected files.  The checkbox to hide extensions can be checked and it will be applied to all files in your selection.
With the global preference set not to show file extensions, my feeling is that new files created will, by default, not have their extension visible.


text:
Q: Динамическое количество параметров запроса в БД Java JPA сама задача состоит в том что есть некий реквест с динамическим кол-вом параметров (/search?param=1&param=2&param=3.....)
ловлю это все через
@RequestParam(value = "param", required = false) List<Integer> paramList)

как мне построить запрос к БД через JPA, в котором должно быть динамическое количество AND в WHERE (допустим select * from t WHERE i.column=q AND i.column=w .... )?
под запросом через JPA имею ввиду
@Query("select....)
public List<Object> findAllBy(@Param);

я использую CrudRepository\JPARepository с хибернейтом

A: Конкретно в указанном случае можно воспользоваться конструкций in. Т.е.
@Query("select o from Obj o where o.col in (:list)")
public List<Object> findAllBy(@Param("list") List<Object> list);

Единственное учти, что входной List должен быть не пустой.


text:
Q: Scroll lateral en Wordpress Tengo un problema, en ciertas páginas me aparece un scroll horizontal que no logro arreglar ni comprender...
https://metalsystem.site/mesas-elevadoras/extraplanas/
Alguien me podría ayudar por favor...!?

A: Por si te sirve de ayuda, añadiendo lo siguiente al selector se soluciona:
.elementor-10
.elementor-element.elementor-element-f56c695
.elementskit-navbar-nav-default
.elementskit-dropdown {
      max-width: 100%;
}

Esto es provocado por el submenú productos.
Un saludo


text:
Q: mysql delete row if all null after update without trigger For a certain table, if a field is updated to Null and all fields for that row are now Null I want to delete this row. I understand this can be done with a trigger, but I have heard that triggers should be avoided whenever possible. Is there another solution to this which avoids triggers, and has lower cost? How expensive would a trigger even be in this case (is it less expensive than running two queries?)

A: You have three options:

*

*Put in  a DELETE FROM TABLE WHERE FIELD ==NULL after every update.

*Use a trigger

*Centralize all updates through a stored procedure so that you can call the SP when you update the record, which can then call the DELETE FROM command in #1.

A: Triggers should not be avoided wherever possible.  They should just be used with discretion.
First, in many systems that I've been involved with, all the DML operations are embedded in stored procedures.  Basically, anything a trigger would do is in the stored procedure -- along with other functionality such as logging.
Second, if you have a problem that requires a trigger, then use a trigger.  For instance, prior to Oracle 12C, you needed a trigger to add an auto-incrementing primary key.  By all means do it, if that is what you need.
Don't go overboard.  But your particular problem seems like an example where a trigger could be quite useful.
Do realize that there might be other solutions.  For instance, perhaps a view would do what you want:
create view v_t as
    select t.*
    from t
    where col1 is not null or col2 is not null or . . .;

This would save all the overhead of the trigger.  If the table got too big, you could delete the all-NULL rows using a scheduled job.


text:
Q: Hyper-V required for testing Windows Phone 8 App on actual device Is Hyper-V still required for testing a WP8 app when you test on actual device?

A: No, you do not need Hyper-V to test on a physical device.


text:
Q: Determine if a Type implements an interface I've created an interface within a managed package that installers can implement (much like the example here and Making your managed package extensible with Apex Plugins). Clients can then configure their class name in a custom setting and I invoke it as required.
Given just the class name as a string, how can I determine if the class it represents implements my interface?
Do I need to construct an instance from the Type so I can use instanceOf?
string className = 'someCustomClientClass';
Type t = Type.forName(className);
object testInstance = t.newInstance();
System.assert(testInstance instanceOf SomeClass.SomeInterface);

I guess this will work (with some additional checks that the type actually exists), but I'd prefer to just rely on the Type object rather than creating an instance and invoking whatever their constructor does.

A: Unlike Java, where the "Class" can be constructed and checked for inheritance, the Type in Apex is fairly limited. One of the few operations it permits is instantiation as an Object of the Type.
The instanceof operator applies only to Object Instances, which would imply that the Type will have to be instantiated to check for inheritance.
(An alternative to instanceof might be attempting to cast it to the interface and handling the 'CastException')
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_type.htm
Whilst I understand your intention to avoid loading any expensive construction logic, I'm guessing you will have to construct the classes for purposes of the actual callback.

A: As of the Spring `22 release there is now the ApexTypeImplementor available via SOQL - Find Which Apex Classes Implement an Interface.
A SOQL query can be used to find/verify that a given class implements a given interface.
List<ApexTypeImplementor> interfaceImpls = [
        SELECT ClassName, ClassNamespacePrefix
        FROM ApexTypeImplementor
        WHERE InterfaceName = 'SomeInterface' and IsConcrete=true];

The Winter '20 release will include the new System.Type.isAssignableFrom(sourceType) method.
This avoids the need to create an actual instance of a class type to determine if it is assignable to another type.
E.g.
string className = 'someCustomClientClass';
Type t = Type.forName(className);

System.assert(SomeClass.SomeInterface.class.isAssignableFrom(t);


text:
Q: IPC: 32 bit process trigger 64 bit process (windows) Environment:
Two processes: one 32 bit and the other 64 bit (Both C++ native, VS2013)
Question:
What is the best way to trigger the 64 bit process to execute functions (including function arguments) by the 32 bit process?


text:
Q: YouTube not working on Ubuntu 11.10 I have just installed Ubuntu 11.10 on my computer, and recently applied all the latest updates. As invariably happens when I do this, YouTube videos have stopped working in Mozilla Firefox. Displaying their web page shows a black box where the video should be.
The version of Mozilla I am running is 10.0.2. Does anyone know how to get these things to work. I have consulted the answer to my previous question on the subject here but to no avail.
Does anyone know how to get these things working again?

A: You will need to install flash on each browser.  You can get around this for youtube videos however, by switching youtube to use html5 video.
Enable HTML5 for youtube here : http://youtube.com/html5

A: I have a similar issue.  I could figure out these solutions. The main problem is a Javascript call – one of those that Google uses to track you your preferences.
Delete your Cookies
What worked for me (and I'm not proud of it but just worked) is to delete my session cookies (accessing YouTube without being logged into my Google account). This means that you are not going to be able to check your Gmail account or anything related to your Google account.
Use the Incognito Window
You can use the Incognito mode to watch YouTube videos (an incognito window is opened pressing Ctrl+Alt+N when using Chrome).


text:
Q: Merge Columns with different number of rows into one data frame in R I am trying to dynamically find the number of columns which is imported from an excel sheet and add that to another data frame. But this has to be done dynamically and the numbers of rows in both data frame will be different so cbind() is not working. I am not able to do that. Can someone help me understand, what is it that I am doing wrong.
The data frame I am working with is given below:
dput(Book1)
structure(list(`Row Labels` = structure(c(1667260800, 1669852800,
1672531200, 1675209600, 1677628800, 1680307200, 1682899200, 1685577600,
1688169600), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    X1 = c(1, 2, 2, 3, 3, 4, 4, 5, 5), X2 = c(2, 3, 2, 3, 2,
    3, 2, 3, 2), X3 = c(3, 4, 3, 4, 3, 4, 3, 4, 3)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -9L))
dput(Book2)
structure(list(`Row Labels` = structure(c(1667260800, 1669852800,
1672531200, 1675209600, 1677628800), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), X6 = c(1, 1, 1, 1, 1), X7 = c(1, 1, 1, 1,
1), X8 = c(1, 1, 1, 1, 1), X9 = c(1, 1, 1, 1, 1)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -5L))

The code which I have written is:
library(readxl)
Book1 <- read_excel("C:/X/X/X/X/Book1.xlsx",sheet = "Sheet1")
View(Book1)
Book2 <- read_excel("C:/X/X/X/X/Book1.xlsx",sheet = "Sheet2")

dput(Book1)
dput(Book2)
ncol(Book2)
colnames(Book2)

cbind(Book1,Book2)

The Expected Output is:

The Error I am getting while using cbind is :

A: You can use full_join
> Book1 %>%
+   full_join(Book2, by = "Row Labels")
# A tibble: 9 × 8
  `Row Labels`           X1    X2    X3    X6    X7    X8    X9
  <dttm>              <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2022-11-01 00:00:00     1     2     3     1     1     1     1
2 2022-12-01 00:00:00     2     3     4     1     1     1     1
3 2023-01-01 00:00:00     2     2     3     1     1     1     1
4 2023-02-01 00:00:00     3     3     4     1     1     1     1
5 2023-03-01 00:00:00     3     2     3     1     1     1     1
6 2023-04-01 00:00:00     4     3     4    NA    NA    NA    NA
7 2023-05-01 00:00:00     4     2     3    NA    NA    NA    NA
8 2023-06-01 00:00:00     5     3     4    NA    NA    NA    NA
9 2023-07-01 00:00:00     5     2     3    NA    NA    NA    NA


text:
Q: VueJS without history mode in Router In this article (Vue.js - How to remove hashbang #! from url?), teach how to remove # from URL.
I'm making an application that need to have # in URL, but when I access a route for the first time, don't load (or don't change the content), but if I refresh, the page load successfully.
EDIT1: I forgot to share my Vue Router.
import Vue from 'vue'
import Router from 'vue-router'
//import axios from 'axios'

import ListComponent from '../pages/ListComponent'
import Formulario from '../pages/Formulario'

const BASE_URL = process.env.VUE_APP_FRONT_SET_URL;
console.log(BASE_URL);

Vue.use(Router)

export default new Router({
       mode: 'hash',
    routes:[

        {
            path: '/formulario',
            name: 'formulario',
            component: Formulario
        },

         {
            path: '/:nr_atendimento' ,
            name: 'list',
            component: ListComponent
        },
    ]
})

And no. console don't show any errors.


text:
Q: android linespacing not working I have customized list view which contains Text view with custom Arabic font.
I tried to set Line spacing using below code:
 qArabic.setLineSpacing(25, (float)2);

above code sets line spacing only for first line, from second line onward line    spacing not working.

A: There was issue with font, I edited font metric details using fontforge,
Here is the link how to edit font line space details
http://www.mobileread.com/forums/showthread.php?t=22374


text:
Q: How to use ::v-slotted in scss if I write following code everything works fine:
::v-slotted(.title) {
  margin-top: 0;
}
::v-slotted(.title_icon) {
    position: relative;
    left: 5px;
    top: 20px;
  }
}

But I want to use scss syntax.
If I write the following it throws an error:
::v-slotted(.title) {
  margin-top: 0;

  &_icon {
    position: relative;
    left: 5px;
    top: 20px;
  }
}

If I write it like this it doesn't throw an error but it does nothing:
::v-slotted(.title) {
  margin-top: 0;

  ::v-slotted(&_icon) {
    position: relative;
    left: 5px;
    top: 20px;
  }
}

What is the correct syntax?


text:
Q: Why does X509Certificate2 sometimes fail to create from a blob? I have an ASP.NET web service which is receiving a byte array representing the contents of a .pfx file containing an X.509 certificate.  The server-side code is using the System.Security.Cryptography.X509Certificate2 constructor to load the certificate from the bytes:
X509Certificate2 native_cert = new X509Certificate2(
                pkcs12_buf /*byte array*/,
                password,
                X509KeyStorageFlags.PersistKeySet |
                X509KeyStorageFlags.Exportable
            );

Depending on who my service process is running as, this call will either succeed, or fail with an "internal error" exception.  The last call on the exception stack is to X509Utils._LoadCertFromBlob, which is unmanaged code in mscore.dll.
This code succeeds when run from a console application in an interactive login using the service account's credentials.  It fails when running under w3wp.exe in an application pool that uses the service account's credentials.  Changing the app pool identity to an administrator fixes the problem, so it must be a privilege issue, but I have no idea what privilege could be necessary for this.  The code does not touch either the filesystem or the Windows certificate stores.
[UPDATE: More Info]
This error appears in the Windows Event Log:
*Cryptographic Parameters:*
**Provider Name:**  Microsoft Software Key Storage Provider
**Algorithm Name:** Not Available.
**Key Name:**   {E182E13B-166D-472A-A24A-CBEF0808E9ED}
    **Key Type:**   User key.

*Cryptographic Operation:*
**Operation:**  Open Key.
    **Return Code:**    0x2

Any ideas?

A: I just found the solution to this one myself:
X509KeyStorageFlags flags = X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet;

X509Certificate2 cert = new X509Certificate2(pkcs12_buf, password, flags);

The trick here is to use the local key store MachineKeySet flag instead of the user profile key store, which is the default if you don't specify an alternative location. Because the ASP.NET process identity doesn't load the user profile store, you can't access the store when importing a certificate programmatically, but you can access the machine store.
I think PersistKeySet just keeps the private key loaded, but I'm not sure exactly what it does - it's required if you need to access the private key for some reason though.

A: Try granting the ASP.NET account permissions to the following folder: C:\Documents And Settings\All Users\Microsoft\Crypto\RSA\MachineKeys\ (may vary according to your environment)


text:
Q: Azure deployment cfn-signal equivalent? I am utilizing cloud-init for my deployments both in AWS and Azure.
In AWS I can signal success/failure using cfn-signal to my CloudFormation stack. In Azure I have not found anything similar.
Example cloud-init:
#cloud-config
write_files:
  - path: /etc/my_script.sh
    permissions: '0775'
    content: |
      #!/bin/bash
      set -Eeuo pipefail

      trap error_report ERR

      error_report() {
        # Some error reporting stuff, including
        cloud-init collect-logs
        # Send them somewhere
        # cfn-signal -e 1 # Present in AWS-version only
      }

      echo 'This is a successful command'
      # some other commands that might fail
      cfn-signal -e 0     # Present in AWS-version only
runcmd:
  - [ bash, /etc/my_script.sh ]

I've read that failing runcmd does not fail the whole cloud-init configuration. I am missing the piece where I can somehow signal the deployment either a success or failure. Failure would be enough, really.
Any help is greatly appreciated. Thanks in advance.


text:
Q: laptop internal Keyboard disable My laptop's F1 key is being activated automatically , in prev version of ubuntu 16.** , I used to disable the internal keyboard by using
{xinput list
[get id of At translated keyboard 2   id=14]
xinput float 14}
But in the present version 17.10
'xinput list' doesn't list At translated keyboard 2
What should I do to disable the internal keyboard?


text:
Q: Can non-templated nested classes of class templates be implemented in a C++ header? Suppose a header file myheader.hxx defines a class template A in which a non-templated class B is defined (that does not depend on the template parameter of A):
template<class T>
class A {
    class B {
        // ...
    };
};

Is it okay in this case to implement B in myheader.hxx, or do I need to write a separate myheader.cxx to avoid duplicate definitions at link time? Is this case handeled consistently by different compilers?

A: It's still either a template (or part of template, don't know the ultra-precise definitions) even if it's not the top-level template, so you need to should implement it in the header (technically, it can be in a source file if that's the only place it's used, but that probably defeats the purpose).
Note: if you're not going to implement its member functions inline with the class definition, you need syntax like:
template<typename T>
void A<T>::B::foo(...)
{
    // ...
}

Also, because it's come up before, if B happened to have its own template parameter, it would be something like:
template<typename T>
template<typename T2>
void A<T>::B<T2>::foo(...)
{
    // ...
}

Not:
template<typename T, typename T2>
void A<T>::B<T2>::foo(...)
{
    // ...
}

Or if B didn't but B::foo did, it would be:
template<typename T>
template<typename T2>
// void A<T>::B::foo<T2>(...) // not this apparently
void A<T>::B::foo(...)
{
    // ...
}

EDIT: apparently it's foo above instead of foo<T2> for a function, at least with GCC (so almost 100% sure that's standard behavior)...I'm sure some language lawyer will be able to explain why :)
Etc.


text:
Q: Find the special function form of $\int_0^{+\infty} \left(\sqrt{1+x^4} - x^2\right) dx$ I'd like to have an expression of the following integral:
$$\int_0^{+\infty} \left(\sqrt{1+x^4} - x^2\right) dx$$
in terms of some special functions (but not in the form given by Wolfram Alpha).

A: The simplified answer seems to be :
$$\frac 23K\left(\frac 1{\sqrt{2}}\right)$$
This means $\frac 23K\left(\frac 12\right)$ using Alpha's convention with a rather interesting alternate form :
\begin{align}
\frac{\Gamma\bigl(\frac 14\bigr)^2}{6\;\sqrt{\pi}}&=\frac{\Gamma\bigl(\frac 14\bigr)^2}{6\;\Gamma\bigl(\frac 12\bigr)}\\
&=\frac 16 B\left(\frac 14,\frac 14\right)\\
&=\frac 13 \int_0^\infty \frac {t^{1/4-1}}{\sqrt{1+t}}\;dt\\
\end{align}
with $B(x,y)$ the Euler integral of the first kind ('beta function') and using the DLMF classical relation $(5.12.3)$. Setting $x:=t^{1/4}$ should bring you nearer to the initial question...
As noted by O.L. the rewriting of the elliptic integral $K(z)$ in terms of $\Gamma$ function is due to $z=\frac 1{\sqrt{2}}$ being one of the singular values of the elliptic integral. It is in fact the first one (see equation $(11)$ here). Your specific case appears in page $3$ of the original article of Chowla and Selberg.


text:
Q: function of this code in matlab R(:,P>.6/2)=0; I am reading a matlab code find have some difficulties in figuring it. the problems is that: R is a 4X5X6 matrix and P is a 5X6 matrix. what's the function of this line R(:,P>.6/2)=0?
it seems that this line will change some elements to zeros, but I do not understand the judgement basis and the relationship between R and P.
thanks a lot

A: It first gets all the elements of P that satisfies the condition P>0.3. The result is used to index the R array, more particularly the second and third dimension.
To give you a concrete exemple, everytime there is a value over 0.3 at position (i, j) then all the R(k, i, j) (with k taking all the possible values) are set to 0.
Best,


text:
Q: Creating loading messages with swfobject I am loading a flash file via swfobject. As the file is large, I want to show a "please wait while loading" message while the flash is loading.
How can I do it with swfobject.

A: You can use a small preloader SWF that triggers a loading-please-wait animation and then loads the real SWF in the background. There are lots of free preloaders on the web.


text:
Q: Магия с Bootstrap? WordPress
После подключение последней версии Bootstrap пропадает меню, но на мобильной версии есть. Само меню подтягивается через шаблон. Если отключить Bootstrap - то меню есть.
P.S. Меню вверху справа
Сайт с траблом:

 www.adv-aura.pro

#site-navigation-wrap {
    font-family: "Helvetica Neue",Helvetica,Arial;
    height: 40px;
    margin-top: -20px;
    position: absolute;
    right: 0;
    top: 50%;
}

 Menu

Головна

Послуги

SEO

Контекстна реклама

SMM

Статистика

Контакти

A: Bootstrap своими стилями к класу dropdown-menu зачеркнул мои стили. Поправил классы - все ок.


text:
Q: How to check values in database on breakpoint during phpunit testing Background
I'm currently debugging some old unit tests in my code base, and I found a failing unit test at this point:
    $this->seeInDatabase('table', [
        'amount'   => //some value,
    ]);

in my phpunit.xml I'm running the tests against my testing env:
<php>
    <env name="APP_ENV" value="testing"/>

Question
I would like to check the value that's actually stored on the database in my unittest environment. However, when I put a break point right before the seeInDatabase line, nothing appears at all in the database (the same happens when I try to run tinker like so:
php artisan tinker --env=testing

ideas?


text:
Q: making php value numeric I used some of this code from this page on Stack Overflow:
Using wp_query is it possible to orderby taxonomy?
It's about the function to be able to sort a query by a taxonomy value. Although it works perfectly, I would want to go one step further.
The value I retrieve from the taxonomy term is a number. If I sort by that number, however, it gives this order: 1 10 11 2 21 22 and so on.
I want it to be sorted 'normally', 1 2 3 5 9 11 15 21 22 etc.
According to google I should add 0 to the value to make it a numeric value, but I don't know where to put it in this code. Somewhere, it should say value + 0. Any idea where I should put it?
It's about this code:
function orderby_tax_clauses( $clauses, $wp_query ) {
    global $wpdb;
    $taxonomies = get_taxonomies();
    foreach ($taxonomies as $taxonomy) {
        if ( isset( $wp_query->query['orderby'] ) && $taxonomy == $wp_query->query['orderby'] ) {
            $clauses['join'] .=<<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;
            $clauses['where'] .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)";
            $clauses['groupby'] = "object_id";
            $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
            $clauses['orderby'] .= ( 'DESC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
        }
    }
    return $clauses;
}

    add_filter('posts_clauses', 'orderby_tax_clauses', 10, 2 );

A: Your question is more about SQL than WordPress.
If you want to sort your term names as numbers, you can in general try
SELECT * FROM wp_terms ORDER BY name+0 ASC

or
SELECT * FROM wp_terms ORDER BY name*1 ASC

or use CAST:
SELECT * FROM wp_terms ORDER BY CAST(name AS SIGNED) ASC

where you can use SIGNED, UNSIGNED or maybe DECIMAL(10,2), just depending on your numbers.
Update
To test the ordering you can then visit your PHPMyAdmin and run this query:
SELECT  tool_terms.name AS tname, tool_posts.* FROM tool_posts
LEFT OUTER JOIN tool_term_relationships ON tool_posts.ID=tool_term_relationships.object_id
LEFT OUTER JOIN tool_term_taxonomy USING (term_taxonomy_id)
LEFT OUTER JOIN tool_terms USING (term_id)
WHERE 1=1
AND tool_posts.post_type = 'landschapselement'
AND (tool_posts.post_status = 'publish' OR tool_posts.post_status = 'draft' OR tool_posts.post_status = 'pending' OR tool_posts.post_status = 'private')
AND (taxonomy = 'beheerseenheidnummer' OR taxonomy IS NULL)
GROUP BY object_id
ORDER BY tool_terms.name+0 ASC, tool_posts.post_title ASC

to see if it works where I replaced
ORDER BY GROUP_CONCAT(tool_terms.name ORDER BY name ASC) ASC

with
ORDER BY tool_terms.name+0 ASC, tool_posts.post_title ASC

where we order the posts by the taxonomy numeric value, and then the second order is on the post title. I also added the field tool_terms.name AS tname to the SELECT part. This works on my install.
You can also try to replace
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
$clauses['orderby'] .= ( 'DESC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';

with:
$clauses['orderby'] = " {$wpdb->terms}.name+0 ";
$clauses['orderby'] .= ( 'DESC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
$clauses['orderby'] = ", {$wpdb->posts}.post_title ASC ";

A: Try to make your query look like this one:
"SELECT *,
CASE WHEN ASCII(RIGHT(`%column_name%`, 1)) > 47 AND ASCII(RIGHT(`%column_name%`, 1)) < 58
THEN LPAD(CONCAT(`%column_name%`,  '-'), 5, '0')
ELSE LPAD(`%column_name%`, 5, '0') END AS `vsort`
FROM `%table_name%` ORDER BY `vsort`;"

From this webpage

Note: you'll want to replace %column_name% with the ACTUAL column name, and %table_name% with the actual table name.

The result would be like one after PHP's natsort() function.


text:
Q: Generating SSH-Keys for Git on Windows 7 I'm experiencing a strange error while attempting to generate SSH keys via the Git Bash command line tool as downloaded from (http://code.google.com/p/msysgit/downloads/list). I'm using Windows 7 Enterprise and have full administrative privileges. When I run the following command from the Git Bash command line:
 ssh-keygen -t rsa -C "your_email@youremail.com"

(using my email address in place of your_email@youremail.com) I get a Windows error dialog box that pops up with the title

ssh-keygen.exe - Application Error
  The application was unable to start correctly (0xc0000142). Click OK to close the application.

Any ideas what may be causing this error?
Things I have tried to fix the problem (without success):

*

*Installing an earlier version of Git for Windows (I've tried 1.7.7, 1.7.6, 1.7.4 and 1.7.3).

*Running Git in compatibility mode.

*Searched the net for others experiencing the same error in relation to Git on Windows.

What might be causing this problem?
UPDATE: Despite not actually determining what was causing this error, I got around it by simply using Putty to log into a friends Linux box and generating the SSH keys from there. Thanks for everyone's help.

A: This developer discussion might be relevant. Maybe you could try an earlier version, as even 1.7.6 was released after those changes were added. Version 1.7.4 would be earlier.
If that version works, you should report a bug on the msysGit mailing list. And if you find no help here, asking there would be a good idea anyway.


text:
Q: Calculating coordinates with postscript I want to calculate coordinates for some lines using pstricks. How can I do this?
Example:
I want something like
(0.5*cos(45) + 8, 0.5*sin(45) + 8)

and use coordinate pairs like this one to draw lines in between.

A: It isn't clear if you want to do the calculation in TeX or PostScript, in PostScript that would be
0.5 45 cos mul 8 add 0.5 45 sin mul 8 add

as you can check by typing to gs (or any other PostScript interpreter):
GS>0.5 45 cos mul 8 add 0.5 45 sin mul 8 add pstack
8.35355377
8.35355377
GS<2>


text:
Q: Angular ui-router not loading external content on state change I have started building a website using Angular, and have started to use ui-router along with ngAnimation for some sick animations! All was going well until I started adding external resources such as Facebook's Page Widget (https://developers.facebook.com/docs/plugins/page-plugin) and Google Maps API for some custom map styles.
The Issue
I have the Facebook widget on the home page, and it loads fine when you first access the URL as can be seen below (Have to block the name of client, totally not just bad design...):

Once I click on another page to load it in (using ui-view to dynamically bring in a view), for example contact view and go back to the home page (where the code is to display the widget), the widget will no longer load but will load the basic header tag that Facebook provide as can be seen below:

This also happens on the contact page when loading in Google Maps API. If I click on the contact page, there will just be a large white area on where the map should be, but if you had to actually refresh the page the map will load.
I am assuming that the issue is that the website is not able to send a request to either Facebook or Google when a view is loaded in, but can only happen when the page is actually refreshed or a new page load.
My Code
Okay so I'll explain the basics of how my application works along with code. I am rather new with Angular so if I have terrible code, please let me know.
Structure
This is a screen shot of my web apps structure. The main template file is index.html, and any view are within the views directory, which are loaded in using ui-router.

Main Angular applications code (app.js)
var app = angular.module('bmApp', ['ngAnimate', 'ui.router', 'ui.bootstrap'])
.config(function($stateProvider, $urlRouterProvider) {

$stateProvider
    .state('header', {
        templateUrl: './assets/views/template.html',
    })
    .state('header.home', {
        url: '/',
        templateUrl: './assets/views/home.html',
        controller: "HomeController"
    })
    .state('header.about', {
        url: '/about',
        templateUrl: './assets/views/about.html',
        controller: "AboutController"
    })
    .state('header.work', {
        url: '/work',
        templateUrl: './assets/views/work.html',
        controller: "WorkController"
    })
    .state('header.services', {
        url: '/services',
        templateUrl: './assets/views/services.html',
        controller: "ServicesController"
    })
    .state('header.contact', {
        url: '/contact',
        templateUrl: './assets/views/contact.html',
        controller: "ContactController"
    });
    $urlRouterProvider.otherwise('/'); //if no views are matched, just redirect back to home page.
})

I am using nested views to keep the header of the website static (not changing) and then loading in views under the header, with ngAnimate to make it look cool.
In my main template, index.html, I have a simple

 to load in the view that is requested. I also have the required script to request Facebook's API just after the . My controllers do not actually currently have anything in them. I did have some vanilla JavaScript in some, but do not currently need it anymore. I also tried to wrap the code provided by Facebook in a function, and call it within the controller for the specific view but that just had the same results of having it within the body on the template (index.html) page.
Pulling my hair out at this, can't seem to find a solution. I hope I have explained my issue without missing out on anything. I appreciate any help you could give, would be so awesome.
Edit: I should have probably mentioned that my main template is index.html, I then inject the view in to /views/template.html AND THEN inject it into index.html. Not too sure if this is best practice, but felt like it would work well (I don't think that is the issue).

A: I will give you only half of an answer, but maybe it will point you to right direction. I also struggled with Google API in SPA application once. I had the same issue - after entering the contact page, a white box appeared instead of map. The solution turned out to be simple - I just needed to force map reload, when I entered contact sheet. This function was attached as onclick event to contact page link:
function reloadGoogleMap() {
    if (counter == 0) {
        document.getElementById('google-map').src += '';
        counter++;
    }
}

I used the counter to make sure it happens only once - you won't need it probably. With Angular, you might need to make sure the reload happens after element is rendered. Maybe a simple directive would work, however I didn't test that:
angular.module('your_directives_module')
    .directive('mapLoaded', [mapLoadedDirective]);

function mapLoadedDirective() {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            elem.on('load', function (event) {
                // Force reload
                elem.src += '';
            });
        }
    };
}

It could be used like:

Maybe Facebook API also has some simple way which you could use to force widget reload when the partial view is loaded, however I've never tried to use that with Angular.

A: Don't you have to wrap it in a $rootScope.$apply function in order to update your view?
$rootScope.$apply(function () {
    // some code
});


text:
Q: How do I compare smalldatetime in SQL? I'm trying to select only rows that occurred within the last 12 hours. The below query works fine without the Where clause, I get exactly what I want for the "Called_At" column. But when I add the where clause it gives me the error "Conversion failed when converting character string to smalldatetime data type."
The query is
SELECT TOP (2000)
      CONVERT(smalldatetime, CONCAT([Call_Date],' ',[Call_Time])) As 'Called_At'
      ,[Other_Column1]
      ,[Other_Column2]
      ,[etc]

  FROM [Database].[dbo].[Table]
  WHERE CONVERT(smalldatetime, CONCAT([Call_Date],' ',[Call_Time])) >= DATEADD(hour,-12,GetDATE())
  ORDER BY [Call_Date] DESC, [Call_Time] DESC

Here is a sample of the columns without the Where part of the statement.
Called_At             Column1       Column2
-------------------   -------       ---------
2020-04-05 23:09:00   Data          MoreData
2020-04-05 20:50:00   Data          MoreData
2020-04-05 17:08:00   Data          MoreData
2020-04-05 16:49:00   Data          MoreData

Why does the first CONVERT() statement work fine but the second one doesn't?

A: This is because of the order of operations.  I would suggest that you find the offensive values using:
SELECT CONCAT([Call_Date], ' ', [Call_Time]))
FROM [Database].[dbo].[Table]
WHERE TRY_CONVERT(smalldatetime, CONCAT([Call_Date], ' ', [Call_Time])) IS NULL

Once you see what the data looks like, you can figure outhow to fix it.


text:
Q: Find a subset of rows (N rows) in a Pandas data frame having the same values at a subset of columns I have a df which contains customer data without a primary key. The same customer might show up multiple times.
I have a field (df2['campaign']) that is an int and reflects how many times the customer shows up in the df. There are also many customer attributes.
In my example, going from top to bottom, for each row (i.e. customer), I would like to find all n rows (i.e. all n customers) whose values of the education and default columns are the same. Remember n is the int contained in df2['campaign']
So as shown below, for row 0 and 1 I should search 1 row but find nothing because there are no matching values for education-default combinations.
For row 2 I should search 1 row (because campaign == 1) where education-default values match, and find 1 row in index 4.
df2.head()

job marital education   default campaign    housing loan    contact
0     3    1     0    0    1    0    0   1
1     7    1     3    1    1    0    0   1
2     7    1     3    0    1    2    0   1
3     0    1     1    0    1    0    0   1
4     7    1     3    0    1    0    2   1

A: Use  df2_sorted = df2.sort(['education', 'default'], ascending=[1, 1]).
Then if your data is not noisy, the rows should become neighbors.


text:
Q: How to make a sort array and count array button? I am trying to create a code that sorts products into alphabetical order and then count the number of them for class. I know how to create a program that does one or the other, but when I try to put them both in it doesn't work, I've tried to change the code around but i still can't find a way for this to work, so I must be doing something wrong. Any help would be really appreciated. Here is the current code:
<!DOCTYPE html>

Printer, Tablet, Router, Computer, Phone.

Click the button to sort the products into Alphabetical Order.

    <button onclick="myFunction()">Try it</button>

    <button onclick="myFunction()">Count the Number of Products!</button>

A: Welcome to programming! It is fun, except when it's not. But it gets fun again right after you solve your problem :)
The problem with your code is, even if you separate your code inside two


text:
Q: Why is it natural to look for solutions involving dimensionless quantities? While studying the Heat Equation, I got stuck in a statement in my book. It says:

We have seen that the combination of variables $\displaystyle \frac{x}{\sqrt{Dt}}$ is not only invariant with respect to parabolic dilations but also dimensionless. It is then natural to check if there are solutions of the Heat Equation involving such dimensionless group.  (...) it makes sense to look for solutions of the form:
$\displaystyle u^{*}(x,t)=\frac{q}{\sqrt{Dt}}U\left( \frac{x}{\sqrt{Dt}} \right)$
where $U$ is a (dimensionless) function of a single variable."

Why is the bold text so? I don't see why it is intuitive to search for such solutions.

A: Dimensionless equations have the advantage that they work for any value of the parameters.  They are scale invariant.  So the solution in terms of a single dimensionless variable applies to all values of $D$ and $t$.
It also allows the definition of characteristic values for the dynamic variables.   In your example, one could say $u_0$ = $\frac{q}{\sqrt{Dt}}$, and $x_0 = \sqrt{Dt}$.  These set the scale of both the independent and dependent variable.  It allows, for example, one to say when a value is "big" (greater than the characteristic value), or "small" (less than the characteristic value).  It's a little strange in this case because these characteristic values change with time.   Things are a bit clearer when they are constants.  Then you would have, for example, a characteristic length, period.
Now if we define dimensionless variable, say $\upsilon = u(x,t)/u_0$ and $\chi = x/x_0$, we can write the much simpler, and more universal equation $$\upsilon(\chi, t) = U(\chi)$$ and "large" and "small" are set by whether or not $\chi$ and $\upsilon$ are greater than or less than unity.  A further feature is that a plot on dimensionless axes will have values on the $x$ and $y$ axis that center around $1$. The plots are cleaner, and also universal.
These kinds of dimensionless solutions are a convenience, but they don't add anything new to the theory.  Whether or not it is natural to look for them ... well, that is in the eye of the beholder.  Personally, I do express equations in dimensionless form whenever possible.
In the case of the heat equation, we see that as time marches on the characteristic length gets larger, that is, the "hot region" grows, as the square root of the time variable, and the size of that region is roughly $x_0$.  Similarly, the characteristic heat variable (perhaps energy density) decreases ... "gets cooler" ... as the square root of the time variable, and its value is roughly $u_0$.

A: Let's say your goal is to describe the shape of some object, such as a box.
You could create a completely arbitrary ruler and measure the three axes of the box, coming out for example with lengths of 11.72, 23.44, and 35.16 of your arbitrary ruler units.
Or you might look at your results more closely and think hmm, something is going on here, since the second two lengths are exact multiples of the first one.
So instead of using arbitrary units, you make the box into its own ruler by choosing pairs of sides and looking at the ratios of their lengths. By the rules of division, such ratios are of course dimensionless, since for example your original arbitrary units would cancel out in the ratio.
But look at the result! Instead of (11.72, 23.44, 35.16), you have stripped out the arbitrary noise created when you defined and arbitrary ruler. As a direct result, your "theory of box" instead becomes a much more interesting sequence such as (1, 2, 3) or (1/3, 2/3, 1), depending on which side you pick as your divisor (or "1") unit of natural length. Such simpler ratios immediately suggest that the box is composed of smaller, more fundamental units.
Physics, and in particular the Standard Model, is of course far more complicated that a simple box. But it too is rich in same-to-same ratios (about two dozen total) that measure different magnitudes of identical quantities. For those pairs, you can again use the ratio trick to strip out any "arbitrary ruler" noise and come up with more fundamental, and hopefully insightful, values for fundamental "size and shape" constants that define the exact "shape" of the Standard Model.
For example, the absolute invariance that special relativity imparts to the speed of light makes c into a brain-dead obvious choice for the natural unit of anything involving velocity. Thus c=1, and any other velocity simply uses that unique velocity as its divisor. The charge of an electron is another good divisor choice, though there you can see that there is some wiggle room in the choices, since you could also argue that the -1/3 charge of a down quark might in some way be more "fundamental."

A: These solutions are preferred because they directly embody the scale invariance of the equation. In general, when a physical problem has some sort of symmetry - like the parabolic dilation invariance of the heat equation - then this establishes a corresponding action of the symmetry group on the solutions. The canonical forms based on dimensionless parameters are often eigenfunctions of this symmetry.
With the heat equation, for example,
$$
\frac{\partial u}{\partial t}=D\frac{\partial^2 u}{\partial x^2},
$$
the nontrivial symmetry is a combined dilation between space and time: on a problem that's twice the size, the solution will be the same except the heat diffusion will take four times as long. To be more precise, if you change coordinates to $x'=a x$ and $t'=a^2 t$, for some scale parameter $0<a<\infty$, then the equation is exactly the same:
$$
\frac{\partial u}{\partial t'}=D\frac{\partial^2 u}{\partial x'^2}.
$$
This means that for any given solution $u_1(x,t)$ of the heat equation, you can always construct an infinite family of solutions,
$$
u_a(x,t)=a\, u_1(a x,a^2t).
$$
(I have added a scale factor in $u$ as well, to keep the conserved total heat $q=\int_{-\infty}^\infty u_a(x,t)\,\text dx$ constant, though this is not strictly that necessary.)
Now, these solutions are probably different to the original one unless that one is completely flat, but as physicists we're not very interested in that and we want to remove this superfluous degree of freedom. (I should note that mathematicians are even more trigger-happy on that, too.) The problem, though, is that since they're all equivalent it's hard to pick one representative of the class. Moreover, in general, all the $u_a$ will be linearly independent, so they are in some sense different.
This is where canonical forms of the type
$$
u^*(x,t)=\frac{q}{\sqrt{Dt}}U(x/\sqrt{Dt})
$$
come in. It should be clear that these solutions are eigenfunctions of the dilation symmetry operator $L_a$, which means that all the corresponding $u_a$ are linearly dependent, which greatly simplifies the corresponding equivalence class.
On a more formal setting, we have a bunch of symmetry operators which commute with each other and with the differential operator $L=D\tfrac{\partial^2 }{\partial x^2}$, which means that we can expand any solution of $L=0$ as a linear combination of the eigenfunctions of the $L_a$ and - crucially - the time evolution under $\tfrac\partial{\partial t}=L$ will preserve the coefficients of this expansion.
On a more pragmatic footing, it is nice that we're guaranteed the existence of such solutions because of the symmetry of the equation, but looking for them is useful because it reduces the dimensionality of the problem: we now have to solve a one-dimensional ODE rather than a two-dimensional PDE, and this is a vastly easier problem. The price we need to pay is that there is no guarantee that the special solutions we find will match the initial conditions we may need to impose, but this is generally something we're OK with, because we can use linear combinations of these special solutions to solve for arbitrary initial conditions.

A: Because it is easier for dimensionless quantities to be combined in arbitrary polynomial terms (or other terms e.g exponential) with no loss (or extra) factors. Think like "characteristic times" used in exponential factors.
Especially quantities appearing in solutions of the form $e^{a} = \sum_0^\infty \frac{a^n}{n!}$, one can see why a dimensionless quantity $a$ is necessary here. Else there would be problem matching the proper dimensions (in an infinite amount of powers).
In a sense they are invariant quantities suitable for expressing solutions in terms of them.
In an analogy with tensor analysis, if we assume for a minute that each quantity that has a dimension (e.g mass, time, etc.) can be a vector or tensor, then a dimensionless quantity can be scalar invariant.

A: The key concept is that the units of measurements you chose to use make no difference to the physical behaviour. I.e you expect the solution behaviour to be independent of the units of measurement used. This means you should get the same solution if we chose to measure $x$ is in meters, and $t$ is in seconds and $D$ is in $m^2/s$ as if we chose to measure $x$ is in furlongs and $t$ is in fortnights and D is in $furlongs^2/fortnight$.
By looking for a solution in terms of the dimensionless parameters we ensure this is occurs. In fact this is the only way it can be ensured.

A: Intuitively a lot of equations we use to describe physical phenomena such as $exp(x)$ take in only dimensionless variables. Moreover in physics we're always taking the derivative or the log of things, and it works out to be much simpler if you're not always having to deal with a dimensioned constant factor that drops out every time you take the derivative.


text:
Q: I am not getting any output & error and i don't know why I am not getting any output and i don't know why but im not getting an error neither in the browser nor in the command prompt so im not clear about what is happening. And I got an error in the starting of the execution like this error:

WebSocketClient.js:16 WebSocket connection to 'ws://localhost:3000/ws' failed

then the error fade away and didn't appear after reloading and I get only one error in the google something like error:

Failed to load resource: the server responded with a status of 404 (Not Found)

this error in got while executing in the browser. So i don't know what's the error itself
this is my server side code
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import postRoutes from "./routes/posts.js";

const app = express();

app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use("/posts",postRoutes);

// mongodb connection
const CONNECTION_URL = "mongodb+srv://memory:memory1213@abscluster.f5vt7.mongodb.net/?
retryWrites=true&w=majority";
const PORT = process.env.PORT || 5000;

mongoose.connect(CONNECTION_URL, { useNewUrlParser:true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => {
    console.log("server running on port :",PORT)
}))
.catch((error) => console.log(error.message))

/* mongoose.set("useFindAndModify", false); */

client side (app.js)
import React,{useEffect} from "react";
import { Container, AppBar, Typography, Grow, Grid} from "@material-ui/core";
import { useDispatch } from "react-redux";
import {getPosts} from "./actions/posts";
import memories from "./images/memories-Logo.png"
import Posts from "./components/Posts/Posts";
import Form from "./components/Form/Form";
import useStyles from "./styles";

function App() {
  const classes = useStyles();
  const dispatch = useDispatch();

  useEffect(()=> {
    dispatch(getPosts());
  },[getPosts])
  return (
    <Container maxWidth="lg">
      <AppBar className={classes.appBar} position="static" color="inherit">
        <Typography className={classes.heading} variant="h2" align="center">Memories</Typography>
        <img className={classes.image} src={memories} alt="memories" height="60"/>
      </AppBar>
      <Grow in>
        <Container>
          <Grid container justifyContent="space-between" alignItems="stretch" spacing={3}>
            <Grid item xs={12} sm={7}>
                <Posts />
            </Grid>
            <Grid item xs={12} sm={4}>
                <Form />
            </Grid>
          </Grid>
        </Container>
      </Grow>
    </Container>
  );
}

export default App;

client side (index.js)
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from "react-redux";
import { legacy_createStore, applyMiddleware, compose } from "redux";
import thunk from 'redux-thunk';
import reducers from "./reducers"

const store = legacy_createStore(reducers, compose(applyMiddleware(thunk)))

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

reportWebVitals();

A: change this const posts = useStyles(); to const posts = useSelector((state) => state.posts);
I think you have made a typo here but if you use above then it will show


text:
Q: How to update services in Kubernetes? Background:
Let's say I have a replication controller with some pods. When these pods were first deployed they were configured to expose port 8080. A service (of type LoadBalancer) was also create to expose port 8080 publicly. Later we decide that we want to export an additional port from the pods (port 8081). We change the pod definition and do a rolling-update with no downtime, great! But we want this port to be publicly accessible as well.
Question:
Is there a good way to update a service without downtime (for example by adding a an additional port to expose)? If I just do:
kubectl replace -f my-service-with-an-additional-port.json

I get the following error message:
Replace failedspec.clusterIP: invalid value '': field is immutable

A: If you name the ports in the pods, you can specify the target ports by name in the service rather than by number, and then the same service can direct target to pods using different port numbers.
Or, as Yu-Ju suggested, you can do a read-modify-write of the live state of the service, such as via kubectl edit. The error message was due to not specifying the clusterIP that had already been set.

A: In such case you can create a second service to expose the second port, it won't conflict with the other one and you'll have no downtime.

A: If you have more that one pod running for the same service you may use the Kubernetes Engine within the Google Cloud Console as follows:
Under "Workloads", select your Replication Controller. Within that screen, click "EDIT" then update and save your replication controller details.
Under "Discover & Load Balancing", select your Service. Within that screen, click "EDIT" then update and save your service details. If you changed ports you should see those reflecting under the column "Endpoints" when you've finished editing the details.
Assuming you have at least two pods running on a machine (and a restart policy of Always), if you wanted to update the pods with the new configuration or container image:
Under "Workloads", select your Replication Controller. Within that screen, scroll down to "Managed pods". Select a pod, then in that screen click "KUBECTL" -> "Delete". Note, you can do the same with the command line: kubectl delete pod <podname>. This would delete and restart it with the newly downloaded configuration and container image. Delete each pod one at a time, making sure to wait until a pod has fully restarted and working (i.e. check logs, debug) etc, before deleting the next.


text:
Q: How to make UILocalNotification not repeat in swift? I'm a newbie in swift language. I am using UILocalNotification to make a local notification. In Objective-C, I can sent repeatInterval to not repeat by assigning it to 0.
UILocalNotification* alarm      = [[UILocalNotification alloc] init];
alarm.repeatInterval    = 0;

But when I assign 0 to repeatInterval in Swift I got an error.
let alarm : UILocalNotification = UILocalNotification()
alarm.repeatInterval = 0

If you have any idea to fix it, please tell me.

A: You could likely set it to zero like this:
alarm.repeatInterval = NSCalendarUnit(rawValue: 0)

This way you are properly casting the value.


text:
Q: How to use useState hook to set markup text? I have a functional component with the following hook:-
const [imagePreview, setImagePreview] = useState('');

Later on, the change event, I have this:-
    if (imagePreviewUrl) {
  setImagePreview( (

));
}

Looks like it doesn't set anything. how do I set it? I could do it as:-
  let imagePreview = null;
if (imagePreviewUrl) {
  imagePreview = (

);
}

But it is bit ugly. I think useState is the recommended way to do it.
Update with more code:-
  const fileChangedHandler = event => {
setSelectedFile(event.target.files[0]);
let reader = new FileReader();
reader.onloadend = () => {
setImagePreviewUrl(reader.result);
}
reader.readAsDataURL(event.target.files[0])
if (imagePreviewUrl) {
// can't break into multiline, sytax error
setImagePreview('(

)');

}
return (

 Profile picture:
  <input className="Column" type="file" accept="image/*"
       onChange={(e) => {fileChangedHandler(e)}} />
  // I want to show the selected image here as preview before upload
  { imagePreview }

 )

Hopefully, I will give a clear understanding. What is my intention?

A: The reason you're having issues is because you're trying to access the state of imagePreviewUrl right after you update it with setImagePreviewUrl - this will not work.
const fileChangeHandler = (event) => {
  // ...
  reader.onloadend = () => {
    // this is asynchronous
    // so this definitely wouldn't get
    // executed before you get to the `if` statement below
    // also, `setImagePreviewUrl` is asynchronous as well
    setImagePreviewUrl(reader.result)
  }
  // ...
  if (imagePreviewUrl) {
    // the old value of imagePreviewUrl is being used
    // here, and since the initial value evaluates to
    // `false`, the `setImagePreview` call below
    // never gets executed
  }
}

Your new value for imagePreviewUrl won't be available immediately because it's asynchronous, so you should probably create a separate hook that listens for changes to imagePreviewUrl and updates imagePreview.
function App() {
  const [imagePreviewUrl, setImagePreviewUrl] = React.useState("");
  const [imagePreview, setImagePreview] = React.useState(null);

  const fileChangedHandler = () => {
    setImagePreviewUrl(
      "https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"
    );
  };

  React.useEffect(() => {
    if (imagePreviewUrl !== "") {
      const image = (

      );
      setImagePreview(image);
    }
  }, [imagePreviewUrl]);

  return (

      <button type="button" onClick={fileChangedHandler}>
        Trigger file change handler.
      </button>
      {imagePreview}

  );
}

Here's a working example:

*

*CodeSandbox

A: This is not a recommended approach, what you want is a conditional rendering:
const [imagePreview, setImagePreview] = useState(false);

if (imagePreviewUrl) {
  setImagePreview(true);
}

return (
  imagePreview && (

  )
);


text:
Q: Easy and cheap way to sink more than 5 A from a power supply For an experiment I need to check a current sensor but I need to parallel too many resistors to achieve that without damaging the resistors. I don't want to do that. The PSU is 12 VDC, 10 A and I want to sink at least 5 A.
Is there a quick common way engineers use, or is an expensive, bulky resistor needed?

A: A 12V 55/60W automobile headlight bulb may be used as the load. A proper enclosure would be required to shield one's eyes from the bright light.
However, its very low cold resistance would cause the power supply to trip.
The solution would be a length of galvanised curtain wire (~ 1.5m long), in series, to preheat the filaments.

The connecting wire may then be slid, along the curtain wire to its opposite end, and secured with a crocodile clip.

A: For something really cheap - we've used this in the past at my former company - just use a container of water.  Then plunge the leads from the PSU into the water, turn it on, and start adding salt until you get the current draw you're looking for.
Not very repeatable, and not something I would do for a deliverable item.  But worked fine for a one-off experiment.
We also used carbon piles, where the resistance of the pile is determined how much force is used to compress the carbon discs.

A: Does the PSU have an (adjustable) current limit function? If so, then just short the output and adjust the current limit to the value you desire.

A: About 1980 I put several light bulbs (130V) into a nice case with an amp meter in series and a voltmeter, it still has the original lamps. I have switches on each lamp so I can switch whatever load I want. The lamps range from 25W to a 500W photoflood lamp. It was designed to operate upto about 30V but tolerate a 120 volt line. I also have electronic loads but this is fast to connect (has banana jacks) and good enough for most of what I do, it is AC/DC hence not polarity sensitive.  This gets used a lot as a load and also in series to limit current or test a potential shorted device. It was great for inrush testing with 42V systems. At 12V the resistance changes some but not a lot as the filament does not get that warm. This is more stable then the common way of using headlamp bulbs while not getting that warm

A: The other suggestions of a 'proper' power resistors are good for a robust semi-permanent experiment. If it's just a one-off, where speed and versatility is important, then using resistance wire may be a good option:
For 5A at 12V you need 2.4 ohms with a power rating of 60W. around 30cm of AWG 26 nichrome resistance wire will give you the resistance you need. Coiling the wire and submerging in a large beaker of water will provide adequate cooling for short term tests as long as you keep the water topped up.

A: Use a 55W car headlight bulb. That will take about 5A @12V

A: Cheap and ugly hack:
A resistor immersed in water can dissipate 20..50x its rated power without getting off spec.
Of course, common sense is required:

*

*stay below 30V. Higher voltages are possible if you really know what you are doing or if you are extra brave.

*use pure water, distilled is best for prolonged experiments.

*it is advisable to protect the resistor leads from too much contact with water using paint or plastic tubes

*take care not to boil off the water and leave the resistor dry, at 10x overload it will burn in seconds.

Edit:
Depending on the circumstances, other liquids can be used as well:

*

*mineral oils: much less conductive than water.

*transformer oil: in fact, the proper liquid for the purpose. Good well into few kV range. Expensive and probably toxic.

*ethanol and ethanol-water mixtures: a lot less conductive than the pure water, much less messy than the oils, well-known toxicity.

*perchlorethylene: non-messy and non-flammable alternative of the above. Dry-cleaning-shop smell. Aggressive to some metals (Al and Zn come to mind). Manageable toxicity.

A: A slightly more expensive option is to use an electronic load (like this). You can find them online for as low as 20 bucks (got mine for free after getting a refund from a supplier in China since it took nearly 6 months to arrive and we thought it had been lost by the courier).
EDIT: I am not saying that you need to wait 6 months for it to arrive. By the time I finally got my first electronic load, I had already purchased another one from a local supplier for nearly £35. It was worth paying the extra money as I needed it with a bit of urgency ;)
With an electronic load, you can accurately vary the current demand and get readings of power being delivered and even set timers for the stability of your circuit.
Here are two examples of what you can get at different price ranges:

A: I don't know what type or resistors you are using but you can try with an inexpensive cement resistor, there are many different values and powers.
You can get 10pcs of 20W 10ohm ceramic (cement) resistors for 8 bucks on Amazon. Put 5 in parallel. Thus the total resistance is 2 ohms which is 6 amps at 12 volts. That's 14.4 Watts per resistor; entirely within technical spec of the devices (no damage) and the user's financial spec (cheap). As long as 5 resistors is not too many, this would solve your problem.

A: 3D printer heater cartridges designed for 30-70W at 12V or 24V are dirt cheap and should meet your need. Of course you'll need somewhere to dump all that concentrated heat. Submerging it in water is probably the easiest way.
Alternatively, nichrome wire is cheap and easy to tune to the exact resistance you want.

A: Semiconductors are better at dissipating heat than resistors, in general.  Make yourself a 5A current source using any of these NPNs, costing as little as $0.71 in single piece quantities.  A 0.2 ohm emitter resistor would dissipate only a watt in such a circuit.


text:
Q: What happens to the electrons at junction? In a Closed circuit at any wire junction, one end of a wire is bound to an end of another wire . Now the Circuit is closed. So the electrons are passing through the wire. Now  at the junction there is macroscopical contact but microscopiclly a large gap between the two wire.
Now what happens to these electrons ?
1.Are they really exiting one wire's surface and entering into others ? How do the particles overcome the gap ?
2. Is it still possible, if the emf of the battery is lower, say 1 V, that does not allow the electrons to have energy more than their work function to get out from the wire's surface?
But at 1 V , still current passes ?
In short , What happens to the electrons at junction?