text:
Q: D3 js fit text inside each node How can I wrap text inside each node making the node automatically resize, just as in css you would do with fit-content or display flex?
Here's the snippet, available at this link: https://codepen.io/boxxello/pen/XWYvRQO
or here:
css:
html, body {
    margin: 0;
    padding: 0;
    background-color: rgb(140, 149, 226);
}
.node {
    cursor: pointer;
}

.node circle {
}
.node-leaf {

}

.node text {
    font: 10px sans-serif;
}

.link {
    fill: none;
    stroke: rgb(55, 68, 105);
    stroke-width: 1px;
}

js:

var margin = {top: 20, right: 90, bottom: 30, left: 90},
    width = 1300 - margin.left - margin.right,
    height = 900 - margin.top - margin.bottom;
var svg = d3
    .select("body")
    .append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var i = 0,
    duration = 750,
    root;
var treemap = d3.tree().size([height, width]);
root = d3.hierarchy(treeData, function (d) {
    return d.children;
});
root.x0 = height / 2;
root.y0 = 0;
root.children.forEach(collapse);

update(root);

function collapse(d) {
    if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
    }
}

function update(source) {
    var treeData = treemap(root);
    var nodes = treeData.descendants(),
        links = treeData.descendants().slice(1);
    nodes.forEach(function (d) {
        d.y = d.depth * 180;
    });
    var node = svg.selectAll("g.node").data(nodes, function (d) {
        return d.id || (d.id = ++i);
    });
    var nodeEnter = node
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
            return "translate(" + source.y0 + "," + source.x0 + ")";
        })
        .on("click", click);
    nodeEnter
        .attr("class", "node")
        .attr("r", 1e-6)
        .style("display", function (d) {
            if (d.depth === 0) { //Is top root
                return 'none';
            }
        });
    nodeEnter
        .append("rect")
        .attr("rx", function (d) {
            if (d.parent) return d.children || d._children ? 0 : 6;
            return 10;
        })
        .attr("ry", function (d) {
            if (d.parent) return d.children || d._children ? 0 : 6;
            return 10;
        })
        .attr("stroke-width", function (d) {
            return d.parent ? 1 : 0;
        })
        .attr("stroke", function (d) {
            return d.children || d._children
                ? "rgb(3, 192, 220)"
                : "rgb(38, 222, 176)";
        })
        .attr("stroke-dasharray", function (d) {
            return d.children || d._children ? "0" : "2.2";
        })
        .attr("stroke-opacity", function (d) {
            return d.children || d._children ? "1" : "0.6";
        })
        .attr("x", 0)
        .attr("y", -10)
        .attr("width", function (d) {
            return d.parent ? 40 : 20;
        })
        .attr("height", 20)
        .classed("node-leaf", true);

    nodeEnter
        .append("text")
        .style("fill", function (d) {
            if (d.parent) {
                return d.children || d._children ? "#ffffff" : "rgb(38, 222, 176)";
            }
            return "rgb(39, 43, 77)";
        })
        .attr("dy", ".35em")
        .attr("x", function (d) {
            return d.parent ? 20 : 10;
        })
        .attr("text-anchor", function (d) {
            return "middle";
        })
        .text(function (d) {
            return d.data.name;
        });

    var nodeUpdate = nodeEnter.merge(node);

    nodeUpdate
        .transition()
        .duration(duration)
        .attr("transform", function (d) {
            return "translate(" + d.y + "," + d.x + ")";
        });
    var nodeExit = node
        .exit()
        .transition()
        .duration(duration)
        .attr("transform", function (d) {
            return "translate(" + source.y + "," + source.x + ")";
        })
        .remove();
    nodeExit.select("rect").style("opacity", 1e-6);
    nodeExit.select("rect").attr("stroke-opacity", 1e-6);
    nodeExit.select("text").style("fill-opacity", 1e-6);
    var link = svg.selectAll("path.link").data(links, function (d) {
        return d.id;
    });
    var linkEnter = link
        .enter()
        .insert("path", "g")
        .attr("class", "link")
        .attr("d", function (d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal(o, o);
        }).style("display", function (d) {
            if (d.depth === 1) { //Is top link
                return 'none';
            }
        })
    var linkUpdate = linkEnter.merge(link);
    linkUpdate
        .transition()
        .duration(duration)
        .attr("d", function (d) {
            return diagonal(d, d.parent);
        });
    var linkExit = link
        .exit()
        .transition()
        .duration(duration)
        .attr("d", function (d) {
            var o = {x: source.x, y: source.y};
            return diagonal(o, o);
        })
        .remove();
    nodes.forEach(function (d) {
        d.x0 = d.x;
        d.y0 = d.y;
    });

    function diagonal(s, d) {
        path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

        return path;
    }

    function click(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
        update(d);
    }
}

The part where you could change the style property is at:
        .attr("width", function (d) {
            return d.parent ? 40 : 20;
        })
        .attr("height", 20)
        .classed("node-leaf", true);

Or at least is where I've tried to deal with it. The current version I'm using of d3js is the 4.2.2, I actually used this version it fitted my needs (found the snippet online and there have been breaking changes in the 7.* which is the current version) not because I didn't want to upgrade it (if it's easier in the newer versions please let me know.
This is an expected output, as you can see the node basically fits all the text inside it (I left the parent nodes blank because they're not relevant in this case, but they would need to do the same thing, so applying a property to all the nodes would be great.


text:
Q: How to filter Select in MySQL I want to filter by query sql.
Which color of blue, type of boy and size :35,36,39 to choose and display.
For Example: SQL Table (PHPMYADMIN)
--------------------------
|id| size | type | color |
--------------------------
|1 | 35   | boy  | blue  |
|2 | 36   | girl | red   |
|3 | 35   | boy  | blue  |
|4 | 37   | girl | red   |
|5 | 38   | boy  | red   |
|6 | 39   | boy  | red   |
--------------------------

Here's my code: (PHP):
$db = mysqli_connect('localhost','root','root','datab');
$qu="SELECT * FROM table
    WHERE color='blue'
    AND size='35'
    OR size='36'
    OR size='39'
    AND type='boy'
    ORDER BY id ASC
    LIMIT 10";
$res = mysqli_query($db, $qu);
while($ro = mysqli_fetch_array($res)) {
    echo $ro["id"].',';
}

Out (HTML):
1,2,3,6,

I need to out(html) the above records to get "1,3," .

A: () Around OR conditions
$db = mysqli_connect('localhost','root','root','datab');
$qu="SELECT * FROM table
    WHERE color='blue'
    AND (size='35' OR size='36' OR size='39' )
    AND type='boy'
    ORDER BY id ASC
    LIMIT 10";
$res = mysqli_query($db, $qu);
while($ro = mysqli_fetch_array($res)) {
    echo $ro["id"].',';
}

A: You are filtering the same column for three values, so it makes better sense to use IN(); then you don't need to worry with parenthetical grouping of conditions.
$qu="SELECT * FROM table
    WHERE color='blue'
    AND size IN ('35','36','39')
    AND type='boy'
    ORDER BY id ASC
    LIMIT 10";

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to i get only .txt formate file list from folder using php, codeigniter I want to only .txt format files are display but all files are
 displaying on screen
controller code is
$this->load->helper('directory');
$data['files'] = directory_map('./software_files');

and view side code is
if(isset($files) && count($files) > 0 ){
    foreach($files as $file){
        echo $file."
";
    }
}

A: Use glob to find filenames matching a pattern. Add *.txt in path to get specific type files list from directory.
$files = array();
foreach( glob("./software_files/*.txt") as $file )
{
    echo $file."
";
}

UPDATE
If you want to print filename only even without file extension, Use the following line
echo basename($file,".txt")."
";

Instead of
echo $file."
";

A: Hope this will help you :
You can use pathinfo() with PATHINFO_EXTENSION to check the extension for file :
foreach ($files as $file)
{

    if (pathinfo($file, PATHINFO_EXTENSION) === 'txt')
    {
        //echo $file;
        $data[] = $file;
    }
}

print_r($data);
/*list all .txt file*/

for more : http://php.net/manual/en/function.pathinfo.php

A: You can try this
$directory = "mytheme/images/myimages";
$images = glob($directory . "*.txt");

foreach($images as $image)
{
  echo $image;
}


text:
Q: Is std::pmr::new_delete_resource thread safe To create a new polymophic_allocator, ppl can use some default resources
std::pmr::polymorphic_allocator<char> newdel { std::pmr::new_delete_resource() };
std::pmr::polymorphic_allocator<char> synced { std::pmr::synchronized_pool_resource() };
std::pmr::polymorphic_allocator<char> nonsync { std::pmr::unsynchronized_pool_resource() };

My question is the new_delete_resource thread-safe?


text:
Q: Imaginary numbers I have a method that takes 3 doubles and calculates the roots via the Quadratic Formula:
public static double[] quadraticFormula(double a, double b, double c) throws ArithmeticException {
    double root1 = 0;
    double root2 = 0;

    //sqrt(b^2 - 4ac)
    double discriminant = (b * b) - (4 * a * c);

    if (Double.isNaN(discriminant)) {
        throw new ArithmeticException(discriminant + " is not a number!");
    }

    if (discriminant > 0) {
        //Two roots
        root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
        root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
    } else if (discriminant == 0) {
        //One root
        root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
    } else if (discriminant < 0) {
        //Imaginary roots
    }

    return new double[] { root1, root2 };
}

I want to expand on this and add support for imaginary numbers. How would I accomplish this? My first thought was, in else if (discriminant < 0), I would get the absolute value of the discriminant and factor the radical. I am going to output the roots to the user, so don't bother with the i, I have a String parser that knows exactly where to put the i. Any ideas on a more efficient method?

A: If you really want to get going on Complex/Imaginary numbers I would suggest to implement a class that represents a complex number.
An example for that can be found here:
http://www.math.ksu.edu/~bennett/jomacg/c.html
If you somehow build your calculations of a mixture of doubles, arrays and strings it will definetely get messy after a while.


text:
Q: Dynamically created input components do not show model values I have some fields of a bean that I need to show programmatically. Is something like this:
         HtmlPanelGrid panel = new HtmlPanelGrid();
         panel.setColumns(4);

         HtmlOutputLabel fieldOut = new HtmlOutputLabel();
         fieldOut.setId("fieldOutId");
         fieldOut.setValue("name");
         panel.getChildren().add(fieldOut);
         HtmlInputText fieldIn = new HtmlInputText();
         fieldIn.setId("fieldInId");
         fieldIn.setPartialSubmit(true);
         fieldIn.setValueExpression(
          "field", UtilFaces.createValueExpression("#{newElementBean.fieldName}",String.class));

         panel.getChildren().add(fieldIn);
         mainForm.getChildren().add(panel);

In newElements.xhtml i've defined a form which is binded to mainForm, in this way:
    <ice:form binding="#{newElementBean.mainForm}">
  <ice:inputText id="ANOTHERFIELD" value="#{newElementBean.anotherField}"/>
  <ice:commandButton  action="#{newElementBean.save}"  value="Save"/>
</ice:form>

When I click on the save button and I go to the next view, the field "ANOTHERFIELD"  has taken the value from the bean, and shows up correctly, but the fields that were dinamically generated shows empty. Its values in the backing bean also are null. It's like the ValueExpression is not working for the HtmlInputText that I created in the backing bean. I'm using Icefaces 3.3 with Mojarra 2.1.17.
How is this caused and how can I solve it?

A: I solved it. I made two mistakes:

*

*The proper setValueExpression call is like this:
fieldIn.setValueExpression("value", UtilFaces.createValueExpression("#newElementBean.fieldName}");

I was incorrectly using "field1" as 1st argument instead of "value".

*This is not visble in the question, but my createValueExpression() helper method was also wrong. The following is working for me:
public static ValueExpression createValueExpression(String expression) {
    Application app = FacesContext.getCurrentInstance().getApplication();
    ExpressionFactory elFactory = app.getExpressionFactory();
    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    return elFactory.createValueExpression(elContext, expression, Object.class);
}


text:
Q: Is there a way to remove reference, cv qualifiers, and pointerness of a type to make it plain? Take the following code:
struct Foo {}

template<typename T>
void passFoo(T t) {}

I would want the domain of passFoo to be restricted to Foo objects, but I don't mind if they are references, pointers, or cv qualified. Is it possible to somehow remove all those aspects of a type to get down to the "plain" type, when using a concept? For instance:
template<typename T>
concept Foo_C = std::is_same_v<Foo, plainify<T>>;

template<Foo_C Foo_c>
void passFoo(Foo_c foo) {}

In that hypothetical code, passFoo could accept only Foo, Foo&, Foo*, const Foo, etc. Is there any actual way to do this?

A: Combination of std::remove_cvref_t and std::remove_pointer_t would work:
template<typename T>
concept Foo_C = std::is_same_v<Foo, std::remove_cvref_t<std::remove_pointer_t<T>>>;


text:
Q: How can I show a the Cartan subalgebra being abelian implies its adjoint representation on the original Lie algebra completely commutes? I am reading a set of notes on the classification of simple Lie algebras, in which the claim is made that since $\mathfrak h\subset g$, a Cartan subalgebra is abelian it then follows that the adjoint action of $\mathfrak h$ on $\mathfrak g$ completely commutes. My attempt at showing this is the following:
$$(\text{ad}(h_1)\circ \text{ad}(h_2))(g)=[h_1,[h_2,g]]=[[h_1,h_2],g]=[[h_2,h_1],g]=[h_2,[h_1,g]]=(\text{ad}(h_2)\circ \text{ad}(h_1))(g).$$ However, the second equality relies on the fact that the algebra is associative, which isn't necessarily true for a Lie algebra. I'm also concerned that since $[h_1,h_2]=0$ this doesn't make sense. Is there a simple way to see this?

A: As you point out yourself, the Lie bracket is in general not associative. Instead one has the Jacobi identity which tells us that
$$[h_1, [h_2, g]] + [h_2, [g, h_1]] + [g, [h_1, h_2]]].$$
Now, that $h_1, h_2$ commute means by definition that $[h_1, h_2]=0$, hence the last term is $=0$, hence
$$[h_1, [h_2, g]] = - [h_2, [g, h_1]].$$
Now use anticommutativity and bilinearity of the Lie bracket to write this as
$$= -[h_2, -[h_1, g]] = [h_2, [h_1,g]].$$

Or, since you write "adjoint action", maybe you know already (as follows from the Jacobi identity) that the adjoint action defines a Lie algebra representation, i.e.
$$ad([x,y]) =ad(x) \circ ad(y) -ad(y) \circ ad(x) \qquad \text{for all } x,y \in g,$$
and now you apply this to $h_1, h_2$ with $[h_1, h_2] = 0$.In short, if two Lie algebra elements commute, their adjoints commute.

A: You have to use a root system: write ${\cal g}={\cal h}\oplus_{\alpha\in A}g_a$ where $A$ is a root system, if $x\in {\cal g}_a, u,u'\in {\cal h}, [u,[u',x]]=a(u)a(u')x$, if $x\in {\cal h}, [u,[u',x]]=0$.


text:
Q: R: Random forest OOB score too high I have a database "Data_j" with 64954 observations of 37 variables. I would like to generate a random forest from this data base. To do so, I divided it into a training set and a testing set.
library(randomForest)
library(ggplot2)
library(ranger

index <- sample(1:nrow(Data_j),round(0.8*nrow(Data_j)))
train <- Data_j[index,]
test <- Data_j[-index,]
train[is.na(train)] = 0
names(train) <- make. Names(names(train))
model <- ranger(SC_3ans ~ . , data = train, importance = "impurity", num.trees = 100)

 model

However I get a very high OOB score: 0.54. How can I improve the performance ? I tried different mtry values and I still get the same value.
Call:
ranger(SC_3ans ~ ., data = train, importance = "impurity", num.trees = 100)

Type:                             Regression
Number of trees:                  100
Sample size:                      51963
Number of independent variables:  36
Mtry:                             6
Target node size:                 5
Variable importance mode:         impurity
Splitrule:                        variance
OOB prediction error (MSE):       0.5432775
R squared (OOB):                  0.6686793


text:
Q: Loading images from assets folder from a bundle I have a bundle with assets folder in it. I have read all the answers on stack about using UIImage(named: "drop_arrow", inBundle: bundle, compatibleWithTraitCollection: nil) (well, it's swift 3 equivalent)
path = Bundle.main.path(forResource: "LiveUI", ofType: "bundle")
if path != nil { // path with bundle is found
     let bundle: Bundle = Bundle.init(path: path!)! // bundle is there
     let image: UIImage? = UIImage(named: "HomePlayButton", in: bundle, compatibleWith: nil)
     // HomePlayButton exists in the bundle/asset folder
     // but image is nil
}

This is my project structure:

Can you see any problem with the code/structure of the project?
UPDATE! ... The image is set for all resolutions as universal:

A: Two things to check.
1) make sure your assets bundle has an Info.plist with a bundle identifier set in it.  From your screenshot it doesn't look like this is the case.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleIdentifier</key>
    <string>MyBundle</string>
</dict>
</plist>

2) Make sure your bundle has a compiled assets catalog in it.  Should be named Assets.car.   I don't think Xcode will just compile an Assets.xcassets folder inside a resource bundle (the bundle is effectively opaque to Xcode; likewise it wouldn't compile any .m source files you put in there).   You may need a custom build step to copy the compiled Assets.car file into your assets bundle before the assets bundle is copied into the app bundle.
You can check these by finding your app bundle and right clicking on it then "Show Package Contents", then again on the contained bundle.
Manual assets compilation command:
xcrun actool Images.xcassets --compile . --platform iphoneos --minimum-deployment-target 9.0

A: Just an idea, make sure the bundle and the asset catalog in the bundle have a Target Membership property assigned to the correct target you are trying to load the images with (Utilities pane -> Target Membership):

It's possible that your target is able to find the bundle but not the asset catalog for some reason.


text:
Q: Unable to start JVM with large heap size on windows In my Windows 7 64 bit PC, I am trying to start a java application with -Xmx2048m.
I need to set a large heap size since the app needs a lot of memory.
My PC has 8GB memory and it has 4GB free when I am trying to start the application.
But, the application fails to start with insufficient memory error.

Could not reserve enough space for xxxx object heap

Since the PC has more than 2GB free memory, it should be possible to start with max heap size = 2GB.
Why does the application fail to start? Is there any way I can start the app with max heap size = 2GB?


text:
Q: Count similar values of a column, show output with Value and Row count. Also retain the order I have data like this
Id      Txt
------------
1   KK
2   KK
3   AA
4   JJ
5   JJ
6   JJ

Id column is an identity key. I want the results grouped by Txt column values and show the row count but the ordering should be retained.
Expected result:
2     KK
1     AA
3     JJ

Count with original ordering of Txt column.

A: You can try:-
SELECT COUNT(id), Txt
FROM YOUR_TABEL
GROUP BY Txt

A: Something like this (please click the tick next to answer if you like it):
create table #tmp
(
    id int identity(1,1)
    , name varchar(10)
)

insert into #tmp values ('kk'), ('kk'),('ss'), ('mm'),('mm'),('mm')

select count(id), name from #tmp
group by name
order by min(id)

drop table #tmp


text:
Q: Замена ссылок во всей странице WordPress Стоит задача в сгенерированной странце (та, что показывается посетителю) автоматически заменять ссылки по правилам.
Как это в Wordpress реализовать?
Я нашел вывод всей страницы в файле
'wp-includes/template-loader.php';
Т.е. там можно получать конечное содержимое и менять его. Но ребята из WordPress.com говорят, что так делать нельзя, потому что это изменение движка и при первом же обновлении будут проблемы.
Есть ли другие варианты?


text:
Q: Normalization PCA for dataframes? I would like to know what is the correct way to normalize a dataframe before applying PCA. I have found two options and I got different results for each one:
    min_max_scaler = preprocessing.MinMaxScaler()
    x_scaled = min_max_scaler.fit_transform(x)
    scaled_data = pd.DataFrame(x_scaled)

or
    scaler = StandardScaler()
    scaler.fit(df)
    scaled_data = scaler.transform(df)


text:
Q: Is modifying Django urlconf via set_urlconf and request.urlconf in a middleware safe? I am changing the default urlconf in a middleware based on the requested hostname and it's working as expected during development, however I am concerned about racing/threads as I am modifying a Django setting at runtime!
My concern is that Django would confuse the urlconfs with many concurrent requests. Is that a valid concern?

A: The TLDR Version
You shouldn't really need to use set_urlconf in your middleware. You are free to set request.urlconf without worrying about threads though.
For each request that django processes, it will either use ROOT_URLCONF or the value of request.urlconf if it has been set in the middleware, to decide what urlconf to use. For this reason you shouldn't need to use set_urlconf. Setting request.urlconf is the recommended way.
How it works
In fact, under the hood, after a request has passed through the middleware, django calls this function, to decide which urlconf to use, so if request.urlconf is set, then any calls to set_urlconf in the middleware will be irrelevant anyway:
# django.core.handlers.base.py

    def resolve_request(self, request):
        if hasattr(request, 'urlconf'):
            urlconf = request.urlconf
            set_urlconf(urlconf)
            resolver = get_resolver(urlconf)

Checkout how django proceeses a request from the official docs for more info.
Thread safety of set_urlconf
Also note that the implementation of set_urlconf is thread-safe:
# django.urls.base.py

# Overridden URLconfs for each thread are stored here.
_urlconfs = Local()

def set_urlconf(urlconf_name):
    """
    Set the URLconf for the current thread (overriding the default one in
    settings). If urlconf_name is None, revert back to the default.
    """
    if urlconf_name:
        _urlconfs.value = urlconf_name
    else:
        if hasattr(_urlconfs, "value"):
            del _urlconfs.value

(That is to say, it only affects the current thread.)


text:
Q: Spring @Value without annotation Instead of using @Value doing this:
@Service
public class MyService{
    @Value("${myValue}")
    private String myValue;
}

I need to get ${myValue} without annotation, and without reading the file again. How to do it?

A: You can get it from Environment:
@Autowired
private Environment env;
// ...
env.getProperty("myValue");

A: One way to access Environment is through EnvironmentAware interface.
Example :
@Service
public class MyService implements EnvironmentAware{

    private String myValue;
    private Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }

    public String getMyValue() {
        return env.getProperty("myValue");
    }
}


text:
Q: EF, Code First, how to initialize database on a specific location (HDD) does anybody know how to spedify exact .mdf/.log file location during EF CodeFirst database initialization?
For a debug and testing scenario (but specifying exact DB files location can be useful in production as well), I'd like to re-deploy database during application start-up, but also I'd like to create DB files on a specific location (e.g. secong hard drive).
public class MyCustomInitialized : DropCreateDatabaseAlways<MyContext>
{
    public override void InitializeDatabase(MyContext context)
    {
        if (context.Database.Exists())
        {
            // set the database to SINGLE_USER so it can be dropped
            context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

            // drop the database
            context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "USE master DROP DATABASE [" + context.Database.Connection.Database + "]");

            // Doesn't work yet
            var directoryPath = ConfigurationManager.AppSettings["DatabaseDirectoryPath"];
            var fileName = ConfigurationManager.AppSettings["DatabaseFileName"];

            if(!Database.Exists())  {
                var qry = string.Format(
                "USE master CREATE DATABASE {0}" + Environment.NewLine +
                "ON PRIMARY" + Environment.NewLine +
                "( NAME = {0}, FILENAME = '{1}')"  + Environment.NewLine +
                "LOG ON"  + Environment.NewLine +
                "( NAME = {2}, FILENAME = '{3}')"  + Environment.NewLine
                , this.Database.Connection.Database,
                  Path.Combine(directoryPath, fileName + ".mdf"),
                  this.Database.Connection.Database + "_log",
                  Path.Combine(directoryPath, fileName + "_log.ldf"));

                // -- EXCEPTION HERE,
                Database.ExecuteSqlCommand(qry);

                Database.ExecuteSqlCommand("USE " + this.Database.Connection.Database);
        }

        base.InitializeDatabase(context);
    }
}

The exeption I get:

Cannot open database "DatabaseName" requested by the login. The login
  failed. Login failed for user 'SomeUser'. A severe error occurred on
  the current command.  The results, if any, should be discarded.

If the database can be created by EF during initialization, how this initialization can be overriden?
Thanks,
Tom

A: I was able to get the below working, in both the database exists and non-exists scenarios, however, there is one issue in that the Code First table creation isn't being triggered (i.e. this is only a partial solution - there is still a step needed to actually get EF to create the Code First tables).
(My context was called Model1)
public class MyCustomInitialized : DropCreateDatabaseAlways<Model1>
{
    public override void InitializeDatabase(Model1 context)
    {
        if (context.Database.Exists())
        {
            // set the database to SINGLE_USER so it can be dropped
            context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
                "ALTER DATABASE [" + context.Database.Connection.Database +
                "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

            // drop the database
            context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
                "USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
        }
        var directoryPath = @"c:\temp";
        var fileName = "Foo";

        var qry = string.Format(
            "USE master CREATE DATABASE {0}" + Environment.NewLine +
            "ON PRIMARY" + Environment.NewLine +
            "( NAME = {0}, FILENAME = '{1}')" + Environment.NewLine +
            "LOG ON" + Environment.NewLine +
            "( NAME = {2}, FILENAME = '{3}')" + Environment.NewLine
            , context.Database.Connection.Database,
            Path.Combine(directoryPath, fileName + ".mdf"),
            context.Database.Connection.Database + "_log",
            Path.Combine(directoryPath, fileName + "_log.ldf"));

        using (var conn = new SqlConnection(@"data source=.\SQLExpress;initial catalog=master;integrated security=True;"))
        using (var cmd = new SqlCommand(qry, conn))
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }

        -- TODO trigger the table creation
        this.Seed(context);
        context.SaveChanges();
    }
}

Some notes:

*

*Database belongs to the context

*You won't be able to recreate the database on the Context connection, since when you drop the database, the Initial Catalog in your EF connection string will have disappeared. I've just used a new Ado Connection to do the Drop, else "Cannot open database \"FOO\" requested by the login". I would also consider moving the DROP of the Context connection into a master connection.

Calling
base.InitializeDatabase(context);

Causes the Db to be dropped and recreated because of the DropCreateDatabaseAlways strategy which includes:
context.Database.Delete();
context.Database.Create(DatabaseExistenceState.DoesNotExist);

So hence
-- missing something here, viz creating the tables
this.Seed(context);
context.SaveChanges();


text:
Q: Can't Drag Items Onto An Empty List Using Scriptaculous Sortables I have three unordered lists that have been created as Scriptaculous Sortables so that the user can drag items within the lists and also between them:
var lists = ["pageitems","rowitems","columnitems"];
Sortable.create("pageitems", { dropOnEmpty: true, containment: lists, constraint: false });
    Sortable.create("rowitems", { dropOnEmpty: true, containment: lists, constraint: false });
    Sortable.create("columnitems", { dropOnEmpty: true, containment: lists, constraint: false });

How can I make it so that if the user drags all the items out of a list, they're able to put them back again? At the moment it won't allow items to be dragged onto an empty list.

A: Maybe the empty list has no height, and therefore no droppable area available. If that's the case, perhaps you just need to set a minimum height, or some padding on the block.

A: add dropOnEmpty:true to the options parameters.

A: Make sure your target list is styled float:left
I had a similar experience today.


text:
Q: AttributeError: 'module' object as no attribute '_Application' At end of my program, I am generating word file then converting this file to .pdf file format as the following:
wdFormatPDF = 17
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(resultfile)
doc.SaveAs(resultfilepdf, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()

The program run properly but when I converting the
.py to .exe using pyinstaller –onefile option I get the following error when executing the .exe file.
Traceback (most recent call last):
  File "C:\python\tub\test\hc.py", line 344, in <module>
    word = comtypes.client.CreateObject('Word.Application')
  File "C:\Users\LT440\Anaconda2\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject
return _manage(obj, clsid, interface=interface)
  File "C:\Users\LT440\Anaconda2\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
obj = GetBestInterface(obj)
  File "C:\Users\LT440\Anaconda2\lib\site-packages\comtypes\client\__init__.py", line 112, in GetBestInterface
interface = getattr(mod, itf_name)
AttributeError: 'module' object has no attribute '_Application'
[4112] Failed to execute script hc

Please advice.

A: I have same。I solved it
Clear Gen's cache! I am deleting all the caches in this directory. The conversion is normal!
..\Python3.6\Lib\site-packages\comtypes\gen


text:
Q: Node.js + express + passport (backend) / jQuery (frontend) I'm coding a website using html/css + javascript / jQuery.
Currently, I'm making a registration + login/logout service, but I'm stuck.
Here is my jQuery code for logging in (frontend):
// Login form
$(function() {
  $('#login_btn').click(function() {
    $.ajax({
      url : '/login',
      type : 'POST',
      dataType : 'json',
      data : {
        username : $('#login_username').val(),
        password : $('#login_password').val()
      },
      cache : false,
      timeout : 5000,

      success: function(data) {
        if (data.reponse == 'success') {
          createCookie('token', data.token, 7);
          $.ajax({
            url :"/account",
            type:'GET',
            headers : { "Authorization" : readCookie('token') },
            dataType: 'json',
            data: {
              role: data.role
            },

            success: function(data, status) {
              console.log("Status " + status);
              console.log(data);
            }
          });
        }
        else {
          if (data.msg == 'user not found') {
            display_login_alert(false, 'user_not_found');
          }
          else if (data.msg == 'wrong password') {
            display_login_alert(false, 'wrong_password');
          }
          else {
            display_login_alert(false, 'unknown');
          }
        }
      },

      error: function() {
        display_login_alert(false, 'unknown');
      }
    });
  });
});

Here is my node.js + express + passport code (backend):
app.post('/login', (req, res) => {
  User.findOne({
    username: req.body.username
  }, (err, user) => {
    if (err)
    throw err;
    if (!user) {
  res.send({reponse: 'error', msg: 'user not found'});
    }
    else {
      // check if password matches
      user.comparePassword(req.body.password, (err, isMatch) => {
        if (isMatch && !err) {
          // if user is found and password is right create a token
          var token = jwt.sign(user, config.secret, { expiresIn: 21600 });
          // return the information including token as JSON
          res.json({
            reponse: 'success',
            token: 'JWT ' + token,
            profile: user.profile,
            role: user.role
          });
        }
        else {
          res.send({reponse: 'error', msg: 'wrong password'});
        }
      });
    }
  });
});

app.get('/account', passport.authenticate('jwt', { session: false }), (req, res) => {
  var token = getToken(req.headers);
  if (token) {
    jwt.verify(token, config.secret, function(err, decoded){
      if (err) {
        return res.redirect("/");
      }
      else if (req.user.role != "Owner") {
        return res.redirect("/");
      }
      else {
        req.decoded = decoded;
        res.sendFile('/.../account.html'); // /.../ : file path is good
      }
    });
  }
});

The problem is that when I use postman, everything is okay.
But when I click on the login button on my website, nothing happens, and there are no error
Can someone help me?


text:
Q: case insensitive highlighting in php without changing the word itself I'm stuck with solving this problem. (I searched for answers here. There are some, but not exactly what I need, that's why I created this question separately. Sorry, if it's a duplicate).
I have the sentence:

"There are many variations of passages of Lorem Ipsum available, but
the majority have suffered alteration in some form".

Also I have two words, provided in lowercase:

Word1: lorem
Word2: ipsum

I need to search $word1 and $word2 in the sentence $text, highlight those words in a given sentence (bake them bold), without changing the case ot the replaced word.
In my example I need  my result to be:

"... Lorem Ipsum ... ", but not "... lorem ipsum ...".

Similarly, for example, if Word1 = "Lorem" and that word in provides text is in lowercase, I just want to make that lowercase word in the text bold, without making it capitalized.
I'd appreciate any help!
Thanks a lot in advance!!!

A: Use ucfirst($str) first, and then do the string search and convert to bold.
$word1 = ucfirst($word1);
$word2 = ucfirst($word2);

Or, you can use case insensitive search using stripos($sentence, $word) to get the position of the word, then convert the content from that position to the length of the $word with bold tags/style tags appended
Hope this is what you are looking for.


text:
Q: Adding text to a file Is there a way to add Document ID in the footer area of a word file? This can be workflow to update a new word file. User will either upload or create new word file in a document library (doc id enabled). After the file is saved to the document library i would like to update the document with the document id via workflow. Is it even possible?

A: You can try creating a Word Template and use it as the default Content Type for the library.
Inside the template you can use Quick Parts for populating list fields. In your case you can add the document ID as a meta data property and then use it in the quick part.
Here is a complete walk through http://blogs.technet.com/b/brenclarke/archive/2009/04/15/automatically-create-word-documents-which-include-list-fields.aspx

A: This link helped. It's little tricky but all steps are well defined.
http://blog.isaacblum.com/2011/02/28/add-document-id-to-word-document-automatically/


text:
Q: CSS Skill Bar Responsive So I am just finally getting some content creation stuff into my first responsive website for mobile and desktop and I would like to know how you can make a skill bar much more readable in mobile. I got what I like in desktop version, but now in mobile I want the bars to fill the screen from left to right and make the text still readable on small devices.
Here is where I got the code from. They don't have any information on how to make this skill bar responsive. So that is my goal here. w3schools
This is what my desktop version looks like now currently

But when I go into Dev mode to view it in iPhone format, this is what it looks like

This is what I was trying to attempt:

* {
  box-sizing: border-box
}

.container {
  width: 75%;
  background-color: #ddd;
  margin-left: 200px;
}

.skills {
  text-align: right;
  padding: 10px;
  color: white;
}

.html {
  width: 90%;
  background-color: #4CAF50;
}

.css {
  width: 80%;
  background-color: #2196F3;
}

.js {
  width: 65%;
  background-color: #f44336;
}

.php {
  width: 60%;
  background-color: #808080;
}

@media screen and (max-width: 768px) {
  .skillResponsive {
    width: 50%;
    text-align: justify;
  }
}

My Skills

HTML

90%

CSS

80%

JavaScript

65%

PHP

60%

So if you could tell me what can I do to get my skill bar to me more responsive when you resize the browser down to tablet and mobile mode. That be great thanks!
A few lines of codes is a plus!

A: Use this code.. its fully responsive for all device... this will help you. :)

* {
  box-sizing: border-box
}

.skillResponsive {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 15px;
}

.container {
  background-color: #ddd;
}

.skills {
  text-align: right;
  padding: 10px;
  color: white;
}

.html {
  width: 90%;
  background-color: #4CAF50;
}

.css {
  width: 80%;
  background-color: #2196F3;
}

.js {
  width: 65%;
  background-color: #f44336;
}

.php {
  width: 60%;
  background-color: #808080;
}

My Skills

HTML

90%

CSS

80%

JavaScript

65%

PHP

60%

A: Try This:

* {
  box-sizing: border-box
}
.skill-set {
  background-color: #ddd;
  margin-left: 20%;
  padding-left: 10%;
  width: 100%;
}
.container {
  width: 75%;
  background-color: #ddd;
}
.skills {
  text-align: right;
  padding: 10px;
  color: white;
}
.html {
  width: 90%;
  background-color: #4CAF50;
}
.css {
  width: 80%;
  background-color: #2196F3;
}
.js {
  width: 65%;
  background-color: #f44336;
}
.php {
  width: 60%;
  background-color: #808080;
}

My Skills

HTML

90%

CSS

80%

JavaScript

65%

PHP

60%

A: Firstly, i suggest to disable touch simulation (it's the blue hand icon). For some reason in Firefox with this feature enabled, simulation does not work correctly.
Secondly, regarding the code, i always prefer using em/rem for font size (instead of px) and vw/vh for padding/margin/etc (instead of px). It gives relative length instead of absolute. You can find further information below:
https://www.w3schools.com/cssref/css_units.asp
Finally, you can find the code as i would use it.

* {
  box-sizing: border-box
}

.container {
  width: 80%;
  background-color: #ddd;
  margin-left: 10vw;
}

.skills {
  text-align: right;
  padding: 0.5rem;
  color: white;
  font-size: 1rem;
}

.title
{
 padding-left: 10vw;
 font-size: 1rem;
}

.html {
  width: 90%;
  background-color: #4CAF50;
}

.css {
  width: 80%;
  background-color: #2196F3;
}

.js {
  width: 65%;
  background-color: #f44336;
}

.php {
  width: 60%;
  background-color: #808080;
}

@media only screen and (max-width: 812px) {
.skills {
     font-size: 1.5rem;
     }
.title {
     font-size: 1.2rem;
     }
}

My Skills

HTML

90%

CSS

80%

JavaScript

65%

PHP

60%


text:
Q: Multibinding File-Paths into a Button ControlTemplate I am trying to develop an application that uses a number of images that are stored in a seperate remote file location. The file-paths to the UI elements are stored within the Application Settings. Although I understand how to access the images from Applications Settings using a MultiBinding and a value converter, I'm not sure how to integrate the Multibinding into the ImageButton ControlTemplate below.  Can anyone steer me in the right direction?
<Image.Source>
     <MultiBinding Converter="{StaticResource MyConverter}">
         <Binding Source="{StaticResource Properties.Settings}" Path="Default.pathToInterfaceImages" />
         <Binding Source="ScreenSaver.png"></Binding>
     </MultiBinding>
</Image.Source>

<Button Click="btn_ScreenSaver_Click" Style="{DynamicResource ThreeImageButton}"
               local:ThreeImageButton.Image="C:\Skins\ScreenSaver_UP.png"
               local:ThreeImageButton.MouseOverImage="C:\Skins\ScreenSaver_OVER.png"
               local:ThreeImageButton.PressedImage="C:\Skins\ScreenSaver_DOWN.png"/>

<Style
    x:Key="ThreeImageButton"
    TargetType="{x:Type Button}">
    <Setter Property="FontSize" Value="10"/>
    <Setter Property="Height" Value="34"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <StackPanel Orientation="Horizontal" >
                    <Image Name="PART_Image" Source= "{Binding Path=(local:ThreeImageButton.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" />
                </StackPanel>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Source" Value="{Binding Path=(local:ThreeImageButton.MouseOverImage), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" TargetName="PART_Image"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Source" Value="{Binding Path=(local:ThreeImageButton.PressedImage), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" TargetName="PART_Image"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Source" Value="{Binding Path=(local:ThreeImageButton.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" TargetName="PART_Image"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

public class ThreeImageButton : DependencyObject
{
    // Add three new Dependency Properties to the Button Class to hold the
    // path to each of the images that are bound to the control, displayed
    // during normal, mouse-over and pressed states.
    public static readonly DependencyProperty ImageProperty;
    public static readonly DependencyProperty MouseOverImageProperty;
    public static readonly DependencyProperty PressedImageProperty;

    public static ImageSource GetImage(DependencyObject obj)
    { return (ImageSource)obj.GetValue(ImageProperty); }

    public static ImageSource GetMouseOverImage(DependencyObject obj)
    { return (ImageSource)obj.GetValue(MouseOverImageProperty); }

    public static ImageSource GetPressedImage(DependencyObject obj)
    { return (ImageSource)obj.GetValue(PressedImageProperty); }

    public static void SetImage(DependencyObject obj, ImageSource value)
    { obj.SetValue(ImageProperty, value); }

    public static void SetMouseOverImage(DependencyObject obj, ImageSource value)
    { obj.SetValue(MouseOverImageProperty, value); }

    public static void SetPressedImage(DependencyObject obj, ImageSource value)
    { obj.SetValue(PressedImageProperty, value); }

    // Register each property with the control.
    static ThreeImageButton()
    {
        var metadata = new FrameworkPropertyMetadata((ImageSource)null);
        ImageProperty = DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ThreeImageButton), metadata);
        var metadata1 = new FrameworkPropertyMetadata((ImageSource)null);
        MouseOverImageProperty = DependencyProperty.RegisterAttached("MouseOverImage", typeof(ImageSource), typeof(ThreeImageButton), metadata1);
        var metadata2 = new FrameworkPropertyMetadata((ImageSource)null);
        PressedImageProperty = DependencyProperty.RegisterAttached("PressedImage", typeof(ImageSource), typeof(ThreeImageButton), metadata2);
    }
}

A: Use XAML property element syntax:
<ControlTemplate TargetType="{x:Type Button}">
  <StackPanel Orientation="Horizontal" >
    <Image>
      <Image.Source>
        <MultiBinding Converter="{StaticResource MyConverter}">
          <Binding Source="{StaticResource Properties.Settings}"
                   Path="Default.pathToInterfaceImages" />
          <Binding Path="(local:ThreeImageButton.Image)"
                   RelativeSource="{RelativeSource TemplatedParent}" />
        </MultiBinding>
      </Image.Source>
    </Image>
  </StackPanel>
</ControlTemplate>

Note this means your attached properties will need to be strings rather than ImageSources, because they are going to be inputs to your path composition converter.


text:
Q: passing image from collectionViewCell which is located tableviewCell I ask for help with determining the right approach
when I click on the picture I need to pass text and her to new VC, but the problem is that the project has a great depth struct
the cell lies in the collectionView, which is in the tableViewCell
How do I properly implement the transfer?
(the number of cells is generated automatically)
Another complication is that the code of the cell with which I work lies in another cell.
those. the transfer of information must also be written in it.
import UIKit
import moa

class RealPhotoInfoTableViewCell: UITableViewCell {

    @IBOutlet private weak var MyCollection: UICollectionView!

    var model: RealPhoto!

    func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        MyCollection.delegate = self
        MyCollection.dataSource = self
        MyCollection.reloadData()
    }
}

extension RealPhotoInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(model?.data.count as Any)
        return model?.data.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RPhotoCell", for: indexPath) as! RealPhotoCollectionViewCell

        cell.realPhotoImage.moa.url = model?.data[indexPath.row].photo

        return cell
    }
}

A: Add a var
class RealPhotoInfoTableViewCell: UITableViewCell {
   weak var delegate:VCName?

Inside cellForRowAt of the table do
cell.delegate = self

Now you can do this inside didSelectItemAt of the collection
delegate?.sendData(image)

A: You have two options:
One is Sh_Khan answer using delegation.
Or you can use Notification observers.
This question has been asked before...

A: You can use delegate protocol in that case. You can implement that protocol. Please find following sample code for that.
protocol ImageSelectionDelegate {
    func imageClicked(imageURL: String)
}

//Class A
class A : ImageSelectionDelegate{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //your existing code
        cell.delegate = self
    }
    //Implement that protocol
    func imageClicked(imageURL: String){
        //You will get url for tapped image
    }
}

class RealPhotoInfoTableViewCell{
    weak var delegate : ImageSelectionDelegate? = nil
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate.imageClicked(model?.data[indexPath.item].photo)
    }
}


text:
Q: How to deal with interaction between several dummy variables and one continuous variables in one or two regression models? I want to know the relationship between revenue and cost in several conditions.
Dependent variables is REVENUE.REVENUE is a continuous variable from 0~1000+.I have several key independent variables: COST, LEVEL1~LEVEL4 and RESPONSE.
COST is continuous variable from 0~1000+. Level1~LEVE4 are dummy variables;LEVEL1=1 means the customer-firm relationship is weak, and LEVEL4=1 means a customer-firm relationship is strongest. RESPONSE is dummy variable; it means that a customer responds to promotion activities in a given month.
My current model is as following.
REVENUE=β0+β1COST+β2LEV1+β3LEV2+β4LEV3+β5LEV4+β6LEV1*COST +β7LEV2 *COST+β8LEV3*COST+β9LEV4*COST
I want to add RESPONSE into the model. I think it will be too complex, if I add one more dummy variable into the model.
Should I change LEVEL1~LEVEL4 to a ordinary variable (NEW_LEVEL=1~4), and put the dummy variable, RESPONSE, into the model?
REVENUE=β0+β1COST+β2NEW_LEVEL+β3RESPONSE+β4NEW_LEVEL * COST+β5 NEW_LEVEL * RESPONSE+β6COST* NEW_LEVEL* RESPONSE
Should I just use RESPONSE to separate the one data set into two data sets and run the model separately? But I do not know how to compare the coefficients in two models.
Group_1:RESPONSE
REVENUE=β0+β1COST+β2LEV1+β3LEV2+β4LEV3+β5LEV4+β6LEV1*COST +β7LEV2*COST+β8LEV3*COST+β9LEV4*COST
Group_2:No_RESPONSE
REVENUE=β0+β1COST+β2LEV1+β3LEV2+β4LEV3+β5LEV4+β6LEV1*COST +β7LEV2*COST+β8LEV3*COST+β9LEV4*COST
Thanks in advance.


text:
Q: Why isn't the char changing the way I Intend it too? I am new here so please excuse me for the poor formatting,
I wrote a simple calculator in c# but it seems my multiplication and division are not working correctly.
when running the code it works fine until I try to output the answer and then it outputs "Error, Unknown operator" which is what I told it to output when it doesn't identify the operator stored in the operation variable.
 here is the code (sorry for dumping so much code, I am not sure what is relevant and what is not):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class MainClass
    {
        public static void Main(string[] args) // method called "main", when the program starts, this runs
        {
        start:
            // variable declarations
            double Num1;
            double Num2;
            int operationId;
            string operationName = "1";
            string operationName2 = "1";
            Char operation;
            double answer;

            // choosing an operator
            Console.WriteLine("select an operation from the list and type it's associated number:");
            Console.WriteLine("1 - sum \n" + "2 - subtraction \n" + "3 - division\n" + "4 - multipication \n");
            operationId = Convert.ToInt32(Console.ReadLine());

            // checking which operation has been chosen
            if (operationId == 1)
            {
                operationName = "added to";
                operationName2 = "added";
                operation = '+';
            } else if (operationId == 2)
            {
                operationName = "subtracted from";
                operationName2 = "subtracted";
                operation = '-';
            } else if (operationId == 3)
            {
                operationName = "divided";
                operationName2 = "divided by";
                operation = '/';
            } else if (operationId == 4)
            {
                operationName = "multiplied";
                operationName2 = "multiplied by";
                operation = '*';
            } else
            {
                Console.WriteLine("Invalid option");
                goto start;
            }

            // receving user input
            Console.WriteLine("Insert a number to be " + operationName + ":");
            Num1 = Convert.ToDouble (Console.ReadLine());
            Console.WriteLine("Insert a number to be " + operationName2);
            Num2 = Convert.ToDouble(Console.ReadLine());

            //calculating answer
            if (operation == '+')
            {
                answer = Num1 + Num2;
            }
            else if (operation == '-')
            {
                answer = Num1 - Num2;
            }
            else if (operationId == '/')
            {
                answer = Num1 / Num2;
            }
            else if (operationId == '*')
            {
                answer = Num1 + Num2;
            } else
            {
                answer = 0000;
                Console.WriteLine("Error, Unknown operator \n");
                goto start;
            }
            Console.WriteLine();
            Console.WriteLine("The result is:");
            Console.WriteLine(answer);

            Console.ReadKey();
            Console.WriteLine();
            goto start;
        }
    }
}

A: I guess the problem is with - 2 conditions are checking operation and 2 conditions are checking operationId. Perhaps you may want to change all the checks to be either with operation or with operationId.
if (operation == '+')
        {
            answer = Num1 + Num2;
        }
        else if (operation == '-')
        {
            answer = Num1 - Num2;
        }
        else if (operationId == '/')
        {
            answer = Num1 / Num2;
        }
        else if (operationId == '*')
        {
            answer = Num1 + Num2;
        } else
        {
            answer = 0000;
            Console.WriteLine("Error, Unknown operator \n");
            goto start;
        }

A: Your first 2 ifs check operation, the second 2 check operationId. Change the multiply and divide ones to also check operation.
//...
else if (operation == '/')
{
    answer = Num1 / Num2;
}
else if (operation == '*')
{
    answer = Num1 * Num2; //<-- Change to this from Num1 + Num2
}
//...

And by the way, your multiply block is adding the numbers, not multiplying. I've fixed that in my block above.


text:
Q: Issues with search query I am trying to run a search query on all of my comments. I am encountering a number of problems. I would to have two search queries one that runs a search on the comment ID and another that runs a search on the username that is connected to the comment through the user_id FK.
Currently im getting the problem:
Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in

Tables:
Comment- id, comment, user_id, timestamps
User - id, name, username
Models:
class Comment extends Model
{

    public function author()
    {
        return $this->belongsTo('App\User','user_id');
    }
}

Controller:
public function index(Request $request)
{
    $comment =Comment::paginate(10);

    $id=$request->input('id');
    $name=$request->input('username');

    if(!empty($id)){
        $comment->where('id', $request->input('id') )->get();
    }
    if(!empty($name)){
        $comment->where($comment->author->username, 'LIKE', '%'.$name.'%')->get();
    }

    return view('comments.index')->withComment($comment);
}

View:

                {!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}

                    {!! Form::label('id', 'Search By ID:') !!}
                    {!! Form::text('id', null, array('class' => 'form-control')) !!}

                    {!! Form::label('username', 'Search By Username:') !!}
                    {!! Form::text('username', null, array('class' => 'form-control')) !!}

                    {!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}

                {!!Form::close()!!}

@foreach($comment as $comments)
//data
@endforeach

A: The paginate function immediately executes the query for you, so you are using Collection functions after that. The get function on collections expects a key as a parameter, this is the problem.
To fix this, you can either remove the ->get() or use the paginate function at the end of your query as shown below.
$comment = Comment::query();
$id = $request->input('id');
$name = $request->input('username');

if (!empty($id)) {
    $comment = $comment->where('id', $request->input('id'));
}

$result = $comment->paginate(10);

A: Since You have Paginated already
public function index(Request $request)
{
    $comment = new Comment();

    $id=$request->input('id');
    $name=$request->input('username');

    if(!empty($id)){
        $comment->where('id', $request->input('id') )->get();
    }
    if(!empty($name)){
        $comment->where($comment->author->username, 'LIKE', '%'.$name.'%');
    }

    return view('comments.index')->withComment($comment->paginate(10));
}

You cannot paginate and get it again, its like using SELECT statement twice on same object.


text:
Q: Access outer scope variable in readFile I'm new to asynchronous programming. Lately I've found a case that I do not really understand. For this example:
var username = "abc";
fs.readFile(filePath, { encoding: 'utf-8' }, function (err, oldUsername) {
    console.log(username); // Print xyz
    if (username == oldUsername)
        // do something, since username is now 'xyz', result failed!
});
username = "xyz";

I want to compare the oldUsername which I got in the file to the username (abc) but the console print "xyz" so the result failed.
How do I get the unmodified value of username?

A: You have to remember, all that code in that callback function, it is not actually run until AFTER everything else in that code runs.
You are just DEFINING the function there, not executing it. You pass it in as an argument to the other function (readFile) so it will call that whenever it's done with it's async i/o.
I guess it's kind of like putting a return address on an envelope, it doesn't matter until after the primary address on the envelope is processed.
So you end up assigning a different value at the end there, BEFORE the console.log ever gets executed.
More info is out there, for example:

A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input. [1]

Good luck! :)


text:
Q: How to put column name in ALV Display I have a definition like this:
TYPES: BEGIN OF ty_workarea,
          data1 TYPE string,
          data2 TYPE string,
          data3 TYPE string,
       END OF ty_workarea.

DATA gt_data  TYPE TABLE OF ty_workarea.

Fields (data1, data2, data3) don't have any column name when I output it (gt_data) in ALV (cl_salv_table). How can I put name for them?
And since they have empty column names, I'm unable to do this trick:
  lo_columns = go_alv->get_columns( ).

  lo_column = lo_columns->get_column( 'CURRENT_NAME' ).

  lo_column->set_long_text( 'NEW_NAME' ).

A: Columns names are taken by default from dict. You can try to use Sap elements or if you want to have custom title , you may define your own data element.
e.g use type MATNR instead of STRING for DataX and the title will be displayed for that column.

A: The get_column method expects the name of the field it represents, not the current heading text. So
lo_column = lo_columns->get_column( 'DATA1' ).

should get you the column you want.
Alternatively, the class CL_SALV_COLUMNS_TABLE (the one behind the lo_columns object) also has a method get which returns an internal table with the names and corresponding CL_SALV_COLUMN objects of all the  columns. This can be useful in a context where you don't know the names of the columns you want to modify.


text:
Q: How to convert JSON Array to List<>? This is my json and I need to access the values under each object in the attendance array:
{"name":" ","course":"","attendance":[{"name":"INTERNATIONAL FINANCE","type":"Theory","conducted":"55","present":"50"},{"name":"INDIAN CONSTITUTION","type":"Theory","conducted":"6","present":"6"}]}

Here is my code:
public class Att
{

    public class Attendance
    {
        public string name { get; set; }
        public string type { get; set; }
        public string conducted { get; set; }
        public string present { get; set; }
    }

    public Att(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject;

        name = (string)jUser["name"];
        course = (string)jUser["course"];
        attender = jUser["attendance"].ToList<Attendance>;

    }

    public string name { get; set; }
    public string course { get; set; }
    public string email { get; set; }
    //public Array attend { get; set; }

    public List<Attendance> attender { get; set; }
}

It is the attender = jUser["attendance"].ToList<Attendance>; line that I have a problem with. It says,

Cannot convert method group ToList to non-delegate type. Did you intend to invoke this method?

How do I access those values?

A: You have a typo!

attendance vs attendence

And this should work
attender = jUser["attendance"].ToObject<List<Attendance>>();

You may find the running result at DotNetFiddle

A: You wanted to write:
attender = jUser["attendence"].ToList<Attendance>(); // notice the ()

About the Error:
When you dont put the parantheses there, C# assumes you want
to assign the function (delegate) ToList to the varaible attender, instead of
invoking it and assign its return value.


text:
Q: Does Slack app support Multi Select dropdown in their message menus? I'm creating a Slack app, where I want to provide Multi Select dropdowns for the Users to select. But, I don't see any documentation for Multi Select on https://api.slack.com/. If it is not available, is there a workaround for it ?

A: it seems now its possible...
Check the block kit:

    {
    "blocks": [
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "Pick one or more items from the list"
            },
            "accessory": {
                "type": "multi_static_select",
                "placeholder": {
                    "type": "plain_text",
                    "text": "Select an item",
                    "emoji": true
                },
                "options": [
                    {
                        "text": {
                            "type": "plain_text",
                            "text": "Choice 1",
                            "emoji": true
                        },
                        "value": "value-0"
                    },
                    {
                        "text": {
                            "type": "plain_text",
                            "text": "Choice 2",
                            "emoji": true
                        },
                        "value": "value-1"
                    }
                ],
                 "action_id": "create_feedback_final_step"
            }
        }
    ]
}

Use this block with action_id for getting all the inputs that the user selected!

A: No.
Slack does not support multi select drop downs. As workaround you can place multiple drop-downs on one page. This works best with Dialogs, since a normal interactive message will only accept one input (and you need a loop to query multiple inputs). But a Dialog will allow for up to 5 inputs to be selected together.


text:
Q: Error when trying to use WEB API on Azure App service I am migrating an app from a standalone IIS / MS SQL to AZURE appService using Azure SQL and I got the basic app up and running. I got the DB created and migrated but when I try and Migrate one of the API's that actually connects to the DB I get the following error message and I googled o try and find a resolve but was not successful.
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'NWMPosNGTrStore.Data.ApplicationDbContext' while attempting to activate 'NWMPosNGTrStore.Controllers.OgetTillConfigObject'.
Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

I am not getting any compiler warnings or erros before this happens, and navigating the site itself works fine I guess because it does not use the DB, but as soon as I want to access the DB the app crashes with the above error message
Te relevant part of the API Controller is below
namespace NWMPosNGTrStore.Controllers
{
    [Route("api/online/till/[controller]")]
    public class OgetTillConfigObject : Controller
    {
        private ApplicationDbContext _context;

        public OgetTillConfigObject(ApplicationDbContext context)
        {
            _context = context;
        }

startup.cs registration of the dependency
namespace NWMPosNGTrStore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
 services.AddTransient<ApplicationDbContext>();

ApplicationDbContext
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using NWMPosNGTrStore.Models;

namespace NWMPosNGTrStore.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
            builder.Entity<OrderHeader>()
                   .HasKey(c => new { c.OrderNumberId, c.TillId });
            builder.Entity<OrderRow>()
                   .HasKey(c => new { c.OrderNumberRowId, c.TillId });
            builder.Entity<Payment>()
                   .HasKey(c => new { c.PaymentId, c.TillId });
            builder.Entity<TillBasicData>()
                    .HasKey(c => new { c.ItemId, c.CompanyId, c.languageCode });
            builder.Entity<MerchHierarchy>()
                    .HasKey(c => new { c.CompanyId, c.CategoryId, c.LanguageCode });
            builder.Entity<MerchHierarchyMapping>()
                    .HasKey(c => new { c.ParentId, c.ChildId, c.LevelId, c.CompanyId });
            builder.Entity<Color>()
                    .HasKey(c => new { c.CompanyId, c.ColorId, c.LanguageCode });
            builder.Entity<Size>()
                    .HasKey(c => new { c.SizeCode, c.SizeProfile, c.CompanyId });
            builder.Entity<LevelDesc>()
                    .HasKey(c => new { c.CompanyId, c.LevelId, c.LanguageCode });
            builder.Entity<LevelMapping>()
                    .HasKey(c => new { c.CompanyId, c.ParentId, c.LevelId });
            builder.Entity<Pricelist>()
                    .HasKey(c => new { c.PricelistId });
            builder.Entity<PriceListRow>()
                  .HasKey(c => new { c.PricelistId, c.ItemId });
            builder.Entity<BackEndConfig>()
                  .HasKey(c => new { c.CompanyId });
            builder.Entity<oh>()
                  .HasKey(c => new { c.BrandId, c.OrderNumber });
            builder.Entity<orp>()
                  .HasKey(c => new { c.BrandId, c.OrderNumber, c.OrderRowNumber });
            builder.Entity<pts>()
                  .HasKey(c => new { c.BrandId, c.OrderNumber, c.ExtRefNo });
            builder.Entity<ItemRef>()
                  .HasKey(c => new { c.ItemId, c.CategoryId });
            builder.Entity<WarehouseLocations>()
                  .HasKey(c => new { c.LocationId });
            builder.Entity<Bin>()
                  .HasKey(c => new { c.BinId });
            builder.Entity<InventoryQty>()
                  .HasKey(c => new { c.BinId, c.ItemId });
            builder.Entity<StorePart>()
                 .HasKey(c => new { c.Id });
            builder.Entity<Safe>()
                  .HasKey(c => new { c.SafeId });
            builder.Entity<NumberSeparator>()
                  .HasKey(c => new { c.Id });
            builder.Entity<Address>()
                  .HasKey(c => new { c.Id });
        }

        public DbSet<Brand> Brand { get; set; }
        public DbSet<Region> Region { get; set; }
        public DbSet<Receipt> Receipt { get; set; }
        public DbSet<TAXType> TAXType { get; set; }
        public DbSet<Pricelist> Pricelist { get; set; }
        public DbSet<CampaignPricelist> CampaignPricelist { get; set; }
        public DbSet<Language> Language { get; set; }
        public DbSet<Currency> Currency { get; set; }
        public DbSet<Promotion> Promotion { get; set; }
        public DbSet<Country> Country { get; set; }
        public DbSet<Area> Area { get; set; }
        public DbSet<City> City { get; set; }
        public DbSet<Store> Store { get; set; }
        public DbSet<Till> Till { get; set; }
        public DbSet<ConfigurationNode> ConfigurationNode { get; set; }
        public DbSet<Payment> Payment { get; set; }
        public DbSet<OrderRow> OrderRow { get; set; }
        public DbSet<OrderHeader> OrderHeader { get; set; }
        public DbSet<TillBasicData> TillBasicData { get; set; }
        public DbSet<MerchHierarchy> MerchHierarchy { get; set; }
        public DbSet<MerchHierarchyMapping> MerchHierarchyMapping { get; set; }
        public DbSet<Color> Color { get; set; }
        public DbSet<Size> Size { get; set; }
        public DbSet<LevelDesc> LevelDesc { get; set; }
        public DbSet<LevelMapping> LevelMapping { get; set; }
        public DbSet<PriceListRow> PriceListRow { get; set; }
        public DbSet<BackEndConfig> BackEndConfig { get; set; }
        public DbSet<oh> oh { get; set; }
        public DbSet<orp> orp { get; set; }
        public DbSet<pts> pts { get; set; }
        public DbSet<CRMPerson> CRMPerson { get; set; }
        public DbSet<ItemRef> ItemRef { get; set; }
        public DbSet<WarehouseLocations> WarehouseLocations { get; set; }
        public DbSet<Bin> Bin { get; set; }
        public DbSet<InventoryQty> InventoryQty { get; set; }
        public DbSet<StorePart> StorePart { get; set; }
        public DbSet<Safe> Safe { get; set; }
        public DbSet<NumberSeparator> NumberSeparator { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

A: Adding following lines of code in ApplicationDBContext class resolved the issue:
protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        IConfigurationRoot Configuration = null;
        string basePath = Directory.GetCurrentDirectory();

        var builder = new ConfigurationBuilder()
            .SetBasePath(basePath)
           .AddJsonFile("appsettings.json");
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
    }


text:
Q: Connecting layout text boxes to item before it in QGIS 3 I have an atlas layout in QGIS 3.16 where input data can vary in character length. Therefore I made a override of box height based on text length. The problem I ran into, is that if the text is longer it goes over the next text box. I want to make this text box dependent on min. y position point of box item before. So is there a way to make a relative position of item in layout based on item before?
Normal position:

Longer text:

What I want it to look like.

A: I am not aware of any relative positioning. Maybe it was implemented already like asked in this post.
Another approach would be to have only one Text Label Input and use HTML Styling. You would only need to replace the div content with your input data:
[%'
Box1:

Foobar

Box2:

Foobaz

'%]


text:
Q: Is it possible to reference a photoshop file or layer comp from within another photoshop file? Creating all the art for a large website often involves a couple dozen 50+mb photoshop files. Frequently, a given module may appear in more than one file.
Is there a way to reference an oft-used module from another file?
For instance -
"site-section-2.psd" references "common-module-h.psd", and "site-section-6.psd" also references "common-module-h.psd", so that any time updates are made to "common-module-h.psd", the updates appear in both files which reference it.
Possible?
(maybe with photoshop javascript?)

A: I've checked the JSX Photoshop Object Model, and you can access LayerComps, but there is no magic function to save from one file to another. Something like this could be written to disk, from file1.psd for example, then loaded into file2.psd.
It's a bit of a long shot and I don't know if it's worth the trouble.
For web prototyping I use Fireworks and and I'm pretty happy. You can easily create symbols (much like in Flash and Illustrator) and even save them to a Common Library, which means it will be easy peasy to keep your navigation items for example up to date, for all the files using it. You can even import PSD files into Fireworks, only not all the filters will be supported.
Don't know if you can keep most of the eye-candy in Photoshop and then assemble reamble versions with ease using Fireworks.

A: You can try converting all the layers into one smart object and then drag the smart object layer into the new .psd file.
Go to the Layers palette: Window > Layers(F7).
LMB SINGLE CLICK the top layer.
Scroll down Layer palette until you get to the bottom.
SHIFT + LMB SINGLE CLICK. At this point all the layers should be hilighted.
RMB SINGLE CLICK any of Layer "Titles".
You should see a menu pop up so use the mouse to scroll until you find "Convert to Smart Object". LMB SINGLE CLICK to convert all the layers into one smart object. The smart object can be edited by double clicking it in the Layers palette. You can also drag a smart object from one .PSD into another .PSD. I usually just open both .PSD files and drag the smart object form one Layers palette to the other Layers palette.


text:
Q: Automating SQL scripts in Toad for Oracle I'm not a DBA, so bear with me.
I've scheduled tasks through Toad's automation designer, but this uses Windows task scheduler. It's using Oracle 12c.
How can I ensure my scripts execute on time without running a local machine with scheduled tasks? Can this be done without additional software? Thanks in advance.

A: I don't know what those scripts do.
However, if they can be rewritten into stored procedures, then you could schedule them as database jobs using either DBMS_SCHEDULER (or DBMS_JOB, which is simpler but still quite usable) package.
As a matter of fact, DBMS_SCHEDULER can even run your operating system scripts, using job_type => 'external_script'. Read documentation for more info.
See if it helps.


text:
Q: Troubles using NVM4W I had observed that each new installations of Node.JS + NPM lately fails, were installation (nvm install 8.11.1 ) seems to work out correctly:
C:\WINDOWS\system32>nvm install 8.11.1
Downloading node.js version 8.11.1 (64-bit)...
Complete
Creating C:\Users\XXXXXXXXXXX\AppData\Roaming\nvm\temp

Downloading npm version 5.6.0... Complete
Installing npm v5.6.0...

Installation complete. If you want to use this version, type

nvm use 8.11.1

On "npm --version" getting this error reply:
module.js:549
    throw err;
    ^

Error: Cannot find module 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
module.js:549
    throw err;
    ^

Error: Cannot find module 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

When checking in Windows Explorer folder "C:\Program Files\nodejs\node_modules" are empty, where it should have "npm" scripts in them.
I suspect that NPM mirror download https://github.com/npm/npm/archive/, which is default not correct anymore when putting in the browser it leads to 404 GitHub page.
1) Does anyone encounter the same issue recently? if yes how did you resolved it?
2) Any idea where those NPM mirror version could be found, somehow not arriving to find those.
If that information is relevant, I'm running windows 8.1 64bit machine.

A: Seems that issue is known under https://github.com/coreybutler/nvm-windows/issues/302.
For a moment best workaround proposed by roman-spiridonov:

*

*nvm install 8.8.1 (or another version you want). Do not switch to it (yet).

*Download the *.zip of the same node version from official site (https://nodejs.org/en/download/current/)

*Substitute the contents of %APPDATA%/nvm/v8.8.1/npm for the npm folder from the downloaded archive

*nvm use 8.8.1

*Enjoy


text:
Q: How to sync user password between 3 different services when they are hashed in different point of time? I have 3 microservices that hold particular user information including their sign-in credentials (email + password). If the services are A, B, and C then the user "John" will have his info stored separately in all three of these services' database.
Now, the user info in service A is updated at an earlier point of time, and at that moment it is not predictable whether services B or C will definitely be activated to be used by that particular user. So, there is no point in creating an entry in B and C for "John". But, as "John" activates B or C at a later point of time, the system can only have access to the hashed password.
It is to be noted that the service C requires the password to be stored in encrypted form so that it can be decrypted later. So, merely storing the hashed value in all 3 services is not feasible, neither do we want all 3 of them to have encrypted password.
What is a feasible solution to sync the password between the services by maintaining the requirements?

A: Your approach implies a lot of problems in addition to the one you already described yourself. I recommend to look into Federated Identity (using OAuth2 and OpenID Connect) which fits for Microservices architectures.
Basically, this means that authentication and credentials handling is performed by a separate highly available and scalable service (usually referred to as identity provider or authorization server) that only does that - handling user credentials, identity and access control - and does it well.
It handles login and issues access tokens which are then sent to your Microservices along with the requests. As each Microservice will trust this identity provider it will be able to verify that the token is valid and was issued by this identity provider (this happens by validating the token with a public key). And the token contains information like user id and information about what actions are allowed with this token.
The identity provider can be a cloud service like Okta, Auth0, Azure AD B2C, etc. (see https://openid.net/developers/certified/#OPServices) or host an identity provider on your own, if you are not able to access cloud services, by using ready-to-use libraries available for your technology stack (https://openid.net/developers/certified/#OPLibs).
So there is no need to store user credentials in each Microservice and sync this information between them. I would consider such an approach as an anti-pattern.
The federated authentication approach also allows to solve other problems such as single-sign-on.
If you are new to that topic it can be a little overwhelming at first but it's something you can't get around if you really want to have all the advantages a Microservices architecture can provide.
This article might help you get started:
https://nordicapis.com/how-to-control-user-identity-within-microservices/


text:
Q: Python - Ways to create dataframe with multiple sources and conditions Let's say we have several dataframes that contain relevant information that need to be compiled into one single dataframe. There are several conditions involved in choosing which pieces of data can be brought over to the results dataframe.
Here are 3 dataframes (columns only) that we need to pull and compile data from:
df1 = ["Date","Order#","Line#","ProductID","Quantity","Sale Amount"]
df2 = ["Date","PurchaseOrderID","ProductID","Quantity","Cost"]
df3 = ["ProductID","Quantity","Location","Cost"]

df3 is the only table in this set that actually contains a unique non-repeating key "productid". The other two dataframes have keys, but they can repeat. the only way to find uniqueness is to refer to date and the other foreign keys.
Now, we'd like the desired result to show which all products grouped by product where df1.date after x date, where df2.quantity<5, where df3.quantity>0. Ideally the results would show the df3.quantity, df.cost (sum both in grouping), most recent purchase date from df2.date, and total number of sale by part from df1.count where all above criteria met.
This is the quickest example I could come up with on this issue. I'm able to accomplish this in VBA with only one problem... it's EXCRUCIATINGLY slow. I understand how list comprehension and perhaps other means of completing this task would be faster than VBA (maybe?), but it would still take a while with all of the logic and decision making that happens behind the scenes.
This example doesn't exactly show the complexities but any advice or direction you have to offer may help me and others understand how to treat these kinds of problems in Python. Any expert opinion, advice, direction is very much appreciated.

A: If I understand correctly:
You simply need to apply the conditions as filters on each dataframe, then group by ProductID and put it together.
df1 = df1[df1.Date > x].groupby('ProductID').agg({'Quantity':'sum','Sale Amount':'sum'})
df2 = df2.groupby('ProductID').agg({'Date':'max','Quantity':'sum','Cost':'sum'})
df2 = df2[df2.Quantity > 5].copy()
df3 = df3[df3.Quantity > 0].copy()

Once you have all of those, probably something like:
g = [i for i in list(df3.index) if i in list(df2.index) and i in list(df1.index)]
df = df3.loc[g] #use df3 as a frame, with only needed indexes

I am not sure what you want to pull from df1 and df2 - but it will look something like:
df = df.join(df2['col_needed'])

You may need to rename columns to avoid overlap.
This avoids inefficient looping and should be orders of magnitude faster than a loop in VBA.


text:
Q: Create image from data-in-uri (base64-encoded PNG) in ActionScript I have a string of of base64-encoded PNG image that is suitable to use as a src (source) attribute in a  tag. However I need to transfer this image to Flash applet where I need to create (show) the image fast. Is there a way to simply use the data string and somehow create an image (inside a Flash movie) from it?
Performance of the operation is a core requirement.

A: At the very least you must decode the base-64 data into binary. You can then load the binary data as an image using Loader.loadBytes().
Here's a fast base64 decoder compiled with alchemy: http://www.blooddy.by/en/crypto/
var bytes:ByteArray = by.blooddy.crypto.Base64.decode(string);
var loader:Loader = new Loader();
loader.loadBytes(bytes);

Update: You can use the "Textfield.getImageReference()" to gain access to the Loader for  tag. Once you have it you can tell it to load the image bytes, like this:
textfield.htmlText = 'hello  hello';
var image:DisplayObject = textfield.getImageReference("myImage");
var loader:Loader = image as Loader;
loader.loadBytes(bytes);

Here's a complete end-to-end example:
var textfield:TextField = new TextField();
addChild(textfield);
textfield.htmlText = 'hello  hello';

var data:String = "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAKqUlEQVRYhe2YWYwc13WGv1q7urt6n+nZF5IzJDWkSCoiRY1MiZToBbYUCrJgx7ADIwECI0igLDYCPSuAEyR5SWIndgzHeTJhSIptGJZs05YFm9o4EmXOkCJFzr5vvVVXd1XXngfSgRWK9JBiHgLkAPVyq07d7/73nnvOvfD/9sFMuF3H+3skKZ9JHm1vSx0z6va7a5vGs28sB/6dhAOQb9cxm058ae9w1zOdxYwmSlL00isX8ywbX72TcADSrToc6pLUu/tSX9s92PG0piqy7wd0FDOC6/kHM1Hj+elKUPvN7z8+kto5kJESsxW/fjuA4q06FDLxPxrozP1hFEVXfyAKOI5HPqsXQ8QT9/e8d8zdxcy32nKJv//s/sTt8N36FKcS6p/HNUVuWA5hGFE2AtYqBo7vk23T/85crP4UuATw8eHYtu6O3IfWNqhsrDXvLOAT+3V517bs59WYMry2YT4/caV69o3lgGrT1StzJbSYSCIuE4tJqKKEKov0FnParsHuF3evlF9dWtr8U1nT/iyf01ndqOWTqpgCzDsG2J6LPxrK6jesUJR6+9r+qqM99bXeqfKX1+uBnE7ItOeTZPQYuVSc9kKaXDaJ63o0ms7gtt7C4HJ/8cm4pmgtx8P1fIDbArxhkAx1xo96oXii3nCpW56YSscPpXX107IU6zq8b0AY2dFJW04nrqkEQYBluwDEVZUogs72jBxGEYZpYxoNTtzbWXh0b2awN+HPjS26W57vGyrYsH1CycNseqiKSBhGQk+H3t/fKQMRoiCQiMVAA6KIIIxwXB/PD9ATMVqOR9Ny8P2QohoxODzyB25tmcmV+mc+dyA4/u1zlvWBAMUwxG75JCUwmy6VCMIQejuS2HadUkUgFlMQEEAARZaIqTKiKNJoOlgtF9vxsG2bkaJGJqazqvdzcMjct2nMDwETWwG84RTvbZfulUTxd79wdBCdBBtLm6w3XZpOgKSIiIKL6/goioyqXB2n1fKo1S0aTQfDbGKaJru7NI7cv4Op8cvYQYCCo0zMVsWRovLD8+ve7SuYVMXZQzuzQSLXIX30xAje6rcgG2fedJmcrpDNJejrDJGVgKYFrhvheQGiJOD5AesVi4Km8NDuIromE8QikuYary3VAy+MfrwV9W4KGEZRquV4YFcor0xTKMZQ4hqDRR1EgQurDaanykwKArG4QlyTiSLwHJ+MIiCRwtG288KbSzxxpIeBoS6+/u0z1J3gmxG8eHJ8S0vwxoBRxEuXl42L/e2puzNhBdNy6Uqn6ComSesqe4bzOG7AbMlhYqVFPiGwvaDSlo6RTcX42+dmePP8GcLdOp7XSVrXKHakXzUWqn9xctxyt6rgDVPdyXHLsN3w9194a3H65NkVY8MXiWsyelJF11W0mEwmFePCeoTdNsrPz5boLKYoZjVUSeCzx3v59JF2Pnm0F5kISRAoZOMh0Noq3E0Br0FOBGH0UBBxUBAFBEFAlt9boXmtJqe+cxIxDJAUGSWToTKj0q8N8+SRIQbb40AEAoRRdMsJ+bfm4pPj1grAX35IIwwjgiB6z/tPPtDFnoE0/X1ZRkaHWD23SadXwC9LuCmVvoM9lK4s4Qch9Ybj3CrglqsZ2w2Wmi0Pzwvf055RBe7bpnP3vh6UuErhrgLVvjqV3nUGH+hE1lQS7VlWSibL6+b4/xpgw/V+uma0qJvOdZAAqq4BEMmQ2pOhrnj84pcXCULYrDT57s8ubZqW969bjd5f25YL1rs7lVK95X0moyqKHpdJxBWE31iOgiCg5XTCMMJxPIrtaXYMtHFubJqTz52latr/pMek599acq8f3R0CXPTCqLliWMethicpooCmSgjiVcqWYWGulLFKdcwNg3fHZnjjexcY++E02wZTPHZk8MGMHvvUSLt4eV+HNDu2uLWd5pYOTX98nx7vyyVeG8jED5xfNJFCge5CHF1XiaIIp+lhbFi01m3izZDhfIoXmk3srMSXntiFnk2wZDjVl96ceeLLp0q/2EqfW1bwTw7r6ZGezHeO7+t+qCOjsbjeZHzBZG7BolHXaCx7RCs2nc2IHckk+3oLbDZbzPUU8M06b8/WGEjJ9Hdn44btH9aj1r+d2J8ZONaffPr+bu3wPX3ya2OLbvQ/+91yyd/fkX76wXsHH43LAlbT4fxGg7akRDIvkn3gPo58+Dgto8mlH/yY8rkJqksV3ChiYO89rF7yKK2U+PeXF/iCLDHQkb5L19Ye37Oz42+689md71xc5tJK+XtcOyrcsoKf/51kz5H9vc9u681Lgesxu9ng9MQmWUWkLSXjZjrYf+gg6XyGHaOHUA7sZV5SaIUR2/fuZeQTjzE9fgazbnNh3WF7W4y64x169NhdQ1lFQJXg0mLlP8YW3dXbUlCVhMeHtxWVMAgAWK1YREFExNXolWQZWZbRUxkEBHbt2YOeSLCwI0UqM8PKrI3phizEBmHgceYnp/jc0OQ2NYywrRaJmEzov39wbwkwEZMP53JJ7PLVo+1i2SYhCggCeEGEEoth1irUqyUss055+jkIyjRqIbrrMX7aY0U7gNM9SjLdTbzYzZ7+NVzTYu7SBvMVG8/+AIBAjij67y2lVveJSQIiAqYXIdUMVq+cp1WrMjU5w6GDBqd+YCPLIol7QnJdKerNj+BbTdyWTdSYJb1bwWt5zC8YbDoecvz9V9uWAE3bq166vI4aRbSlFQICljyBqigS+QLHWvMUSiabywYHExErb9k88lGFpZLGTyYHueLto+lWkFUVgJRoIvgB1ZJFreFhCD4NP7wugrcE+MWjhb69946OnH13BjVwyHel6RsY5EzV8srdH1GSmsTDjyxiz8yxoy+FFpMorEQ8ezrBy+LH8EIBz2nhlC+ihTXsgYdpqgpWrUmrbjNXcwgyghGEXLllwKdG9YHBod2viAK9hb6+yaX5mRnRjR0/OHpYPjv5n8pYwyKT7YEwoFiIszJXoewEpDWRvriDuV4hcAwU8zJ5e/qK7zuzob36yFRml/KyW6Y/FeKkBL9ihX+dUIXGLQE+NaoLqUzuH/q3D/euLMzOXpo4+yCwUezses5znScPDHXw1rkpqsk0ZdPHWjJYnCxRtXy0uEw2o5Hd/BGRU19rtuyfXzGCM14QOZ2pxYv51uros2WpLyH5AYLwL6mY8NXvj9vvy3EzBfu7ewce1hJJjGr5G8D6V15v8EzH6nzPwBCKItWSjXca5XJP76uTIY8VVCpNn5YX0vA8ujMylrHx9amK/yugCYwDC6tm0Fo1g1/329rVJoevzt/4WvFm5ZaSzuWVMAho2ZZyTdV8vq3jU3WjQq3pTpZr1ZOp2uve98cjHElAick0nIBQELC8gIYXVYAq8AJwAagDLmBde8LLpZvfed4wkxzuUxu5QvtDnuvs2LnnwMMjBw79Xs/A9mcEQWwrlUrlb7749j8v14MZLTSXNH9z++SGrx87kCOeiHHPcIZfTlWab6+6pxw/+u41yNuyGwKOLbnBsFY9HdPivVPvnk8360bcbjaMRr128vSvLn/xjTnrFHDRdKMLtutMRq4lbBhWerBNNc/N18xXFqyJBSP4xzBi4XbhYAvl1lOj+nVtX3n9+oArJkW252WG8zIVO2SuFvDOxm+/Ofg/b/8FrV74eebdEP8AAAAASUVORK5CYII=";

var bytes:ByteArray = by.blooddy.crypto.Base64.decode(data);

var image:DisplayObject = textfield.getImageReference("myImage");

var loader:Loader = image as Loader;
loader.loadBytes(bytes);


text:
Q: Java Console Scanner Color Let's say I have a console app in Java that reads input from the user and then prints it back out (very basic)
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        while(true) {
            Scanner scanner = new Scanner(System.in);
            String message = scanner.nextLine();
            System.out.println(message);
        }
    }
}

Is it possible to make the text the user enters when typing a different colour when compared to the text that is printed out with System.out.println?
For example if I ran that program in a console that defaults to white text on a black background the following would happen.
I would type "hello world" and it would show in red. When I press enter, it prints "hello world" in the default white.
As a bonus, is it possible to configure a background for the "hello world" when it is printed in red? This means that I can choose two contrasting colours in case a user has their console background at a default setting of red.
Thanks!

A: You can start a windows console by using this code:
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe");
p.waitFor();

Use this code to start your Java-application and set the fontcolor / backgroundcolor of the console.
The /c- switch means that you give the console a command it should run.
You can test this by clicking on (Windows) Start -> cmd /k color 2c ... this will start a console with some very ugly colors that you can change to suit your needs:
https://ss64.com/nt/color.html
Then use Sergei's methods to change the color of the Java-output to what you want.
Since I did not test this solution, I dont know if the colors will get lost after you've changed them with Sergei's methods! You have to try that.
Some side notes:

*

*Why do you want to change the input-colors? This seems to be a lot of effort just for a fancy effect.

*You might overwrite the preferences that a user has made on his console! For example I use a green font since I can read it better. Having a program change this color permanently(?) might upset a user.

*This solution only works on windows. When a user runs it on a linux-based machine, this might fail. So you would have to implement a switch for the different OS like demonstrated here: https://stackoverflow.com/a/5738345/1368690

A: You need to do something like this:
import java.util.Scanner;

public class App {

    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_RED = "\u001B[31m";
    public static void main(String[] args) throws Exception {

        System.out.println("Movie Name:" + ANSI_RED);
        Scanner read = new Scanner(System.in);
        String movieName = read.nextLine();
        System.out.println(ANSI_RESET +"\nMovie Genre:" + ANSI_RED);

    }
}


text:
Q: Catching an exception to throw another one, not working as expected I have something like this in a Symfony controller:
try {
    $entity = $this->getDoctrine()->getRepository(Entity::class)->findOneBy(['uuid' => $uuid]);
} catch(\Exception $ex) {
    // die('Invalid uuid'); <- this works
    throw $this->createNotFoundException('Resource not found...'); // this doesn't work
}

if(!$campaign) {
    // this works if the uuid has a valid format but doesn't exist in db
    throw $this->createNotFoundException($this->get('translator')->trans(Utils::NOT_FOUND_STRING));
}

I want to show an error 404 and not a 500 if the user opens a page with an invalid UUID.
The exception is caught, because if I put a die() it works. But with throw $this->createNotFoundException(, I get:

ConversionException
Could not convert database value "55012772-4801-4e26-8..." to Doctrine Type uuid_binary


text:
Q: Map image/texture to a predefined uneven surface (t-shirt with folds, mug, etc.) Basically I was trying to achieve this: impose an arbitrary image to a pre-defined uneven surface. (See examples below).
 -->
I do not have a lot of experience with image processing or 3D algorithms, so here is the best method I can think of so far:

*

*Predefine a set of coordinates (say if we have a 10x10 grid, we have 100 coordinates that starts with (0,0), (0,10), (0,20), ... etc. There will be 9x9 = 81 grids.

*Record the transformations for each individual coordinate on the t-shirt image e.g. (0,0) becomes (51,31), (0, 10) becomes (51, 35), etc.

*Triangulate the original image into 81x2=162 triangles (with 2 triangles for each grid). Transform each triangle of the image based on the coordinate transformations obtained in Step 2 and draw it on the t-shirt image.

Problems/questions I have:

*

*I don't know how to smooth out each triangle so that the image on t-shirt does not look ragged.

*Is there a better way to do it? I want to make sure I'm not reinventing the wheels here before I proceed with an implementation.

Thanks!

A: This is called digital image warping.  There was a popular graphics text on it in the 1990s (probably from somebody's thesis).  You can also find an article on it from Dr. Dobb's Journal.
Your process is essentially correct.  If you work pixel by pixel, rather than trying to use triangles, you'll avoid some of the problems you're facing.  Scan across the pixels in target bitmap, and apply the local transformation based on the cell you're in to determine the coordinate of the corresponding pixel in the source bitmap.  Copy that pixel over.
For a smoother result, you do your coordinate transformations in floating point and interpolate the pixel values from the source image using something like bilinear interpolation.

A: It's not really a solution for the problem, it's just a workaround :
If you have the 3D model that represents the T-Shirt.
you can use directX\OpenGL and put your image as a texture of the t-shirt.
Then you can ask it to render the picture you want from any point of view.


text:
Q: Can I recover the replaced file by SVN in eclipse I am using SVN as code repository. Accidentally I replaced my entire project with the one in SVN. As soon as I replaced, i tried to look at the local history of some files and figured out that there won't be any.
Is there anyway I can switch back my project (or atleast a file in that project) to previous versions in eclipse?

A: History is stored in this (hidden) folder:
.metadata/.plugins/org.eclipse.core.resources/.history/
So you should be able to restore from there.

A: Use the svn history. In Eclipse IDE (with subeclipse):

*

*right click

*show history

*in the history window, locate the desired version (e.g. 55)

*right click on it and Switch to Revision 55


text:
Q: Adding curried closure as static property with expando metaclass loses default parameter value I encountered this in both Groovy 1.8.6 and 2.0.0.
So these scenarios all work as expected:
def ay = { one, two=[:] -> [one, two] }
def be = { one, two, three=[:] -> [one,two,three] }
def ayprime = ay.curry('PRIME')
def beprime = be.curry('PRIME')
def beprimer = be.curry('PRIME', 'PRIMER')

assert ay(1,2) == [1,2]
assert ay(1) == [1,[:]]
assert be(1,2,3) == [1,2,3]
assert be(1,2) == [1,2,[:]]

assert ayprime(1) == ['PRIME', 1]
assert ayprime() == ['PRIME', [:]]
assert beprime(1,2) == ['PRIME', 1, 2]
assert beprime(1) == ['PRIME', 1, [:]]
assert beprimer(1) == ['PRIME', 'PRIMER', 1]
assert beprimer() == ['PRIME', 'PRIMER', [:]]

As does this:
class Klass {
    static def smethod = { one, two=[:] -> [one, two] }
}
assert Klass.smethod(1,2) == [1, 2]
assert Klass.smethod(1) == [1, [:]]

This also works, as expected:
Klass.metaClass.static.aymethod << ay
assert Klass.aymethod(1) == [1, [:]]

The default parameter to the uncurried closure survives the assignment to Klass.
However, this fails:
Klass.metaClass.static.ayprimemethod << ayprime
assert Klass.ayprimemethod() == ['PRIME', [:]]

thusly:
assert Klass.ayprimemethod() == ['PRIME', [:]]
             |               |
             [PRIME, null]   false

and similarly, this fails:
Klass.metaClass.static.beprimermethod << beprimer
assert Klass.beprimermethod() == ['PRIME', 'PRIMER', [:]]

thusly:
assert Klass.beprimermethod() == ['PRIME', 'PRIMER', [:]]
         |                |
         |                false
         [PRIME, PRIMER, null]

With the curried closures, the default parameter value works directly, but is lost when the closure is assigned as a static member of Klass.
This seems like a bug. I couldn't find this behavior documented anywhere. Am I missing something?

A: If the problem is still bothering you, i think this might be a workaround, until it gets fixed in groovy trunk. The python way to curry stuff:
def ayprime = { x -> x ? ay('PRIME', x) : ay('PRIME') }
def beprime = be.curry('PRIME')
def beprimer = { x -> x ? be('PRIME', 'PRIMER', x) : be('PRIME', 'PRIMER') }