text:
Q: Apply CsvHelper custom converter to specific class map field(s) Running CSVHelper 7.0.0 and trying to add a custom string convertor that can be applied to specific class map fields (do not want to applied globally to all fields of type string). Below are snippets on how I currently have my class map, custom convertor, and csv writter calls setup.
Class Map code snippet with custom convertor on NextReviewDate map field:
public sealed class MyCustomClassMap : ClassMap<MyCustomClass>
{
    public MyCustomClassMap()
    {
        Map(m => m.ContentId).Index(0);
        Map(m => m.Name).Index(1);
        Map(m => m.ContentOwner).Index(2);
        Map(m => m.ContentOwnerName).Index(3);
        Map(m => m.CopyrightOwner).Index(4);
        Map(m => m.CopyrightOwnerName).Index(5);
        Map(m => m.NextReviewDate).Index(6).TypeConverter<DateTimeStringConverter>();
        Map(m => m.ContentStatus).Index(7);
        Map(m => m.UsageRights).Index(8);
        Map(m => m.SchemaName).Index(9);
    }
}

Custom string converter code snippet:
public class DateTimeStringConverter : StringConverter
{
    public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
    {
        string formattedDateString = string.Empty;

        if (DateTime.TryParse(text, out DateTime dateobj))
        {
            formattedDateString = dateobj.ToString("MM-dd-yyyy");
        }

        //throw new Exception("DateTimeStringConverter value: " + formattedDateString);

        return formattedDateString;
    }
}

Snippet of code of how I am registering my class map and write records:
csv.Configuration.RegisterClassMap<MyCustomClassMap>();

csv.WriteRecords(results);

To troubleshoot I added a throw exception in DateTimeStringConverter and appears it never gets called. Am I missing a piece? Right now the CSV is generating and includes the original NextReviewDate map field value without ever calling the custom convertor.
EDIT: based on @Self feedback changing custom string converter to the following resolved issue:
public class DateTimeStringConverter : DefaultTypeConverter
{
    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        string strVal = (string)value;

        if (DateTime.TryParse(strVal, out DateTime dateobj))
        {
            strVal = dateobj.ToString("MM-dd-yyyy");
        }

        return strVal;
    }
}

A: CSV Helper 26.1.0
First StringConverter offers only one method to overwrite object ConvertFromString(..).
The converstion to string is handled by nothing because it's suppose to be a string.
Here I supposse that your Type is DateTime and you got it in multiple Exotique format.  If you have only one format you can change the default format for that type.
A simple demo class and it's mapping:
public class Test
{
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
    public DateTime Date { get; set; }
    public DateTime Time { get; set; }
}
public sealed class TestMap : ClassMap<Test>
{
    public TestMap()
    {
        AutoMap(CultureInfo.InvariantCulture);
        Map(x => x.Date).TypeConverter(new DateStringConverter("MM - dd - yyyy"));
        Map(x => x.Time).TypeConverter(new DateStringConverter("mm # hh # ss"));
    }
}

I used a converter that inherit from ITypeConverter in order to have both ConvertFromString and ConvertToString.
With Customisable Format, culture, and style.
public class DateStringConverter : ITypeConverter
{
    private readonly string _dateFormat;
    private readonly CultureInfo _CultureInfo;
    private readonly DateTimeStyles _DateTimeStyles;

    public DateStringConverter(string dateFormat) :
    this(dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None)
    { }

    public DateStringConverter(string dateFormat, CultureInfo cultureInfo, DateTimeStyles dateTimeStyles)
    {
        _dateFormat = dateFormat;
        _CultureInfo = cultureInfo;
        _DateTimeStyles = dateTimeStyles;
    }

    public object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
    {
        string formattedDateString = string.Empty;
        if (DateTime.TryParseExact(text, _dateFormat, _CultureInfo, _DateTimeStyles, out DateTime dateObj))
        {
            return dateObj;
        }
        return null;
    }
    public string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        if (value == null) return string.Empty;

        if (DateTime.TryParse(value.ToString(), out DateTime dt))
            return dt.ToString(_dateFormat);
        else
            return string.Empty;
    }
}

Writing a CSV:
using (var writer = new StringWriter())
using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture, true))
{
    csvWriter.Context.RegisterClassMap<TestMap>();
    csvWriter.WriteRecords(datas);
    csvWriter.Flush();
    csvTextOuput = writer.ToString();
}

Result:
Id,DateTime,Date,Time
1,04/14/2021 09:18:02,04 - 14 - 2021,18 # 09 # 02
2,04/15/2021 09:18:02,04 - 15 - 2021,18 # 09 # 02
3,04/16/2021 12:18:02,04 - 16 - 2021,18 # 12 # 02

Reading a CSV:
using (var reader = new StringReader(csvTextOuput))
using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture, true))
{
    csvReader.Context.RegisterClassMap<TestMap>();
    ObjectFromCSV = csvReader.GetRecords<Test>().ToArray();
}

Result:
[
   {
   Date      : 04/14/2021
   DateTime  : 04/14/2021
   Id        : 1
   Time      : 04/14/2021
   },
   {
   Date      : 04/15/2021
   DateTime  : 04/15/2021
   Id        : 2
   Time      : 04/14/2021
   },
   {
   Date      : 04/16/2021
   DateTime  : 04/16/2021
   Id        : 3
   Time      : 04/14/2021
   }
]

Live demo https://dotnetfiddle.net/EMdhtn

CSV Helper 7
https://dotnetfiddle.net/5DgwxY
The only modification should be the absence of culture in the reader/writer ctor. And RegisterClassMap that moved from Configuration to Context

*

*~new CsvReader(reader, CultureInfo.InvariantCulture, true))~ => new CsvReader(reader))

*~csvWriter.Context.RegisterClassMap()~ => csvWriter.Configuration.RegisterClassMap();

Homogenous datetime format accros all property.
In case youhave the same format everywhere you those proposed solution:

*

*CsvHelper changing how dates and times output
N.B:TypeConverterFactory or TypeConverterCache on older version.


text:
Q: Java Vector Stack Contains Implementation My contains and remove method is not returning the right output. This program takes a stack of names and use the contains, remove, and empty method. I wrote my methods and I'm using a driver to see if I wrote my methods correctly. I'm pretty sure that all my methods are correct besides contains and remove method. Here's my code

    public boolean remove(T obj) {
        if (obj == null)
            return false;
        while (!store.empty() && store.peek().compareTo(obj) < 0) {
            temp.push(store.pop());
        }

        store.pop();

        while(!temp.empty()) {
            store.push(temp.pop());
        }
        size--;
        return true;
    }

public boolean contains(T obj) {
    while (!store.empty() && store.peek().compareTo(obj) < 0) {
        if (store.peek().equals(obj)) {
            return true;
        } else temp.push(store.pop());
    }
    while(!temp.empty()) {
        store.push(temp.pop());
    }
    return false;
}

A: Here are implementations of the methods remove and contains:
public boolean remove(T obj) {
    if (obj == null)
        return false;
    boolean removed = false;
    while (!store.empty()) {
        if(store.peek().equals(obj)) {
            store.pop();
            size--;
            removed = true;
        }else {
            temp.push(store.pop());
        }
    }

    while (!temp.empty()) {
        store.push(temp.pop());
    }
    return removed;
}

public boolean contains(T obj) {
    while (!store.empty()) {
        if (store.peek().equals(obj)) {
            return true;
        } else
            temp.push(store.pop());
    }
    while (!temp.empty()) {
        store.push(temp.pop());
    }
    return false;
}

The problem with your implementation of remove was that there was no if statement that tested equality of the objects, which should be removed. The remove method also was returning true and decrementing size regardless if the object was removed or not.
The problem with contains method was that it was never testing equality of objects.

You should apply DRY(Don't Repeat Yourself) principle. Having that on mind you should extract code
    while (!temp.empty()) {
        store.push(temp.pop());
    }

into separate method and don't repeat the same code again and again. Something like this:
private void pushFromTempToStore(){
    while (!temp.empty()) {
        store.push(temp.pop());
    }
}

Than your methods could look like this:
public boolean add(T obj) {
    if (obj == null)
        return false;
    while (!store.empty() && store.peek().compareTo(obj) < 0) {
        temp.push(store.pop());
    }
    store.push(obj);
    pushFromTempToStore();
    size++;
    return true;
}

public boolean remove(T obj) {
    if (obj == null)
        return false;
    boolean removed = false;
    while (!store.empty()) {
        if(store.peek().equals(obj)) {
            store.pop();
            size--;
            removed = true;
        }else {
            temp.push(store.pop());
        }
    }

    pushFromTempToStore();
    return removed;
}

public boolean contains(T obj) {
    while (!store.empty()) {
        if (store.peek().equals(obj)) {
            return true;
        } else
            temp.push(store.pop());
    }
    pushFromTempToStore();
    return false;
}

Another important thing to have in mind is testing. You should use some testing framework, like JUnit or TestNG, instead of a driver. There are plenty of materials to learn about testing. Here is a nice book that helped me a lot Test-Driven Java Development. It's a bit dated, so maybe you should try to find some newer resources...

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get sum of vowels in list in kotlin i need to get sum of vowels from list of strings with help function .fold
i tried:
val student = listOf("Sheldon", "Leonard", "Howard", "Raj", "Penny", "Amy", "Bernadette")

val vowels = setOf('a','A','e','E','i','I','o','O','y','Y','u','U')

val sumVowels = student.fold(0){acc, student, ->
if(student.contains(vowels)) acc + 1 else acc + 0

I don't know how to place vowels in .contains. Maybe I choose not the right way to solve the problem, but I should use fold anyway

A: val list = listOf("Sheldon", "Leonard", "Howard", "Raj", "Penny", "Amy", "Bernadette")
val vowels = setOf('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'y', 'Y', 'u', 'U')

val result = list
  .joinToString("")
  .count { char -> char in vowels }

println(result)   // Output: 16

A: you can write
val sumVowels = student.fold(0){acc, s -> acc + s.count{it in vowels}}

A: val list = listOf("Sheldon", "Leonard", "Howard", "Raj", "Penny", "Amy", "Bernadette")
val vowels = setOf('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'y', 'Y', 'u', 'U')
var numberOfVowels = 0
list.forEach{s ->
   numberOfVowels += s.count{it in vowels}
}
println(numberOfVowels)

Output: 16


text:
Q: Positive lookahead with javascript regex I have been messed up with regex.. I found it difficult for me..I have seen a code like:
function myFunction() {
   var str = "Is this all there is";
   var patt1 = /is(?= all)/;
   var result = str.match(patt1);
   document.getElementById("demo").innerHTML = result;
}

When i run this code it gave me the output is.
But when i add like /is(?=there)/ it didnt output anything. I am new to regular expression ..hope you guys  can help in in understanding positive lookahead in regex..I have followed many tutorials it didnt helped me.
Hope you guys can help me out. Thanks!

A: The Positive Lookahead fails for the fact that there does not immediately follow is.
is(?=there) # matches is when immediately followed by there

To match is if there follows somewhere in the string, you would do:
is(?=.*there)

Explanation:
is          # 'is'
(?=         # look ahead to see if there is:
  .*        #   any character except \n (0 or more times)
  there     #   'there'
)           # end of look-ahead

See Demo
A detailed tutorial I recommend: How to use Lookaheads and Lookbehinds in your Regular Expressions

A: The regex is(?= all) matches the letters is, but only if they are immediately followed by the letters all
Likewise, the regex is(?=there) matches the letters is, but only if they are immediately followed by the letters there
If you combined the two in is(?= all)(?=there), you are trying to match the letters is, but only if they are immediately followed both by the letters all AND the letters there at the same time... which is not possible.
If you want to match the letters is, but only if they are immediately followed either by the letters all or the letters there, then you can use:
is(?= all|there)
If, on the other hand, you want to match the letters is, but only if they are immediately followed by the letters all there, then you can just use:
is(?= all there)
What if I want is to be followed by all and there, but anywhere in the string?
Then you can use something like is(?=.* all)(?=.*there)
The key to understanding lookahead
The key to lookarounds is to understand that the lookahead is an assertion that checks that something follows, or precedes at a specific position in the string. That is why I bolded immediately. The following article should dispel any confusion.
Reference
Mastering Lookahead and Lookbehind


text:
Q: Bayes theorem confusion... A denotes event that present was hidden by mom.
B denotes event that present was hidden by dad.
E denotes event that present was hidden upstairs.
F denotes event that present was hidden downstairs.
P(A)=.6
P(B)=.4
P(E|A)=.7
P(F|A).3
P(E|B)=.5
P(F|B)=.5
Find P(E)
Can you explain why the answer is:
P(E) = P(A)P(E|A)+P(B)P(E|B)
     = (.6)(.7)+(.4)(.5)
     = .42 +.2
     = .62

A: The present could be upstairs in two different (and disjoint) ways: (i) Mom hid the hiding and hid the present upstairs or (ii) Dad did the hiding and hid it upstairs.
What is the probability of (i)? In symbols, it is $\Pr(A\cap E)$. But we have the general formula
$$\Pr(X|Y)\Pr(Y)=\Pr(X\cap Y)=\Pr(Y\cap X).$$
Putting $X=E$ and $Y=A$ gives us $\Pr(A\cap E)$.
Do a similar calculation for the probability of (ii), that is, $\Pr(B\cap E)$.
Then add up.


text:
Q: Devolver un Array con REACT Estoy obteniendo los datos de un fichero JSON con la información y he creado una función para obtener los datos de dicho fichero JSON. Hasta aquí bien, pero quiero poner estos datos en un DataGrid de MUI, que me pide rows y columns, las columnas las puse a mano pero los rows quiero rellenarlo automáticamente con los datos que obtengo del fichero JSON.
Código función:
function Productos() {
const [data, setData] = useState([]);
const getData = () => {
  fetch("dadesBD.json", {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  })
    .then(function (response) {
      //console.log(response);
      return response.json();
    })
    .then(function (myJson) {
      // console.log(myJson);
      setData(myJson);
    });
};
useEffect(() => {
  getData();
}, []);

return (

    {data && data.length > 0 && data.map((item) => (
           `
           id:${item.id}
           nombre:${item.nombre}
           `
      ))}

);

}
Lo que quiero llegar a conseguir es una const así:
const rows = [
{
  id: 1,
  nombre: "Jose",
},];

Para poder pasarle al componente:
<DataGrid
    rows={rows}
    columns={columns}
    pageSize={5}
    rowsPerPageOptions={[5]}
    checkboxSelection
    disableSelectionOnClick
  />

A: Ya lo solucione! Dejo mi ejemplo por si alguien le sirve de ayuda
https://codesandbox.io/s/hungry-wilbur-hpx48?file=/src/components/EjemploFetch/FetchDB.js


text:
Q: SharePoint autogenerated JSON formatting and use of operator or field choice not working I did a search on this topic and I am not that JSON familiar, so I thought I'd see if I can find the answer here to my question from the community.
I have a view from a list that I am formatting in SharePoint (SP) that creates some automated JSON.  It simply colors the items based on if the value matches in the generated JSON code.  I am trying to tweak it but having trouble getting the format to come up as a match.
I am trying to use just the one column called Display.  It's a calculated field which concatenates a bunch of string text.
Here is what the generated section of code from SP I am trying to tweak looks like (this is not all of it):
{  "operator": "==",
    "operands": [
    "[$Display]",
     "LOCATED"
    ]
     }, =if(@isSelected == "true" etc...

So the formatting will happen if the data in field Display = LOCATED returning true and will apply the formatting.  What I am trying to do, is get some sort of string contains or wild card matching.
The contents of the field Display in the SP list will contain something dynamic and possibly the word LOCATED somewhere in the text.
So ideally I'd like to tweak this code to return true for the formatting if the Display field content said something like  "John Doe LOCATED New York" for example.
if anyone has any ideas how I could solve this that would be great.  Also I was trying another field which is a choice field for exact matching but I couldn't get it to work either.
Thanks.

A: This issue has been resolved, by doing an exact field match instead of wildcarding.


text:
Q: Immer - Immer forbids circular references I am trying to query some post and I keep running into the same error:
[Immer] Immer forbids circular references
import { DataStore } from '@aws-amplify/datastore';
import { Post } from '../../models'

export default function HomeScreen ({ navigation }) {
const [post, setPost] = useState([]);

const fetchPost = async () => {
const results = await DataStore.query(Post);
setPost(results);

    };

    useEffect(() => {
    fetchPost();
    }, []);


text:
Q: Carousel View not refresh the content I want to create a multi-step like this UI:

So I create a CarouselView
<CarouselView>
        <CarouselView.ItemsSource>
            <x:Array Type="{x:Type ContentView}">
                <local:P1 Style="{DynamicResource BindingVariables}" />
            </x:Array>
        </CarouselView.ItemsSource>
        <CarouselView.ItemTemplate>
            <DataTemplate>
                <ContentView Content="{Binding .}" />
            </DataTemplate>
        </CarouselView.ItemTemplate>
    </CarouselView>

Even when I am adding the binding RelativeSource in page and four each list but when the properties of each page change the view still the same.
Any idea where is the problem?


text:
Q: Discord.py successfully sends an embedded image but it fails to load in channel I have created this nsfw command for my discord.py bot that sends a random gif from this subreddit as an embed. The command works fine as expected and throws no error messages, but the gif never loads in the discord channel after using the command.
Here is my code for the command:
# Here you can just add your own commands, you'll always need to provide "self" as first parameter.
@commands.hybrid_command(
    name="nsfw",
    description="Generates a random nsfw gif.",
)
# This will only allow non-blacklisted members to execute the command
@checks.not_blacklisted()
@commands.is_nsfw()
async def nsfw(self, context: Context):
    """
    Generates a random nsfw gif.

    :param context: The application command context.
    """
    embed = discord.Embed(title="Wowzers!", description="Here you go, ya horny bastard")
    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/NSFW_GIF/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await context.send(embed=embed)

This is the image failing to load.


text:
Q: Passing value from popup window to parent form's TextBox Work on ASP.NET Visual Studio 2008 C#. I have a page. From this page I need to call a page on popup. On the popup page selected value will be set on the parent page text control.

*

*One parent page

*One child page.

*Call parent to child as popup.

*On popup window contain a grid.

*On popup grid have command select,click on select  close popup and selected value will set on parent page text control.

I have done steps 1,2,3 and 4. But I need to complete step no 5.

A: On parent page:
<script type="text/javascript">
    function f1() {
        window.open("child.aspx");
    }
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><input type="button" onclick="f1();" value="pop up" />

On child page:
<script type="text/javascript">
function f2() {

    opener.document.getElementById("TextBox1").value = "hello world";
}
</script>
<input type="button" value="return hello world" onclick="f2();" />

Also you can pass ID of control which you want fill from child page as GET parameter:
window.open("child.aspx?controlID=<%=TextBox1.ClientID %>");


text:
Q: local storage not updating array properly I have a function that updates a stringified array of objects in local storage. Although it works locally it does not work properly for local storage. Wat happens is the local storage array of objects is updated to the new value but the old value disappears. here is my code...
addSingleItem = (item) => {

const itemName = item.split("-")[0];
const itemDescription = item.split("-")[1];
const itemPrice = item.split("-")[2];

try {

    let products = JSON.parse(localStorage.getItem("products"));

    products.map((product, index) => {

        if(product.name === itemName) {
            products.splice(index, 1);
            localStorage.setItem("products", JSON.stringify(products));
            document.getElementsById(`itemName-${itemName}`).innerText = "Add To Cart";
            return;
        }

    });

    products.push({
        name: itemName,
        description: itemDescription,
        price: itemPrice
    });

    localStorage.setItem("products", JSON.stringify(products));
    document.getElementsById(`itemName-${itemName}`).innerText = "Remove From Cart";

} catch(err) {

    localStorage.setItem("products", JSON.stringify([{
        name: itemName,
        description: itemDescription,
        price: itemPrice
    }]));

    document.getElementById(`itemName-${itemName}`).innerText = "Remove From Cart";

}

}

A: That is the way localStorage works. localStorage.setItem() does not add values to the existing key. It overwrites the existing localStorage key
If you want to append items instead of overwriting, you can use the following workaround:
let products = JSON.parse(localStorage.getItem("products"));
//I assume you stored something like this [{ name: "Apple", price: "10" }, { name: "Banana", price: "20" }]

//Then, if you want to add something:
products.push({ name: "Coffee", price: "140" });

//Then, localStorage.setItem("...", JSON.stringify(products));

When you edit localStorage variables you need to store the original value in a variable then, change variable values in a new variable, combine both and finally execute setItem() so that the old value also stays (if you want).


text:
Q: Depicting complex numbers Sorry for a stupid question but how would you depict
$0\leq arg(z)\leq \frac{7\pi}{3}$ on the complex plane?
Is this a circle or is it going to be the the same as when you depict $0\leq arg(z)\leq \frac{\pi}{3}$?
(Suppose $|z|=1$)

A: Firstly, as a geometrical angle, it is clear that whole circle rotations do not change the point, so angles differing by an integer multiple of $2\pi$ radians (a complete circle) are the same, as reflected by the figure below. Similarly, from the periodicity of $\sin (x)$ and $\cos (x)$, the definition
$$
z=r\left( \cos \varphi +i \sin \varphi \right)=re^{i \varphi}$$
also has this property. The argument of zero is usually left undefined.

A: It will be a circle, since all points with argument in the interval $[0,2 \pi)$ satisfy the inequality.


text:
Q: Confusion about conservation of angular momentum tensor in classical field theory? In my lectures, we considered the conserved stress energy tensor $T^{\mu \nu}$ and noted that we could always add a conserved tensor to it such that $T^{\mu \nu}$ is symmetric.
As a consequence, a tensor of higher rank, $M^{\lambda \mu \nu}= x^\mu T^{\lambda \nu} - x^{\nu}T^{\lambda \nu}$ is always conserved in that $\partial _{\lambda} M^{\lambda \mu \nu}=0$.
What I don't understand is that the claim is that the conservation of $M^{\lambda \mu \nu}$ results in the conservation of the total angular momentum tensor:
$J^{\mu \nu} = \int d^3x M^{0 \mu \nu}$
In essence, it is claimed that symmetry of stress energy tensor -> conservation of $M^{\lambda \mu \nu}$ -> Conservation of $J^{\mu \nu}$.
I don't see how this last step holds. I have tried the algebra, but I don't see how you can deduce anything about $\partial _{\mu} M^{0 \mu \nu}$, which you would need to vanish for $\partial _{\mu} J^{\mu \nu}$ to vanish i.e. for the angular momentum tensor to be conserved, based on $\partial _{\lambda} M^{\lambda \mu \nu}=0$ where $\lambda$ has not been set to 0, and is a sum over $\lambda$.

A: The quantity $J^{\mu\nu}(t)$ isn't a conserved current, it's a conserved quantity. Unlike $M^{\lambda \mu\nu}(\mathbf{x}, t)$, it doesn't have spatial dependence; at each time it is a tensor rather than a tensor field. The statement is that it doesn't depend on time at all.
The proof of this statement is just the same as the proof for a rank one tensor, since the extra indices just come "along for the ride". If we know $\partial_\mu J^\mu(\mathbf{x}, t) = 0$, then we define
$$Q(t) = \int J^0(\mathbf{x}, t) \, d^3x.$$
Then $Q(t)$ is conserved because
$$\frac{dQ}{dt} = \int \partial_0 J^0(\mathbf{x}, t) \, d^3x  = - \int \nabla \cdot \mathbf{J} \, d^3x = - \int \mathbf{J} \cdot d\mathbf{S} = 0$$
where the last integral is at spatial infinity, and we assume $\mathbf{J}$ vanishes there. The same proof works for $M^{\lambda \mu \nu}$ since the extra two indices don't interfere. (For the case of curved spacetime, see here.)


text:
Q: Asymmetry definitions electric $\chi_e$ and magnetic susceptibility $\chi_m$ Could anybody explain the asymmetry in the definitions of the electric susceptibility $\chi_e$ and the magnetic susceptibility $\chi_m$:
$$D=\epsilon_0 E+P\qquad\qquad P=\epsilon_0\chi_e E$$
$$B=\mu_0 H+\mu_0 M\qquad\qquad M=\chi_m H$$
The following definition would make more sense to me:
$$D=\epsilon_0 E+P\qquad\qquad P=\epsilon_0\chi_e E$$
$$B=\mu_0 H+M\qquad\qquad M=\color{red}{\mu_0}\chi_m H$$
Edit: The electric and magnetic parts appear in the Maxwell equations in a very similar way:
$$\nabla\times E+\frac{\partial B}{\partial t}=0$$
$$\nabla\times H-\frac{\partial D}{\partial t}=j$$
$$\nabla\cdot D=\rho$$
$$\nabla\cdot B=0$$

A: It's ultimately a matter of definition but note there is an asymmetry in how the defining factors $\epsilon_0$ and $\mu_0$ occur.
From Gauss's law
$$
\oint \vec E\cdot d\vec S =\frac{q_{encl}}{\epsilon_0}\qquad \qquad \vec\nabla \cdot \vec E=\frac{\rho}{\epsilon_0}
$$
with $\epsilon_0$ entering in the denominator.  From Ampere's law
$$
\oint \vec B\cdot d\vec \ell = \mu_0 I_{encl}\qquad \qquad \vec\nabla\times \vec B=\mu_0\vec J
$$
with $\mu_0$ now appearing in the numerator.  As a result the fields $\vec B$ and $\vec E$ which are defined by "elementary" integral laws are related to $\vec H$ and $\vec D$ by multiplicative or dividing factors rather than by two multiplicative or two dividing factors.  Note that the magnetization $\vec M$ is defined in terms of the field $\vec H$ whereas the polarization $\vec P$ is in terms of the "fundamental field" $\vec E$.


text:
Q: How do I store my ObjectResults to a POCO? This question is probably most trivial to most but I am just getting started with EF 4 and can't seem to assign my results from a stored procedure to my object.   Is this possible?
List<GetRotationSummary_Result> currentPD;
RotationData myData = new RotationData();

currentPD = context.GetData(compId, roleId, email).ToList()
MyData = currentPD;  // Can this even be done???

I want to store the data in the MyData object since users will have the ability to change the data.  After which I would like to update the database.    Completely open to any suggestions.   Many thanks.

A: You can't directly assign the objects like that since they are completely different types. You would need to create a function to do a field-by-field assignment of properties from currentPD to myData.  A tool like automapper can make this much easier.


text:
Q: How can I sleep my iMac's internal display when it's not in use, but not my attached tv (playing video) I've got a 2015 iMac running Yosemite, attached via HDMI to a 1080p TV, in extended desktop mode that I use simultaneously as a video server/media player and an occasional work machine.
In short, I'd like to sleep the internal display but not the external on demand.
More detail: I'd like to be able to run a video player (Plex) in full screen mode on the TV (Screen 2), but set the internal display (Screen 1) to automatically sleep if I'm not doing anything else on the computer but playing video on Screen 2.
Apps like Plex have an option to blank the other screen, but that doesn't work here, as I'd like to be able to use Screen 1 some of the time. I used to make this work on my old Mac Pro by simply turning the computer monitor off but leaving the TV on, but that's not an option with the iMac.
Something akin to an off switch (or hotkey) for the internal display (that doesn't disable the desktop) would be perfect, as I often remotely control Screen 1 from another computer while video is playing on Screen 2.
Have tried SwitchResX, which is great, but it doesn't seem to have the right combination of settings/features to meet my goals (or I've failed to figure them out).
Any advice would be appreciated. Thanks!

A: DisableMonitor
I found an open source project called DisableMonitor and it worked for me on macOS 10.12, Sierra, as well.

Warning
It has been reported that the software is able to cause irretrievable damages to your computer.
  Use at your own risk!
The project development has been stopped and won't be continued, if you want to be a maintainer consider opening an issue.

A: I don't think this is possible on macOS. For a portable, close the lid and run in closed clamshell mode. For iMac, you'll want to lower the brightness to minimum and then place a black (or other color) blanket or custom hood over it if light escaping or just seeing it faintly is your main concern.


text:
Q: Need to configure IIS for multiple clients. All of them will use a single code base but different application pools and databases I have a requirement to configure IIS for more than one client that will use a single codebase but different application pools and databases. For example, let's assume that the base URL of my website is https://www.mywebsite.com/ and I have five clients Client1, Client2, Client3, Client4, Client5. So the URLs should be the following: https://www.mywebsite.com/Client1, https://www.mywebsite.com/Client2, https://www.mywebsite.com/Client3, https://www.mywebsite.com/Client4, https://www.mywebsite.com/Client5, and every client must have its own application pool and database but they should use the same codebase.
Is there a possibility to configure IIS based on the above requirement?

A: I Suggest you to create an image from your codebase and use Docker to solve your problem.
You can move all of your database settings to config file and change them easily for each image.
Here is a tutorial of working with docker:
https://www.scalyr.com/blog/create-docker-image/


text:
Q: Using SQL Server 2008 R2 to query Progress OpenEdge10.2 We just acquired a company that has some apps running on Progress. We're a Microsoft shop and need to query the data from SQL Server (in the short term). We have the following ODBC drivers installed on SQL Server, but they don't show up when I try to add a link server, or as a provider under linked servers:
32-bit

64-bit

When I go to Linked Servers, I see this. I've never done anything with providers, so not sure if I need to add something.

The IT Guy there connects in VB.net using a connection string like this, but never got SQL to connect:
Driver={Progress OpenEdge 10.2B Driver};uid=USERNAME;host=HOSTNAME;db=DBNAME;port=2701;pwd=!PASSWORD

I tried using this as a connection string, but no luck.
Anyone know how to do this?
Thanks
Mark

A: Try this entry from the Progress Knowledgebase - http://knowledgebase.progress.com/articles/Article/P97292
If this doesn't suit, then you can search the KB for other options.

A: It's an ODBC driver, so focus on Microsoft OLE DB for ODBC Drivers
Here's an example for a DSN (Data Source Name) called 'Service Now'. That could be any database, probably not Progress, but a DSN is  DSN.
http://wiki.servicenow.com/index.php?title=Using_ODBC_Driver_in_SQL_Server_2008_and_2012
Create a DSN (in the system DSN tab of ODBCAD32) for your Progress database and reference it as in these examples.
Of course the bitness of your DSN needs to match the bitness of your SQL Server.
WARNING:
Using linked servers over unreliable ODBC drivers will give you headaches. You should test this thoroughly and be aware that in many cases if you, for example, join two tables over a linked sever, all of the data from the two tables will be dragged over and joined on the SQL Server. You can use OpenRowset to alleviate this as it lets you write pass through queries over a linked server.
You need to ensure that this really is a temporary measure!


text:
Q: MySQL SELECT JOIN WHERE ORDER BY performance I'm having two tables that are growing and slowly the queries that where always performing nice, don't perform so quick anymore.
I'm having two tables:
# Accounts table
CREATE TABLE `account` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `firstname` varchar(50) DEFAULT NULL,
  `lastname` varchar(50) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

# Orders table
CREATE TABLE `order` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `account_id` int(11) DEFAULT NULL,
  `datetime` datetime DEFAULT NULL,
  `ip` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

See SQLFiddle for full example with data.
The query in question
SELECT
    o.id,
    a.email
FROM `order` o
JOIN account a ON o.account_id = a.id
WHERE a.email LIKE '%@hotmail.com%'
ORDER BY o.id DESC
LIMIT 2

This query is running fast with just a couple of records. But using the EXPLAIN feature shows that it searches for all records in the account table, not te limited set of 2.

This ORDER BY o.id DESC will cause trouble in bigger tables. How can I fix this the best way?

*

*Split the query in two queries. First get all matching accounts, and then a second query on order with WHERE o.account_id IN (1, 3, 5) ORDER BY o.id DESC.

*Use subqueries (no clue how to).

*Other options...

I'm open for suggestions on how to handle this kind of queries in bigger datasets.
Note: I know this question is asked several times, but those questions don't have a answer I can use.

A: How about this:
SELECT
o.id,
a.email
FROM `order` o
JOIN (SELECT id, email
FROM account
WHERE email LIKE '%@hotmail.com%') a ON o.account_id = a.id
ORDER BY o.id DESC;

A: I think you may be able to 'trick' MySQL into delaying the lookups with something like this (untested):
SELECT x.id
     , x.email
  FROM
     ( SELECT o.id
            , a.email
         FROM `order` o
         JOIN account a
           ON o.account_id = a.id
        WHERE a.email LIKE '%@hotmail.com%'
        ORDER
           BY o.id DESC
        LIMIT 2
     ) x
  JOIN `order` y
    ON y.id = x.id
 ORDER
    BY y.id;


text:
Q: Trying to get enemy to deal damage every set seconds (Unity) I am creating a 3D Shooter and I am trying to make an enemy deal damage to the player every set seconds. I have made the enemy deal damage with a raycast but it deals the damage way too fast.
I thought using yield return new WaitForSeconds(2) would take 1 damage away from the player every 2 seconds but it deals damage to the player a lot faster.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMove : MonoBehaviour
{
    public Transform target;
    public Transform player;
    public float enemySpeed;
    public int moveTrigger = 1;
    public int isAttacking;

    public float distanceFromPlayer;

    void Update()
    {
        distanceFromPlayer = Vector3.Distance(target.transform.position, player.transform.position);

        if (distanceFromPlayer <= 10 && moveTrigger == 1)
        {
            transform.LookAt(target);
            StartCoroutine(EnemyDamage());
        }
        if (distanceFromPlayer <10 && moveTrigger == 1 && distanceFromPlayer >3)
        {
            transform.Translate(Vector3.forward * enemySpeed * Time.deltaTime);
        }
    }

    IEnumerator EnemyDamage()
    {
        RaycastHit PlayerHit;
        if (Physics.Raycast(target.transform.position, target.transform.forward, out PlayerHit))
        {
            Debug.Log(PlayerHit.transform.name);
            Target target = PlayerHit.transform.GetComponent<Target>();
            if (target != null)
            {
                yield return new WaitForSeconds(2);
                GlobalHealth.playerHealth -= 1;
                yield return null;
            }
        }
    }
}

A: You are starting a coroutine in every update loop so every frame your damage coroutine gets called and applies your 1 damage after 2 seconds.
If you want a damage over time effect the suggestion of using an game tick timer is correct, but if you want your enemy to only be able to attack every x seconds you need to implement some kind of cooldown on your damage function. For example add up Time.deltaTime until the time you want has past, and only then the enemy is able to deal damage again. You can do that with a boolean.

A: You can use FixedUpdate → set a local variable bool alreadyShoot = false.

*

*In your EnemyDamage() add a if(!alreadyShoot) before damages application and set alreadyShoot to true after damages application.

*In FixedUpdate you can set alreadyShoot to false.
You can choose an other solution to set alreadyShoot to false instead of FixedUpdate (for example a coroutine that trigger each seconds, ...)

A: in update loop, check when two seconds have passed when the player is in range
float timeInRange = 0.0f;
bool inRange = false;

if (distanceFromPlayer <= 10 && moveTrigger == 1)
{
    inRange = true;
}
else
{
    inRange = false;
    timeInRange = 0;
}

if (inRange)
{
    timeInRange += Time.DeltaTime;
}

if (timeInRange > 2.0f)
{
    GlobalHealth.playerHealth -= 1;
    timeInRange = 0.0f;
}

A: As mentioned in other answers, you are starting a new coroutine each frame. You should do all your waiting and looping inside your coroutine, as execution exits and re-enters your coroutine from the yeild statment. This is how you would write this to work
// in update
if (distanceFromPlayer <= 10 && moveTrigger == 1){
        transform.LookAt(target);
        if(!isAttacking)
            StartCoroutine(EnemyDamage());
}

IEnumerator EnemyDamage()
{
    isAttacking = true;
    while(distanceFromPlayer <= 10){ // in range
        RaycastHit PlayerHit;
        if (Physics.Raycast(target.transform.position, target.transform.forward, out PlayerHit)){
            Target target = PlayerHit.transform.GetComponent<Target>();
            if (target != null){
                GlobalHealth.playerHealth -= 1;
                yield return new WaitForSeconds(2);
            }
        }
    }
    isAttacking = false; // out of range
    yield return null;
}


text:
Q: I would like to close one already open div and show another when I click a link I have this function that opens and closes a div when I click a link, and close it again on the next click on the same link. It works just fine.
But now I would like add another div that shows when page load, but close when I click the same link I use to open the first div. Is that possible to fix?
I have searched for simular function but I hav not find a one that does the job.

...show more...

 ... my content

This content should be seen when page loads but hidden after click on the link

A: Add this to your function:
document.getElementById('my_new_div').style.display = "none";


text:
Q: What does Angular Material's dashboard schematic boilerplate code do? I used an Angular schematic (ng generate @angular/material:dashboard) to generate the following code in the component.ts file:
cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
map(({ matches }) => {
  if (matches) {
    return [
      { title: 'Card 1', cols: 1, rows: 1 },
      { title: 'Card 2', cols: 1, rows: 1 },
      { title: 'Card 3', cols: 1, rows: 1 },
      { title: 'Card 4', cols: 1, rows: 1 }
    ];
  }

  return [
    { title: 'Card 1', cols: 2, rows: 1 },
    { title: 'Card 2', cols: 1, rows: 1 },
    { title: 'Card 3', cols: 1, rows: 2 },
    { title: 'Card 4', cols: 1, rows: 1 }
  ];
})

);
However I'm having trouble understanding what it's doing. There are several components that cause some confusion:

*

*What is the => syntax doing? I had trouble coming up with a Google search since it is a symbol. EDIT: The answer to this is here

*What is the map function doing? I understand map, but normally I'm mapping a function to a set of values. Is that what is happening here? Said another way, what is being mapped onto what?

*What is the pipe function doing here? From this post I understand:

The pipe() function takes as its arguments the functions you want to
  combine, and returns a new function that, when executed, runs the
  composed functions in sequence.

However it's not clear to me what the composed functions are doing here.

A: *

*The pipe simply allow you to combine mutiple functions. Instead of having :

f1(f2(f3(param)));

You'll have:
pipe(f1, f2, f3)(param);

Here is a good explanation : How pipe works

*

*The map is part of rxjs, a set of tool, it will project each item of an observable. Here the related docuentation : Understanding map. Here, matches is a special attribute of Angular which is true when the conditions inside observe are true. Matches is being mapped into the if condition. In this case, if the breakpointObserver detects that the screen is smaller than handset, matches will be true and subsequently only a single column of cards will be returned. Otherwise, the if condition resolves to false and the two column version is returned. See this blog for a detailed explanation.

*The arrow function (lambda) is just a way to write a function, so instead of:
Observable.map(item => {//do something});
You could have :
Observable.map(function(item) {//do something});
Be aware that the arrow function hide some behaviors I wouldn't risk myself to explain, but in React (since you added the tag), the arrow function allow you to bind a method to 'this' without having to do it the old way(const myFunc = this.myFunc.bind(this))


text:
Q: Replicate deferred/async launch policies from C++ in Java In C++ you can start a thread with a deferred or asynchronous launch policy. Is there a way to replicate this functionality in Java?
auto T1 = std::async(std::launch::deferred, doSomething());
auto T2 = std::async(std::launch::async, doSomething());

Descriptions of each--
Asynchronous:

If the async flag is set, then async executes the callable object f on a new thread of execution (with all thread-locals initialized) except that if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.

Deferred:

If the deferred flag is set, then async converts f and args... the same way as by std::thread constructor, but does not spawn a new thread of execution. Instead, lazy evaluation is performed: the first call to a non-timed wait function on the std::future that async returned to the caller will cause the copy of f to be invoked (as an rvalue) with the copies of args... (also passed as rvalues) in the current thread (which does not have to be the thread that originally called std::async). The result or exception is placed in the shared state associated with the future and only then it is made ready. All further accesses to the same std::future will return the result immediately.

See the documentation for details.

A: Future
First of all, we have to observe that std::async is a tool to execute a given task and return a std::future object that holds the result of the computation once its available.
For example we can call result.get() to block and wait for the result to arrive. Also, when the computation encountered an exception, it will be stored and rethrown to us as soon as we call result.get().
Java provides similar classes, the interface is Future and the most relevant implementation is CompletableFuture.
std::future#get translates roughly to Future#get. Even the exceptional behavior is very similar. While C++ rethrows the exception upon calling get, Java will throw a ExecutionException which has the original exception set as cause.

How to obtain a Future?
In C++ you create your future object using std::async. In Java you could use one of the many static helper methods in CompletableFuture. In your case, the most relevant are

*

*CompletableFuture#runAsync, if the task does not return any result and

*CompletableFuture#supplyAsync, if the task will return a result upon completion

So in order to create a future that just prints Hello World!, you could for example do
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> System.out.println("Hello World!"));
/*...*/
task.get();

Java not only has lambdas but also method references. Lets say you have a method that computes a heavy math task:
class MyMath {
    static int compute() {
        // Very heavy, duh
        return (int) Math.pow(2, 5);
    }
}

Then you could create a future that returns the result once its available as
CompletableFuture<Integer> task = CompletableFuture.runAsync(MyMath::compute);
/*...*/
Integer result = task.get();

async vs deferred
In C++, you have the option to specify a launch policy which dictates the threading behavior for the task. Let us put the memory promises C++ makes aside, because in Java you do not have that much control over memory.
The differences are that async will immediately schedule creation of a thread and execute the task in that thread. The result will be available at some point and is computed while you can continue work in your main task. The exact details whether it is a new thread or a cached thread depend on the compiler and are not specified.
deferred behaves completely different to that. Basically nothing happens when you call std::async, no extra thread will be created and the task will not be computed yet. The result will not be made available in the meantime at all. However, as soon as you call get, the task will be computed in your current thread and return a result. Basically as if you would have called the method directly yourself, without any async utilities at all.

std::launch::async in Java
That said, lets focus on how to translate this behavior to Java. Lets start with async.
This is the simple one, as it is basically the default and intended behavior offered in CompletableFuture. So you just do runAsync or supplyAsync, depending on whether your method returns a result or not. Let me show the previous examples again:
// without result
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> System.out.println("Hello World!"));
/*...*/ // the task is computed in the meantime in a different thread
task.get();

// with result
CompletableFuture<Integer> task = CompletableFuture.supplyAsync(MyMath::compute);
/*...*/
Integer result = task.get();

Note that there are also overloads of the methods that except an Executor which can be used if you have your own thread pool and want CompletableFuture to use that instead of its own (see here for more details).

std::launch::deferred in Java
I tried around a lot to mock this behavior with CompletableFuture but it does not seem to be possibly without creating your own implementation (please correct me if I am wrong though). No matter what, it either executes directly upon creation or not at all.
So I would just propose to use the underlying task interface that you gave to CompletableFuture, for example Runnable or Supplier, directly. In our case, we might also use IntSupplier to avoid the autoboxing.
Here are the two code examples again, but this time with deferred behavior:
// without result
Runnable task = () -> System.out.println("Hello World!");
/*...*/ // the task is not computed in the meantime, no threads involved
task.run(); // the task is computed now

// with result
IntSupplier task = MyMath::compute;
/*...*/
int result = task.getAsInt();

Modern multithreading in Java
As a final note I would like to give you a better idea how multithreading is typically used in Java nowadays. The provided facilities are much richer than what C++ offers by default.
Ideally should design your system in a way that you do not have to care about such little threading details. You create an automatically managed dynamic thread pool using Executors and then launch your initial task against that (or use the default executor service provided by CompletableFuture). After that, you just setup an operation pipeline on the future object, similar to the Stream API and then just wait on the final future object.
For example, let us suppose you have a list of file names List<String> fileNames and you want to

*

*read the file

*validate its content, skip it if its invalid

*compress the file

*upload the file to some web server

*check the response status code

and count how many where invalid, not successfull and successfull. Suppose you have some methods like
class FileUploader {
    static byte[] readFile(String name) { /*...*/ }
    static byte[] requireValid(byte[] content) throws IllegalStateException { /*...*/ }
    static byte[] compressContent(byte[] content) { /*...*/ }
    static int uploadContent(byte[] content) { /*...*/ }
}

then we can do so easily by
AtomicInteger successfull = new AtomicInteger();
AtomicInteger notSuccessfull = new AtomicInteger();
AtomicInteger invalid = new AtomicInteger();

// Setup the pipeline
List<CompletableFuture<Void>> tasks = fileNames.stream()
    .map(name -> CompletableFuture
        .completedFuture(name)
        .thenApplyAsync(FileUploader::readFile)
        .thenApplyAsync(FileUploader::requireValid)
        .thenApplyAsync(FileUploader::compressContent)
        .thenApplyAsync(FileUploader::uploadContent)
        .handleAsync((statusCode, exception) -> {
            AtomicInteger counter;
            if (exception == null) {
                counter = statusCode == 200 ? successfull : notSuccessfull;
            } else {
                counter = invalid;
            }
            counter.incrementAndGet();
        })
    ).collect(Collectors.toList());

// Wait until all tasks are done
tasks.forEach(CompletableFuture::join);

// Print the results
System.out.printf("Successfull %d, not successfull %d, invalid %d%n", successfull.get(), notSuccessfull.get(), invalid.get());

The huge benefit of this is that it will reach max throughput and use all hardware capacity offered by your system. All tasks are executed completely dynamic and independent, managed by an automatic pool of threads. And you just wait until everything is done.

A: For asynchronous launch of a thread, in modern Java prefer the use of a high-level java.util.concurrent.ExecutorService.
One way to obtain an ExecutorService is through java.util.concurrent.Executors. Different behaviors are available for ExecutorServices; the Executors class provides methods for some common cases.
Once you have an ExecutorService, you can submit Runnables and Callables to it.
Future<MyReturnValue> myFuture = myExecutorService.submit(myTask);

A: If I understood you correctly, may be something like this:
private static CompletableFuture<Void> deferred(Runnable run) {
   CompletableFuture<Void> future = new CompletableFuture<>();
   future.thenRun(run);
   return future;
}

private static CompletableFuture<Void> async(Runnable run) {
    return CompletableFuture.runAsync(run);
}

And then using them like:
public static void main(String[] args)  throws Exception {
    CompletableFuture<Void> def = deferred(() -> System.out.println("run"));
    def.complete(null);
    System.out.println(def.join());

    CompletableFuture<Void> async = async(() -> System.out.println("run async"));
    async.join();
}

A: To get something like a deferred thread, you might try running a thread at a reduced priority.
First, in Java it's often idiomatic to make a task using a Runnable first.  You can also use the Callable<T> interface, which allows the thread to return a value (Runnable can't).
public class MyTask implements Runnable {
  @Override
  public void run() {
    System.out.println( "hello thread." );
  }
}

Then just create a thread.  In Java threads normally wrap the task they execute.
MyTask myTask = new MyTask();
Thread t = new Tread( myTask );
t.setPriority( Thread.currentThread().getPriority()-1 );
t.start();

This should not run until there is a core available to do so, which means it shouldn't run until the current thread is blocked or run out of things to do.  However you're at the mercy of the OS scheduler here, so the specific operation is not guaranteed.  Most OSs will guarantee that all threads run eventually, so if the current thread takes a long time with out blocking the OSs will start it executing anyway.
setPriority() can throw a security exception if you're not allowed to set the priority of a thread (uncommon but possible).  So just be aware of that minor inconvenience.
For an asynch task with a Future I would use an executor service.  The helper methods in the class Executors are a convenient way to do this.
First make your task as before.
public class MyCallable implements Callable<String> {
  @Override
  public String call() {
    return "hello future thread.";
  }
}

Then use an executor service to run it:
MyCallable myCallable = new MyCallable();
ExecutorService es = Executors.newCachedThreadPool();
Future<String> f = es.submit( myCallable );

You can use the Future object to query the thread, determine its running status and get the value it returns.  You will need to shutdown the executor to stop all of its threads before exiting the JVM.
es.shutdown();

I've tried to write this code as simply as possible, without the use of lambdas or clever use of generics.  The above should show you what those lambdas are actually implementing.  However it's usually considered better to be a bit more sophisticated when writing code (and a bit less verbose) so you should investigate other syntax once you feel you understand the above.


text:
Q: Sharing the Build Queue defined variables in Release pipeline? How can we use the Build pipeline Queue defined variables in Release pipeline?

A: Use a variable group and share the variable group between your builds and releases.

A: Assuming on your build pipeline you've created variable like PipelineVariable and either assigned a default value or assigned one at queue time.  Assume you set the parameter value to Testing
In your release pipeline, you can use the Builds API to get the queue-time parameters.  You can make them available using an inline powershell script calling the API and using the setvariable command to save a release variable.  You might want to use this as opposed to Variable Groups if you are entering queue time variables.
$uri = "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$(Build.BuildId)"

$buildParameters = Invoke-RestMethod -uri $uri -Headers @{ Authorization = "Bearer
$env:SYSTEM_ACCESSTOKEN" } -Method Get |
    Select-Object -ExpandProperty parameters |
    ConvertFrom-Json

$buildParameters |
    Get-Member -MemberType NoteProperty |
    Select-Object -ExpandProperty Name |
    ForEach-Object {
        Write-Host "##vso[task.setvariable variable=$_]$($buildParameters.$_)"
    }

Now in following phases you can reference that value.  For example, if you created an inline powershell script to print the value:
Write-Host "$env:PIPELINEVARIABLE"

Returns:

Testing


text:
Q: How to save first item in for loop Below is my script:
from __future__ import print_function

# import statements
import sys, subprocess
import wmi, win32api, win32con

# get the arguments and extract user's IP address
argument = sys.argv[1]
attr_map = dict(item.strip().split('=') for item in argument.split(','))
userIP =  attr_map['sender-ip']
print (userIP)

# subprocess
ping = subprocess.Popen(
    ["ping", "-n", "1", userIP],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

# can we ping the user's IP address?
out, error = ping.communicate()

# if we cannot ping user's IP address then print error message and exit program
if out.find("Reply from") == -1:
    print (userIP, "is NOT pingable.")
    sys.exit()

# try to access wmi
try:
    c = wmi.WMI(userIP)
except:
    print ("Cannot access WMI for", userIP)
    sys.exit()

for os in c.Win32_OperatingSystem():
    print (os.Caption)

# perform system lookup of IP address

for us in c.Win32_LogonSession():
    try:
        for user in us.references("Win32_LoggedOnUser"):
            print(user.Antecedent.Domain, user.Antecedent.Name, sep="\\")
    except:
        pass

But it outputs multiple users.
DOMAIN\Glowie
DOMAIN\service_account
DOMAIN\service_account
DOMAIN\service_account
DOMAIN\service_account

How to get first user?

A: In a tuple or array, you can use the brackets to access an element:
>>> x = [1,2,3,4,5]
>>> x[0]
1


text:
Q: How do I escape comma in WMIC inside like string I wish to be able to run a query like the following:
wmic path Win32_Service where "DisplayName like 'FooBarService % (X, Y)'" get *
But, it doesn't work because of the comma inside the like string. The error I get is "Invalid Verb." I tried escaping it with a backslash, and I tried escaping it using brackets as underscores are meant to be escaped, and both resulted in the "Invalid Verb." error.
As a less-than-ideal workaround, I can replace the commas with underscores, and it works, but the underscore will match any single character rather than just the comma, so I'd rather find a way to escape the commas.
Is there a way to escape the comma like in this example?

A: One way I have found to include a comma in the like clause is to place the entire where expression in parentheses. Unfortunately, I also found that this means I cannot include a close paren in the string at the same time (but an open paren is okay). I experimented with the /trace:on option to see what was going on under the covers a little bit and it helped me find a couple things the program accepts:
Here is an example I got to work with a comma, but it apparently cannot contain a close paren:
C:\> wmic /trace:on path Win32_Service where (Description like '%(%, %') get DisplayName
And here is an example I got to work with both open and close parentheses, but apparently it cannot contain a comma (obviously, this is quite similar to your original example):
C:\> wmic /trace:on path Win32_Service where "Description like '%(TAPI)%'" get DisplayName
It seems like the parser just isn't complex enough to handle these cases, but with tracing on, you can see the WMI Win32 functions that it uses, so maybe you could write your own program that uses the functions directly. I think IWbemServices::ExecQuery is capable of what you're looking to do.


text:
Q: Execution time of multiple requests (100+) I'm looking for the time of execution of a pack of 552 SQL requests on MySQL. I want one execution time for the 552 requests (or the sum of 552 execution times). Ideally, what I need is an SQL requests based way to do it. My MySQL version is 5.7.
I've done a lot of research (maybe not in a good way because what I found is not that relevant, although it seems to be a common question).
I've found this but you can measure only 100 queries max (15 by default). Although I can approach the result by doing:
SELECT SUM(Duration)*5.52 as execTime
FROM information_schema.profiling

However, I can't change the default query allowed number from "15" to "100" anyway. When I try:
SET profiling_history_size = 100

*

*mysql console returns Query OK, 0 row affected, 1 warning

*phpMyAdmin returns Table 'performance_schema.session_variables' doesn't exists. Note that I've a performance_schema sub-folder in my mysql/data folder but no session_variables.frm file in it.

I would like to know:

*

*if there is a way to bypass the 100 queries limit? (even if the method is different)

*If not, how to change the profiling_history_size value?


text:
Q: OS X Eclipse C++ Launch Failed - Binary Not Found I am quite troubled as this shouldn't be causing me such a headache.  I've downloaded the most recent Eclipse Indigo and all CDT C++ plugins for MAC OS X 10.7.1/
Upon restarting after installing the above CDT plugins, I've developed a simple 'hello world' c++ application and have tried running the application, "Launch failed. Binary not found." error message.  I've read multiple fixes but none have worked.  I tried adding the -arch i386 flag to the linker and compiler commands, still no luck.
Has anyone successfully gotten Eclipse C++ running on 10.7.1??????  This blows my mind.  I can simply write the same program in VIM and compile it just fine via the terminal and execute just fine.  ECLIPSE DOESN'T WANT TO PLAY ALONG.
I will be deeply indebted to anyone who can help!!!!!
EDIT: compiler output
**** Build of configuration Debug for project HelloWorld ****
make all Building file: ../main.cpp
Invoking: GCC C++ Compiler g++ -I/Developer/SDKs/MacOSX10.6.sdk/usr/include -O0 -g3 -Wall -c -fmessage-length=0 -arch i386 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
Finished building: ../main.cpp
Building target: libHelloWorld
Invoking: MacOS X C++ Linker g++ -arch i386 -dynamiclib -o "libHelloWorld" ./main.o
Finished building target: libHelloWorld
**** Build Finished ****

A: I had the same problem, then I found a solution on this site.
Let me explain shortly;

*

*Create your c++ project,

*Have a look at project properties(⌘I),

*Select  Mach-O parser under binary properties,

*Write your codes down,

*Do not forget building your project (⌘B) before run.

A: You should change the settings for your project to build an executable instead of a dynamic library:

Invoking: MacOS X C++ Linker g++ -arch i386 -dynamiclib -o "libHelloWorld" ./main.o`

Go to project properties -> C/C++ Build -> Settings -> Build artifact, and select Executable in the first drop down list.

A: I am using Eclipse Juno with CDT on a 2007 Macbook running Snow Leopard. I have the two symptoms:

*

*No Binaries folder in Project Explorer, and

*The 'Launch failed. Binary not found' error.

I have spent hours searching on Google for an answer, long enough to ascertain that these two symptoms are indicative of any number of problems which have been reported for not quite a decade without adequate resolution. That is a problem right there because after a decade there should have been more than enough input data to provide one troubleshooting procedure somewhere which walks the user step by step through the elimination of all possible causes.
Instead, for hours I have read about a multitude of people, many of whom have resolved their particular problem but all of them seeming to have had to do something slightly different to get there.
This should not be that difficult to resolve. Particularly in cases such as mine [but I am not the only one] when the Console view displays a Build with no errors yet the user can copy the binary file [which Eclipse bizarrely says it can not find] to the Desktop and run it without any problems from either Finder or a bash terminal session.
All of this seems to be pointing rather emphatically toward the lack of adequate indicators in the Mach0 64 binary parser which should be designed to tell us exactly what it needs which it is not seeing.
Admittedly, this is exacerbated in the case of MacBooks like mine which are running a 64bit OS [Snow Leopard] on a 64bit CPU which the manufacturer, unfortunately, hamstrung with a 32-bit bootup kernel. But, be forewarned, I have already tried the -arch i386 g++ switch, and the relinking of g++ to g++-4.0 without any change in the symptoms.
ADDENDUM ADDED 10/07/2012:
I am adding this checklist in the hope of clarifying a Way for the undoubtedly many others who will ask this question in the years to come. This Way reflects what I found to be necessary when using Eclipse Juno with a Mac running Snow Leopard:
1) Go to Preferences->C/C++->New CDT Project Wizard, and under Preferred Toolchains, make sure all the Executable project types are set to MacOSX GCC.
2) This is a biggie. I was able to get a Binaries folder in Project Explorer, and hence be able to run the project after building it, by using a Project name which does not contain dots ['.']. This I learned from another answer here, edited a few hours after my previous message. This requirement is easy to miss, hence a common one particularly if you are Eclipse experienced but only with other languages, because tutorials for other language plugins [such as with PyDev or for Java] frequently have you create Projects with dots in the name. If you have developed that habit with other languages, break it when using CDT for C/C++. Be forewarned, however, that it is not enough to just do a Right-Click and Rename an existing project name this time not using dots. The simplest Way is to delete your old project and create a new one with a name without dots.
3) There are many websites cautioning you to make sure you either use the -arch i386 compiler switch or change the links for /usr/bin/gcc and /usr/bin/g++ to point to gcc-4.0 and g++-4.0 instead of gcc-4.2 and g++-4.2. I created a bash script to ease switching back and forth and investigated if this was necessary. It was not, at least not with my Macbook. Based on what I read at one site from a Mach-O developer, I suspect that the current version of Mach-0 64 goes both ways. Which is a good segue to ...
4) In the Project Properties, not Preferences, go to C/C++ Build->Settings and under Binary Parsers make sure Mach-O 64 Parser is checked. Make sure this, and not the deprecated Mach-O parser, is checked.
5) At this point, after you build your project, several things should be evident in the Project Explorer:
6) There should now be a Binaries folder under project's folder.
7) Within that Binaries folder should now be your executable file. It should have [x86_64/le] next to it if, like me, your Mac is effectively 32bit. Now is not the best time to get into the confusing topic of whether your Mac is effectively 32bit or 64bit. If you do not know, and a lot folks don't because Apple does make it confusing, check out the little app which can be downloaded from http://www.ahatfullofsky.comuv.com/English/Programs/SMS/SMS.html which will tell you What Is Truth. It is free, but the 'price' is that you have to scroll pass the ads at the top of the page reflecting the programmer's political disposition.

A: For those of you that are new to programming/eclipse/IDEs and get the same error but the solutions above don't work, I solved my "Launch Failed. Binary Not Found." error by doing the following: Simply be sure to build your project ("Project" > "Build All") before attempting to run or debug. I was thinking that the IDE would do the building when I clicked debug or run, but that is not the case (obviously, in retrospect). Newbie lesson learned. Once you build you should see a "Binaries" and "Debug" folder under the root directory of the project.
I was using OS X 10.7.3, if it matters, though I assume the mistake I made is fundamental and any eclipse distro would give the same error.

A: I am using Eclipse Oxygen and the following fixed my problem:

Right-click on your project and go to properties. Navigate to C/C++ Build > Tool Chain Editor and select MacOSX GCC in the Current toolchain, and Apply and Close.
Build your project with CMD+B and then run it.

A: I was having the same problem. The answer can be hard to find as the "binary not found" issue has cropped up several times before, with different causes and solutions (selecting the 64-bit parser, etc.).
It turns out that, in my case, the fix was simple: you have to do a manual build, just once, for every new project you create. After that, works as usual.
Details: using a fresh fresh install of Eclipse Indigo Service Release 1 on Mac OS 10.7.2.

A: If your project name contains a "." (dot), the binary file will not be generated on building project.
Remove all the "."(dots) from the project name and rebuilt it or try creating a new project.
Happy coding!

A: If you can successfully built but when try to run it getting error:

Possible solution could be adding new configuration with full path to your binary output file
(Run->Run Configuration...->Main->C++ Application):

A: on mac:

*

*Make sure you have xcode installed. Test it by writing "info g++" you must see proper information about the compiler.

*Build your project.

*Go to the folder of your project. You should see an executable file in Debug or realise folder, depending to your building configurations. If you d-click on the executable file you should see the result on the terminal.

*Back to Ecliipse, from Run/Run Configurations... and then browse to the folder that you have the executable file - one you already found - you can also change build configurations as you wish in that window. And make build automatic for each run.

*Run again it should work.
Good luck !

A: I solved a similar problem with Eclipse by creating a "Launch Configuration". I am using the Indigo release of Eclipse on OSX Lion with CDT (C/C++ dev environment). I found the option to create a new launch configuration in Project->Properties->Run/Debug Settings.
I encountered this problem after creating and building an empty "Hello World Ansi C Autotools Project". The build process created a working executable as src/a.out. I could run a.out successfully from the terminal but Eclipse did not understand that this was an executable for my project until I created a launch configuration pointing to it. Once I did that I was able to run a.out as usual using the green run button.

A: I had the same problem, even when i had set the artifact to executable. It was because the shared lib setting was ticked and this causes a dylib to be made even though you have specified an executable.

A: I go this to run by setting the Builder Type to Internal Builder on the C/C++ Build tab, in the project properties dialog.

A: No matter which approach to take to solve this issue on your workspace, this problem seemed to have become native to the project that I had created. Neither using the arguments or making sure the gcc version for linking did not work. I did find an intuitive solution. Here it is:to the "...binary not available..." error.
Do the following:(remember the following steps are after you have taken either of the above routes and none of those have solved the issue.
1.) delete everything - the project and the files.
2.) create new project and source files

A: I had the similar issue but code was different. In File.h file make sure
virtual ~Destructor () {}; //Don't forget Curly braces {}

Above statement shows destructor initialized () and defined with curly braces { } . In my code I forgot to define Destructor.
Hope this helps

A: I was having the same problem, so I fiddled around a littpe bit and found out that if I clicked on the "profile" button (green play icon with a little clock under it), to the right of the "run" button, my program would Run the next time I clicked on the Run button.
I actually dont know what that did, but it allowed me to run the code.
if anybody knows why this helped, and whether it is an actual solution or not dont hesitate to relpy!


text:
Q: Dynamic type parameter for Blazor components I want to design a common radzen data grid for multiple data types. Which means on the razor page I have common markup for radzen data grid. Record set and column definition bind to the grid dynamically. My problem is with 'TItme'.
I need something like:
TItem="typeof(data.records[0])"

Datagrid as follows:
<RadzenDataGrid FilterMode="FilterMode.Simple" Data="@data.records" TItem="typeof(data.records[0])" AllowFiltering="@data.allowFiltering" AllowPaging="@data.allowPaging" AllowSorting="@data.allowSorting">
    <Columns>
        @foreach (var colDef in data.columnDefinitions)
        {
            <RadzenDataGridColumn TItem="typeof(data.records[0])" Property="@colDef.columnProperty" Title="@colDef.columnTitle"  />
        }
    </Columns>
</RadzenDataGrid>

A: You may want to try dynamic component in dotnet 6:
<DynamicComponent Type="@componentType" Parameters="@parameters" />

@code {
    private Type componentType = ...;
    private IDictionary<string, object> parameters = ...;
}

DOCS:
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-6.0
Another option for other dotnet versions would be to try to define a render fragment directly in code (notice the line with ATTENTION comment):
@page "/built-content"

Build a component

    @CustomRender

<button @onclick="RenderComponent">
    Create three Pet Details components
</button>

@code {
    private RenderFragment? CustomRender { get; set; }

    private RenderFragment CreateComponent() => builder =>
    {
        for (var i = 0; i < 3; i++)
        {
            builder.OpenComponent(0, typeof(PetDetails));
            builder.AddAttribute(1, "PetDetailsQuote", "Someone's best friend!");
            builder.AddAttribute(2, "TItem", typeof(data.records[0])); // ATTENTION
            builder.CloseComponent();
        }
    };

    private void RenderComponent()
    {
        CustomRender = CreateComponent();
    }
}

DOCS:
https://learn.microsoft.com/en-us/aspnet/core/blazor/advanced-scenarios?view=aspnetcore-3.1


text:
Q: Overlaying 2 line plots With Factors R I'm trying to overlay two line graphs on the same space using R and a shiny web application.
This is the only example I can find with a similar problem, but I don't see how they relate. This is also the only plot that exhibits this problem; the rest of my shiny application graphs are fine.
My code (relevant parts) is
x1 <- c( 10, 25, 19)
x2 <- c( 3, 24, 11)
x3 <- c( 4, 15, 1)
df <- data.frame( "October" = x1, "November" = x2, "August"=x3)
x <- factor(1:3, labels = c("October", "November", "August"))
t1 <- as.numeric(df[1,1:3])
t2 <- as.numeric(df[2,1:3])
plot(t1 ~ x, type="n", ylim=c(min(t1),max(t2)))
lines(t1 ~ x, col="blue")
lines(t2 ~ x, col="red")

But no matter what I change the type of the initial plot to, it gives me horizontal lines at all the plotted points. I originally had it as type="l" but it did the same thing, so I manually added the line that belongs there, and tried to make the horizontal bars disappear with type="n" Does anyone have any insight into this problem.
I'd prefer solutions in base R, so not using ggplot.

A: Because x is a factor, plot(t1 ~ x) actually produces a barplot. You only have one measurement per month, so all you see is a horizontal line.
You could do the following:
plot.default(t1 ~ x, type="n", ylim=c(min(t1),max(t2)), xaxt = "n");
axis(1, at = as.numeric(x), labels = levels(x))
lines(t1 ~ x, col="blue")
lines(t2 ~ x, col="red")


text:
Q: Footer disappearing with use of Google Maps Before I put in the code for a google map, the footer was showing up fine, and still shows up fine on other pages. I have tried playing with floats, absolute/fixed/relative positioning, etc and nothing seems to keep the footer from disappearing.
You can see it briefly before it vanishes here
This is the code for the relevant areas:

<?php include 'includes/menu.php'; ?>

<?php include 'includes/footer.php'; ?>

And the CSS I've used for these areas:
#map-canvas { height: 500px;
            font-family:magic;
            margin-top: -370px;
            float:right;
            width:550px;
            margin-bottom:0px;}
#footer {
        font-family:magic;
        font-size:20px;
        float:left;
        margin-left:150px;
        text-align:center;
        margin-top:25px;
        }


text:
Q: Component identification - do you know what are the values of these components? I am trying to identify the capacitance and resistance of two components that are soldered on a PCB.
The capacitor below should be 10 nF according to the datasheet. But its code is not 103. What's the value of this capacitor?

The resistor below should be 4k7 Ohms according to the datasheet. Then the band colors should be yellow, violet, red, and tolerance. But the third band is black instead of red. Then it is 47 Ohms instead of 4k7. Am I right?

A: The cap is 33nF (333 -> 33 x 10^3 = 33000pF)
The resistor is 4k7. It's an odd-looking 5-band, so the 4 resistance bands are:
4701 (470 x 10^1 = 4700).
The 5th band looks brown-ish, so probably 1% tolerance.


text:
Q: How to call a user defined function to print inside a  in react I have a react class component which prints a table. I am retrieving an array from the database along with the other data and now I want to print the values in the array in a single row (). I am trying to to do that using a separate function instead of writing a for loop within the  tag
This is how I did i :-
export default class ViewWeekdayWorkingDays extends Component{

    constructor(props){
        super(props);

        this.state = {
            dayType : '',
            noOfWorkingDays : 0,
            arr_workingDays : [],
            workingHours : 0,
            workingMinutes : 0,
            timeSlot : ''
        };

        this.printDays = this.printDays.bind(this);
    }

    componentDidMount() {

        axios.get('/workingdays/get', { params : {dayType : 'Weekday'}})
            .then(res => {

                if(res.data.success){

                    this.setState({
                        dayType : res.data.result.dayType,
                        noOfWorkingDays : res.data.result.noOfDays,
                        arr_workingDays : res.data.result.workingDays,
                        workingHours : res.data.result.workingHours.hours,
                        workingMinutes : res.data.result.workingHours.minutes,
                        timeSlot : res.data.result.workingTimeSlot
                    })
                } else {
                    alert("Empty data set")
                }

            })
            .catch(err => alert("Error Reading Data"))

    }

    //method to print the array data
    printDays = () => {

        const days = '';

        this.state.arr_workingDays.map(day => {

            days = days + day + "\n";
        })

        return days;
    }

    render() {
        return (

                <WorkingDaysNav/>

Weekday

                            Total Working Days
                            {this.state.noOfWorkingDays}

                            Days

                               {this.printDays}             // <-------- this is how I call the method

                            Working Hours
                            {this.state.workingHours} hours {this.state.workingMinutes} minutes

                            Time Slot
                            {this.state.timeSlot}

                    <form>

                                <button type="submit"
                                    className="btn mb-2"
                                    style={{backgroundColor: "#312450", color: "white", marginLeft: "50%", width: "100px"}}
                                >Edit</button>

                                <button type="submit"
                                    className="btn mb-2"
                                    style={{backgroundColor: "#312450", color: "white", marginLeft: "40px", width: "100px"}}
                                >Delete</button>

                    </form>

        );
    }
}

It doesn't print anything.The array consist all the weekdays and I want to print them one by one in a new line. How can I solve this issue. Thanks in advance!

A: Ciao, unfortunately this happens because reactjs re-render page content only if you change state. Try to put const days in state like this:
this.state = {
   dayType : '',
   noOfWorkingDays : 0,
   arr_workingDays : [],
   workingHours : 0,
   workingMinutes : 0,
   timeSlot : '',
   days: ''
};

And then your componentDidMount becomes:
componentDidMount() {

    axios.get('/workingdays/get', { params : {dayType : 'Weekday'}})
        .then(res => {

            if(res.data.success){

                this.setState({
                    dayType : res.data.result.dayType,
                    noOfWorkingDays : res.data.result.noOfDays,
                    arr_workingDays : res.data.result.workingDays,
                    workingHours : res.data.result.workingHours.hours,
                    workingMinutes : res.data.result.workingHours.minutes,
                    timeSlot : res.data.result.workingTimeSlot
                }, () => {
                    const days = '';
                    this.state.arr_workingDays.map(day => {
                    days = days + day + "\n";
                    this.setState({days: days});
                 })
               );
            } else {
                alert("Empty data set")
            }

        })
        .catch(err => alert("Error Reading Data"))

}

And your render function becomes:
render() {
        return (

                <WorkingDaysNav/>

Weekday

                            Total Working Days
                            {this.state.noOfWorkingDays}

                            Days

                               {this.state.days}

                            Working Hours
                            {this.state.workingHours} hours {this.state.workingMinutes} minutes

                            Time Slot
                            {this.state.timeSlot}

                    <form>

                                <button type="submit"
                                    className="btn mb-2"
                                    style={{backgroundColor: "#312450", color: "white", marginLeft: "50%", width: "100px"}}
                                >Edit</button>

                                <button type="submit"
                                    className="btn mb-2"
                                    style={{backgroundColor: "#312450", color: "white", marginLeft: "40px", width: "100px"}}
                                >Delete</button>

                    </form>

        );
    }

In this way, printDays function could be removed.

A: 2 things

*

*call the function with ()

*inside the function return the output

relevant sample js:
import React, { Component } from "react";

const  Example = () => {

  const someArray = [
    {dayType: 'working day', hours: 8 },
    {dayType: 'weekend', hours: 0 },
    {dayType: 'project-go-live', hours: 12 },
    {dayType: 'time in lieu', hours: 0 },
  ]

  const dayPrinter = () => {
    return someArray.map(x=> (

{x.dayType} |  {x.hours} hrs

      ))
  }

    return (
      <>
      {dayPrinter()}
      </>
    )

}

export default Example;

working snippet here


text:
Q: How can I find the bigrams per row? I want to derive bigrams and used the following code to do so:
from sklearn.feature_extraction.text import CountVectorizer
def create_vectorizer():
    return CountVectorizer(lowercase=False, stop_words=['a', 'an','the','The'], ngram_range=(1, 3))

reviews_english["Review Gast"] = reviews_english["Review Gast"].astype(str).str.lower()

res = [(x, i.split()[j + 1]) for i in reviews_english["Review Gast"]
       for j, x in enumerate(i.split()) if j < len(i.split()) - 1]
res

I got the following results:

However, I would like to get the bigrams per row rather than for the whole list.
How can I do this?
Thanks

A: You can use CountVectorizer to fit_transform per row. However since it requires a corpus/list of text you will have to convert your string in the row to a list of single string.
Sample
df = pd.DataFrame({
    'text': ["a cat on the table",
             "a dog under the table",
             "an apple over the tree"]
})

cv = CountVectorizer(analyzer='word', ngram_range=(2, 2))
bigrams = []
for txt in df["text"].astype(str).str.lower():
  cv.fit_transform([txt])
  bigrams.append(cv.get_feature_names())

df['bigrams'] = bigrams

print (df)

output:
                     text                                     bigrams
0      a cat on the table                 [cat on, on the, the table]
1   a dog under the table           [dog under, the table, under the]
2  an apple over the tree  [an apple, apple over, over the, the tree]


text: Q: Why X11 automatically shutdown during a calculation? I was using X11 to calculate crystallization of a primitive magma. The calculation went well in small increments. But when I launch bigger calculations in wider T ranges, X11 shutdown automatically with no reason.


text:
Q: Looping through json in Angular I am reading a JSON from a file in Angular. The content of the file is:
{
"mango":
[
{
  "id": 3,
  "image": "Mango1.jpg",
  "text": "I am mango 3"
},
{
  "id": 2,
  "image": "Mango2.jpg",
  "text": "I am mango 2"
}
]

}
I am reading it in my controller:
    $.getJSON("../json/list.json", function (json) {
    $scope.mangoLists = json;

When i output to console, it shows the mango object etc. But I am unable to output them to the UI by doing this:

        {{mango.text}}

Please assist.

A: You need to also update the view of the controller data after calling $.getJSON by using $scope.$apply() like so:
$.getJSON("../json/list.json", function (json) {
    $scope.mangoLists = json;
    $scope.$apply();
}

$scope.$apply() will trigger a digest cycle which will update the view.

A: Can you try as below i think you did something wrong in ng-repeat
i hope this will help you

<!DOCTYPE html>

        {{mango1.text}}


text:
Q: Как сделать логин к сайту api без токена? Создал тестового юзера:
username: "david"
password: "framework"
let urlString = "http://gemcave.pythonanywhere.com/api/order"

            let email = "david"
            let password = "framework"

            let parameters = [
                "username": email,
                "password": password
            ]

            Alamofire.request(.GET, urlString,parameters: parameters).responseJSON {response in
                let json = JSON(response.data!)
                let swiftyJsonVar = json["truckType"].string
                print(swiftyJsonVar)
            }

Ошибка: return nil - аутентификация не проходит
Я не знаю в чем именно проблема в сервере или приложении
Бэкэнд: Django Rest Framework
JSON пример:
[
    {
        "id": 1,
        "textDep": "Paris",
        "textDest": "Deli",
        "truckType": "Грузовик1",
        "created_date": "2015-12-22T09:42:38Z",
        "author": 1
    },
    {
        "id": 4,
        "textDep": "Astana",
        "textDest": "Almata",
        "truckType": "Грузовик1",
        "created_date": "2015-12-22T09:44:13Z",
        "author": 1
    }
]

A: Могу предположить, что вы не активировали тестового юзера, попробуйте поднять django-admin, и оттуда уже проверить есть ли пользователь, активен ли он, есть ли у него соответствующие права, по части сервера всё сразу станет ясно.


text:
Q: In hardmode, how large of a gap can hallow/corruption cross? After destroying the Wall of flesh, the corruption and new hallow start to spread aggressively. I've noticed that they can spread across air gaps and (I think) past terrain they can't assimilate. How large of a space can they cross?
Related Question: How can I halt the spread of corruption after winning hell?

A: Corruption, Crimson, and Hallow can jump up to three blocks to affect other blocks, and Corruption and Crimson can spread farther by using vines. You can prevent them from doing so by digging a 4 block wide channel. You may be able to leave it empty, but if you have trouble with corrupted vines, you may need to stop them with blocks that cannot be converted, such as Ash, Bricks, or Wood.

A: From my experience, the corruption, crimson, and hallow, can spread to any corruptible block up to 3 blocks away, so a three block gap  should be sufficient to stop spread. If you are blocking surface crimson/corruption, you should fill the gap up with non corruptible blocks (only from the underground crimson/corruption (the music will change) to the surface) to stop vines/thorny bushes, or just line it with any block that doesnt produce them, such as crim/ebonstone (make sure to keep the 3 block gap tho)


text:
Q: ThreadSafeClientConnManager not multithreading I've been asked to fix up a Servlet that sits in between two applications. It's purpose is to convert SAML authorisation request to and from SAML v2.0 / SAML 1.1. So it:

*

*receives a HTTP SAML v2.0 authorisation request from one app

*converts the request into SAML v1.1

*sends the request to the second app

*receives the SAML v1.1 response from the second app

*converts the response into SAML v2.0

*sends the response back to the first app

Don't worry about the SAML stuff, it's the HTTP stuff that's the problem. The code does it's job, but it suffers greatly under load. I've found through testing that even though the code utilises a ThreadSafeClientConnManager from Apache httpcomponents, each request that hits the servlet is being handled in a single-threaded manner. To put it more accurately, the second the code reaches the HTTPClient.execute() method the first thread to create a connection will run through the entire rest of the process before any other thread begins working. For example:

*

*15 requests hit the servlet at the same time

*servlet spawns 15 threads to service the requests

*all 15 threads retrieve their respective request data

*all 15 threads convert their respective data from SAML v2.0 to SAML v1.1

*Thread 1 calls HTTPClient.execute()

*

*Thread 1 sends the request on to the second app

*Thread 1 receives the response from the second app

*Thread 1 decodes the response and converts it from SAML v1.1 to SAML v2.0

*Thread 1 sends the response back to the first app

*Thread 2 calls HTTPClient.execute()

*... and so on ...

I've included the code below. From what I can see all the necessary items are present. Can anyone see anything wrong or missing that would prevent this servlet from servicing multiple requests at the same time?
public class MappingServlet extends HttpServlet {

private HttpClient client;
private String pdp_url;

public void init() throws ServletException {
    org.opensaml.Configuration.init();
    pdp_url = getInitParameter("pdp_url");

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    HttpRoute route = new HttpRoute(new HttpHost(pdp_url));
    cm.setDefaultMaxPerRoute(100);
    cm.setMaxForRoute(route, 100);
    cm.setMaxTotal(100);
    client = new DefaultHttpClient(cm);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    long threadId = Thread.currentThread().getId();
    log.debug("[THREAD " + threadId + "] client request received");

    // Get the input entity (SAML2)
    InputStream in = null;
    byte[] query11 = null;
    try {
        in = request.getInputStream();
        query11 = Saml2Requester.convert(in);
        log.debug("[THREAD " + threadId + "] client request SAML11:\n" + query11);
    } catch (IOException ex) {
        log.error("[THREAD " + threadId + "]\n", ex);
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                log.error("[THREAD " + threadId + "]\n", ioe);
            }
        }
    }

    // Proxy the request to the PDP
    HttpPost httpPost = new HttpPost(pdp_url);
    ByteArrayEntity entity = new ByteArrayEntity(query11);
    httpPost.setEntity(entity);
    HttpResponse httpResponse = null;
    try {
        httpResponse = client.execute(httpPost);
    } catch (IOException ioe) {
        log.error("[THREAD " + threadId + "]\n", ioe);
        httpPost.abort();
        return;
    }

    int sc = httpResponse.getStatusLine().getStatusCode();
    if (sc != HttpStatus.SC_OK) {
        log.error("[THREAD " + threadId + "] Bad response from PDP: " + sc);
        httpPost.abort();
        return;
    }

    // Get the response back from the PDP
    InputStream in2 = null;
    byte[] resp = null;
    try {
        HttpEntity entity2 = httpResponse.getEntity();
        in2 = entity2.getContent();
        resp = Saml2Requester.consumeStream(in2);
        EntityUtils.consumeStream(in2);
        log.debug("[THREAD " + threadId + "] client response received, SAML11: " + resp);
    } catch (IOException ex) {
        log.error("[THREAD " + threadId + "]", ex);
        httpPost.abort();
        return;
    } finally {
        if (in2 != null) {
            try {
                in2.close();
            } catch (IOException ioe) {
                log.error("[THREAD " + threadId + "]", ioe);
            }
        }
    }

    // Convert the response from SAML1.1 to SAML2 and send back
    ByteArrayInputStream respStream = null;
    byte[] resp2 = null;
    try {
        respStream = new ByteArrayInputStream(resp);
        resp2 = Saml2Responder.convert(respStream);
    } finally {
        if (respStream != null) {
            try {
                respStream.close();
            } catch (IOException ioe) {
                log.error("[THREAD " + threadId + "]", ioe);
            }
        }
    }
    log.debug("[THREAD " + threadId + "] client response SAML2: " + resp2);

    OutputStream os2 = null;
    try {
        os2 = response.getOutputStream();
        os2.write(resp2.getBytes());
        log.debug("[THREAD " + threadId + "] client response forwarded");
    } catch (IOException ex) {
        log.error("[THREAD " + threadId + "]\n", ex);
        return;
    } finally {
        if (os2 != null) {
            try {
                os2.close();
            } catch (IOException ioe) {
                log.error("[THREAD " + threadId + "]\n", ioe);
            }
        }
    }
}

public void destroy() {
    client.getConnectionManager().shutdown();
    super.destroy();
}

}

Thanks in advance!

A: The HttpClient.execute() does not return until the called server send out all of the http headers. Your code works fine. I think the called service is the real bottleneck. I've created a simple proof of concept code (based on your snippet) for it:
import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

public class MyHttpClient {

    private static final String url = "http://localhost:8080/WaitServlet";

    private final DefaultHttpClient client;

    public MyHttpClient() {
        final ThreadSafeClientConnManager cm =
                new ThreadSafeClientConnManager();
        final HttpRoute route = new HttpRoute(new HttpHost(url));
        cm.setDefaultMaxPerRoute(100);
        cm.setMaxForRoute(route, 100);
        cm.setMaxTotal(100);
        client = new DefaultHttpClient(cm);
    }

    public void doPost() {
        final HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(httpPost);
        } catch (final IOException ioe) {
            ioe.printStackTrace();
            httpPost.abort();
            return;
        }

        final StatusLine statusLine = httpResponse.getStatusLine();
        System.out.println("status: " + statusLine);
        final int statusCode = statusLine.getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            httpPost.abort();
            return;
        }
    }
}

And a test:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class HttpClientTest {

    @Test
    public void test2() throws Exception {
        final ExecutorService executorService =
                Executors.newFixedThreadPool(16);

        final MyHttpClient myHttpClient = new MyHttpClient();

        for (int i = 0; i < 8; i++) {
            final Runnable runnable = new Runnable() {

                @Override
                public void run() {
                    myHttpClient.doPost();
                }
            };
            executorService.execute(runnable);
        }

        executorService.shutdown();
        executorService.awaitTermination(150, TimeUnit.SECONDS);
    }
}

Finally, the called WaitServlet:
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WaitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            Thread.sleep(30 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        final PrintWriter writer = resp.getWriter();
        writer.println("wait end");
    }
}