text:
Q: How create indexes for 2 fields to make their unique in collection I have the entity with bson configuration
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

[BsonElement("Email")]
public string Email { get; set; }

[BsonElement("PhoneNumber")]
public string PhoneNumber { get; set; }

[BsonElement("Role")]
public Role Role { get; set; }

In collection, I want to have a unique pair of fields Email and Role. However, how to realize it in core API, doesn't understand?
I found the property  Indexes and this property has CreateOne or CreateMany but how to configure that?

A: Once you have established your connection etc. and have the collection object...
You would call the Index Keys API you found (https://mongodb.github.io/mongo-csharp-driver/2.8/reference/driver/definitions/#index-keys)
var indexModel = new CreateIndexModel<YourType>(
     new IndexKeysDefinitionBuilder<YourType>()
        .Ascending(x => x.Email)
        .Ascending(x => x.Role),
     new CreateIndexOptions() { <use if desired> });

collection.Indexes.CreateOne(indexModel);

You can also use the literal name such as "Email" (if you don't want or need type safety), of course do Descending instead of Ascending, and either omit or use the CreateIndexOptions (sounds like you'd want Unique = true here).


text:
Q: Augeas in Puppet for mysql config failing I'm currently developing some basic Puppet manifests and modules to install my application dependencies after my server has been deployed. It's a suite of basic stuff: -

*

*OS -> Ubuntu 14.04 LTS

*Nginx

*PHP5-FPM

*MySQL

Simple, right?
Everything is going pretty well for the most part; until I stumbled upon the ability to use Augeas to update the config files with my custom config items. I've set the PHP config items without any problems, as such:
augeas { 'php.ini':
    require => [
        Package['php5-fpm'],
        Package['libaugeas-ruby'],
    ],
    notify => Service['php5-fpm'],
    context => '/files/etc/php5/fpm/php.ini',
    changes => [
        'set PHP/cgi.fix_pathinfo 0',
    ],
}

This works just fine. No issues at all.
However, now I've come to the MySQL config file, I'm using the following (which was nearly a copy and paste job)
augeas { 'my.cnf':
    require => [
        Package['mysql-server'],
        Package['libaugeas-ruby'],
    ],
    notify => Service['mysql'],
    context => '/files/etc/mysql/my.cnf',
    changes => [
        'set mysqld/bind-address 0.0.0.0',
    ],
}

Unfortunately, this just isn't working. I looked at the augeas documentation regarding the lenses it ships with, and no issues. The following is the initial output from the Puppet apply command.
Error: /Stage[main]/Mysql/Augeas[my.cnf]: Could not evaluate: Save failed with return code false, see debug

The next logical step was, of course, to look at the debug information. Which was the following information in it.
Debug: Augeas[my.cnf](provider=augeas): sending command 'set' with params ["/files/etc/mysql/my.cnf/mysqld/bind-address", "0.0.0.0"]
Debug: Augeas[my.cnf](provider=augeas): Put failed on one or more files, output from /augeas//error:
Debug: Augeas[my.cnf](provider=augeas): /augeas/files/etc/mysql/my.cnf/error = put_failed
Debug: Augeas[my.cnf](provider=augeas): /augeas/files/etc/mysql/my.cnf/error/path = /files/etc/mysql/my.cnf
Debug: Augeas[my.cnf](provider=augeas): /augeas/files/etc/mysql/my.cnf/error/lens = /usr/share/augeas/lenses/dist/mysql.aug:39.13-.60:
Debug: Augeas[my.cnf](provider=augeas): /augeas/files/etc/mysql/my.cnf/error/message = Failed to match

A: Okay, so I've managed to get SOMETHING happening; but without probably fully understanding what's going on.
Prior to asking the question above, I checked on the stock lenses available, and I saw both the PHP and MySQL lenses in the list at http://augeas.net/stock_lenses.html
Neither of the links work that SHOULD be taking you through to the documentation - so, knowing that the PHP lens worked in a 'set section/setting value' type of way, I was assuming it's the same for the MySQL lens.
Not exactly the case. The following syntax worked for me.
augeas { 'my.cnf':
    require => [
        Package['mysql-server'],
        Package['libaugeas-ruby'],
    ],
    notify => Service['mysql'],
    context => '/files/etc/mysql/my.cnf',
    changes => [
        "set target[.='mysqld']/bind-address 0.0.0.0",
    ],
}

The following two resources were where I found the information. If anybody has any other documentation they can point me to, I'd be more than grateful.
This gave me an idea of what the syntax probably should be: - https://www.adammalone.net/post/playing-augeas-fun-and-profit#.VXAEy1yqpBc
And lines 62-65 of this script reaffirmed it for me: - https://github.com/example42/puppet-mysql/blob/master/manifests/augeas.pp

redpajama_set_name: RedPajamaStackExchange


text:
Q: About the raised negative sign in some basic textbooks In a math document recently (a UK A level test paper from the EdExcel board), I noticed that the negative/minus sign was raised and aligned to the top of the number. I'm interested to know whether this is a local or regional habit, how common or widespread it is, and whether it's considered a good idea.
(The only anecdote I have about this habit is that a student queried the sign as if it were some kind of printing error...:)
Examples

$A$ and $B$ are points with coordinates $(5,2)$ and $(\vphantom 1^- 1, 4)$ respectively.

and

Given that $(x+2)$ and $(x-3)$ are factors of $f(x)$, show that $a=3$ and $b=\vphantom 1^- 10$.

(These are not from the same question.)


text:
Q: How do you control MySQL timeouts from SQLAlchemy? What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy?  The connect_timeout URL parameter seems to be insufficient.
I'm more interested in what happens when the machine that the database is running on, e.g., disappears from the network unexpectedly.  I'm not worried about the queries themselves taking too long.
The following script does what you'd expect (i.e., time out after approximately one second) if somehost is unavailable before the while loop is ever reached.  But if somehost goes down during the while loop (e.g., try yanking out its network cable after the loop has started), then the timeout seems to take at least 18 seconds.  Is there some additional setting or parameter I'm missing?
It's not surprising that the wait_timeout session variable doesn't work, as I think that's a server-side variable.  But I threw it in there just to make sure.
from sqlalchemy import *
from sqlalchemy.exc import *
import time
import sys

engine = create_engine("mysql://user:password@somehost/test?connect_timeout=1")
try:
    engine.execute("set session wait_timeout = 1;")
    while True:
        t = time.time()
        print t
        engine.execute("show tables;")
except DBAPIError:
    pass
finally:
    print time.time() - t, "seconds to time out"

A: this isn't possible due to the way TCP works. if the other computer drops off the network, it will simply stop responding to incoming packets. the "18 seconds" you're seeing is something on your TCP stack timing out due to no response.
the only way you can get your desired behavior is to have the computer generate a "i'm dying" message immediately before it dies. which, if the death is unexpected, is completely impossible.
have you ever heard of hearbeats? these are packets that high-availability systems send to each other every second or less to let the other one know they still exist. if you want your application to know "immediately" that the server is gone, you first have to decide how long "immediate" is (1 second, 200 ms, etc.) and then designed a system (such as heartbeats) to detect when the other system is no longer there.

A: I believe you are reaching a totally different error, this is a dreaded "mysql has gone away" error, If I'm right the solution is to update to a newer mysqldb driver as the bug has been patches in the driver.
If for some reason you can't/won't update you should try the SA fix for this
db= create_engine('mysql://root@localhost/test', pool_recycle=True)

A: Could this be a bug in the mysql/python connector?
https://bugs.launchpad.net/myconnpy/+bug/328998
which says the time out is hard-coded to 10 seconds.
To really see where the breakdown is, you could use a packet sniffer to checkout the conversation between the server and the client. wireshark + tcpdump works great for this kind of thing.


text:
Q: How to properly use style format in apache-poi? I am trying to format my excel generated file from my java code. This is what my code snippet looks like:
...
Row row = sheet.createRow(rowNum++);
CellStyle textCellStyle = workbook.createCellStyle();
if (rowNum % 2 == 0) {
    textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
    textCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    textCellStyle.setFont(textFonts1);
} else {
    textCellStyle.setFont(textFonts2);
}

cell = row.createCell(0);
cell.setCellValue(student != null ? student.getIdNumber() : "");
cell.setCellStyle(textCellStyle);
...

My expectation was all even rows will be filled with green background but the produced output was different, instead it produced black background. I already tried different color or even changing my fill pattern but i always get black.
I am using poi-3.17 and poi-ooxml-3.17, excel 2007 and java 1.6

A: You have set a fill pattern for the cell as FillPatternType.SOLID_FOREGROUND. But you did not set a foreground color. This means that the standard color (black) is used as the foreground color.
Try to exchange...
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());

... with ...
textCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());

... and it should render as you expect. The text in the cells should also be visible.
It seems counterintuitive to set a foreground color and fill pattern when you want to set a background though.

A: I'm an Apache POI newbie and don't know much about the details yet. But—in some circumstances—what follows may be useful to you.
This code...
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CellBackground {

  public static void main(String[] args) throws Exception {

    XSSFWorkbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet();
    int rowNum = 0;
    for (FillPatternType fpt : FillPatternType.values()) {
      Row row = sheet.createRow(rowNum++);
      Cell cell = row.createCell(0);
      XSSFCellStyle textCellStyle = wb.createCellStyle();
      textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
      textCellStyle.setFillPattern(fpt);
      cell.setCellValue(fpt.name());
      cell.setCellStyle(textCellStyle);
      sheet.createRow(rowNum++).setHeightInPoints(7);
    }
    sheet.autoSizeColumn(0);

    OutputStream fileOut = new FileOutputStream("CellBackground.xlsx");
    wb.write(fileOut);
    wb.close();
  }
}

...will produce this output in LibreOffice Calc (Apache POI 4.0.1):


text:
Q: SVG Opacity Image keeps popping up after fade                 <animate id="op"
                attributeName="opacity"
                values="0;1;0"
                dur="1s"
                begin="1s;op.end+3s"
                />

I have this code that's being used to fade an image off then back on with a delay of 3 seconds but when it fades off during the 3 second delay the image pops back up and is visible.  How can I make it invisible during the delay?

A: add fill="freeze" if you want the animation state to persist once the animation ends.

A: <animate id="op"
                attributeName="opacity"
                values="1;0;0;1"
                keyTimes="0;0.2;0.8;1"
                dur="5s"
                begin="1s"
                />

You can use keyTimes. One keyTime corresponds to one value and represents at which proportion of the duration this given value should be reached. So here it begins with opacity 1 at time 0*5s = 0s, then at time 0.2*5s = 1s it reaches opacity 0 (fade off), it keeps opacity 0 up to time 0.8*5s = 4s and returns to opacity 1 at time 1*5s = 5s (fade on).
Working example:

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="-50 -50 100 100">
<circle r="50">
        <animate id="op"
                attributeName="opacity"
                values="1;0;0;1"
                keyTimes="0;0.2;0.8;1"
                dur="5s"
                begin="1s"
                />
</circle>
</svg>


text:
Q: Insertar varios datos en una tabla a la vez Buen día muchachos.
estoy trabajando con Genexus 15 con JAVA y vengo de nuevo con otra interrogante y es que deseo crear en un Web Panel una grilla parecida a esta.

La cual me permita ingresar varios datos en una tabla con un solo botón y si podría hacerlo sin necesidad de insertar el código de cada dato que estoy ingresando.
Esta es mi tabla.

Tengo entendido que es con una Grilla, pero no se como ponerlo en mi Web Panel, si con variables o atributos y como insertar una linea nueva.
Espero no causar molestias.
Saludos.

A: Lo que intentas hacer es que un WebPanel haga de Insert para una transacción de 2 niveles. Lamento decirte que para esto es muy complicado controlar el tema de la Grilla, ya que debes controlar algunas cosas. De las cuales debes considerar.

*

*Debes trabajar con variales.

*La grilla al no tener una navegación va a generar una sola fila y no te va a funcionar asignandole rows a la misma.

*Deberas generar procedimientos que te ayuden con el insert a la base, por la transacción padre y el for each line del grid que deberás barrer para generar cada insert del hijo.

Como ves es engorroso, ya que es posible que debas recurrir hasta a SDT's para que almacenen brevemente los datos.
Mi recomendación
Utiliza una Transacción, estas fueron creadas para trabajar al cien el CRUD de tus entidades. En caso de no poder modelar el Form de la transacción que ya tienes, solo basta con guardrar una nueva a partir de esta, como lo haces:

*

*Abres la transacción.

*Click derecho en la pestaña de la misma.

*Save As...

*El nombre que desees. Y listo.

Esta es una copia de la transacción que ya tienes (alumno), pero esta va a hacer como tu formulario perzonalizado para cierta situación. Y en ella si puedes manejar a tu antojo el Grid y los eventos de commit y demás.
Espero haberte guiado por el camino adecuado y que te ayude mas que nada la respuesta a aclarar que en este tipo de situaciones debes usar transacciones. Saludos.


text:
Q: Using the read command within a while loop and running an awk script I'm attempting to search for different file extensions and then run an awk script against each of those files however the terminal is looking for user input and I'm wondering if it's something specific to running it with the awk script as it's an interpreter? Or is it just something I'm doing wrong in my command as I'm relatively new to bash and awk
find ./ -type f -name '\*.txt' | while  IFS= read file; do awk -f awkScript.awk "$file" done;

Update ***
I was missing a semi colon but when I add this and fill in the rest of the file extensions I am looking for it give me;
-bash: syntax error near unexpected token `done'

on this command;
find ./ -type f \( -iname \*.gs -o -iname \*.pcf -o -iname \*.gr -o -iname \*.gsx -o -iname \*.en -o -iname \*.gst -o -iname \*.gosu -o -iname \*.descriptor -o -iname \*.txt \) -print0 | while  read -d $'\0' file do awk -f awkScript.awk "$file"; done;

A: Are you sure about what you are doing? You are looking for all textfiles inside your directory. Each of those files are read, and then you treat every line inside that textfile as a file. Is this what you want?
I assume you want to do some awk on all textfiles, which can be done as in following example:
find ./ -name "*.txt" -exec awk -F. '{print $1}' {} \;

(find all textfiles and read the first column of those files)

A: As for your updated command, you are still missing a semicolon before do awk.
BTW you could simplify your command as:
find . -type f -regextype posix-egrep -iregex '.*\.(gs|pcf|gr|gsx|en|gst|gosu|descriptor|txt)$' -print0 | xargs -0 awk -f awkScript.awk


text:
Q: Android set images to background of a TextView programmatically I have an app where need to put images to background programmatically, but it doesn't work, the code is (2 methods from BankMenuParser):
    public void getProviderFields(String file, String providerId) throws DocumentException, IOException {

        String xml = readFile(file);
        Document doc = DocumentHelper.parseText(xml);

        System.out.println("field name start");

        List list = doc.selectNodes("//root/operators/operator[@id='" + providerId + "']/fields/field/name");
        for (Iterator itr = list.iterator(); itr.hasNext();) {
//          Attribute attr = (Attribute) itr.next();
//          outList.add(attr.getValue());
            Element el = (Element) itr.next();
            Node elNode = (Node) itr.next();
//          elNode.getText();
            System.out.println("in array");
            System.out.println("field name: " + elNode.getText().toString());
        }
        System.out.println("field name end");
    }

public String getProviderImg(String file, String providerName) throws DocumentException, IOException {

    String xml = readFile(file);
    Document doc = DocumentHelper.parseText(xml);

    String img = doc.selectSingleNode("//root/menu/group/operator_id[@name='" + providerName + "']/@image").getText();

    return img;

}

public class Helpers {

    public static int getResourceId(Context context, String name, String resourceType) {
        return context.getResources().getIdentifier(name, resourceType, context.getPackageName());
    }

These methods called in Activity:

        Bundle menuExtras = getIntent().getExtras();

        BankMenuParser bmp = new BankMenuParser();
String img = bmp.getProviderImg("data/menu.xml", menuExtras.getString("provider_name"));
TextView textView = (TextView) findViewById(R.id.provider_logo);
int resid = Helpers.getResourceId(PaymentActivity.this, img, "drawable");
textView.setBackgroundResource(resid);
bmp.getProviderFields("data/provider_fields.xml", menuExtras.getString("provider_id"));

I'm interested in set the background to the image in LogCat I see the output like:
 07-13 13:27:36.178: I/System.out(677): mob_beeline.png

So, the image should be set right in all drawables I have a mob_beeline.png and layers.xml with content:
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/mob_beeline"
        android:gravity="center" />
    </item>
</layer-list>

A:  textView.setBackgroundResource(R.drawable.mob_beeline);

See here


text:
Q: WCF Service under loadbalancer problem In loadbalancer (bigip/f5) environment WCF services are not working after the website is set to run under asp.net 4.0. The Javascript proxy requests are going as http instead of https under asp.net 4 which is causing "Access denied" errors in JS.
the same working with no issues on previous version of asp.net. Any idea??

A: This is a .NET4 regression that has been reported to Microsoft on Connect (please go vote it up), but has no fix from Microsoft as of yet. For now we wrote some F5 rules that rewrites the protocol in the content on the way back out. Sucks, but prevents having to change anything at the app level (like writing a custom HttpModule).
First we check if it's a we have to even process the request, if so we flag and remove the Accept-Encoding header from the client because otherwise we wouldn't be able to mess with the content if it got GZipped on the way back:
when HTTP_REQUEST
{
   set normalizedPath [string toupper [HTTP::path]]

   if {$normalizedPath ends_with ".SVC/JS" || $normalizedPath ends_with ".SVC/JSDEBUG"}
   {
       set needToFixSvcReference 1

       if {[HTTP::header exists "Accept-Encoding"]}
       {
           HTTP::header remove "Accept-Encoding"
       }
   }
   else
   {
      set needToFixSvcReference 0
   }
}

Then for the response processing we check if we were supposed to mess with the response and if so we collect the content:
when HTTP_RESPONSE {
   if($needToFixSvcReference equals 1)
   {
       # grab the response
       if { [HTTP::header exists "Content-Length"] }
       {
          set content_length [HTTP::header "Content-Length"]
       }
       else
       {
          set content_length 20000
       }

       if { $content_length > 0 }
       {
            HTTP::collect $content_length
       }
   }
}

Then we again check if we're supposed to do anything with this response and replace any set_path("http with set_path("https.
when HTTP_RESPONSE_DATA {
    if { $needToFixSvcReference equals 1 }
    {
        HTTP::payload replace 0 [HTTP::payload length] [string map {set_path("http set_path("https}[HTTP::payload]]
        HTTP::release
    }
}


text:
Q: How to access one class variable in another class using Java? I have created 2 classes as follows...
public class A extends JFrame {
    public String x = "abcdefg";
}

public class B extends JFrame {
    public String y;
}

Both of these classes extend JFrame. I am wondering whether there is a way that the String y in Class B can inherit the value of String x in Class A? I want it such that updating either x or y will also update the other String.
Is there a way that I can make these Strings common to the 2 classes?

A: Just make class B extend A.
public class A extends JFrame {

}

public class B extends A {

}

But TBH, we all think it's a terrible idea to have public fields!

A: I would do something like this..
class a
{
    private String aVal = "abc";

    public String returnAVal(){
         return aVal;
    }
}

class b extends a
{
    private String y = returnAVal();

    public void testY(){
        System.out.println(y);
    }
}

Hope it helps.
PhilNerd

A: It is not good idea to have Inheritance for the sake of single varibale.check LSP.
Make it private and provide setters and getters to access it.


text:
Q: Data from my react front end not getting to mysql database I have a react front-end, node server, and MySQL database. I'm making use of express server and Axios for my post request. The code doesn't appear to have an error, also in the console and network in chrome. However, no data gets to my database. I'll really appreciate the help. Here are my codes;
Client
import React, { useState } from 'react';
import './register.css';
import {Link} from 'react-router-dom';
import Image from '../../assets/Image.png';
import Axios from 'axios';

const Register = () => {

  const [uploadReq, setUploadReq] = useState('')
  const [usernameReq, setUsernameReq] = useState('')
  const [fullnameReq, setFullnameReq] = useState('')
  const [emailReq, setEmailReq] = useState('')
  const [passwordReq, setPasswordReq] = useState('')

  const registration = () => {
    Axios.post("http://localhost3000/register",{
      upload: uploadReq,
      username: usernameReq,
      fullname: fullnameReq,
      email: emailReq,
      password: passwordReq,
    }).then((response) => {
     console.log(response);
    });

  };

  return (

register

Upload Profile pic

browse media on your device

        <form className='register-writeForm' autoComplete='off' >

            Upload
            <input type="file" className='custom-file-input'
             onChange={(e) => {
              setUploadReq(e.target.value);
            }}
          />

            Full Name
            <input type="text" placeholder='Name'
            onChange={(e) => {
            setFullnameReq(e.target.value);
          }}
            />

            Username
            <input type="text" onChange={(e) => {
              setUsernameReq(e.target.value);
            }}placeholder='Username'  />

            Email
            <input type="email" placeholder='Email'
            onChange={(e) => {
            setEmailReq(e.target.value);
            }}
            />

            Password
            <input type="text" onChange={(e) => {
              setPasswordReq(e.target.value);
            }} placeholder='Password'   />

          <button className='register-writeButton' onClick={registration}>register</button>
          <Link to="/login">
            <button className='reg-login-writeButton' >Login</button>
          </Link>

        </form>

   )
};

export default Register;

Server
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");

app.use(express.json());
app.use(cors());

const db = mysql.createPool({

    host: "localhost",
    user: "root",
    password: "xyz",
    database: "nftdatabase",
 });

 app.post('/register', (req, res) => {

    const upload = req.body.upload
    const Fullname = req.body.fullname
    const Username = req.body.username
    const Email = req.body.email
    const Password = req.body.password

    db.query("INSERT INTO user (upload, fullname, username, email, password) VALUES (?,?,?,?,?)",
    [upload, Fullname, Username, Email, Password],
    (err, result) => {
        console.log(err);
    });

 });

app.listen(3001, () => {

    console.log("running on port 3001");
});

A: Your server is running on PORT 3001 whereas from your client you are calling the API endpoint on PORT 3000. Have you used proxy in client side. Have you added this line in package.json file?
"proxy": "http://localhost:3001"


text:
Q: what does 'skipping ancestor revision' mean when using 'graft'? I'm using the graft command to pull 4 changesets from a BranchA into BranchB. When I do, some are grafted and some are not:
PS D:\Dev\ProjectAlpha> hg graft 5f403abb2b24
skipping ancestor revision 15911
PS D:\Dev\ProjectAlpha> hg graft 535ff712c5a3
grafting revision 15925
PS D:\Dev\ProjectAlpha> hg graft cf42b7113e02
grafting revision 15931
PS D:\Dev\ProjectAlpha> hg graft 6920922ee602
skipping ancestor revision 15910

I can't find anything documented that explains this. I can find the source, but maybe it'd be helpful to someone else if someone could come along and explain this.
Is there an order of operations with graft that I need to keep in mind? Am I doing it wrong?

A: From hg help glossary:
Ancestor
    Any changeset that can be reached by an unbroken chain of parent
    changesets from a given changeset. More precisely, the ancestors of a
    changeset can be defined by two properties: a parent of a changeset is
    an ancestor, and a parent of an ancestor is an ancestor. See also:
    'Descendant'.

so graft is refusing to make those revisions descendants of your current changeset because they're already ancestors of your current changeset, and having your ancestors be your descendants was shown to not work in the Back to the Future movies. ;)


text:
Q: Dynamically group rows by their values I am looking for a way to group rows by linking the values of the cells (see link for image). For example, Row 1 is linked to row 2 by the letter "B", and row 2 is linked to row "3" by the letter C -- making those three rows group 1. Whereas, row 4 has no links and is considered group 2.
Example image
UPDATE: When I say 'linked' I mean that rows can be grouped by a common value in a cell. Given my first example, the letter "B" is present in both row 1 and row 2, which I then consider 'linked'. See the next link for a sub-sample of my original, but more complex, data.
Sub-sample of original data
I apologize in advance if this question has been addressed in an earlier post but I simply don't know how to phrase it.

A: A simple solution (if I understand your problem) - Assuming you have data in columns A and B, and group numbers in C.
Put the number 1 in the first row, "group" column (cell C1).  Then put the following formula in cell C2, and drag down:
=IF(B1 = A2, C1, C1 + 1)

when the cells match, the group number is the same, otherwise it increments.  Simple sample:

Formula view of the same thing:

A: Managed to find a way of solving this problem using R and the RBGL package. Really appreciate everyone's input. See link...
identify groups of linked episodes which chain together


text:
Q: Conditional Compilation of schema objects in SSDT Project Our SSDT database project includes a table that has a computed column that can take one of several forms, depending on customer requirements. I'm trying to figure out how to manage this computed column so that we can still use the Publish function without reverting everyone's columns back to the default.
What I'm trying to accomplish can be explained in the following invalid T-SQL code:
CREATE TABLE dbo.Customer
(
  Id INTEGER,
  Region INTEGER,
  Name VARCHAR(50),
  AccountNumber AS dbo.FormatAccountNumber(Id, Region)
)

CREATE FUNCTION [dbo].[FormatAccountNumber]
(
  @Id INTEGER,
  @Region INTEGER
)
RETURNS VARCHAR(20)
AS
BEGIN
  IF '$(AccountType)' = 'Regional'
    RETURN CONVERT(VARCHAR, @Region) + '-' + CONVERT(VARCHAR, @Id)

  IF '$(AccountType)' = 'Merged'
    RETURN CONVERT(VARCHAR, @Region * 100000 + @Id)

  IF '$(AccountType)' = 'Flat'
    RETURN CONVERT(VARCHAR, @Id)
END

This, of course, doesn't work because the $(AccountType) SQLCMD variable can't be used inside of the function, and wouldn't be set properly at run-time anyway. I've also trying putting the SQLCMD conditional around the entire function:
IF '$(AccountType)' = 'Flat'
  CREATE FUNCTION ...

but this produces the error that "CREATE FUNCTION must be the only statement in the batch."
Is there any way to do any sort of conditional compilation of schema in the SSDT project? And if not, what options do I have for maintaining this sort of customizable field within the SSDT publishing process?

A: You could use a Post-Deploment script to imperatively deploy your object in dynamic SQL:
IF NOT EXISTS (SELECT * FROM sys.objects
            WHERE object_id = OBJECT_ID(N'[dbo].[FormatAccountNumber]')
            AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
EXEC('CREATE FUNCTION [dbo].[FormatAccountNumber] () RETURNS BIT AS BEGIN RETURN 0 END')
GO

IF '$(AccountType)' = 'Regional'
BEGIN
    EXEC('
        ALTER FUNCTION [dbo].[FormatAccountNumber]
        (
          @Id INTEGER,
          @Region INTEGER
        )
        RETURNS VARCHAR(20)
        AS
        BEGIN
            RETURN CONVERT(VARCHAR, @Region) + ''-'' + CONVERT(VARCHAR, @Id)
        END
    ')
END

Note that by doing this, you won't be able to make any references to the dbo.FormatAccountNumber function in your SSDT Database Project (unless those objects also included in the Post-Deployment script).
I also toyed with an alternate solution which involved addition conditionals within the .sqlproj file itself (within the ItemGroup elements), but this did get a bit messy since MsBuild Properties aren't exactly like-for-like with SQLCMD Variables, but I can post this if you like.
If you find yourself needing to conditionally deploy objects in your database often, you may like to consider moving to an imperative-based deployment solution (as opposed to the declarative style of SSDT projects). Imperative deployment, often called migrations, gives you greater control of deploy-time behaviour.
Disclaimer: I am the founder of ReadyRoll, which makes a product for VS that uses imperative deployment.

A: I have had an open discussion on MSDN about this need.  Have not made much progress.  The ideal situation would allow you to flag db objects as "inheritable" in base ssdt projects so that other projects that reference the base project or DAC won't complain of the duplicate object,  and would only create the base object or "stub" if it did not exist. This would allow you to have "layers" of database models.   See my post on msdn Extending SSDT Composite Solutions with Overriden Stored Procedures


text:
Q: I need to get number series in suffix character I need to get number series in suffix in the cell example given below

A1 = Recurring12453-001
A2 = Recurring12453-001

Please help me out from this problem
function ff() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('O2:O4').activate();
  spreadsheet.getRange('O2:O4').autoFill(spreadsheet.getRange('O2:O19'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
  spreadsheet.getRange('O2:O19').activate();
};

A: I didn't find any reference to

SpreadsheetApp.AutoFillSeries

or

Range.autoFill()

Maybe you could link us a reference ?
Otherwise, here is a (bit ugly) solution which provide you what you looking for :
function ff() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var value = sheet.getRange('A1').getValue().split("-");
  var prefix = value[0];
  var suffix = parseInt(value[1]);
  var data = [];
  for(var i = 1; i<=21; i++){
    suffix++;
    data.push(["" + prefix + "-" + ('00' + suffix).slice(-3)]);
  }
  sheet.getRange('A2:A22').setValues(data);
};


text:
Q: iOS Ad Hoc generates small .ipa file size In order to distribute your app via Ad Hoc distribution, you have to create a provisioning profile for ad hoc distribution, download the provisioning profile file, verify that is valid in Xcode, sign the application with the provisioning profile (should be the same bundle id), edit the scheme to duplicate the release configuration and rename it to ad hoc, also change it so the archive command takes the ad hoc configuration, hit the command "Archive", follow the organizer screens until you distribute it for ad hoc, save the ipa file and you're done.
Everything works as expected, I've successfully deployed for ad hoc distribution before many times, the problem is that the final .ipa file is way smaller than the whole application folder, from 17MB it ends up as a 3.3 MB file, in addition itunes won't install this application.
Have you any clues on what's happening?

A: The application folder often contains a number of different builds (for Simulator and actual devices) and sometimes repository data, so you should not have to worry about the size difference.
The folder of one of my iOS projects has a size of 25MB, while the IPA only has 6 MB.
Moreover, PNGs are optimized for iOS while compiling, so if the original PNGs were not much bigger before, an image size of 4KB does not necessarily mean something is wrong.
I'd suggest you to concentrate on the real problem, which must be related to your provisioning profile. Have you made sure that your provisioning profile includes the device you want to install your app on?


text:
Q: Fundamental Group! Say you have two surfaces of genus 2, say $X$ and $Y$ and you want to attach them via homotopy attaching maps $f$ along their waist curves. Then what will the fundamental group of the adjunction space $X\bigcup_fY$ be?
Any Hints on how to proceed?
Thanks


text:
Q: Excel separate cell value
How do I split the text so each option goes to the appropriate option cell(A,B,C.D,E).
Please note that the option text length may vary as well and some option might be missing. For example option B might be missing, leaving the option in the cell as ACDE, how can I get it to skip the empty option and go to the next.

A: I would tend to use 2 cells working together.
Typically, assuming that the string to parse is in C5, your cell first cell (D5 in my example) could contain:
=MID(C5,FIND("|",C5)+1,LEN(C5))

This cell would contain the remaining string to parse.
Your second cell could contain:
=LEFT(C5,LEN(C5)-LEN(D5)-1)

It would use the remaining string to parse as determined above and take the left part of it until the next delimiter.
If you do so, the last column will not work, so you will have to take care about manually.


text:
Q: Solving Bayes' Theorem I am provided $P(A|B) = 0.980$, $P(B) = 0.0005$, $P(A'|B') = 0.987$ and I calculated $P(B') = 0.9995$. I am asked to calculate the overall probability of $P(A)$. I tried to solve it by rearranging the Bayes' Theorem formula but I was left with two unknowns e.g. $P(B|A)P(A) = 0.00049$

A: Bayes theorem is basically:
$$P(A\cap B)=P(A|B)P(B)=P(B|A)P(A)$$
The total probability of A, $P(A)$ is going to be the probability of A, given B, multiplied by the probability of B i.e. $P(A|B)P(B)$ plus the same but if B is not true, which translates to:
$$P(A)=P(A|B)P(B)+P(A|B')P(B')$$
Now it is clear that:
$$P(A|B')=1-P(A'|B')$$
and:
$$P(B')=1-P(B)$$
so combining it all we get:
$$P(A)=P(A|B)P(B)+[1-P(A'|B')][1-P(B)]$$
and these are all values you are given, so you are done :)

A: You have what you need.
$$P(A)=P((A\cap B) \cup (A\cap B')) = P(A\cap B) + P(A\cap B')$$
$$= P(A|B)P(B)+P(A|B')P(B')$$
and use
$P(A|B')=1-P(A'|B')$


text:
Q: Read values from console in a loop in Haskell I want to read values(strings) from console in a loop until a certain value is entered.
What is the code for that?

A: With Haskell there are a multitude ways of writing such a loop, and the one you choose will depend on context -- i.e. what larger program is this loop part of?
To get you started with some simple imperative-style loops, both the Haskell Wikibook and the Haskell Wiki have some good resources:

*

*Haskell Simple Input and Output

*IO for Imperative Programmers
Update
From your comment it appears you want to write a "command processor". Have a look at this SO question and answer:

*

*Number guessing game error and keeping count of guesses
Alternatively, if your bool expression type has a Show instance how about using the REPL in ghci?
ghci> :load your_code
ghci> let e = ...initial bool expression...
ghci> e
...e is displayed...
ghci> let f = e || blah
ghci> f
...f is displayed...
ghci> it && whatever             -- it refers to the last expression
...some output...
ghci> not it
...

it is a variable maintained by ghci which always refers to the last evaluated expression.


text:
Q: Including external libraries jar into NetBeans Project without moving problems Problem: How to include extenal libraris and how to store in the files project in order to don't have problems when you move the project folder or something like that.
I am thinking about CVS project. If I include a jar (that its stored in project folder), and other user go on working, he has problems with referencing libraries...
How to include libraries?
How to store libraries?
What is the proper way to do this.
Thanks in advance

A: The easiest way to make sure that everyone has the libraries that are needed, is to use Maven. I've made a video How to import iText 7 in Netbeans to create a Hello World PDF?  that shows how to create a Maven project in NetBeans.
NetBeans creates a pom.xml file to which you can add dependencies. For instance;
<dependencies>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>kernel</artifactId>
        <version>7.0.1</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>layout</artifactId>
        <version>7.0.1</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>io</artifactId>
        <version>7.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.18</version>
    </dependency>
</dependencies>

When you build the project, these libraries will be downloaded from the Maven Central Repository. Obviously, I assume that you are using library that are published on that repository. If not, you have to create your own repository. For instance: at iText, we have a couple of private repositories for our own use within the company.


text:
Q: Handling alerts using if/else in Java How to handle the alerts using if/else commands? If alerts comes up do accept/dismiss, if not proceed further. I was trying with below code but an error at (r==true) says incompatible type.
bool r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
if (r = true) {
    driver.switchTo().alert().accept();
} else {
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

A: The incompatible type is for the reason that
driver.findElement

would return a WebElement type and not a boolean(that's java). You might want to change the code to:
try {
    WebElement r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
    driver.switchTo().alert().accept(); // this would be executed only if above element is found
} catch (NoSuchElementException ex) {
    // since the element was not found, I 'm still doing some stuff
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

A: As r is of boolean type so there is no need to write if(r == true) or if(r == false) you can directly write if(r) and java will understand the code.

A: driver.findElements will check the existence of the object and will return 1 if exist else zero.
So in your case though the alert exist or not, it will handle and based on size it will execute next step. Hope this helps in your case.

int r= driver.findElements(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]")).size();
if(r!=0){
    driver.switchTo().alert().accept();
} else {
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}


text:
Q: Boxplot by group and then column in r How do I make a boxplot such that each group of boxes in the boxplot contains columns of variables from a dataframe.
For example using the mpg dataset:
head(mpg)

# A tibble: 234 x 11
   manufacturer model      displ  year   cyl trans      drv     cty   hwy fl    class
   <chr>        <chr>      <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr>
 1 audi         a4           1.8  1999     4 auto(l5)   f        18    29 p     compact
 2 audi         a4           1.8  1999     4 manual(m5) f        21    29 p     compact
 3 audi         a4           2    2008     4 manual(m6) f        20    31 p     compact
 4 audi         a4           2    2008     4 auto(av)   f        21    30 p     compact
 5 audi         a4           2.8  1999     6 auto(l5)   f        16    26 p     compact
 6 audi         a4           2.8  1999     6 manual(m5) f        18    26 p     compact
 7 audi         a4           3.1  2008     6 auto(av)   f        18    27 p     compact
 8 audi         a4 quattro   1.8  1999     4 manual(m5) 4        18    26 p     compact
 9 audi         a4 quattro   1.8  1999     4 auto(l5)   4        16    25 p     compact
10 audi         a4 quattro   2    2008     4 manual(m6) 4        20    28 p     compact
# ... with 224 more rows

So within each cyl group (4,5,6,8), I want to have boxplots for each variable/column cty,hwy, and displ.
Usually, one will set the fill in ggplot to be a factor variable but in this case, I have 3 variables.
It should look something like this:

A: You need to tranform your data to long format on your three variables. Here an example with data.table and melt function, but you will easily find the same with tydr:
library(ggplot2)
library(data.table)

mpg <- setDT(copy(mpg))
mpg_plot <- melt(mpg,measure.vars = c("cty","hwy","displ"),value.name = "val",variable.name = "var")

ggplot(mpg_plot, aes(x = as.factor(cyl),y = val,fill = var))+
  geom_boxplot()+
  theme_light()


text:
Q: Fast Linq operation on list of file names I have tens of thousands of files that have a filename format:
public static string mTimeFormat = "yyyyMMdd_HHmmss_fff__N";

where N could be anything from 1 to a big number (lets say 1,000,000).
Those are the file names enumerated in a sub-folder - please don't ask me how and why - it is an existing project - it works and its fast. The N number had to be added just now. This breaks the fast retrieval of range of files that was originally done by:
// retrieve range of file names
string t1 = startTime.ToString(mTimeFormat);
string t2 = endTime.ToString(mTimeFormat);
List<string> results = fileNameList.FindAll(s => (String.Compare(s, t1, true) > 0) && (String.Compare(s, t2, true) < 0));

In order to keep the existing code working (which is fast) I need to strip "__N"
the the filenames in order to keep the fast retrieval of filename range.
I tried iterating through the list but it is not fast enough...Any suggestion for Linq operation that will strip "__N" from each and every file name in one fast operation?

A: While the end-part "could be anything" the first part should be fixed so just taking the substring from there should be fine. LINQ however will not bring a speed benefit probably as it is iterating over the list internally as well. This code however might be worth a try:
var lengthOfFirstPart = "yyyyMMdd_HHmmss_fff".Length;
fileNameList = fileNameList
               .Select(f=>f.SubString(0, lengthOfFirstPart)
               .ToList(); // assuming it was a List<string> before


text:
Q: Exit Loop if `all Matches` are found Using below code to Match a range on sheet "Auto" against a range on specific sheets on the same workbook.
If a match found, then some values will be inserted on that specific Sheets.
Practically, There will not be any duplicate matches, so I need to exit the main Loop if all matches are found.
e.g values 111 and 222 are found on sheets "North" and sheet "central" receptively,So there is no need to search for a match on the other sheets,so the need to exit loop.
in advance,grateful for any useful help comment and answers.
Option Explicit
Option Compare Text

    Sub Run_Modified()

         Dim Auto_Data As Range: Set Auto_Data = Sheets("Auto").Range("A2:A21")

         Dim ws As Worksheet
    For Each ws In Sheets(Array("North", "Central", "Onshore", "South"))  'exit this Loop if all below Match are found

         Dim WorkOrder As Range: Set WorkOrder = ws.Range("B3:B250")

         Dim cell As Object, Match_A As Variant
         For Each cell In WorkOrder
     Match_A = Application.Match(cell.value, Auto_Data, 0)
          If Not IsError(Match_A) Then
             cell.Offset(, 6).Resize(1, 3).value = Array("Close", Now, ws.name)
          End If

        Next cell

     Next ws 'I need to exit this Loop if all Matches are found

    End Sub

A: Exit For is your friend.
If I understand you correctly this should be the part where you have to insert it:
If Not IsError(Match_A) Then
    cell.Offset(, 6).Resize(1, 3).value = Array("Close", Now, ws.name)
    exit for
End If

If there is a match on the sheet, data will be inserted and the For each cell-loop will be exited.
Next sheet will be handled.

A: the idea of this answer is fully credits to @FaneDuru
As stated on question that there are no duplicate matches.
So, the answer is to compare the number of matched values against count of (Range of match) Auto_Data.If the result is equal each other ,that is means all values are matched and no need to complete the rest of both Loops.
Sub Run_Modified_1()

     Dim Auto_Data As Range: Set Auto_Data = Sheets("Auto").Range("A2:A21")

     Dim ws As Worksheet
For Each ws In Sheets(Array("North", "Central", "Onshore", "South"))
     Dim WorkOrder As Range: Set WorkOrder = ws.Range("B3:B250")

     Dim cell As Object, Match_A As Variant, k As Long
     For Each cell In WorkOrder
 Match_A = Application.Match(cell.value, Auto_Data, 0)
      If Not IsError(Match_A) Then
         cell.Offset(, 6).Resize(1, 3).value = Array("Close", Now, ws.name)
         k = k + 1
         If k = WorksheetFunction.CountA(Auto_Data) Then Exit Sub
      End If
    Next cell
 Next ws
End Sub


text: Q: Restrict use of program to certain devices I have a timeclock program (written in PHP on the server) in use by my company.  We use it to collect time-in and out on a daily basis.  We currently allow anyone in our intranet to use it based on a flag in their employee record, meaning they have to be onsite to clock in at any device at our 9 different locations.  We also have a flag that says they can clock in from any device, anywhere.  This is for our traveling salesmen and management. Now they want 7 devices designated as "timeclocks" only and a flag assigning certain employees to only use those devices to clock in.  We are using iPads for those devices, mounted on the walls in various warehouses. They are in 5 different states, all on our intranet with various subnets (i.e. 192.168.xx.xxx).  Is there a way I can do this?  when I try to use any of the $_Server variables, the proxy server seems to be a problem.  Any suggestions would be appreciated.


text:
Q: Linq to nhibernate string comparison I have a question on linq to nhibernate. I need to create a query in which I could use string comparison:
session.Linq<User>()
       .Where(u => String.Compare(u.Name, givenName) < 0)
       .ToList()

Do I understand correctly that this is not supported in linq-to-nhibernate? Is there a way to use string comparison in linq-to-nhibernate?

A: The new integrated provider in NHibernate 3 allows extending it to support pretty much any construct you want.
Check http://fabiomaulo.blogspot.com/2010/07/nhibernate-linq-provider-extension.html for a full example.
Of course, you'll need to think of a reasonable HQL representation of that expression.

A: This is no longer needed. The lambda expression in the question is now supported.


text:
Q: How to swap values of two rows in Yii2 without violating unique constraint? I need somethink like
START TRANSACTION;
    UPDATE tasks
    SET priority = 2
    WHERE id = 1;

    UPDATE tasks
    SET priority = 1
    WHERE id = 2;
COMMIT;

when task1 haw priority 1, and task2 - 2.

A: I have a solution in MySQL:
UPDATE tasks a
INNER JOIN tasks b on a.id <> b.id
SET a.priority = b.priority
WHERE a.id IN (1,2)
      AND b.id IN (1,2)

I hope you can convert it into ActiveRecord.


text:
Q: local variable or repeated calls? I have a very basic question. Which if the below 2 is better performance-wise:
if (getSomeValue() != null) {
    processSomeValue(getSomeValue());
}

OR
String someValue = getSomeValue();
if (someValue != null) {
    processSomeValue(someValue);
}

getSomeValue() is a normal getter which does not do anything else.

A: A best practice is to always use the 2nd way even you already know that the getSomeValue() is a simple getter. The key thing is that the call might be maintained in the future and changed by someone in the future. Any developer if change the inner code of getSomeValue() may not be aware of the invocation method that you are currently using.


text:
Q: Twitter4j OAuth "Bad Authentication data" code 215 after changing app permissions I've been able to authenticate multiple Twitter accounts for months now, however I just changed my app's permissions to allow DM viewing. After that I reauthentiacted my accounts and the first one worked fine, but any additional account did not.
I decided to print out the consumer key, consumer secret, access token and access token secret to the console. For the my first account there are no spaces and they look correct. However the second account's access token is 10 characters longer than any of the access tokens before I allowed direct messages. Also whenever I attempt to authenticate I get this error:
400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
message - Bad Authentication data.
code - 215

According to the error message and some google searches it seems like this error is ran whenever a request is made without authenticating. However I am authenticating. Also whenever I change the keys in any way it gives me a completely different error about invalid or expired tokens (error 89).
This only happens with additional accounts, and not the first account I authenticate (the first account works perfectly, as expected). This is the code I'm running:
public class Tweeter {
    private String consumerKey = null;
    private String consumerSecret = null;
    private String accessToken = null;
    private String accessSecret = null;
    private Twitter twitter = null;

    public Tweeter(String consumerKey, String consumerSecret, String accessToken, String accessSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.accessToken = accessToken;
        this.accessSecret = accessSecret;

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessSecret);

        TwitterFactory factory = new TwitterFactory(cb.build());
        twitter = factory.getInstance();

        Logger.log("\"" + factory.getInstance().getConfiguration().getOAuthConsumerKey() + "\"");
        Logger.log("\"" + factory.getInstance().getConfiguration().getOAuthConsumerSecret() + "\"");
        Logger.log("\"" + factory.getInstance().getConfiguration().getOAuthAccessToken() + "\"");
        Logger.log("\"" + factory.getInstance().getConfiguration().getOAuthAccessTokenSecret() + "\"");
    }

    public String getConsumerKey() {
        return consumerKey;
    }

    public String getConsumerSecret() {
        return consumerSecret;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public String getAccessSecret() {
        return accessSecret;
    }

    public Twitter getTwitter() {
        return twitter;
    }
}

This is the same code I've used in the project I'm working on for months now, even with some of the same additional Twitter accounts. The only thing that changed is the app permissions now allow me to view DMs. Any ideas how I can get this working again? Thanks

A: The problem is solved. Not sure why this was happening but I tried to reauthenticate additional accounts and it works now. Not sure if there was a problem on Twitter's end or what, I do not believe that I've changed any of the code that was affecting this system in any way.


text:
Q: Library file (.a) where the contents of the structure changes I am creating an algorithm in C that is confidential and cannot be shared with external customers. So, I decided to go with creating a library (.a) file which compiles my algorithm and lets others use it without modifying it. It basically alters the data of a variable within a structure. Now, the structure as such is visible externally (The structure is defined in a separate header file which is included in my .c file) and is generated based on user's configuration. But the said variable is always present within the structure - only remaining data is changed based on user's configuration.
The problem is that if the structure is not exactly the one I used to create the library file, the code fails.
So is there a way to create a library file to modify the data inside a structure, if the structure itself is not available in the beginning?
Any help is greatly appreciated...

A: Technically all structures you use must be character by character equal everywhere. If you have any difference between the same structure in two (or more) translation units that will lead to undefined behavior.
There are ways around that though, for example by using nested structures. For example you could create one structure to contain your private data, and then another structure whose first member is an instance of the first private structure.
For example something like this:
struct private_data
{
    // TODO: The private members here
};

struct public_data
{
    struct private_data private;
    // TODO: The public members here
};

This is in effect similar to inheritance of an object-oriented language. A pointer to the public_data structure can be cast as a pointer to the private_data structure and passed to the functions that need it.
To keep the private data, well, private you could use opaque data types and opaque pointers:
// Forward declaration of the actual private data
struct actual_private_data;

// The "public" private structure
struct private_data
{
    // Pointer to the actual private data
    struct actual_private_data *private;
};

It's important to note that this only works for the private data used for the library. If the public data structure contains data that needs to be accessed by the library as well, you might want to rename the private_data structure and put the common data there. Note that this common data must be in all variants of the structure, it can't be auto-generated differently than what is used in the library.

A: If you are interested only in one data member of a structure,Then get the address of that variable in your confidential application and modify it's value.


text:
Q: I want to import design library in androidx 29 version(latest version) Below image clarify my question. I was try multiples of times to import design library in android studio lastest version 29 (android x) but library does'nt work kindly tell me the design library for androidx 29.

A: The library androidx.design:design:1.0.0 doesn't exist.
You have to use the Material Components library.

Material Components for Android is a drop-in replacement for Android's Design Support Library.

Add one of these in your build.gradle:
implementation 'com.google.android.material:material:1.1.0-beta01'  //beta
implementation 'com.google.android.material:material:1.0.0'  //stable

A: You can use : -
implementation 'com.google.android.material:material:1.0.0' library in androidx for design.


text:
Q: Serilog doesnt create index on ElasticSearch and i dont know why? I have coding Docker Compose, Asp.Net Core 6, Elastic Stack etc. Elastic Stack succesfully running. Serilog succesfully log in console but unsuccesful log in ElasticSearch. My Github Repo.
I use this package:

*

*Serilog.AspNetCore

*Serilog.Enrichers.Environment

*Serilog.Exceptions

*Serilog.Settings.Configuration

*Serilog.Sinks.Debug

*Serilog.Sinks.Elasticsearch

My Docker Compose file is:
version: '3.4'

networks:
    mediatrexample:
        driver: bridge
    elk_stack:
        driver: bridge

services:
    pgsql_image:
        image: postgres:latest
        container_name: postgersql_db
        restart: always
        environment:
            POSTGRES_USER: "postgres"
            POSTGRES_PASSWORD: "123456"
            POSTGRES_DB: "ecommerce"
        ports:
            - 5432:5432
        networks:
            - mediatrexample

    redis_image:
        image: 'redis:latest'
        container_name: redis_db
        restart: always
        environment:
            - REDIS_PASSWORD=RRnFPZ93tjBHB9W62p
            - REDIS_PORT=6379
        ports:
            - '6379:6379'
        command: [ "redis-server" ]
        networks:
            - mediatrexample

    elastic_image:
        image: docker.elastic.co/elasticsearch/elasticsearch:7.16.1
        container_name: elk_elastic
        environment:
            - node.name=elastic01
            - xpack.monitoring.enabled=true
            - xpack.watcher.enabled=false
            - xpack.security.enabled=true
            - xpack.security.audit.enabled=true
            - discovery.type=single-node
            - ELASTIC_PASSWORD=DkIedPPSCb
            - ES_JAVA_OPTS=-Xms512m -Xmx512m
        ulimits:
            memlock:
                soft: -1
                hard: -1
        networks:
            - elk_stack
        ports:
            - 9200:9200
            - 9300:9300

    kibana_image:
        image: docker.elastic.co/kibana/kibana:7.16.1
        container_name: elk_kibana
        environment:
            - ELASTICSEARCH_URL=http://elastic_image:9200
            - ELASTICSEARCH_HOSTS=http://elastic_image:9200
            - ELASTICSEARCH_USERNAME=elastic
            - ELASTICSEARCH_PASSWORD=DkIedPPSCb
        networks:
            - elk_stack
        depends_on:
            - elastic_image
        links:
            - elastic_image
        ports:
            - 5601:5601

    mediatrexample.api:
        image: ${DOCKER_REGISTRY-}mediatrexampleapi
        container_name: mediatr_example
        depends_on:
            - pgsql_image
            - redis_image
            - elastic_image
            - kibana_image
        build:
            context: .
            dockerfile: MediatrExample.API/Dockerfile
        networks:
            - mediatrexample
        ports:
            - 5001:80
        links:
            - pgsql_image
            - redis_image
            - elastic_image
        environment:
            - CONNECTIONSTRINGS__NpgSQLConnection=User ID=postgres;Password=123456;Host=pgsql_image;Port=5432;Database=ecommerce
            - Redis__Host=redis_image
            - Redis__Port=6379
            - Redis__Password=RRnFPZ93tjBHB9W62p
            #- Serilog__WriteTo__1__Args__nodeUris=http://elastic:DkIedPPSCb@elastic_image:9200

My Log Configuration Code is:
public static class MyLogger
    {
        public static void ConfigureSeriLog(IConfiguration configuration)
        {
            string elasticUser = configuration["SeriLogConfig:ElasticUser"];
            string elasticPassword = configuration["SeriLogConfig:ElasticPassword"];

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                .WriteTo.Debug()
                .WriteTo.Console()
                .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(configuration["SeriLogConfig:ElasticUri"]))
                {
                    AutoRegisterTemplate = true,
                    AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
                    IndexFormat = $"{configuration["SeriLogConfig:ProjectName"]}-{configuration["SeriLogConfig:Environment"]}-logs-{0:yyyy.MM.dd}",
                    ModifyConnectionSettings = s => s.BasicAuthentication(elasticUser, elasticPassword),
                    FailureCallback = e => { Console.WriteLine("Hasan - Unable to submit event -- " + e.MessageTemplate); e.Properties.Values.ToList().ForEach(x => Console.Write(x)); },
                    EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog |
                                   EmitEventFailureHandling.WriteToFailureSink |
                                   EmitEventFailureHandling.RaiseCallback |
                                   EmitEventFailureHandling.ThrowException,
                    FailureSink = new FileSink("./failures.txt", new JsonFormatter(), null)
                })
                .Enrich.WithProperty("Environment", configuration["SeriLogConfig:Environment"])
                .ReadFrom.Configuration(configuration, "SerilogLogLevels")
                .CreateLogger();
        }
    }

My Program.cs Code is:
var builder = WebApplication.CreateBuilder(args);
var Configuration = builder.Configuration;
// Add services to the container.

MyLogger.ConfigureSeriLog(Configuration);
builder.Host.UseSerilog();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opt =>
    {
        opt.TokenValidationParameters = new TokenValidationParameters()
        {
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTTokenOptions:SecretKey"])),
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1), //Skew default 5 minute
            ValidateAudience = false,
            ValidateIssuer = false,
            ValidateIssuerSigningKey = true
        };
    });

builder.Services.AddControllers();

var multiplexer = RedisUtility.ConnectRedis(Configuration);
builder.Services.AddSingleton<IConnectionMultiplexer>(multiplexer);

builder.Services.AddMediatR(Assembly.GetAssembly(typeof(GetAllUserRequest)));
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddMyServiceLifeCycles(Configuration);
builder.Services.AddValidatorsFromAssembly(Assembly.GetAssembly(typeof(GetAllUserRequestValidator)));
builder.Services.ConfigureMyOptionModels(Configuration);

builder.Services.AddEntityFrameworkNpgsql().AddDbContext<AppDbContext>(opt =>
{
    opt.UseNpgsql(Configuration.GetConnectionString("NpgSQLConnection"), npsqlOpt =>
    {
        npsqlOpt.CommandTimeout(150);
        npsqlOpt.MigrationsAssembly("MediatrExample.Data");
    });
});
// Above Code for "timestamp with time zone' literal cannot be generated for Local DateTime: a UTC DateTime is required" error solution
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

builder.Services.AddCors(options => { options.AddPolicy("AllowOrigin", policy => policy.AllowAnyOrigin()); });

var app = builder.Build();

app.UseMyCustomMiddleware();

app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.MapGet("/", () =>
{
    using (var scope = app.Services.CreateAsyncScope())
    {
        var service = scope.ServiceProvider;
        var logger = service.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("Example Log Date: {0}", DateTime.Now);
    }
    return "Server is Running...";
});

#region Auto Run Pending Migration
using (var scope = app.Services.CreateAsyncScope())
{
    var services = scope.ServiceProvider;
    var dbContext = services.GetRequiredService<AppDbContext>();
    if (dbContext.Database.GetPendingMigrations().Any())
    {
        dbContext.Database.Migrate();
    }
}
#endregion

app.Run();

My appsetting.json file is:
{
  "ConnectionStrings": {
    "NpgSQLConnection": "User ID=postgres;Password=123456;Host=pgsql_image;Port=5432;Database=ecommerce;Integrated Security=true;Pooling=true;"
  },
  "Environment": {
    "EnvironmentName": "dev"
  },
  "Redis": {
    "Host": "0.0.0.0",
    "Port": "6380",
    "Password": "123456"
  },
  "JWTTokenOptions": {
    "SecretKey": "v5PSdoOHjeB34wUkmMwr4x4Z1HWkudFoyVZTx7sFvm",
    "TokenExpireTimeMinute": 120
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.Elasticsearch", "Serilog.Enrichers.Environment" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "Elasticsearch",
        "Args": {
          "nodeUris": "http://localhost:9200",
          "indexFormat": "mediatr-example-logs-{0:yyyy.MM.dd}",
          "autoRegisterTemplate": true,
          "autoRegisterTemplateVersion": "ESv7",
          "DetectElasticsearchVersion": true,
          "OverwriteTemplate": true,
          "emitEventFailure": "WriteToSelfLog",
          "registerTemplateFailure": "IndexAnyway",
          "numberOfShards": 20,
          "numberOfReplicas": 10,
          "connectionGlobalHeaders": "Authorization=Basic ZWxhc3RpYzpEa0llZFBQU0Ni"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ]
  },
  "SerilogLogLevels": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "System": "Warning"
      }
    }
  },
  "SeriLogConfig": {
    "ProjectName": "mediatr-example",
    "ElasticUri": "http://localhost:9200",
    "Environment": "development",
    "ElasticUser": "elastic",
    "ElasticPassword": "DkIedPPSCb"
  },
  "AllowedHosts": "*"
}

I have triesd two ways for Serilog logging on Elastic Stack but each way doesnt work.

*

*Serilog Configuration Set in MyLogger.ConfigureSeriLog

*Serilog Configuration Set in appsetting.json

Please help Why Serilog doesn't logging on Elastic Stack?


text:
Q: installing redmine_backlog with chiliproject I installed chiliproject 3.3.0. After some problems it worked fine...
But now i try to add the BackLog Plugin and i am stucking there...
I did the installation instruction from here: http://www.redminebacklogs.net/en/installation.html
When i call that command "bundle exec rake redmine:backlogs:install" i always get that error:
root@debian2:~/redmine_backlogs# bundle exec rake redmine:backlogs:install
/opt/ruby-enterprise-1.8.7-2012.02/lib/ruby/gems/1.8/gems/bundler-1.2.0/lib/bundler/rubygems_integration.rb:147:in `gem': rake is not part of the bundle. Add it to Gemfile. (Gem::LoadError)
        from /opt/ruby-enterprise-1.8.7-2012.02/bin/rake:18

I really don't know what to try anymore :S
Please tell me which information do you need to help me.

A: Make sure to execute the command in your ChiliProject main directory, e.g. /path/to/chiliproject. Any rake or bundle invocations have to be performed in that main directory, not in the individual plugin directories.


text:
Q: Prove $h^{-1}fh \in K_4$ for $f\in K_4$, $h\in S_4$.
I want to show if  $f \in K_4=\{id,(1 2)(3 4),(1 3)(2 4),(1 4)(2 3)\}$, then for all permutations $h \in S_4$ also $h^{-1}fh \in K_4$ (not using group theory).

The elements in $K_4$ except for the identity are the elements in $S_4$ which are a product of two disjoint 2-cycles.
Therefore, I am trying to prove that $h^{-1}fh$ in disjoint cycle notation are two 2-cycles.
Then I consider different cycle structures of $h$, $4$ 1-cycles, one 3-cycle and one 1-cycle etc.
However, I am not sure why it is true for instance if $h$ is $(1)(2 3 4)$, taking the $f$ to be the identity I get $(1)(2)(3 4)$ which is not two 2-cycles.

A: What you're trying to show is that $K_4$ is a normal subgroup of $S_4$.

However, you said you wish not to use group theory. No problem.

Theorem: For any $n\in\Bbb N$ and permutations $\alpha,\beta\in S_n$ with
$$\beta=\prod_{i}(b_{i,1}\cdots b_{i,j_i}),$$
we have that
$$\alpha^{-1}\beta\alpha=\prod_{i}(\alpha(b_{i,1})\cdots \alpha(b_{i,j_i})),\tag{1}$$
where $\alpha(x)$ is $\alpha$ applied to $x\in \overline{1,n}:=\{1,\dots, n\}$, and the cycle structure of $\beta$ is preserved in the RHS of $(1)$.

Then one just needs to observe that each $h\in S_4$ is a bijection on $\overline{1,4} $, so that the disjoint cycle nature of each $f$ in $K_4$ is preserved.

And as Tobias pointed out, you made an error in your calculation.


text:
Q: From what viewpoint do Omnioculars show past events? Omnioculars are magical eyeglasses that allow viewing events slowed down, or replay past events.  They were introduced in Harry Potter and the Goblet of Fire chapter 7, and in chapter 8, Harry was watching the Quidditch match through them.  From what viewpoint do Omnioculars show events?

*

*Do they show the events from where the glasses were looking at the time the events happened?  That would make it not very useful in a sports match, where the spectators are sitting close to the events and have to turn their head to watch different parts of the stadium.

*Do they show the events from the viewpoint where the viewer is looking at when they are at the time of viewing?  That ability would be obviously overpowered and broken, since you could spy on any event that happens in a room that you can later get into.

A: They show what happens in the direction they're looking in.
Omnioculars work to slow down, replay, and explain the game, but not to record in all directions or watch the entire field. They're never described or seen to record anything they weren't pointed at.

"Omnioculars,' said the saleswizard eagerly. 'You can replay action … slow everything down … and they flash up a play-by-play breakdown if you need it."- Harry Potter and the Goblet of Fire, Chapter 8 (The Quidditch World Cup)

The Omnioculars can slow down and replay whatever was happening in the direction they were pointing at the time when they were pointed in that direction. They have to be pointed that way first.

"That's him, that's him!' yelled Ron, following Krum with his Omnioculars; Harry quickly focused his own." - Harry Potter and the Goblet of Fire, Chapter 8 (The Quidditch World Cup)

They work something like a camera with slow motion and rewind function - they'll replay and slow down the footage, but it's only captured for the direction it was pointed at the time.

"Seven green blurs swept onto the pitch; Harry spun a small dial on the side of his Omnioculars, and slowed the players down enough to read the word 'Firebolt' on each of their brooms, and see their names, embroidered in silver, upon their backs." - Harry Potter and the Goblet of Fire, Chapter 8 (The Quidditch World Cup)

Throughout the game, people keep following certain things they want to see with their Omnioculars, so they need to be redirected if someone wants to look at anything moving, like a specific player.

"What?' Harry yelled, looking wildly around through his Omnioculars. 'But Levski's got the Quaffle!'
'Harry, if you're not going to watch at normal speed, you're going to miss things!' shouted Hermione, who was dancing up and down, waving her arms in the air while Troy did a lap of honour of the pitch." - Harry Potter and the Goblet of Fire, Chapter 8 (The Quidditch World Cup)

Omnioculars don't stop people having to turn their heads to watch things, not can they replay previous events that they weren't directed at when they were happening.


text:
Q: String can't be extended via 'PLUS' I have a simple question. Please have a look at following script:
def myFunc(string):
    res=''
    for i in string:
        if not i in res:
            res+i
    return res
res=myFunc('aaaa')
print(res)               # return a string 'a'

This script should be able to delete the repeated char in the input string.
Actually, however, I got nothing. The 'res' is NULL.
Do you have any ideas?
Thanks!

A: res+i is not setting its result to a variable. You need to add this back to the string..
res = res + i

A: The problem is that you didn't make an assignement. Check my code where I do res = res+i.
def myFunc(string):
    res=''
    for i in string:
        if not i in res:
            res = res+i
    return res

res=myFunc('aaaa')
print(res)               # return a string 'a'


text:
Q: Magento 2 Set $_POST to an empty Array() I can't seem to find a way to set $_POST to an empty array.
I have a form in phtml action to self I can get $_POST values the following ways:
$this->getRequest()->getPostValue('form_key');

$this->getRequest()->getParam('form_key');

The Above will give Array ( [form_key] => FThdknnc_347djcncKey_)
Now I've tried to reset by doing:
$this->getRequest()->setPostValue('form_key');

But it gives me:
Array ([form_key] =>)

That ain't right browser still popping up saying that it will resend data from form: It should return Array () But the form_key key is still in the $_POST Array. one can do in php:
$_POST = Array(); and that would be enough but it doesn't work with magento.
Anyone any idea?

A: Try this:
/** @var \Zend\Stdlib\ParametersInterface $postParameters */
$postParameters = $this->getRequest()->getPost();
$postParameters->fromArray([]);

Use getQuery method to clean GET parameters.

A: You can try like this,
$formKey = $this->getRequest()->getPostValue('form_key');

unset($formKey);

than after you can try to set again
$this->getRequest()->setPostValue('form_key','your_value');

Hope it helps.


text:
Q: Adding a row with a colums to be a combination of two other cells in sql servers I am not sure if asking it right.
Is it possible to have rows in sql tables where some values can be a combination of a particular cell in a row , similar to excel ?
E.g)

ID(string)  | Name(string)

1 | Xyx

2 | yzw

3  | Combine Name from table where Id is 1 and Id is 2

Use Case:
We use the database values for a list box. We want a way so allow multiple selections in list box, but our vendor front endt does not allow multi selection list boxes and we were trying to combine values. The ID will be the display string. So I am trying to accomplish something like Select All as option
From what I searched trigger is the way to go? or are there some other ways to go about it? dont think values can be variable types.

A: I am assuming you are not able to write your SQL query in such a way as to concatenate the columns manually? Like, you are using some sort of front-end tool that automatically maps the drop-down contents to a single database column?
If that is the case, then you may want to look at defining a computed column for the "combined value" that you want. See http://technet.microsoft.com/en-us/library/ms191250(v=sql.105).aspx


text:
Q: CanCan Ability Model I have a Rails 4 app that i wrote a CanCan Ability model for based on my model setup in my app. While testing it works sometimes and then it doesn't. Im not sure what the problem is. There is nothing in the logs that would point to a problem. I also don't think that it is that clean anyway. Any suggestions on how to improve this Ability model? It seems very redundant and confusing.
if user
      ##
      can :manage, User do |u|
        case u.account
          ## If user is a Developer allow it to only be managed by itself (user)
          when Developer
            u == user
          ## If user is a Organization allow it to only be managed by it's founders
          when Organization
            u.account.founders.exists?(user)
          else
            false
        end
      end

      can :manage, App do |a|
        case a.appable
          ## If app belongs to a Developer allow it to only be managed by it owner (developer)
          when Developer
            a.appable.id == user.id
          ## If app belongs to a Organization allow it to only be managed by its organizations' founders
          when Organization
            a.appable.founders.exists?(user)
          else
            false
        end
      end
      ##
    end

A: As for cleaning it up, you could consider instead organizing the logic by user role.  This way you can easily look at a given role and understand all the abilities that they do and do not have access to.
Something like this:
if user.developer?
  can :manage User, id: user.id
  can :manage App, App.appable_by(user)
end

NOTE: you may need to write some custom finders like App.appable_by(user) in order to test the rule
I don't fully follow what you are trying to do with Organization / founders.  If this is a role like user.founder?  Then treat it like mentioned above, but with a different authorization rule.


text:
Q: Dart perform runtime subtype checking I would like to perform runtime subtype checking in Dart without using dart:mirrors.
What I mean by this is that given two types A and  B, either as variables with type Type or as type arguments on a generic class (i.e the variables being checked would be, using List as a dummy class, List<A> and List<B>), I would like to check if A is a subtype of B.
Here is some code written with dart:mirrors that performs what I want:
bool isSubtype(Type a, Type b) => reflectType(a).isSubtypeOf(reflectType(b));

// OR

bool isSubType<A, B>(List<A> a, List<B> b) => reflect(a).type.typeArguments[0].isSubtypeOf(reflect(b).type.typeArguments[0]);

I would like to perform this check without using dart:mirrors. I have tried using the following code:
bool isSubType<A, B>(List<A> a, List<B> b) => <A>[] is List<B>;

However, while this code works with expressions with a static type:
print(isSubType(<Iterable>[], <Iterable>[])); // true
print(isSubType(<Iterable>[], <List>[]));     // true
print(isSubType(<Iterable>[], <String>[]));   // false

it does not work with expressions without a static type:
List a = <Iterable>[];

List<List> types = [<Iterable>[], <List>[], <String>[]];

for (final type in types) {
  print(isSubType(type, a)); // true, true, true
}

How can I implement isSubType to get the correct result for types that are unknown at compile-time?
Note: I don't need this to be compatible with the JS runtime, just AOT and JIT compiled Dart.

A: If all you want is to chcek the subtype relation of two types, you don't need arguments at all, only type arguments.
bool isSubtype<S, T>() => <S>[] is List<T>;

You also can't extract the runtime type of an object as a type argument.
I'm guessing that's what you are trying to do with the arguments and type inference, but type inference happens at compile-time and only uses the static types of the arguments.
The call print(isSubType(type, a)) infers the type List<dynamic> for both type arguments from the expressions type and a, and does so at compile-time and independently of the actual run-time type that variable will contain.
There is no general way, outside of dart:mirrors, to check whether two objects have runtime types that are related to each other, because it's not possible to get the runtime type of an object into a type variable.
You also can't do anything similar with Type objects. A Type object is only really good for passing into dart:mirrors, and maybe compare for equality. It doesn't understand subtyping at all.


text:
Q: How can I validate that a mapping field has at least one item with Cerberus? I'm validating documents with Cerberus that roughly look like this:
{"a_dict": {"field1": "test1",
            "field2": "test2",
            "field3": "test3"}}

Not all of the fields in the subdocument need to be present, but one should. So far my schema looks like this:
"a_dict": {"type": "dict",
           "schema": {"field1": {"type": "string",
                                 "required": False},
                      "field2": {"type": "string",
                                 "required": False},
                      "field3": {"type": "string",
                                 "required": False}}}

How can I enforce that at least one of the fieldX is provided?
This question is derived fom this issue.

A: This does the trick:
string_field = {'type': 'string'}
schema = {'a_dict': {'type': 'dict',
                     'minlength': 1,
                     'allow_unknown': False,
                     'schema':
                         {f: string_field for f in ('field1', 'field2', 'field3')}
                     }}

*

*The minlength rule ensures that there's at least one field in a_dict.

*The allow_unknown rule makes sure no other fields than field<1…3> pass the validation.

*The required rule is False by default.


text:
Q: Find the maximum flow in any network by a given algorithm can you help me with the following problem?:
Suppose we have an algorithm to solve the problem of maximum flow in a flow network in which each node's outdegree is at most 2.
I need to show how to use this algorithm to solve the problem of maximum flow in any network.
If this is a repetition then kindly redirect me to relevant answers.
Thank you all

A: It is indeed possible to transform the graph in such a way that the out-degree of each node is at most 2, and the maximum flow in the transformed graph is equal to the maximum flow in the initial graph.
One such transformation is described below. Assume we have a node whose out degree is larger than 2. Then we can add as many intermediary nodes as the out-degree of this node and connect them in the way depicted in the following image.

The infinite capacity edges ensure that we can send the same flow as initially from A to any of its successors. The edges from X nodes to B nodes ensure that we can not send a flow larger than it was initially possible.
By repeating this transformation for each node with out-degree larger than 2 we obtain a graph where each node has out-degree at most 2, and whose maximum flow is equal to the maximum flow of the initial graph.


text:
Q: C# Listview is not drawing the ListView SubItems on linux but works on windows I am creating a C# .NET Mono application to read logs in from a text file and display them in a listview. The logs are stored in JSON format so they can be parsed easily and be displayed as subitems in the listview.
Picture of the working ListView run on Windows
My application is working correctly when I run the application on windows, however when I run it on the raspbian OS using mono none of the items in the listview are shown. I know that the logs are being read correctly from the text file on both Windows & Linux, as I have logged them to the console for debugging purposes. I have also confirmed that the logs have been copied into the ListViewItem "eachRow" correctly by logging it to the console as well.
I am hoping to find the problem that is causing the ListView Items to not be displayed when run on Raspbian. Due to the fact that I have the data stored correctly all the way up until it is added to the listview, I believe my problem is with the redrawing of the screen/listview.
This is the code I am using to Add each JSON item to the listview.
private void AddLogsToScreen()
    {
        //Create a copy of the current logList Stack
        LogMutex.WaitOne();
        Stack<string[]> logListCopy = new Stack<string[]>(new Stack<string[]>(LogList));
        Console.WriteLine("LLC: " + string.Join(" , ", logListCopy.Peek()));
        LogMutex.ReleaseMutex();

        if (HUBsLogsListView.InvokeRequired)
        {
            HUBsLogsListView.Invoke(new MethodInvoker(delegate
            {
                MessageBox.Show("Invoke Begin Update");
                HUBsLogsListView.BeginUpdate();

            }));
        }
        else
        {
            MessageBox.Show("Begin Update");
            HUBsLogsListView.BeginUpdate();
        }

        var allItemsToAdd = new List<ListViewItem>();

        int totalLogs = logListCopy.Count;
        for (int logNum = 0; logNum < totalLogs; logNum++)
        {
            string[] log = logListCopy.Pop();
            string[] deepLogCopy = new string[8];

            // Copy to avoid messing up original
            log.CopyTo(deepLogCopy, 0);

            deepLogCopy[2] = DateTime.Parse(log[2]).ToString("dd-MM-yyyy, hh:mm:ss tt");
            ListViewItem eachRow = new ListViewItem(deepLogCopy);
            Console.WriteLine("ListViewItem eachRow: " + eachRow.SubItems[0] + " , " + eachRow.SubItems[1] + " , " + eachRow.SubItems[2] + " , " + eachRow.SubItems[3] + " , " + eachRow.SubItems[4] + " , " + eachRow.SubItems[5] + " , " + eachRow.SubItems[6] + " , " + eachRow.SubItems[7]);
            if (deepLogCopy[4] == "3") //Warning
            {
                eachRow.BackColor = Color.Yellow;
            }
            else if (deepLogCopy[4] == "4")  //Error
            {
                eachRow.BackColor = Color.Red;
            }
            allItemsToAdd.Add(eachRow);
        }

        if (HUBsLogsListView.InvokeRequired)
        {
            HUBsLogsListView.Invoke(new MethodInvoker(delegate
            {
                ListView.ListViewItemCollection lvic = new ListView.ListViewItemCollection(HUBsLogsListView);
                lvic.AddRange(allItemsToAdd.ToArray());
                HUBsLogsListView.EndUpdate();
            }));
        }
        else
        {
            ListView.ListViewItemCollection lvic = new ListView.ListViewItemCollection(HUBsLogsListView);
            lvic.AddRange(allItemsToAdd.ToArray());
            HUBsLogsListView.EndUpdate();
        }
    }

I can't come up with a reason why this function is acting differently, with the same files, on Windows compared to running on Linux using mono. I am not as experienced writing .NET programs using mono, so any and all help is appreciated.
Does anyone have any idea what could be the problem? Thanks!


text:
Q: Display number of friends using app I'm trying to display the number of friends a user has using my app. I've figured out through FQL how to pull out an array of the users friends using the app.
SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND is_app_user=1
Right now, it pulls up an array when displayed. I'm trying to just display the result as a single numerical value. I'm coding in PHP. Anyone know where I need to go from here?

A: Select count(*) perhaps.
SELECT count(*) FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND is_app_user=1

A: print count($array); should return the amount of entries in the array


text:
Q: How do I add a frame title specifying the section and subsection names whenever a new subsection come up? I'm very new to StackExchange, let alone LaTeX. The issue here is temporarily adding a frame title to whichever frame comes right after a new subsection is defined. Following is a sample code with an empty ribbon left behind on the first slide.
\documentclass{beamer}
\usepackage{lipsum}
\usetheme{Frankfurt}
\AtBeginSubsection[]
{
\addtobeamertemplate{frametitle}{\let\insertframetitle\insertsubsectionhead}{}
}

\makeatletter
  \CheckCommand*\beamer@checkframetitle{\@ifnextchar\bgroup\beamer@inlineframetitle{}}
  \renewcommand*\beamer@checkframetitle{\global\let\beamer@frametitle\relax\@ifnextchar\bgroup\beamer@inlineframetitle{}}
\makeatother

\begin{document}
\section{Introduction}

\begin{frame}
\lipsum[2]
\end{frame}

\subsection{XYZ}

\begin{frame}
\lipsum[2]
\end{frame}

\end{document}

Basically wanting a similar set-up to this but only for the first frame right after a new subsection starts, without any permanent impact to other frames/frame titles (like said empty ribbons on pages).
EDIT: Found this link which got 90 percent of the job done, but the subsection frame title disappears if overlay specifications (like \uncover) are present in the same frame, as well as displaces individual frame titles (that makes sense).
TLDR for edit: stays only on first slide after new subsection, not same frame.
\documentclass{beamer}
\usepackage{lipsum}
\usetheme{Frankfurt}

\makeatletter
\newcommand<>{\insertsubsectiontitle}{\frametitle{\insertsubsection}}
\let\oldbeamer@checkframetitle\beamer@checkframetitle% Store the \frametitle checking mechanism
\renewcommand<>{\subsection}{%
  \gdef\beamer@checkframetitle{% Update \frametitle checking to ...
    \insertsubsectiontitle% ...insert the section title and...
    \global\let\beamer@checkframetitle\oldbeamer@checkframetitle% ...revert to it's old definition
  }% Regular \section stuff follows
  \alt#1{\@ifnextchar[\beamer@subsection\beamer@@subsection}
    {\beamer@secgobble}}
\makeatother

\begin{document}
\section{Introduction}

\begin{frame}
\lipsum[2]
\end{frame}

\subsection{XYZ}

\begin{frame}
\lipsum[2]
\end{frame}

\end{document}

A: If the frame following the subsection only has one overlay, you can use the following redefinition of the frametitle template.
(if your document starts with a subsection on frame one, remove \ifnum\thepage>1 ... fi from the code)
\documentclass{beamer}
\usepackage{lipsum}
\usetheme{Frankfurt}

\makeatletter
\setbeamertemplate{frametitle}{%
\ifnum\thepage>1
\ifnum\insertsubsectionstartpage=\thepage
  \ifbeamercolorempty[bg]{frametitle}{}{\nointerlineskip}%
  \@tempdima=\textwidth%
  \advance\@tempdima by\beamer@leftmargin%
  \advance\@tempdima by\beamer@rightmargin%
  \begin{beamercolorbox}[sep=0.3cm,left,wd=\the\@tempdima]{frametitle}
    \usebeamerfont{frametitle}%
    \vbox{}\vskip-1ex%
    \if@tempswa\else\csname beamer@fteleft\endcsname\fi%
    \strut\insertsubsectionhead\strut\par%
    {%
      \ifx\insertframesubtitle\@empty%
      \else%
      {\usebeamerfont{framesubtitle}\usebeamercolor[fg]{framesubtitle}\strut\insertframesubtitle\strut\par}%
      \fi
    }%
    \vskip-1ex%
    \if@tempswa\else\vskip-.3cm\fi% set inside beamercolorbox... evil here...
  \end{beamercolorbox}%
\fi\fi
\ifx\insertframetitle\@empty
\else
  \ifbeamercolorempty[bg]{frametitle}{}{\nointerlineskip}%
  \@tempdima=\textwidth%
  \advance\@tempdima by\beamer@leftmargin%
  \advance\@tempdima by\beamer@rightmargin%
  \begin{beamercolorbox}[sep=0.3cm,left,wd=\the\@tempdima]{frametitle}
    \usebeamerfont{frametitle}%
    \vbox{}\vskip-1ex%
    \if@tempswa\else\csname beamer@fteleft\endcsname\fi%
    \strut\insertframetitle\strut\par%
    {%
      \ifx\insertframesubtitle\@empty%
      \else%
      {\usebeamerfont{framesubtitle}\usebeamercolor[fg]{framesubtitle}\strut\insertframesubtitle\strut\par}%
      \fi
    }%
    \vskip-1ex%
    \if@tempswa\else\vskip-.3cm\fi% set inside beamercolorbox... evil here...
  \end{beamercolorbox}%
\fi
}

\CheckCommand*\beamer@checkframetitle{\@ifnextchar\bgroup\beamer@inlineframetitle{}}
\renewcommand*\beamer@checkframetitle{\global\let\beamer@frametitle\relax\@ifnextchar\bgroup\beamer@inlineframetitle{}}
\makeatother

\begin{document}
\section{Introduction}

\begin{frame}
\lipsum[2]
\end{frame}

\subsection{XYZ}

\begin{frame}
\lipsum[2]
\end{frame}

\begin{frame}
\frametitle{title}
\lipsum[2]
\end{frame}

\end{document}


text:
Q: C# Entity Framework - Social Network - Friendship, Chat Entity I am trying to do a database model for my social network school project. I am using Entity Framework 6. The problem is how should I model my Friendship and Chat entity.
I get this error:

Unhandled Exception:
  System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:
Friendship_Chat_Source: : Multiplicity is not valid in Role 'Friendship_Chat_Source' in relationship 'Friendship_Chat'. Because the dependent role properties are not the key properties, the upper bound of the multiplicity of the dependent role must be '*'.

It has probably something to do with this: EF Code-First One-to-one relationship: Multiplicity is not valid in Role * in relationship
I don't really get it how should I do it here. Even if I get rid off this error somehow (different db model), entity framework in Friendship table creates User_Id column as a foreign key, and I dont really know why it does it (I don't want it there). But I really feel that my model should look like this, not different. So I want to really figure out, how should I edit this model. However if you have different model idea I would also appreciate it.
User entity:
public class User
{
    public int Id { get; set; }

    [Required, MinLength(1), MaxLength(50)]
    public string NickName { get; set; }

    [Required, MinLength(6), MaxLength(50)]
    public string PasswordHash { get; set; }

    #region Settings

    //true if anyone can see user posts
    public Visibility PostVisibilityPreference { get; set; } = Visibility.Visible;

    #endregion

    #region Navigation properties

    public virtual HashSet<Friendship> Friendships { get; set; }
    public virtual HashSet<Post> Posts { get; set; }
    public virtual HashSet<GroupUser> GroupUsers { get; set; }
    public virtual HashSet<Comment> Comments { get; set; }

    #endregion
}

Friendship entity:
public class Friendship
{
    #region Primary keys

    public int User1Id { get; set; }
    public int User2Id { get; set; }

    #endregion

    [Required]
    public DateTime FriendshipStart { get; set; }

    #region Foreign keys

    //defined using fluent api in MyDbContext:
    //User1Id
    //User2Id
    //and

    [ForeignKey("Chat")]
    public int? ChatId { get; set; }

    #endregion

    #region Navigation properties

    public virtual User User1 { get; set; }
    public virtual User User2 { get; set; }
    public virtual Chat Chat { get; set; }

    #endregion
}

With this overrided function OnModelCreating in MyDbContext:
protected override void OnModelCreating(DbModelBuilder builder)
    {
        builder.Entity<Friendship>()
            .HasKey(k => new { k.User1Id, k.User2Id });

        builder.Entity<Friendship>()
            .HasRequired(u => u.User1)
            .WithMany()
            .HasForeignKey(u => u.User1Id);

        builder.Entity<Friendship>()
            .HasRequired(u => u.User2)
            .WithMany()
            .HasForeignKey(u => u.User2Id)
            .WillCascadeOnDelete(false);
    }

Chat entity:
public class Chat
{
    public int Id { get; set; }

    #region Foreign keys

    public int? FriendshipUser1Id { get; set; }
    public int? FriendshipUser2Id { get; set; }

    #endregion

    #region Navigation properties

    public virtual HashSet<Message> Messagges { get; set; }

    [ForeignKey("FriendshipUser1Id, FriendshipUser2Id")]
    public virtual Friendship Friendship { get; set; }

    #endregion
}

A: If I understand your model right. 1 friendship has 1 user1 and 1 user2. Your settings are excluded.
builder.Entity<Friendship>()
        .HasRequired(u => u.User1)
        .WithMany()
        .HasForeignKey(u => u.User1Id);

It means user1 has many... (many what?). Model doesn't have any list that could accept these settings. Your model has only single objects.
If you want it one to one/zero:
builder.Entity<Friendship>()
        .HasRequired(u => u.User1)
        .WithRequiredDependant(u => u.User2)
      or
        .WithRequiredPrincipal(u => u.User2)
      or
        .WithOptional(u => u.User2)

You can also try composite key for example: Creating Composite Key Entity Framework
Also I suggest you to use or Fluent API or Data Annotation convention. It will make your code more readable.


text:
Q: jsp ${pageContext.request.contextPath} dosent get requested Currently i have a .jsp project where my welcome page is a servlet
<welcome-file>frontpage</welcome-file>

The servlet sets gets two ressources, a header file containing the < nav> and a footer containing the < footer>
request.setAttribute("header1", sc.getResource("/includes/nav.jsp").toString());
request.setAttribute("footer", sc.getResource("/includes/footer.jsp").toString());

And forwards to the index.jsp page
getServletContext().getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);

My question is.
When i get the ressource (footer.jsp), how can i in the footer.jsp dynamically import / include images?
I tried the following
<img src="${pageContext.request.contextPath}/images/picture1.png" alt="picture1"/>

But the expression ${pageContext.request.contextPath} gets treated as a string instead of a command, and does not get the context path.
I suspect its because the content of the footer.jsp is fetched in this manner and their for the context path isint actually ever requested within the footer.jsp.
But how do i solve this?

A: add <%@ page isELIgnored="false" %> in top of your JSP page, to enable expression language.
and to include a JSP page with other use <jsp:include like:
<jsp:include page="/includes/nav.jsp"/>
<jsp:include page="/includes/footer.jsp"/>

A: This is not the way to include stuff. Use jsp:include action to include the header/footer. If for some reason you really want to do it in the servlet, see this post. As long as you just grab a resource like you do, you're  reading the file like any text, there is no JSP compilation/evaluation.