text:
Q: How can I correctly initialize the type `Dispatch>` as a context state? Overview
I have an app where I want to build some global state between pages in Next.js and I'm using React Context as a solution + TypeScript. I created the context (MusicContext) and provider (Music Provider) where I want to pass the state of the MusicProvider, which includes:

*

*playlistTitle

*setPlaylistTitle

*songsMatched

*setSongsMatched

*songsMissing

*songsMissing

Question
How can I correctly initialize the type Dispatch<SetStateAction<string>> as a context state? Right now, the issue is coming from here:
  setPlaylistTitle: (value: string) => value,
  setSongsMatched: (value: Array<ISong>) => value,
  setSongsMissing: (value: Array<ISong>) => value,

Error
Type '(value: string) => string' is not assignable to type '() => Dispatch<SetStateAction<string>>'.ts(2322)
musicContext.ts(12, 3): The expected type comes from property 'setPlaylistTitle' which is declared here on type 'IMusicContext'
(property) IMusicContext.setPlaylistTitle: () => Dispatch<SetStateAction<string>>

React Context: MusicContext
// Imports: Dependencies
import { createContext, useContext, Dispatch, SetStateAction } from 'react';

// Imports: TypeScript Types
import { ISong } from '../types/types';

// TypeScript: Music Context
interface IMusicContext {
  playlistTitle: string;
  songsMatched: Array<ISong>;
  songsMissing: Array<ISong>;
  setPlaylistTitle: () => Dispatch<SetStateAction<string>>;
  setSongsMatched: () => Dispatch<SetStateAction<string>>;
  setSongsMissing: () => Dispatch<SetStateAction<string>>;
}

// React Context: Music
export const MusicContext = createContext<IMusicContext>({
  // Data
  playlistTitle: 'Default Text', // Button Title
  songsMatched: [],
  songsMissing: [],
  // Set State (TODO: HOW DO I INITIALIZE THE SET STATE VALUES???)
  setPlaylistTitle: (value: string) => value,
  setSongsMatched: (value: Array<ISong>) => value,
  setSongsMissing: (value: Array<ISong>) => value,
});

// React Context: useMusicContext
export const useMusicContext = () => useContext<IMusicContext>(MusicContext);

React Context: MusicProvider
// Imports: Dependencies
import { useState } from 'react';

// Imports: React Context
import { MusicContext } from './musicContext';

// Imports: TypeScript Types
import { ISong } from '../types/types';

// TypeScript Type: Props
interface IProps {
  value: any;
  children: JSX.Element;
}

// React Context: Provider
export const MusicProvider: React.FC<IProps> = ({ value, children }: IProps) =>  {
  // React Hooks
  const [playlistTitle, setPlaylistTitle] = useState<string>('');
  const [songsMatched, setSongsMatched] = useState<Array<ISong>>([]);
  const [songsMissing, setSongsMissing] = useState<Array<ISong>>([]);

  return (
    <MusicContext.Provider value={{ playlistTitle, songsMatched, songsMissing, setPlaylistTitle, setSongsMatched, setSongsMissing  }}>
      {children}
    </MusicContext.Provider>
  );
};

A: The direct answer to your question is this: as long as you don't use the context before the MusicContext.Provider is rendered (and there are few cases that would ever be necessary), there's no need to initialize a value by providing an argument to createContext. The reason for this is that whatever value you would have provided will be overwritten by the value provided to the MusicContext.Provider. (You can read more about this in detail in another answer.)
Some of the types in your IMusicContext type need to be modified as well. Here's what those changes would look like:
TS Playground
import {
  createContext,
  useContext,
  Dispatch,
  SetStateAction,
} from 'react';

// You didn't show this type in the question information:
type ISong = unknown;

export interface IMusicContext {
  playlistTitle: string;
  songsMatched: ISong[];
  songsMissing: ISong[];
  setPlaylistTitle: Dispatch<SetStateAction<string>>;
  setSongsMatched: Dispatch<SetStateAction<ISong[]>>;
  setSongsMissing: Dispatch<SetStateAction<ISong[]>>;
}

export const MusicContext = createContext<IMusicContext>(undefined as any);
export const useMusicContext = () => useContext(MusicContext);

Any function that you provide in an initialized value won't be of use anyway because there's no state to update yet at that point. If you want to provide an initial value for the properties that are of type Dispatch<SetStateAction<T>>, you can use this function and TypeScript will accept it:
function noop () {}


text:
Q: React typescript getting data from local json file to highcharts I'm trying to get data from my local json file to a tsx file in my react project.
const dataMap = test.map(r => ({
   y: r.value
}));

"test" is where the json data is, it is read correctly. But when im trying to iterate to specific data point in the json im getting this error: "Property 'value' does not exist on type '({here is the json data displayed as it is in the json file. Example of one: number: string;".
So basically im trying to get the dataMap variable to highcharts.
EDIT:
So, I managed to do some process. Thank you for your answers.
But Im getting another error. Im getting "Type 'string' is not assignable to type 'number'.ts(2322)
myscriptname.tsx(17, 3): The expected type comes from property 'test' which is declared here on type 'Iinterface'" from the "test" part
.then(response => {
    const data: Iinterface[] = [];
    response.data.map(i => {
      data.push({
        test: `${i.test}`
      });
    });
    setChartData(data);
  });
  });

I have tried to assign the "test" part in my interface method as number but im getting the above error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Customize grub menu label in Debian live build I am trying to roll my own distro using Debian live, following this documentation. Everything is fine in that the compiled iso runs/installs perfectly, and has the name I have specified in the config file ("MY_LINUX"). However, one peculiar problem is that after installation, the grub menu does not show "MY_LINUX", but "*Debian GNU/Linux". I have searched all the documentation, including the lb-config and lb-build manpages, but have not been able to figure out what option I need to put in where, so that the grub menu shows the name of my distro ("MY_LINUX"), and not the default. Do I have to put in a grub.cfg file before building the image? My config file is given below:
     #!/bin/sh

set -e

lb config noauto \
    -b iso-hybrid \
    --apt-options "--force-yes --yes" \
    --cache true \
    --apt-recommends true \
    --architecture amd64 \
    --mirror-bootstrap "http://debian.csail.mit.edu/debian/" \
    --mirror-chroot "http://debian.csail.mit.edu/debian/" \
    --archive-areas "main contrib non-free" \
    --parent-archive-areas "main contrib non-free" \
    --debian-installer live \
    --mode debian \
    --debian-installer-gui true \
    --win32-loader false  \
    --grub-splash "/boot/grub/spash.png" \
    --security true \
    --backports true \
    --updates true \
    --image-name "MY_LINUX" \
    --verbose \

    "${@}"

A: Yes you do need a grub.cfg in your installation disks boot directory. The GRUB 2 (assuming you are using GRUB 2) configuration file, grub.cfg, is generated during installation, or by invoking the /usr/sbin/grub2-mkconfig utility, and is automatically updated by grubby each time a new kernel is installed. So you need to generate the grub.cfg at install time with proper label and other details (kernel/initrd locations etc.). Also you need to install GRUB in disk prior to generating grub.cfg.
When generating the grub.cfg using grub2-mkconfig, the file is generated according to the template files located in /etc/grub.d/, and custom settings in the /etc/default/grub file. Edits of grub.cfg will be lost any time grub2-mkconfig is used to regenerate the file, so care must be taken to reflect any manual changes in /etc/default/grub as well.
Hope that helps you get the flow. Check Red Hat - System administration guide for more details on grub.cfg file configuration.


text:
Q: Search product URL as catalog/view/id/213 Magento 2 I have disabled Use Categories Path for Product URLs, so the product URL
Example: www.example.com/product-url
Which is fine.
But I have added some products which have visibility as search only.
When I am searching these products then search results are fine. But the search products URL is not same as above example.
URL is as www.example.com/catalog/view/id/213.
If I change visibility as catalog or catalog,search then the URL with url-key as exam
How can I change URL as www.example.com/product-url ?

A: You can set a redirect 301 to correct product url, in .htaccess or in backend in Marketing > SEO & SEARCH > Url rewrites
EDIT
Create an url rewrite for product in backend with target url www.example.com/product-url


text:
Q: How to convert json object to an html svg vector graphic diagram i have a json object which needs to be converted into an svg vector graphic chemistry diagram but idk how to do it
The pastebin link below shows what the json object is.           is there is there a library that will do it for me so that if i just paste the json object, then it will just generate and output the svg html code or how do i do it.  also is there a dynamic solution or is it just a fixed solution. this first pastebin link shows what the json object is
https://pastebin.com/Gv0p9qnP
i

this second pastebin link shows what the html code needs to be https://pastebin.com/Jv0mA8sY


text:
Q: Multiple phrases per language in cakephp I am creating a website using CakePHP that requires translation not only into multiple languages but also multiple phrases per language depending on the type of the logged in user.  This will allow the same functionality but with more formal or more friendly language without duplication.
As a very simple example:

*

*Type 1: "Customer", "purchase","shopping cart"

*Type 2: "Client", "buy", "basket"

*Type 3: "User", "order","invoice"

Each of these types would be available in multiple languages.
I've got the standard localization working in CakePHP (one of the reasons I chose it!) and have the appropriate default.po files in the /Locale/[lang]/LC_MESSAGES/ directory and all is working fine there (thank you to the user who noted on this site that ger needed to be deu to work ;) ).
Before I get too far into the app I'd like to add the phrasing so I can set e.g. the language as French and phrasing as type2.  If I was doing this outside of a framework I'd have a matrix look-up to find the correct string based on language and phrase keys but am unsure of how to do this within CakePHP's localization.
Currently I'm using the standard __([string]) convention but as this is early in the development cycle it would be trivial to change if necessary.
I was considering using __d([phrase],[string]) but can't see how to set this without creating my app as a plugin and then I'm back to the same problem with /Locale/
I have been unable to find any example of this in my searches on SO or the cakePHP community sites so would be grateful for any suggestions.
Is there a standard way to do this within cakePHP?  if not, what would be a good "best practice" way to implement this?
Edit - following the answer below here's how it was implemented:
in /app/Locale/[lang]/LC_MESSAGES/ I created a new .po files with the new phrasing in them as phrase1.po, phrase2.po etc.
Where I set the language I also set the phrasing where the phrase file matches the name of the po file:
Configure::write('Config.language', 'deu');
Configure::write('App.langDomain', 'phrase1');

and all strings were wrapped with:
__d(Configure::read('App.langDomain', 'string')

And it just works.

A: Use __d() like this:
__d(Configure::read('App.langDomain'), 'Some string');

In bootstrap.php check the conditions and set App.langDomain based on whatever you need.
__d() has nothing to do with plugins, you can use it everywhere.
And alternative would be to wrap your translations with a custom method, something like
__dd(Configure::read('App.langDomain'), array('foo' => __('String1', 'bar' => __('String2'));

The array is an array of langDomain => stringForThatDomain mappings. Your __dd() method would take the one that is passed in the first argument.


text:
Q: Java. Вывод информации в файл Есть написанный код, который ищет в определенной папке файлы по маске и, есои находит, выводит список этих файлов. Вывод стандартный в консоли. Хотелось бы сделать работу программы удобнее:
1. Создать графическое окошко с одной кнопкой, по нажатию которой выводило бы этот список файлов в специальное поле в этом же окошке. Как это сделать?
2. Вывести список файлов в файл *.txt. Как это реализовать?
То есть все то, что выводится в консоли в результате выполнения кода - как это все переместить в графическое окошко либо в txt-файл?

A: Для первого я бы порекомендовал JavaFX (сам с ней работаю сейчас)
а для второго почитать что-то типа этого

A: Благодарю. Я разобрался. Нужно было добавить всего несколько строк в main-класс (в начало файла, при объявлении переменных):
PrintStream out = null;
try {
    out = new PrintStream(new FileOutputStream("output.txt"));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
System.setOut(out);


text:
Q: Re-arrange the position of the object using Javascript / lodash In my angular project, I have the array of objects as below. I need to re-arrange the position of the object using javascript / lodash
Does anyone help me?
Response (Array of Object):
[
   { 'name': 'MMK', 'desc': 'test descritpion', 'hrcode': 'EMP001' },
   { 'name': 'SSK', 'desc': 'test descritpion', 'hrcode': 'EMP002' },
   { 'name': 'AAK', 'desc': 'test descritpion', 'hrcode': 'EMP002' },
]

Here, I am getting the response as above and that should be changed the order of the keys, not the value.
Expected value
[
       { 'hrcode': 'EMP001', 'name': 'MMK', 'desc': 'test descritpion' },
       { 'hrcode': 'EMP002', 'name': 'SSK', 'desc': 'test descritpion'  },
       { 'hrcode': 'EMP002', 'name': 'AAK', 'desc': 'test descritpion'  },
    ]

A: The short answer is you can not. Objects have indeterminate order - even though it usually looks stable when you run a project over and over, you should not rely on their order.
If you really want to iterate through object keys in a particular order for some reason, you can create an array with the keys in the order you want, then iterate over that array. Something like the following:
var response = {... your object ...}
var keyOrder = ['hrcode', 'name', 'desc'];
keyOrder.forEach(key => {
  console.log(key, 'response:', response[key]);
});

Without knowing exactly why you want them in that order, I can't give a better example.


text:
Q: Geolocation of BGP Automous Systems Hi friends I've been looking around for the past few days on a way to find the geolocation of the BGP AS's, preferably through the use of some API. I've been using the ripestat API for the majority of my work on this, but it comes up inconclusive on some of the AS's, for example AS 10000. RIPE tells me the location is in JP. Which is sort of fine, I just would like to narrow it down more to like a city / postal code / etc if possible. Is there another API suited for this? or is it just a manual task of fixing all the information once gathered.
Alternatively, if it is possible to grab the IP address of the actual AS itself, and not the range, that would likely work as well.

A: IP Geolocation isn't nearly accurate enough to pinpoint an IP to a specific City/ZIP code. In many cases, IPs from the same block will be used across a large area in an ISP's control, so it's not possible to be very accurate. Autonomous Systems don't really have "an IP", as there's no one specific location of them.
If you're looking for the locations where they peer to other providers, you might want to check out PeeringDB.


text:
Q: Image watermarking on specific position in an image in python Currently I am working with an image processing project in which I need to split the image into several segments and then apply watermark on each of the segment.
I have written a code which divides the image into segments by masking. You may find the code here. Now i want to implement watermark on each of these segments. The tutorial for watermarking can be found here.
How am I supposed to do that?
Please help as I am new to OpenCV and Python.
Feel free to ask for any further information needed to solve this.
Thank you!
EDIT
I am adding some code for your inference:
`
segment= 'segment storing location'
image = cv2.imread(image path)
segments = slic(img_as_float(image),compactness= 100.0, n_segments = 10, sigma = 5)    #segmentation of image
row, col, _ = image.shape
for (i, segVal) in enumerate(np.unique(segments)):
    # construct a mask for the segment
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255 #masking image with different mask to create unique segments
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    cv2.imwrite(segment + str(i) + ".png",bb) #save image segments created

`
Now after saving the segments, I need to watermark each one of them by calling them one after another. This is the code for watermarking:
import numpy as np
import cv2
import os
wk= 'D:\\watermark\\wm.png'
input_im= 'D:\\watermark\\input\\image_01.jpg'
op= 'D:\\watermark\\output'
alpha = 0.25
watermark = cv2.imread(wk, cv2.IMREAD_UNCHANGED)
(wH, wW) = watermark.shape[:2]
image = cv2.imread(input_im)
(h, w) = image.shape[:2]
image = np.dstack([image, np.ones((h, w), dtype="uint8") * 255])
overlay = np.zeros((h, w, 4), dtype="uint8")
overlay[h - wH - 500:h - 500, w - wW - 500:w - 500] = watermark #This is the line where we can set the watermark's coordinates
output = image.copy()
cv2.addWeighted(overlay,alpha, output, 1.0, 0, output)
filename = input_im[input_im.rfind(os.path.sep) + 1:]
p = os.path.sep.join((op, filename))
cv2.imwrite(p, output)

 Now how can I extract the coordinates of this segment in order to watermark it?
Edit
This is what I get when the lines
`cv2.circle(im, (cX, cY), 7, (255, 255, 255), -1)
 cv2.putText(im, "center", (cX - 20, cY - 20),
 cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2`

are kept outside the loop:

And this is what I get when they are executed within the loop:

A: You need to find the countour of the image (I've downloaded your segment image to try this), then compute the center of the contour.
To find the contour, you need to convert the image to gray scale and threshold it, dividing totally black pixels (black background) from non-black ones (your segment).
Finding the center of the segment
The only assumption I've made is that the pixel values of your segments are different from 0 (total black). This assumption may be invalid but, since you're working with photos of natural landscape (like the one you posted) this should not be a problem.
Feel free to ask for further details.
import numpy as np
import cv2

im = cv2.imread('try.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,1,255,0)  # Threshold to highlight non black pixels
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
  # compute the center of the contour
  M = cv2.moments(c)
  cX = int(M["m10"] / M["m00"])
  cY = int(M["m01"] / M["m00"])

  # draw the contour and center of the shape on the image
  cv2.drawContours(im, [c], -1, (0, 255, 0), 2)
  cv2.circle(im, (cX, cY), 7, (255, 255, 255), -1)
  cv2.putText(im, "center", (cX - 20, cY - 20),
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

  # show the image
  cv2.imshow("Image", im)
  cv2.waitKey(0)

This is what I get:

Placing the watermark
Let's say you have the coordinates of the center of the segment region. Knowing the size of the watermark you can convert them coordinates locating the point of the image where to put the left upper corner of the watermark. In this example I assume that them are (x=10,y=10).
I've reused the last image you posted (I'm not drawing the contours, just the watermark).
import numpy as np
import cv2 as cv

# Coordinates where to put the watermark (left upper corner)
cy = 10
cx = 10

# Reading the image
image = cv.imread("try.png")
(h,w) = image.shape[:2]
image = np.dstack([image, np.ones((h, w), dtype="uint8") * 255])

# Reading the watermark
watermark = cv.imread("watermark.png", cv.IMREAD_UNCHANGED)
(wH, wW) = watermark.shape[:2]
(B, G, R, A) = cv.split(watermark)
B = cv.bitwise_and(B, B, mask=A)
G = cv.bitwise_and(G, G, mask=A)
R = cv.bitwise_and(R, R, mask=A)
watermark = cv.merge([B, G, R, A])

# Creating the image's overlay with the watermark
overlay = np.zeros((h, w, 4), dtype="uint8")
overlay[cy:wH + cy, cx:wW + cx] = watermark

# Applying the overlay
output = image.copy()
cv.addWeighted(overlay, 0.4, output, 1.0, 0, output)

cv.imshow("out", output)
cv.waitKey()


text:
Q: Is there some sort of Priority operator on RxSwift? I have a textfield that has 2 rules for validation: minimum amount of chars and alphanumerical chars.
I want to be able to represent to the user what he's doing wrong in an error label but the problem is that if I bind the textfield to both rules it can be creepy because once one rule gets approved the ui does a little flickering from the color of the separator for example changing from red to green to red because of the other validation failing.
I'd like to know if there's a way to prioritize one bind over the other. For example, this is what I currently have:
let minimumValidator
    = inputField.textField
      .rx.text.orEmpty.map { $0.count >= 8 } // Min amount of chars is 8

minimumValidator.bind(to: inputField.rx.minimumChars)
    .disposed(by: bag)

let regexValidator
    = inputField.textField
      .rx.text.orEmpty.map { $0.matches(regex) }

regexValidator.bind(to: inputField.rx.regex)
    .disposed(by: bag)

rx.minimumChars and rx.regex are custom binders
    var minimumChars: Binder<Bool> {
        return Binder(self.base) { control, value in
            UIView.animate(withDuration: 0.1) {
                if value {
                    control.separator.backgroundColor = .white
                    control.errorLabel.isHidden = true
                } else {
                    let error = "Needs more characters"
                    control.separator.backgroundColor = .red
                    control.errorLabel.text = error
                    control.errorLabel.isHidden = false
                }
            }
        }
    }

So my idea is to prioritize idk... let's say alphanumerical validation - so it would show error from minimum char till alphanumerical error came up, so till the user resolved the alphanumerical validation it would ignore the other stream from minimum amount of chars. I'm pretty sure i'm missing some combination of combineLatest with merge or idk.

A: Make a single Binder that uses a custom enum
enum Validation {
    case valid
    case minimumChars
    case alphaNumeric
}

And then have each validator return a value of this enum. Then combineLatest the two validators and map the result to a single Validation and bind.
Something like
Observable.combineLatest(minimumValidator, regexValidator) { v1, v2 in
    // if v1 is not valid return it. Otherwise return v2
}


text:
Q: Can PInvoke convert [out] parameter into return value? I'm new to PInvoke and I need some help.
I want to access IEnumGUID using PInvoke, and I found a code block on pinvoke.net.
 [ComImport, Guid("0002E000-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false)]
 public interface IEnumGUID
 {
     int Next(int celt, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)]Guid[] rgelt);
     void Skip(int celt);
     void Reset();
     [return: MarshalAs(UnmanagedType.Interface)]
     IEnumGUID Clone();
 }

The Clone function here gives IEnumGUID as a return value, while the function in the the original C++ interface gives it as an out parameter.
HRESULT Clone(
  [out]  IEnumGUID **ppenum
);

I have learnt that PInvoke automatically converts HRESULT into COMException, but I don't know how PInvoke works to convert the out parameter to a return value.
Please give some explanation about this, so that I can correctly use this method later.

A: The pinvoke.net website isn't exactly perfect.  It has a lot of mistakes, inversely proportional to the likelihood that anybody uses the declaration in their code.   Low odds for this one, the declaration you found is badly broken.
This does not have anything to do with pinvoke, COM interop is a distinctive feature in .NET.  The ability to transform an argument to a return value is highly specific to COM Automation and highly specific to an argument that's decorated with the [out, retval] attribute.  It is [retval] that provides the hint to the COM client runtime support library that the argument can be treated as a return value.  Very common, any scripting language takes advantage of that for example.  So does any .NET language, unless that conversion is explicitly suppressed with the [PreverseSig] attribute.
IEnumGUID::Clone()'s argument doesn't have the [retval] attribute so should not be declared like it has one.  That's not the only mistake, the other members require the [PerserveSig] attribute since you need to know their return value to use them correctly.  The proper declaration is:
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("0002E000-0000-0000-C000-000000000046")]
public interface IEnumGUID
{
    [PreserveSig]
    int Next(int celt, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] Guid[] rgelt, out int pceltFetched);
    [PreserveSig]
    int Skip(int celt);
    [PreserveSig]
    int Reset();
    void Clone(out IEnumGUID ppenum);
}

COM IEnumXxxx interfaces are very common, distinguished only by the type of element returned by the enumerator.  Several of them are present in the .NET Framework, compare to this one for example.


text:
Q: Error on looping through a RelatedLinks property of dynamic Node in Razor I have a Razor partial which displays my site navigation:
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    var home = CurrentPage.Site();
    umbraco.NodeFactory.Node navigationSettingsNode = MySite.Umbraco.NavigationSettings;
    dynamic navigationSettings = new umbraco.MacroEngines.DynamicNode(navigationSettingsNode.Id);
    var settings = home.Children.Where("DocumentTypeAlias == \"Settings\"").First();
}

@if (navigationSettings.HasValue("topNavigation"))
{

        dynamic topNavigation = navigationSettings.topNavigation;
        var topNavigation2 = settings.topNavigation;
        @topNavigation
        @topNavigation2

        foreach(dynamic item in topNavigation)
        {

            @item.caption

        }

}
Initially I was looping through topNavigation2 items which worked fine and with no problem.
Now I'm looping through topNavigation items and it throws an error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'char' does not contain a definition for 'link'

I don't want to use var settings anymore, I want to use only dynamic navigationSettings variable. In order to get the right node of navigationSettings I need to some operation and I don't fancy to paste the same code in every view I want to use it so I want it to be accessible from dll and available to use anywhere.
Also the navigationSettings node in my Umbraco is outside of main content tree so is not a child of Home.
Why isn't it working? Both
        dynamic topNavigation = navigationSettings.topNavigation;
        var topNavigation2 = settings.topNavigation;

produce the same json result and both are dynamic objects.
How to make it work correctly?
I'm using MVC 5.2.3

A: It looks like your topNavigation property is a string, and so when you call for each on it, it's iterating through the characters in the string.
Also, don't use NodeFactory, it's deprecated. You should be using IPublishedContent instead.
I'd use the strongly typed content objects instead of dynamic, as a) they're faster, and b) they're easier to work with.
Here's a great article explaining the different ways of getting content: https://24days.in/umbraco-cms/2015/strongly-typed-vs-dynamic-content-access/


text:
Q: MYSQL -what is the best practice for checking if multiple phone numbers exist in table my table contains 5 milion enteries of phone numbers. suppose i need to check if a specific phone numbers exist in that table - i got an input of 1 milion numbers, and need to check what numbers exist in my table - the result has to be under 20 seconds - what is the query for this ?

A: *

*Create one new table for 1 million of phone numbers.

*

*tableA: 5 million of phone numbers

*tableB: 1 million of phone numbers

*Create index for tableA's phone numbers field and tableB's field

*Execute the below SQL script
select
  tableA.phoneNumber,
  ....
from
  tableA
where EXISTS(select * from tableB where tableA.phoneNumber=tableB.phoneNumber)

According to your request, please use the below sql script.
I strongly discourage this because it does not use the index of numbersFromRequest.
SELECT number
FROM
    (SELECT '0546313243' number
    UNION ALL
    SELECT '0527844910' number
    UNION ALL
    SELECT '0542307563' number
    UNION ALL
    SELECT '0587918462' number
    UNION ALL
    SELECT '0545496228' number ) AS numbersFromRequest
WHERE NOT exists
    (SELECT 1 from PhoneNumber
    where PhoneNumber.number = numbersFromRequest.number)

Also, I create some data for your testing. link
Like this as below.
CREATE TABLE numbersFromRequest
  (number varchar(20), INDEX USING BTREE (number))
  ENGINE = MEMORY;

INSERT INTO numbersFromRequest(number)
SELECT '0546313243' number
UNION ALL
SELECT '0527844910' number
UNION ALL
SELECT '0542307563' number
UNION ALL
SELECT '0587918462' number
UNION ALL
SELECT '0545496228' number

And then you can use temp table.


text:
Q: 0/1 Knapsack with few variables: which algorithm? I have to implement the solution to a 0/1 Knapsack problem with constraints.
My problem will have in most cases few variables (~ 10-20, at most 50).
I recall from university that there are a number of algorithms that in many cases perform better than brute force (I'm thinking, for example, to a branch and bound algorithm).
Since my problem is relative small, I'm wondering if there is an appreciable advantange in terms of efficiency when using a sophisticate solution as opposed to brute force.
If it helps, I'm programming in Python.

A: You can either use pseudopolynomial algorithm, which uses dynamic programming, if the sum of weights is small enough. You just calculate, whether you can get weight X with first Y items for each X and Y.
This runs in time O(NS), where N is number of items and S is sum of weights.
Another possibility is to use meet-in-the middle approach.
Partition items into two halves and:
For the first half take every possible combination of items (there are 2^(N/2) possible combinations in each half) and store its weight in some set.
For the second half take every possible combination of items and check whether there is a combination in first half with suitable weight.
This should run in O(2^(N/2)) time.

A: Brute force stuff would work fine for 10 variables, but for, say, 40 you'd get some 1000'000'000'000 possible solutions, which would probably take too long to enumerate. I'd consider approximate algorithms, e.g. the polynomial time algorithm (see, e.g. http://math.mit.edu/~goemans/18434S06/knapsack-katherine.pdf) or use a search algorithm such as branch-and-bound, maybe with an additional heuristic.

A: Brute force algorithms will always return the best solutions. The problem with them is that in exponential order problems they quickly become not feasible.
If you are guaranteed to have up to 20 variables, you will test no more than 1 million solutions (2^20= 1M). Hence, brute force is feasible and no other algorithm will return a better solution.
Heuristics are great, but they should be used only when we have no exact solution to the problem. There is a great book that might help you: How to Solve it, by Michalewicz.


text:
Q: Display user who started a bounty on question in featured tab The "featured" question tab shows a list of the questions with bounties with the user who originally asked the question, and the date it was originally asked.  I am generally much more interested in who modified it to put the bounty on it, and more importantly when the bounty was added.
Could the display be changed to show who modified the question by putting the bounty on, since that seems to be the more pertinent information in it's being in the "featured" queue?

A:
that seems to be the more pertinent information in it's being in the "featured" queue

I don't think so (it is my opinion, others opinions may differ). Question is promoted with bounty, and it doesn't matter who started it. The important information is when bounty expires and its amount. If you really want to know when the bounty was started and who started it, see revisions of the question.  You will see who started a bounty and when he was started it.

Also on the notice the starter of bounty is written.


text:
Q: What is the key shortcut to close a project in Sublime Text 3? What is the key shortcut to close a project in Sublime Text 3? Do I have to create a new key bind, if so, what is it?
Thank you, I appreciate it.

A: You can define
{
"keys": ["ctrl+alt+w"], "command": "close_workspace"
},

then you can close using ctrl+alt+w

A: Ctrl + W closes the tab you are working on. Currently there is no combination shortcut to close a project all together. You can create a new key bind, Instructions here : http://www.sublimetext.com/docs/key-bindings


text:
Q: How to export XML data to excel using JavaScript? I have a variable that contains XML data and I need to export that into MS Excel? How can I achieve that using JavaSript and/or JQuery?

A: I have used the code to export XML data to excel using the code from site "codeproject" I'm sharing the link hope with will work for you!.
Export html table to excel using javascript


text:
Q: Missing virtual downloads woocommerce I am working on a live website for someone who sells his MP3s. I have noticed now that the virtual files have no download link, after being purchased and on the product page in the backend. Thing is, I know they existed before as people have purchased MP3s without issue. So they have been lost somewhere perhaps because of a Wordpress update or theme change.
I exported my current wordpress product and variable product database and can see that the link information is actually there. I don't have any experience working with databases so this is a bit out of my depth, but I can see this:
<wp:postmeta>
        <wp:meta_key><![CDATA[_file_paths]]></wp:meta_key>
        <wp:meta_value><![CDATA[a:1:{s:32:"a97427231bd5a0eb7c0763ee6444bcc0";s:65:"http://domainname.com/wp-content/fl_dl/Deep-Relaxation.zip";}]]></wp:meta_value>

Which is the correct url for the mp3. How do I get Wordpress to realise that the links are already there? I really do not want to have to go through every product and input the link again as there are hundreds!


text:
Q: Restoring Image corrupted by Gaussian and Motion Blur An image is given to us that has been corrupted by:

*

*Gaussian blur

*Gaussian noise

*Motion blur

in that order. The parameters of all the above (filter size, variance, SNR, etc) are known to us.
How can we restore the image?
I have tried to compute the aggregate degradation function by convolving the above and then used the Weiner filter to restore, but the attempts have failed so far, since the blur still remains.
Could anyone please shed some light?

A: For Gaussian and motion blur, it is a matter of deducing the convolution kernel.  Once it is known, deconvolution can be done in Fourier space.  The Fourier transform of the image, divided by the Fourier transform of the kernel, gives the Fourier transform of a (hopefully) improved image.
Gaussians transform into other Gaussians, so there is no problem with divide by zero. But Gaussians do fall of rather fast, as exp(-x^2), so you'd be dividing by small numbers to obtain large whacky high frequency amplitudes.  So, some sort constant bias or other way of keeping the FT of the kernal from getting small must be applied.  That's where the Wiener filter comes in.  The bias is usually chosen in relation to random noise levels, or quantization.
For motion blur, a typical case is when the clean image is convolved with a short line segment.  Unfortunately, sharply cut-off line segments have plenty of zeros.  Again, Wiener filter to the rescue.
Additive Guassian noise cannot be removed, but can be averaged out.  The simplest quickest way is to blur the image with Gaussian, box, or other filter.  Biggest problem with that - you end up with a blurred image!  Median filters are somewhat better at preserving edges and details if not too small.   There are many noise reduction techniques out there.
Sometimes noise reduction is easy for certain types of images. For Cassini imaging work, most image features were either high-contrast hard edges (planet edges, craters), or softly varying (cloud details in atmospheres) so I used an edge detector, fattened (dilated) its output, blurred it, and used that as a mask to protect parts of the image from a small-radius blur filter.  Applying different filters.
There's Signal Processing Stack Exchange site (in beta for now) which may have questions and answers about restoring corrupted images. https://dsp.stackexchange.com/questions


text:
Q: Buildozer APK crash "Consumer closed input channel or an error occurred. events=0x9" I've build my first apk using buildozer without error, but now it crash on android.
I found in logs "Consumer closed input channel or an error occurred.  events=0x9" but I don't know why I get this error:
Here are the logslogs and here is buildozer.specspec
Thanks for your help!

A: I had the error you mentioned, but it turned out I had a different problem. That "Consumer closed..." message is just a signal that something else is wrong.
Now, as John Anderson already stated, the actual problem you have is that Python never loads when your app starts. On GitHub, you said that you have Python 3.7 installed, so not sure why, it doesn't load in your case.
I have the same errors, but have Python 3.8 installed, so it loads and everything works as expected.


text:
Q: How to use Automator to give a GUI to ditto? How do I create an Automator workflow, service or folder action to use ditto. The intention here is to use ditto to merge folders and/or files avoiding the unacceptable Finder's behavior of replacing the folder/file by the new one.

A: Create a Service that receives folders in Finder. Add a single Run AppleScript action to it with the following script code:
on run {input, parameters}
    set dest to choose folder with prompt "Select destination:"
    set dest_path to (POSIX path of dest) as text
    set src_paths to ""
    repeat with idx from 1 to count (input)
        set src_paths to src_paths & (quoted form of (POSIX path of item idx of input as text)) & " "
    end repeat
    set cmd to "ditto " & src_paths & quoted form of dest_path
    do shell script cmd
end run

The script will execute
ditto selectedFolder1 selectedFolder2 selectedFolderN folderChosenInDialog

Assign a keyboard shortcut for convenient access in System Preferences » Keyboard » Keyboard Shortcuts » Services.


text:
Q: php interval and timezone I would like to get the date time interval between two dates in a time zone that uses daylight savings time.
The following snipet shows the problem.
$timezone = new DateTimeZone('UTC');
$from_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', '2014-10-31 23:59:59',$timezone);
$to_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', '2014-11-20 23:47:02',$timezone);
$interval = $from_date_obj->diff($to_date_obj, TRUE);
print_r($interval);

For UTC timezone this shows:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 19
[h] => 23
[i] => 47
[s] => 3
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 19
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)

Now this one:
$timezone = new DateTimeZone('America/Los_Angeles');
$from_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', '2014-10-31 23:59:59',$timezone);
$to_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', '2014-11-20 23:47:02',$timezone);
$interval = $from_date_obj->diff($to_date_obj, TRUE);
print_r($interval);

shows:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 20
[h] => -1
[i] => 47
[s] => 3
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 19
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)

the one in UTC shows 19 days/23 hours/47 minutes and 3 seconds.  The one for PT shows 20 days/-1 hours/47 minutes and 3 seconds.  I think the right answer for PT should be 20 days/0 hours/47 minutes and 3 seconds.
Is there any way to do a diff in the pacific time zone and not end up with the negative hour?  Is the -1 hours indication the desired result and what does it mean exactly?

update:  I found out that indeed PHP doesn't seem to handle the diff with respect to DST which is discussed here:
PHP's DateTime::Diff gets it wrong?
As far as the results I was getting it appears to be a PHP bug as indicated in the above link.

A: There are two issues raised here:
One has to do with the difference between two dates and times when there is a clock change due to DST (Daylight Savings Time).  In reality the difference between two dates and times should take into account the clock change, but apparently it does not.
That is documented pretty well in the following link:
PHP's DateTime::Diff gets it wrong?
Further I am chalking up the -1 problem as a php bug.  Since PHP doesn't handle the DST changes between two date times anyway, and in my case the difference without taking DST into effect is close enough anyway, I will just do the diff calculation in UTC.

A: What php version are you using ? Im getting this result for 2nd code block -
DateInterval Object (
[y] => 0
[m] => 0
[d] => 19
[h] => 23
[i] => 47
[s] => 3
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 19
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)

both of the codes should display the same result as your comparing the same date with just different timezone each time

A: Even after 8 years it is still not supported:
    $day = \DateTime::createFromFormat('Y-m-d', '2023-03-26', new \DateTimeZone('Europe/Budapest'));
    $followingDay = \DateTime::createFromFormat('Y-m-d', $day->format('Y-m-d'), new \DateTimeZone('Europe/Budapest'));
    $followingDay->add(new \DateInterval('P1D'));
    $day2 = \DateTime::createFromFormat('Y-m-d', '2023-03-27', new \DateTimeZone('Europe/Budapest'));
    var_dump($day->getTimestamp(), $followingDay->getTimeStamp(), $day2->getTimeStamp());
    var_dump($day, $followingDay, $day2);

Not to mention that it adds current time instead of 00:00:00 which I read in the documentation, so better to be careful. Though I generally hate PHP because of the low quality documentation, so I almost always write automated tests when I use a built-in function. It is full of bugs or undocumented behavior.
int(1679794696)
int(1679881096)
int(1679877496)

class DateTime#397 (3) {
  public $date =>
  string(26) "2023-03-26 03:38:16.000000"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(15) "Europe/Budapest"
}
class DateTime#404 (3) {
  public $date =>
  string(26) "2023-03-27 03:38:16.000000"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(15) "Europe/Budapest"
}
class DateTime#399 (3) {
  public $date =>
  string(26) "2023-03-27 02:38:16.000000"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(15) "Europe/Budapest"
}


text:
Q: C# antivirus block smtp check I am trying to check smtp server with the below method.
Seems working fine, but there is a block alert from my antivirus.
Is there anyway to check if the antivirus is blocking and then stop the smtp check?
Thanks.
public static bool Check(string host, string port, string username, string password)
        {
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect(host, Convert.ToInt32(port));

            NetworkStream netStream = tcpClient.GetStream();
            System.IO.StreamReader strReader = new System.IO.StreamReader(netStream);
            byte[] WriteBuffer = new byte[1024];
            ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            WriteBuffer = enc.GetBytes("USER " + username + "\r\n");
            netStream.Write(WriteBuffer, 0, WriteBuffer.Length);

            WriteBuffer = enc.GetBytes("PASS " + password + "\r\n");
            netStream.Write(WriteBuffer, 0, WriteBuffer.Length);

            if (strReader.ReadLine().Contains("+OK"))
            {
                return true;
            }
            return false;
        }

A: I am unable to find the exact way to stop it. Therefore I decided to catch the socketexception instead.


text:
Q: Centralize vertically a text and an image inside a  element My simple HTML:

    My Text

My CSS:
a {
    padding: 6px;
}

Fiddler: http://jsfiddle.net/sa3LT/
Hi everybody!!
I'm having a trouble with this question. Is simple, I think, but for me I don't find a resolution for this problem.
Tks for all.

A: It sounds like you want the text in the a tag to be vertically centered next to the image. Adding this bit of CSS will solve the issue (and as pointed out from Smeegs, this CSS will be for all img tags inside an a block:
a img {
    vertical-align: middle;
}

JSFiddle: http://jsfiddle.net/sa3LT/1/


text:
Q: Prove $\cos(x)$ is continuous I'm stuck at a particular step and could use some help.
By definition, a function is continuous at $x=a$ iff $\lim_{x \to a} f(x) = f(a)$.
So I assume to prove $\cos(x)$ is continuous we must use the definition of a limit to show that:
$$\lim_{x \to a} \cos(x) = \cos(a) \iff \forall \epsilon > 0, \exists \delta>0 : 0 < |x - a| < \delta \implies |\cos(x)-\cos(a)| < \epsilon$$
From some triangle proofs it can be shown that:
$\cos(\alpha + \beta) = \cos(\alpha)\cos(\beta) - \sin(\alpha) \sin(\beta)$
$\cos(\alpha - \beta) = \cos(\alpha)\cos(\beta) + \sin(\alpha) \sin(\beta)$
Subtract the two equations:
$$\cos(\alpha + \beta) - \cos(\alpha - \beta) = -2\sin(\alpha) \sin(\beta)$$
Let $x = \alpha + \beta$ and $a = \alpha - \beta$.
Then $\alpha = \frac{x+a}{2}$ and $\beta = \frac{x-a}{2}$, implying:
$$\cos(x) - \cos(a) = -2\sin\left(\frac{x+a}{2}\right)\sin\left(\frac{x-a}{2}\right)$$
So
$$\left|\cos(x)-\cos(a)\right| = 2\left|\sin\left(\frac{x+a}{2}\right)\right| \cdot \left|\sin\left(\frac{x-a}{2}\right)\right|$$
I feel like I am close because I was able to change it so at least we have an $x-a$ term but now I'm not sure where to go from here.

A: Use that $|\sin u|\leq\min\{|u|,1\}$, then $2\left|\sin\left(\dfrac{x+a}{2}\right)\right|\cdot\left|\sin\left(\dfrac{x-a}{2}\right)\right|\leq 2\left|\dfrac{x-a}{2}\right|=|x-a|<\epsilon$ if we take $\delta=\epsilon$.

A: Note that
$$
\cos(x+h)=\cos(x)\cos(h) - \sin(x)\sin(h)
$$
and so
\begin{align}
\lim_{h \to 0}\cos(x+h) &= \lim_{h \to 0}\cos(x)\cos(h)-\lim_{h \to 0}\sin(x)\sin(h) \\
&= \cos x\lim_{h \to 0}\cos(h)-\sin(x)\lim_{h \to 0}\sin(h) \, .
\end{align}
The problem reduces to showing that $\sin$ and $\cos$ are continuous at $0$. For $\sin$, note that when $h>0$,
$$
0 < \sin(h) < h \, ,
$$
and since $\lim_{h \to 0^{+}}h=0$, by the squeeze theorem we find that $\lim_{h \to 0^+}\sin(h)=0$. The same argument can be made for $x<0$, but with the inequalities reversed. Hence, $\lim_{h \to 0}\sin(h)=0$. We can prove $\lim_{h \to 0}\cos(h)=1$ directly by the epsilon-delta definition of a limit. First, note that because $\cos$ is an even function, this problem reduces to proving that $\lim_{h \to 0^+}\cos(h)=1$. Now, if we set $\delta=\arccos(1-\varepsilon)$*, then
\begin{align}
& h < \arccos(1-\varepsilon) \\
\implies & \cos(h) > 1-\varepsilon \\
\implies & \cos(h) - 1 > -\varepsilon \\
\implies & 1 - \cos(h) < \varepsilon
\end{align}
and the result follows.

If $\varepsilon > 2$, then any value of $\delta$ suffices.


text:
Q: how to execute terminal commands in C i`m trying to simulate a terminal, and in my code almost all commands execute just fine, but the commands cd folder and cd .. when i try to execute those nothing happends, can any one help me with this
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAXLEN 100
#define TRUE 1
#define FALSE 0

typedef struct command {
    char *cmd;              // string apenas com o comando
    struct command *next;   // apontador para o próximo comando
} COMMAND;

COMMAND *insert(COMMAND *list, char *cmd);
COMMAND *startList();
int strCompare(char *str1, char *str2);
int strLenght(char *str);

int main(void) {
    char command[MAXLEN] = "start";
    int id, return_command = 0;
    COMMAND *commands = startList();
    char exit_com[5] = "exit\0";
    int r;
    while(r = strCompare(command, exit_com)){
        char cwd[1024];

        if (getcwd(cwd, sizeof(cwd)) != NULL){
           fprintf(stdout, "%s: ", cwd);
        }

        fgets(command, MAXLEN, stdin);

        commands = insert(commands, command);

        id = fork();
        if (id == 0){
            return_command = system(command);

            if (return_command == -1){
                printf("\nErro ao executar o comando '%s'\n", command);
                exit(0);
            }

            COMMAND *c = commands;

            while(c != NULL){
                printf("%s\n", c->cmd);
                c = c->next;
            }
            exit(0);
        }
        wait(id);
    }
    return 0;
}

int strCompare(char *str1, char *str2){
    char aux = str2[0];
    int i = 0;
    while(aux != '\0'){
        if (str1[i] != str2[i])
            return 1;
        aux = str2[++i];
    }
    return 0;
}

COMMAND *startList(){
    return NULL;
}

COMMAND *insert(COMMAND *list, char *cmd){
    COMMAND *newCommand = (COMMAND*) malloc(sizeof(COMMAND));
    newCommand->cmd = cmd;
    newCommand->next = list;
    return newCommand;
}

A: You may like to use chdir call to change the working directory of your shell process. The child processes started by system call inherit the working directory from the parent process

A: It's because the system function starts a new process, so every command you run through system will be only in that process. That's why shells commonly handles commands like cd internally.


text:
Q: Sorting an NSMutableArray by criteria I want to sort the NSMutableArray by date order:
var currentReminders: NSMutableArray

This array stores reminder objects like this:
class Reminders: NSObject {

    var title: String?
    var dueDate = NSDate()

    init(...) {...}
}

I want to sort the currentReminder in ascending order of date (which one having the most recent dueDate will stand above)
Can someone tell me how to do it?

A: Create NSSortDescriptor object and sort the array with it:
var dateDescriptor = NSSortDescriptor(key: "dueDate", ascending: true)
var sortedArray = currentReminders.sortedArrayUsingDescriptors([dateDescriptor])

The new sortedArray will contain objects ordered by dueDate.
Also, I would suggest using native Swift objects like Array<T> without NSObjectsubclasses. That would make sorting and data handling much easier.


text:
Q: Setting a standard size for all examples in a dataset I have an experimental dataset containing time-series examples with different sizes.
Let's say that for different examples, the sizes are:
(8135, 2),
(8201, 2),
(8188, 2),
etc... How can I set a standard size for all examples, e.g. (8150, 2), in order to be used by a convolutional neural network?I can't set the smallest size as the standard one, because I will lose information from other examples. Also, it is important to keep the first and the last observation (data-point) for each time series. I guess this problem can be solved by binning the time series, or an interpolation?
Thanks in advance


text:
Q: Show Bottom Sheet only if Firestore field does not have a value I have this in initState using scaffoldKey to show BottomSheet (there may be a better solution?)
@override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback(
      (_) => _scaffoldKey.currentState
          .showBottomSheet((context) => Info()),
    );
  }

But I only want to show the Bottom Sheet if a field in Firestore is empty, if it has a value I don't want to show it. I'm really struggling with this

A: The recommended approach for this kind would be to use Providers.
This is a state management approach where you can choose which widget to show based on data fields.


text:
Q: Entity framework core - user specified primary key value not saving I am using this code to save a student to student table. ID is the primary key in the table.
_context.Add(student);
await _context.SaveChangesAsync();

A student object with these values works and the record is added with the next available ID in the table.
Firstname: Firstname
Lastname: Lastname
Date: {03/02/2019 23:59:00}
ID: 0

The below student object fails and causes a "DbUpdateException" Exception.
Firstname: Firstname
Lastname: Lastname
Date: {03/02/2019 23:59:00}
ID: 66 (or any other int value that isn't already used in the table)

Is it not possible to specify a value for a Primary Key in EF?  Or is there a particular way of specifying a user value?

A: Maybe you are using auto-generated primary key?


text:
Q: 3D figure using tikz-pgf - Intersection of two planes I'm trying to draw a figure using tikz-pgf. This figure should have two planes in it: z=x and z=0. So far I've managed to write the following:
\documentclass[a4paper,12pt]{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[domain=-1:1,y domain=-1:1]
        \addplot3[surf] {0};
        \addplot3[surf] {x};
    \end{axis}
\end{tikzpicture}
\end{document}

But the result is weird, because it's not clear where the intersection of both planes is. I would like the plane z=0 to "cover" a bit of the plane z=x, as if the figure was viewed from above. Is there any easy way to do this?

A: You can use the method of this answer. There a combination of surface colors, opacities and plots get close to the desired result.
Your intersection is x=0, y=-1:1, z=0 with \addplot3+ you can draw this line. mark=none disables the marks. Optional you can use the style thick.

MWE:
\documentclass[a4paper,12pt]{article}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[domain=-1:1,y domain=-1:1]
        \addplot3[surf, opacity=0.35] {0};
        \addplot3[surf, opacity=0.35] {x};
        \addplot3+[mark=none,thick]({0},{y},{0});
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Reverse the order of integration of $\int_{-1}^4\int_{y-4}^{4y-y^2} (y+1)dxdy$ and then evaluate The answer key says that the original integral is equivalent to the following sum of iterated integrals:
$$\int_{-5}^0\int_{2-\sqrt{4-x}}^{x+4} \ (y+1) \ dydx+ \int^4_0 \int_{2-\sqrt{4-x}}^{2+\sqrt{4-x}} \ (y+1) \ dydx$$
But where do these limits come from?!?
I understand why $[-5,4]$ needs to be split up into two (the region is not vertically simple otherwise) and why $y \leq x+4$ when $-5\leq x \leq 0$. But how can we determine the other limits in terms of the inequality $(1)$?
$$4-y \leq x\leq 4y-y^2 \tag {1}$$

A: It is the region bounded by the line from the picture below. So:

*

*If $-5\leqslant x\leqslant0$, then $2-\sqrt{4-x}\leqslant y\leqslant x+4$;

*If $0\leqslant x\leqslant4$, then $2-\sqrt{4-x}\leqslant y\leqslant2+\sqrt{4-x}$.


text:
Q: R - find name in string that matches a lookup field using regex I have a data frame of ad listings for pets:
ID    Ad_title
1     1 year old ball python
2     Young red Blood python. - For Sale
3     1 Year Old Male Bearded Dragon - For Sale

I would like take the common name in the Ad_listing (i.e. ball pyton) and create a new field with the Latin name for the species. To assist, I have another data frame that has the latin names and common names:
ID    Latin_name           Common_name
1     Python regius        E: Ball Python, Royal Python G: Königspython
2     Python brongersmai   E: Red Blood Python, Malaysian Blood Python
3     Pogona barbata       E: Eastern Bearded Dragon, Bearded Dragon

How can I go about doing this? The tricky part is that the common names are hidden in between text both in the ad listing and in the Common_name. If that were not the case I could just use %in%. If there was a way/function to use regex I think that would be helpful.

A: The other answer does a good job outlining the general logic, so here's a few thoughts on a simple (though not optimized!!) way to do this:
First, you'll want to make a big table, two columns of all 'common names' (each name gets its own row) alongside it's Latin name. You could also make a dictionary here, but I like tables.
    reference_table <- data.frame(common = c("cat", "kitty", "dog"), technical = c("feline", "feline", "canine"))

  common technical
1    cat    feline
2  kitty    feline
3    dog    canine

From here, just loop through every element of "ad_title" (use apply() or a for loop, depending on your preference). Now use something like this:
apply(reference_table,1, function(X) {
if (length(grep(X$common, ad_title)) > 0){ #If the common name was found in the ad_title
[code to replace the string]})

For inserting the new string, play with your regular regex tools. Alternatively, play with strsplit(ad_title, X$common).  You'll be able to rebuild the ad_title using paste(), and the parts that make up the strsplit.
Again, this is NOT the best way to do this, but hopefully the logic is simple.

A: Well, I tried to create a workable solution for your requirement. There could be better ways to execute it, though, probably using packages such as data.table and/or stringr. Anyway, this snippet could be a working starting point. Oh, and I modified the Ad_title data a bit so that the species names are in titlecase.
# Re-create data
Ad_title <- c("1 year old Ball Python", "Young Red Blood Python. - For Sale",
              "1 Year Old Male Bearded Dragon - For Sale")
df2 <- data.frame(Latin_name = c("Python regius", "Python brongersmai", "Pogona barbata"),
                  Common_name = c("E: Ball Python, Royal Python G: Königspython",
                                  "E: Red Blood Python, Malaysian Blood Python",
                                  "E: Eastern Bearded Dragon, Bearded Dragon"),
                  stringsAsFactors = F)

# Aggregate common names
Common_name <- paste(df2$Common_name, collapse = ", ")
Common_name <- unlist(strsplit(Common_name, "(E: )|( G: )|(, )"))
Common_name <- Common_name[Common_name != ""]

# Data frame latin names vs common names
df3 <- data.frame(Common_name, Latin_name = sapply(Common_name, grep, df2$Common_name),
                  row.names = NULL, stringsAsFactors = F)
df3$Latin_name <- df2$Latin_name[df3$Latin_name]

# Data frame Ad vs common names
Ad_Common_name <- unlist(sapply(Common_name, grep, Ad_title))
df4 <- data.frame(Ad_title, Common_name = sapply(1:3, function(i) names(Ad_Common_name[Ad_Common_name==i])),
                  stringsAsFactors = F)

A: obviously you need a loop structure for all your common name lookup table and another loop that splits this compound field on comma, before doing simple regex. there's no sane regex that will do it all.
in future avoid using packed/compound structures that require packing and unpacking. it looks fine for human consumption but semantically and for computer program consumption, you have multiple data values packed in single field, i.e. it's not "common name" it's "common names" delimited by comma, that you have there.
sorry if i haven't provided R or whatever specific answer. I'm a technology veteran and use many languages/technologies depending on problem and available resources. you will need to iterate over every record of your latin names lookup table, within which you will need to iterate over the comma delimited packed field of "common names", so you're working with one common name at a time. with that single common name you search/replace using regex or whatever means available to you, over the whole input file. it's plain and simple that you need to start at it from that end, i.e. the lookup table. you need to iterlate/loop through that. iteration/looping should be familiar to you, as it's a basic building block of any program/script. this kind of procedural logic is not part of the capability (or desired functionality) of regex itself. I assume you know how to create a iterative construct in R or whatever you're using for this.


text:
Q: How do you show that the differential of a map between smooth manifolds is smooth? Given a smooth map $f:M\to N$ between smooth manifolds how do you show that the differential map $df:TM\to TN$ is smooth?

A: This is proved in Proposition $3.21$ of Lee's Introduction to Smooth Manifolds (second edition) for example.
If $v \in TM$, then choosing a coordinate chart $(U, \varphi)$ containing $p = \pi(v)$ where $\pi : TM \to M$ is the projection, one obtains a coordinate neighbourhood $(\pi^{-1}(U), \widetilde{\varphi})$ containing $v$. More precisely, in local coordinates,
$$v = \left.v^1\frac{\partial}{\partial x^1}\right|_p + \dots + \left.v^m\frac{\partial}{\partial x^m}\right|_p$$
and $\widetilde{\varphi}(v) = (x^1(p), \dots, x^m(p), v^1, \dots, v^m)$. Once you have such charts, the local expression for $df$ becomes
$$df(x^1, \dots, x^m, v^1, \dots, v^m) = \left(f^1(x), \dots, f^n(x), \frac{\partial f^1}{\partial x^i}(x)v^i, \dots, \frac{\partial f^n}{\partial x^i}(x)v^i\right).$$
As $f$ is smooth, all the components of $df$ (in these local coordinates) are smooth, and therefore $df : TM \to TN$ is smooth.


text:
Q: writing to a .json file what is being used as a log in system, not working Im setting up a dice roll game for a computing gcse. I am having some troubles with adding new user to my .json file. I am new to coding and not the greatest at it so any help would appreciated! I want it to add a new usernames and passwords in the format {"username":"password"}
I have looked around on this forum and have tried changing how it is opening the file such as a and w. I get confused by all of the answers and cannot relate it to mine.
    path_to_json = "./logins.json"
    logins = json.load(open("logins.json", "a"))
    username = (input('New Username: '))
    password = (input('New Password: '))

    logins = ['login'].append({username:password})

    with open('logins.json', 'a') as outfile:
        json.dump(logins)

I am hoping it will add a user however I am getting the errors:

Traceback (most recent call last):   File "", line 1, in

      new_user()   File "N:\NEA Computing\NEA code.py", line 32, in new_user
      logins = json.load(open("logins.json", "a"))   File "C:\Program Files\Python36\lib\json__init__.py", line 296, in load
      return loads(fp.read(), io.UnsupportedOperation: not readable

I have got a .json file in my directories on my computer.

A: Change the "a" to "r" in order for your file to be readable.
 logins = json.load(open("logins.json", "r"))

A: @kuco23 solved first issue but there were several other of them. First being, you don't have to assign while using append() on Python lists. While second being, dump() expects a file pointer as another parameter.
Also, I'm not sure why you were using append more for writing since you are already appending in list. I changed that to write mode.
import json

path_to_json = "./logins.json"
with open("logins.json", "r") as content:
    logins = json.load(content)

username = input('New Username: ')
password = input('New Password: ')

logins.append({username: password})

with open("logins.json", "w") as outfile:
    json.dump(logins, outfile)

Or something closer to what OP did
import json

path_to_json = "./logins.json"
logins = json.load(open("logins.json", "r"))

username = input("New Username: ")
password = input("New Password: ")

logins.append({username: password})

json.dump(logins, open("logins.json", "w"))


text:
Q: Cборка андроид ММ 6.0.1 Получаю ошибку, которая связана с фреймворками:
frameworks/av/services/audiopolicy/AudioPolicyInterfaceImplLegacy.cpp: In member function 'virtual audio_io_handle_t android::AudioPolicyService::getInput(audio_source_t, uint32_t, audio_format_t, audio_channel_mask_t, int)':
frameworks/av/services/audiopolicy/AudioPolicyInterfaceImplLegacy.cpp:233:91: error: no matching function for call to 'android::AudioEffect::AudioEffect(effect_uuid_t*, int, int, int, int&, audio_io_handle_t&)'
         sp<AudioEffect> fx = new AudioEffect(&effect->mUuid, -1, 0, 0, audioSession, input);
                                                                                ^
frameworks/av/services/audiopolicy/AudioPolicyInterfaceImplLegacy.cpp:233:91: note: candidates are:
In file included from frameworks/av/services/audiopolicy/AudioPolicyService.h:32:0,
                 from frameworks/av/services/audiopolicy/AudioPolicyInterfaceImplLegacy.cpp:21:
frameworks/av/include/media/AudioEffect.h:247:5: note: android::AudioEffect::AudioEffect(const char*, const android::String16&, const char*, int32_t, android::AudioEffect::effect_callback_t, void*, int, audio_io_handle_t)
     AudioEffect(const char *typeStr,
     ^
frameworks/av/include/media/AudioEffect.h:247:5: note:   no known conversion for argument 1 from 'effect_uuid_t* {aka effect_uuid_s*}' to 'const char*'
frameworks/av/include/media/AudioEffect.h:234:5: note: android::AudioEffect::AudioEffect(const effect_uuid_t*, const android::String16&, const effect_uuid_t*, int32_t, android::AudioEffect::effect_callback_t, void*, int, audio_io_handle_t)
     AudioEffect(const effect_uuid_t *type,
     ^
frameworks/av/include/media/AudioEffect.h:234:5: note:   no known conversion for argument 2 from 'int' to 'const android::String16&'
frameworks/av/include/media/AudioEffect.h:209:5: note: android::AudioEffect::AudioEffect(const android::String16&)
     AudioEffect(const String16& opPackageName);
     ^
frameworks/av/include/media/AudioEffect.h:209:5: note:   candidate expects 1 argument, 6 provided
In file included from frameworks/av/services/audioflinger/AudioFlinger.h:44:0,
                 from frameworks/av/media/mediaserver/main_mediaserver.cpp:32:
frameworks/native/include/binder/BinderService.h: In instantiation of 'static android::status_t android::BinderService<SERVICE>::publish(bool) [with SERVICE = android::AudioPolicyService; android::status_t = int]':
frameworks/native/include/binder/BinderService.h:49:41:   required from 'static void android::BinderService<SERVICE>::instantiate() [with SERVICE = android::AudioPolicyService]'
frameworks/av/media/mediaserver/main_mediaserver.cpp:136:29:   required from here
frameworks/native/include/binder/BinderService.h:41:45: error: invalid new-expression of abstract class type 'android::AudioPolicyService'
                 new SERVICE(), allowIsolated);
                                             ^
In file included from frameworks/av/media/mediaserver/main_mediaserver.cpp:38:0:
frameworks/av/services/audiopolicy/AudioPolicyService.h:40:7: note:   because the following virtual functions are pure within 'android::AudioPolicyService':
 class AudioPolicyService :
       ^
In file included from frameworks/av/services/audiopolicy/AudioPolicyService.h:30:0,
                 from frameworks/av/media/mediaserver/main_mediaserver.cpp:38:
frameworks/av/include/media/IAudioPolicyService.h:45:22: note:  virtual android::status_t android::IAudioPolicyService::setDeviceConnectionState(audio_devices_t, audio_policy_dev_state_t, const char*, const char*)
     virtual status_t setDeviceConnectionState(audio_devices_t device,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:61:22: note:  virtual android::status_t android::IAudioPolicyService::getOutputForAttr(const audio_attributes_t*, audio_io_handle_t*, audio_session_t, audio_stream_type_t*, uid_t, uint32_t, audio_format_t, audio_channel_mask_t, audio_output_flags_t, audio_port_handle_t, const audio_offload_info_t*)
     virtual status_t getOutputForAttr(const audio_attributes_t *attr,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:72:22: note:  virtual android::status_t android::IAudioPolicyService::startOutput(audio_io_handle_t, audio_stream_type_t, audio_session_t)
     virtual status_t startOutput(audio_io_handle_t output,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:75:22: note:  virtual android::status_t android::IAudioPolicyService::stopOutput(audio_io_handle_t, audio_stream_type_t, audio_session_t)
     virtual status_t stopOutput(audio_io_handle_t output,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:78:18: note:  virtual void android::IAudioPolicyService::releaseOutput(audio_io_handle_t, audio_stream_type_t, audio_session_t)
     virtual void releaseOutput(audio_io_handle_t output,
                  ^
frameworks/av/include/media/IAudioPolicyService.h:81:23: note:  virtual android::status_t android::IAudioPolicyService::getInputForAttr(const audio_attributes_t*, audio_io_handle_t*, audio_session_t, uid_t, uint32_t, audio_format_t, audio_channel_mask_t, audio_input_flags_t, audio_port_handle_t)
     virtual status_t  getInputForAttr(const audio_attributes_t *attr,
                       ^
frameworks/av/include/media/IAudioPolicyService.h:90:22: note:  virtual android::status_t android::IAudioPolicyService::startInput(audio_io_handle_t, audio_session_t)
     virtual status_t startInput(audio_io_handle_t input,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:92:22: note:  virtual android::status_t android::IAudioPolicyService::stopInput(audio_io_handle_t, audio_session_t)
     virtual status_t stopInput(audio_io_handle_t input,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:94:18: note:  virtual void android::IAudioPolicyService::releaseInput(audio_io_handle_t, audio_session_t)
     virtual void releaseInput(audio_io_handle_t input,
                  ^
frameworks/av/include/media/IAudioPolicyService.h:127:22: note:     virtual android::status_t android::IAudioPolicyService::listAudioPorts(audio_port_role_t, audio_port_type_t, unsigned int*, audio_port*, unsigned int*)
     virtual status_t listAudioPorts(audio_port_role_t role,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:134:22: note:     virtual android::status_t android::IAudioPolicyService::getAudioPort(audio_port*)
     virtual status_t getAudioPort(struct audio_port *port) = 0;
                      ^
frameworks/av/include/media/IAudioPolicyService.h:137:22: note:     virtual android::status_t android::IAudioPolicyService::createAudioPatch(const audio_patch*, audio_patch_handle_t*)
     virtual status_t createAudioPatch(const struct audio_patch *patch,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:141:22: note:     virtual android::status_t android::IAudioPolicyService::releaseAudioPatch(audio_patch_handle_t)
     virtual status_t releaseAudioPatch(audio_patch_handle_t handle) = 0;
                      ^
frameworks/av/include/media/IAudioPolicyService.h:144:22: note:     virtual android::status_t android::IAudioPolicyService::listAudioPatches(unsigned int*, audio_patch*, unsigned int*)
     virtual status_t listAudioPatches(unsigned int *num_patches,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:148:22: note:     virtual android::status_t android::IAudioPolicyService::setAudioPortConfig(const audio_port_config*)
     virtual status_t setAudioPortConfig(const struct audio_port_config *config) = 0;
                      ^
frameworks/av/include/media/IAudioPolicyService.h:150:18: note:     virtual void android::IAudioPolicyService::registerClient(const android::sp<android::IAudioPolicyServiceClient>&)
     virtual void registerClient(const sp<IAudioPolicyServiceClient>& client) = 0;
                  ^
frameworks/av/include/media/IAudioPolicyService.h:152:18: note:     virtual void android::IAudioPolicyService::setAudioPortCallbacksEnabled(bool)
     virtual void setAudioPortCallbacksEnabled(bool enabled) = 0;
                  ^
frameworks/av/include/media/IAudioPolicyService.h:154:22: note:     virtual android::status_t android::IAudioPolicyService::acquireSoundTriggerSession(audio_session_t*, audio_io_handle_t*, audio_devices_t*)
     virtual status_t acquireSoundTriggerSession(audio_session_t *session,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:158:22: note:     virtual android::status_t android::IAudioPolicyService::releaseSoundTriggerSession(audio_session_t)
     virtual status_t releaseSoundTriggerSession(audio_session_t session) = 0;
                      ^
frameworks/av/include/media/IAudioPolicyService.h:160:26: note:     virtual audio_mode_t android::IAudioPolicyService::getPhoneState()
     virtual audio_mode_t getPhoneState() = 0;
                          ^
frameworks/av/include/media/IAudioPolicyService.h:162:22: note:     virtual android::status_t android::IAudioPolicyService::registerPolicyMixes(android::Vector<android::AudioMix>, bool)
     virtual status_t registerPolicyMixes(Vector<AudioMix> mixes, bool registration) = 0;
                      ^
frameworks/av/include/media/IAudioPolicyService.h:164:22: note:     virtual android::status_t android::IAudioPolicyService::startAudioSource(const audio_port_config*, const audio_attributes_t*, audio_io_handle_t*)
     virtual status_t startAudioSource(const struct audio_port_config *source,
                      ^
frameworks/av/include/media/IAudioPolicyService.h:167:22: note:     virtual android::status_t android::IAudioPolicyService::stopAudioSource(audio_io_handle_t)
     virtual status_t stopAudioSource(audio_io_handle_t handle) = 0;
                      ^
make: *** [/home/mirsaid02/CM13.0/out/target/product/glacier/obj/SHARED_LIBRARIES/libaudiopolicyservice_intermediates/AudioPolicyInterfaceImplLegacy.o] Ошибка 1
make: *** Ожидание завершения заданий...
make: *** [/home/mirsaid02/CM13.0/out/target/product/glacier/obj/EXECUTABLES/mediaserver_intermediates/main_mediaserver.o] Ошибка 1


text:
Q: How to change color of label in Visual Studio's Text Editor? I'm using alot of label jump in my C# code. I want change these label color for better seeing. How can I change this? Thank.
goto someLabel;
someLabel: // <--------------------- I want change color of this text


text:
Q: Is there a fully quantum-field theoretic treatise of Planck's Law for black-body radiation? I recall from my undergraduate statistical mechanics and QM classes that Planck's Law may be derived fairly straight-forwardly by considering the density of states of EM radiation in thermal equilibrium with a particle inside a cubic box. Indeed the derivation on this wiki page is just the same and appears (IMO) to be fairly concise and accurate.
I wondered therefore, that if we invoke all the magic of QFT (such as the fields being promoted to operators and higher (than tree-level) order particle interactions taken into account,) can a similar derivation still be carried out? (Or indeed a dissimilar one?)
Associated to which, would such a derivation (if it is even possible) require consideration of QED alone or would the effects of the broken electro-weak symmetry have a significant effect on recreating the correct radiation spectrum?

A: The derivation of the Planck distribution takes into account the quantization of the electromagnetic field: any particular wave-vector of the field can have quantized energies, which are interpreted as the number of photons times the energy of each one of them. At the time Planck derived his formula, this is all he needed. He had no formulation of a physical theory in which the electromagnetic field was quantized, but he showed that when you manage to get one, that quantization alone will be sufficient.
In quantum field theory, this is built-in as the starting point: you promote each field to an operator, and when you "second quantize"* you satisfy the requirement for the deriving the Planck spectrumm - the energy in each mode of the electromagnetic field is quantized. I believe second quantization of the Maxwell field (no need to add electrons to get QED) can be found in every text on the subject. After you do that, the derivation of the Planck spectrum is not all that different from Planck's.
This is only the starting point though. Once you have QFT you can add interactions and calculate corrections to the spectrum and any other thermodynamic quantity - due to QED, electroweak symmetry breaking, and what have you. Those will be normally small corrections**.
For the spectrum, the corrections comes effectively from adding interactions between the photons. The single photon stays massless (because of gauge invariance) and therefore its spectrum does not get modified. But the energy of two photons is no longer the sum of their individual energies. This should correct the measured spectrum in a small way.
(As a side comment: those calculations in thermal field theory are not that simple, as compared to usual loop integrals you get at zero temperature.)

*

*Just for the record, I strongly dislike this term for other reasons, but here is seems appropriate.

** It is interesting whether or not such corrections have been measured - thermal effects of QED. I don't know the answer to that.


text:
Q: How do I retrieve/iterate over and save the users positions to a model w/LinkedIn? omniauth-linkedin-oauth2 Rails 5.2 I've been able to complete the oauth2 login process and grant the current_user access to the application with Devise. My main goal was to iterate over the user's positions from LinkedIn and create a Position.create(..) object for each individual position & then save their user_id to the object after a successful LinkedIn login attempt. Afterwards, I would just display the information inside of the app. It should check for a Position where its first_or_create, to avoid duplicating the data on each login attempt. How can I get the user's positions and company hash (JSON object) to store inside of the database?
I created a position model with a company JSON serializable attribute. I attempted to retrieve the user's profile using the auth.extra.info.positions fields. Afterwards, I tried to retrieve the information from the user in session. I could not succeed in getting an array of Positions back.
create_positions.rb | migration
class CreatePositions < ActiveRecord::Migration[5.2]
  def change
    create_table :positions do |t|
      t.string :title
      t.text :summary
      t.date :start_date
      t.date :end_date
      t.boolean :is_current
      t.json :company
      t.references :user, foreign_key: true

      t.timestamps
    end
  end
end

user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :omniauthable, :trackable, :confirmable,
         :omniauth_providers => [:twitter, :facebook, :linkedin, :google_oauth2,
                                 *(:developer if Rails.env.development?)]

  has_many :positions

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email
      user.name = auth.info.name
      user.password = Devise.friendly_token[0, 20]
      user.provider = auth.provider
      user.uid = auth.uid
    end
  end

  protected
  def confirmation_required?
    false
  end
end

position.rb
class Position < ApplicationRecord
  serialize :company, JSON
  belongs_to :user, dependent: :destroy
 end

omniauth_callbacks_controller.rb
# frozen_string_literal: true

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  skip_before_action :verify_authenticity_token

  def sign_in_with(provider_name)
    @user = User.from_omniauth(request.env['omniauth.auth'])
    sign_in_and_redirect @user, event: :authentication
    set_flash_message(:notice, :success, kind: provider_name) if is_navigational_format?
  end

  def save_user_positions
     Position.create(:title => auth.extra.info.positions['title'], :summary => auth.extra.info.positions['summary'], :start_date => auth.extra.info.positions['start-date'], :end_date => auth.extra.info.positions['end-date'], :is_current => auth.extra.info.positions['is-current'], company: {id: auth.extra.info.positions.company['id']})

end
      def facebook
        sign_in_with 'Facebook'
      end
  def linkedin
    sign_in_with 'LinkedIn'
  end

  def twitter
    sign_in_with 'Twitter'
  end

  def google_oauth2
    sign_in_with 'Google'
  end

  def developer
    sign_in_with 'Developer'
  end
end

Expected Results: When User logs into LinkedIn through omniauth, their positions/companies are saved to the rails database.
Actual Results: Only user email/name/basic attributes are retrievable.


text:
Q: Qual a maneira correta de adicionar um botão no arquivo php Estou precisando colocar um botão em meu arquivo php onde irei utilizar para cadastrar. Segue o código.
echo "<button type=\'"button"'\ class=\'"btn btn-default btn-lg"'\>";
        echo " Inserir";
    echo "</button>";

Qual a maneira correta de fazer ?

A: Não precisa disso, Renan.
Feche a rotina PHP com o ?> e adiciona o botão na linguagem HTML mesmo.
Mas se for realmente necessário fazer isso que você quer:
echo "<button type='button' class='btn btn-default btn-lg'> Inserir </button>";

Pense sempre assim:
" Aspas Simples 'dentro' de Aspas Duplas "
ou
' Aspas Duplas "dentro" de Aspas Simples '

A: Procure utilizar mais html e menos php. Um exemplo:
....
?>
<button type="button" class="btn btn-default btn-lg <?php echo $algumaClasse; ?>">

        <?php echo $algumaAcaoParaBotao; ?>
</button>
<?php
....

Esta seria a melhor forma.


text:
Q: How to create hierarchy of projects in MS Project Server PWA? I need to create a hierarchy of projects as well as projects access rights within MS-PWA.
the idea is to have a "Corporate Project" , of which underneath it resides our R&D, Finance, Marketing projects.

*

*Restricitions off course should apply per project (some will have access to the root project - while others only access to their specific projects (sales people, marketing dept, etc.)

Is it possible to create such Hierarchy in MS-Project Server 2010 PWA?

A: Answer to your question is: No, you cannot insert project into another project using PWA, you cannot define cross project links using PWA. This can be done only using Project Pro.
And btw we also started with the same idea: to have a master project and manage security on a level of sub projects. That idea failed because it took too long to open the master - Project Pro opens all subproject together with master to update progress; another problem was high integration of the subprojects - too many cross project links.
One of reasons why you may want to create such structure is to see a progress of the whole company using data from departmental subprojects. Here is another problem - only Project Pro can update status of the master.
I would recommend to create a view(s) in PWA just to see all of the projects grouped somehow together - this will be easier and faster.


text:
Q: Launch4j doesn't work (main class not found) I am using Launch4j to create an setup file. I have 7 classes, under a package. And JavaSamp is my main class. I have created jar files for all the classes. And my launch4j looks like this:
 <launch4jConfig>
  <dontWrapJar>true</dontWrapJar>
  <headerType>gui</headerType>
  <jar></jar>
  <outfile>install\Piratechx.exe</outfile>
  <errTitle></errTitle>
  <cmdLine></cmdLine>
  <chdir>.</chdir>
  <priority>normal</priority>
  <downloadUrl>http://java.com/download</downloadUrl>
  <supportUrl></supportUrl>
  <customProcName>true</customProcName>
  <stayAlive>false</stayAlive>
  <manifest></manifest>
  <icon></icon>
  <classPath>
    <mainClass>JavaSamp</mainClass>
    <cp>lib/JavaSamp.jar</cp>
    <cp>lib/DataBaseHelper.jar</cp>
    <cp>lib/JavaDemo.jar</cp>
    <cp>lib/FileEncryption.jar</cp>
    <cp>lib/SendEmail.jar</cp>
    <cp>lib/WriterHelper</cp>
  </classPath>
  <jre>
    <path>jre6</path>
    <minVersion></minVersion>
    <maxVersion></maxVersion>
    <jdkPreference>jreOnly</jdkPreference>
  </jre>
  <versionInfo>
    <fileVersion>1.0.0.0</fileVersion>
    <txtFileVersion>1.0</txtFileVersion>
    <fileDescription>Piratechx</fileDescription>
    <copyright>Copyright (c) 2007 FSP</copyright>
    <productVersion>1.0.0.0</productVersion>
    <txtProductVersion>1.0</txtProductVersion>
    <productName>Piratechx</productName>
    <companyName>FSP</companyName>
    <internalName>Piratechx</internalName>
    <originalFilename>Piratechx.exe</originalFilename>
  </versionInfo>
 </launch4jConfig>

Any suggestion pls...

A: You can't just define JavaSamp as main class. If it is in a seperate namespace or something (which it probably is considering you are using multiple jars) you would need to declare the full 'proper' name


text:
Q: Which type of OpenAPI pattern format is valid? Currently looking at an openapi.yaml that has two different formats for the pattern validator for a string.
    Country:
      pattern: ^(A(D|E|F|G|I|L|M|N|O|R|S|T|Q|U|W|X|Z)|B(A|B|D|E|F|G|H|I|J|L|M|N|O|R|S|T|V|W|Y|Z))$
      type: string
    Currency:
      pattern: /^AED|AFN|ALL|AMD$/
      type: string

The documentation doesn't show / as a boundary character at all, so is this valid or invalid?
I've used the Swagger Editor to input both but neither gives an error.

A: The correct format for the pattern is myregex (formatted as a YAML or JSON string, with proper escaping if needed), not /myregex/ or /myregex/flags.
Source: https://github.com/OAI/OpenAPI-Specification/issues/1985
Examples of valid patterns:
# YAML
pattern: \d+      # not anchored
pattern: ^\d+$    # anchored

pattern: '\d+'    # \d+
pattern: "\\d+"   # \d+

# JSON
"pattern": "\\d+"     # \d+
"pattern": "^\\d+$"   # ^\d+$

In your example, the Country pattern is correct, and the Currency pattern is incorrect.
In case of pattern: /^AED|AFN|ALL|AMD$/ (which is equivalent to pattern: "/^AED|AFN|ALL|AMD$/"), the / is considered a part of the pattern string itself, not the boundary character. As a result, this pattern won't match anything because extra characters appear outside of ^...$.


text:
Q: Importing file fails in Node.js when implementing server side rendering I'm working on a implementing server side rendering on React project written in typescript. All the components,containers and other directories are in src directory.
When react imports a file from say ./src/providers/xxProvider.ts it can simply import it as import * from "providers/xxProvider". I'm guessing this is something done by webpack when bundling.
But now when I'm trying to use Node.js for ssr, node.js cannot find the xxProvider file when its imported as import * from "providers/xxProvider" because it starts looking in node_modules.
How can I solve this issue?

A: You probably do not have proper path mapping defined in your tsconfig.json. Try this for example:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": [
        "*",
        "src/*"
      ]
    }
  }
}

A: I found the answer. The issue is from using the webpack-node-externals plugin. When we use that, webpack will automatically ignore the node-modules folder when bundling.
When I import something as import * from providers/xxProvider and at the same time I have a directory in node_modules as providers/xxx, webpack will exclude all directories called providers when bundling.


text:
Q: Swagger basic authentication fails with php client When I try to use the generated php client from a yaml file it doesn't seem to work. I get a authentication error even though I had filled in the configuration for the authentication. But when I replace the options variable inside the generated API with the basic auth options it does work. See the code below:
public function getLiveWegvakkenDataWithHttpInfo()
    {
        $returnType = '\Swagger\Client\Model\Wegvak[]';
        $request = $this->getLiveWegvakkenDataRequest();

    try {
        $options = $this->createHttpClientOption();
        try {
            $response = $this->client->send($request, $options);
        } catch (RequestException $e) {
            throw new ApiException(
                "[{$e->getCode()}] {$e->getMessage()}",
                $e->getCode(),
                $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
            );
        }

The above code doesn't work but when I replace the $options with this:
[
    'auth' => [
         'username',
         'password',
]]

It does work. Can someone explain what I am doing wrong? Since it seems weird to me that the standard implementation doesn't work.

A: I found out in the end that my yaml file didn't include this: https://swagger.io/docs/specification/authentication/basic-authentication/
In the docs above it says that you need this code:
components:
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
security:
  - basicAuth: []

When you add this code it will implement inside the API code to actually use the basic authentication that you filled in inside the configuration. Otherwise without it, it will just make requests without adding the auth inside the request header.
So after adding this and filling in the configuration it worked for me.


text:
Q: how to get javascript variable in java? (like javascript parser?) like code:
public static void main(String[] args) throws Exception {
    String content=""
     +"<TITLE>title</TITLE>"
     +""
     +""
     +"
"
     +""
     +""
    ;
}

in this case,how to get jsvar variable value?
thanks for help :)

A: If you want to execute JavaScript code in Java, You can use scripting API of Java 6 and Java 6 is included with Mozilla Rhino engine.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
jsEngine.eval("jsvar = 123");
System.out.println(jsEngine.get("jsvar")); //prints 123.0

Reference: http://download-llnw.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

A: Seems to me that this is backward. If you are serving the page then you already have the value on the server. I would inject the value from Java into JavaScript not the other way around.

A: In fact, you're asking something that requires a browser. As a consequence, you may have to take a look at HtmlUnit, which could solve your issue.
However, were you to directly run pure javascript code from Java, you would have better using a Javascript interpreter like Rhino (I think).


text:
Q: How to call a function that is in the code behind of jquery dialog I try to show jquery dialog by clicking the Delete button ( which also serves to erase data if the user than in the dialog ), but when I press the Delete dialog then disappears after the second and screen pops .
I'd love someone to help me because I really green in jquery
And how to check user code approved in dialog
Thank you :)

    <script type="text/javascript">
            $(function () {
                $("#dialog-confirm").hide();
                $("#but_Delete").click(function () {
                    $("#dialog-confirm").dialog({
                        resizable: false,
                        height: 250,
                        width: 500,
                        modal: true,
                        buttons: {
                            "delete": function () {
                                $.ajax({
                                    type: "GET",
                                    contenttype: "application/json; charset=utf-8",
                                    data: "{null}",
                                    url: "Home.aspx/but_Delete_Click",
                                    dataType: "json",
                                    success: function but_Delete_Click(res) {

                                    },

                                });
                                $(this).dialog("close");
                            },
                            "Cancel": function () {
                                $(this).dialog("close");
                            }
                        }

                    });

                    //$(".selector").dialog({Zz
                    //    closeOnEscape: false

                    //});
                });

            });

  </script>

protected void but_Delete_Click()
{
     if (TextBox_campeny.Text != null || TextBox_Addres.Text != null || TextBox_tel.Text != null)
     {
           con.Open();
           string id = tb.Tables[0].Rows[i]["id"].ToString();
           SqlCommand cmd = new SqlCommand("Delete from tbl_Customer where Id='" + id + "'", con);
           cmd.ExecuteNonQuery();
           Response.Write("blabla!");
           con.Close();
           con.Open();
           SqlCommand cmd_u = new SqlCommand("Delete from tbl_Users where IdCustomer='" + id + "'", con);
           SqlDataAdapter dac = new SqlDataAdapter(cmd_u);
           dac.Fill(tb);
           if (butuc == 1)
           {
                 Response.Redirect("LoginPage.aspx");
           }
           else
           {
                 if(tb.Tables[0].Rows.Count != 1)
                 {
                     if (i == 0)
                     {
                           bind();
                     }
                     else
                     {
                           if (tb.Tables[0].Rows.Count - 1 == i)
                           {
                                  i--;
                                  bind();
                           }
                           else
                           {
                                  bind();
                           }
                      }
                      else
                      {
                           Empty_Textbox();
                           but_Delete.EnableTheming = false;
                      }

                  }
             }
             con.Close();
       }
}

A: This deletion button when pressed appears Dialog

     <input type="button" value="Delete" id="but_Delete" name="but_Delete" runat="server" />

and this is the div of the dialog

 <div id="dialog-confirm" title="Are you sure you want to delete?">

A: Because of server side

*

*Remove custom dialog box, use window confirm

*Create new function in javascript OnClick="but_Delete_Click"     OnClientClick="return somefunction();"
function somefunction() {
        return window.confirm("Are you sure you want to delete?");
}

*public void but_Delete_Click(object sender, EventArgs e)
Note :
1. use update panel for use but_Delete_Click event from javascript with __doPostBack()
2. you can use web method but server side control like textbox or button not find in it you should manual passed from parameter which value use in web method