text:
Q: How to check if a nested list contain only empty strings In pyqt I have a qtableview which a user can edit. If the users makes a change to the table, the table will be copied when the user is done. If no changes are made, the table is skipped. The table is filled with empty strings i.e:
table = [["","",""],["","",""]]

I want to check if the table contains only "", and if it does, ignore it. If it doesnt, i.e. contains a "1", some code runs on the list.
Now I have a working code but its not very pythonic and I wonder how I can improve it. My code is as follows:
tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
    for item1 in item:
        if item1 == "":
            pass
        else:
            meh = 1
if meh == 1:
    do the thing

A: To check if any element in any of the sublist fulfills the condition you could use any and a nested generator expression:
tabell1 = [["","",""],["","",""]]
if any(item for sublist in tabell1 for item in sublist):
    # do the thing

This also has the advantage that it stops as soon as it finds one not-empty string! Your method would continue to search until it checked all items in all sublists.
Empty strings are considered False and every string containing at least one item is considered True. However you could also explicitly compare to empty strings:
tabell1 = [["","",""],["","",""]]
if any(item != "" for sublist in tabell1 for item in sublist):
    # do the thing

A: The primary thing I see that could be more pythonic is using the fact that empty strings are considered false, something like this...
tabell1 = [["","",""],["","",""]]
meh = 0
for sublist in self.tabell1:
    if any(sublist):  # true if any element of sublist is not empty
        meh = 1
        break         # no need to keep checking, since we found something
if meh == 1:
    do the thing

A: Or you could avoid looping through the list by converting it to a string, removing all the characters that would only appear if it were empty, then checking if it is empty or not:
tabell1 = [["","",""],["","",""]]
if not str(tabell1).translate(None, "[]\"\', "):
    #do the thing

Although this will mean that any tables containing only instances of [, ], ", ', and  will be considered empty.


text:
Q: ExpressionEngine show channel content outside of loop I know this sounds crazy, but I need to show some post information outside of the loop in the expression engine channel module. Is this possible?

A: You could use EE's SQL Query template tags (if you know, or have access to the database table names and know what to look for in the database):
http://expressionengine.com/user_guide/modules/query/index.html
Basically, you'd output only what you need - it doesn't have to belong to a channel, or anything specific. The one kicker is that you'd have to know the basics of SQL syntax, but if you have a small working knowledge of it, you can do tons of additional things with it.

A: If you're not keen on SQL, you could simply embed a template within the template that you're working on. Here's a simple example that assumes you're editing the index and meta templates inside of a template group called 'news':
index template contents:
{exp:channel:entries channel="news"}

{title}

{body}

    {embed="news/meta" this_entry_id="{entry_id}"}

{/exp:channel:entries}

meta template contents:
{exp:channel:entries channel="news" dynamic="no" limit="1" entry_id="{embed:this_entry_id}"}

{entry_date}

{author}

{/exp:channel:entries}

As you can see, the index template is embedding the meta template. Note that we're passing a parameter to the meta template so that it knows which entry ID to print information about. If you're unfamiliar with EE's template embedding feature, you can read more about it in the EE docs. Embedding templates in other templates is a great way to access the {exp:channel:entries} loop multiple times.

A: There's an add-on called MX Jumper that allows you to "set" a variable from inside your entries loop and then "get" it elsewhere in the template (before or after in the HTML loop doesn't matter because it parses later).
Alternatively, the approach that's all the rage now is to use the add-on Stash to store any and all elements you need to use distinctly as stash variables that you set and then get - similar to the above, except that once you set them, getting them has to happen at a later parsing stage.  The beauty of this approach is stash will store the "set" variables for reuse either at a user or site level, and you can determine what the expiry period is - which then results in better performance. When you apply this broadly using the "template partials" mindset, you can store everything with stash, and then call them into a small number of wrapper templates.  This makes it possible to use stash to set, for example, your entry title, then get it three separate times in the wrapper template without any additional load - no need for separate loops within your template - one loop to set the variable, and then you can call that variable as needed in your template - it's kind of like creating global variables on the fly.

A: I would also suggest looking at Stash.

redpajama_set_name: RedPajamaStackExchange


text:
Q: convert read string to integer in bash I'm trying to read from user and then do the following.
read framechoice
 if [ $framechoice -gt 100 ]; then
   if [ $framechoice -lt 0 ]; then
          framechoice=101
   fi
 fi

It gives me the following error.

[: -gt: unary operator expected

Can anyone tell me where I am going wrong.

A: This happens if you don't input anything:
$ cat myscript
read framechoice
 if [ $framechoice -gt 100 ]; then
   if [ $framechoice -lt 0 ]; then
          framechoice=101
   fi
 fi
$ bash myscript
<enter>
myscript: line 2: [: -gt: unary operator expected

Try instead to actually enter something:
$ bash myscript
42<enter>

The script then exits with success.

A: Your program needs to cope with empty input.  This is most easily achieved by properly quoting the variable; then
if [ "$framechoice" -gt 100 ]; then

evaluates to [ "" -gt 100 ] which is no longer is a syntax error; however, instead, it throws the warning integer expression expected.
Even better, maybe filter the input so that you do not attempt numeric comparisons before making sure the input is numeric.


text:
Q: form does not set config form controls after reset and initialize in angular In my angular app I have a form with some fields: inputs, datepicker, selects,...
First, in ngOnInit() I initialize the form group calling an initilizeForm() function where I created the form group and I set some config like form control disabled or its "default" value.
Then, the user writes some info and then I save the form group data. After that, I reset the form to have a clear state form and then I call again the initializeForm function to set default values. But, at this moment, the function does not do anything and I do not know why.
Initialize call in OnInit:
public formGroup: FormGroup;
ngOnInit() {
  this.initializeForm();
}

Initialize function:
this.formGroup = this.formBuilder.group({
      input1: [
        { value: '', disabled: true },
        [Validators.XX, Validators.YY]
      ],
      input2: [
        { value: '', disabled: false },
        [
         Validators.XX, Validators.ZZ
        ]
      ],
      select1: [
        { value: 'Value1', disabled: true },
        [Validators.XX]
      ]
//.... more fields
});

Reset form after "save"
  public savedOk() {
    this.formGroup.reset();
    this.formGroup.enable();
    this.initializeForm();
  }

I do not know why when I call initialize form in ngOnInit form group is created as expected and then, if I call initialize form the form group does not show form controls with the value set in that function.
select1 should be disabled and should have the option with Value1 selected.
It can be solved with this.formGroup.get('fieldName').setValue('Value1')
and with .disabled() but I would like to use initialize function for that.
I am using Angular 7 and angular material.
Example Template example:
<form [formGroup]="formGroup">
<mat-form-field>
      <input matInput name="inputName" formControlName="inputName" required />
    </mat-form-field>

<mat-form-field>
    <mat-label>label</mat-label>
    <mat-select placeholder="label" formControlName="select1">
      <mat-option *ngFor="let op of options, trackBy: trackByFn" [value]="op.value">{{
                op.label |
                translate }}</mat-option>
    </mat-select>
  </mat-form-field>

</form>

Looking more info I think I should use the next in on save:
   this.formGroup.reset({
      select1: { value: 'Value1', disabled: true }
    });


text:
Q: how to get a json variable Whose value contains a "-" i have a  json object  that contains :
                  {
                    "-database": "URL",
                    "-id": "Veveve",
                    "value": [
                        "*.serse.pl/*",
                        "*.qq.serser/*",

                        ]
                    }

my question is :
after Accepted the json at the Clint and saved my json object at my myjson Virabel
how i set the "-id" value at ba-panel-title=""  ?
**when i do myjson.-id  i got  a 'undefined` parameter
Thank you

A: Use myjson["-id"]
console.log(myjson["-id"]);

DEMO

var myjson = {
  "-database": "URL",
  "-id": "Veveve",
  "value": [
    ".serse.pl/",
    ".qq.serser/"
  ]
};

console.log(myjson["-id"]);

A: You can pull keys and values from an object with ng-repeat. Here is a simple demo:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myjson = {
    "-database": "URL",
    "-id": "Veveve",
    "value": [
      ".serse.pl/",
      ".qq.serser/"
    ]
  };
});

KEY: {{key}} | VALUE: {{val}}

And here is an example if you have an array of objects:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myjson = [{
    "-database": "URL",
    "-id": "Veveve",
    "value": [
      ".serse.pl/",
      ".qq.serser/"
    ]
  }, {
    "-database": "URL2",
    "-id": "Wiwiwi",
    "value": [
      ".qq.serser/"
    ]
  }, {
    "-database": "URL3",
    "-id": "Uauaua",
    "value": [
      ".serse.pl/"
    ]
  }];
});

KEY: {{key}} | VALUE: {{val}}


text:
Q: Having trouble iterating through array please advise This is my attempt to create a function that reads a user move and adjusts it accordingly in an array. I know there's something simple wrong but I cannot find it.
def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#
    move = int(input("What space would you like to claim? "))

    for row in board:
        for column in row:
           if move == column:
               column = "O"
    return board

board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

EnterMove(board)
print(board)

A: Assigning to column doesn't change the contents of the list. You need to get the index and assign that. You can use enumerate() to get the indexes and values.
    for row in board:
        for i, column in enumerate(row):
           if move == column:
               row[i] = "O"

A: I think I understand what you are trying to achieve. I debugged the code and changed a couple of things. I realize that this is a basic solution but figured that it will be easily readable and traceable. I am not sure if this is what you are looking for, but I hope it helps.
Here is a program that should work if anybody else is having a similar issue and needs help:
def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#
    move = int(input("What space would you like to claim? "))
    row = 0
    while(row<len(board)):
        col = 0
        while(col<len(board[0])):
           if move == 1+row*3+col:
               board[row][col] = "0"
           col+=1
        row+=1
    return board
board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
board = EnterMove(board)
print(board)

One of the issues I noticed is that in the statement array[index], the index has to be an integer, which is not the case in the for loop you were using. I converted to while loops to increase readability and show what wasn't working.
I hope this was helpful.


text:
Q: How should I best search through a custom list generated dynamically based on id for a specific element? So, I have this scenario where I have a list of div elements of a class 'item', and want to traverse through those elements for elements with a specific attribute.
Example HTML:

Bob

Ted

Mike

Joe

With that list, my current method of selecting a specific element is through the dataset property, where I store a person's id under data-id.
Using JQuery, I have:
var specificElement = $('.item[data-id=(user id)]);

Then, I perform operations on that element such as highlighting, showing and hiding.
Now, my dilemma is whether this is actually an efficient method of sifting through the list, since I heard that accessing dataset could be slow.
Should I change my HTML schema and store the id a different way (such as using a classlist)? I am hesitant on marking each with an id such as user_bob123 since I feel like that could potentially create conflicts within the rest of the html, even though that would allow access just by
document.getElementById('user_' + id);

I am open to suggestions, and since selecting elements are a common part of my application I want to be sure to do that as efficiently as possible.

A: There's no concept of dataset in HTML5. These data- attributes are just custom attributes. That is, there's no additional overhead when retrieving elements by using a selector than it could have any other case, excepting when you get by id (i.e. document.getElementById), which may be optimized by the browser storing both ids and elements in a hash table for fast access.
BTW, if you want to optimize this access to elements with data-id, you should be able to store references of these elements in an object and access them using regular JavaScript functions:

// Vanilla JS!!
var items = [].slice.call(document.querySelectorAll(".item[data-id]"))
  .reduce(function(result, currentElement) {
    result[currentElement.getAttribute("data-id")] = $(currentElement);
    return result;
  }, {});

// Now access these elements by id, and you won't need to query the document
// anymore. Accessing object properties is actually faster than a selector:
var bob123Element = items["bob123"];

setTimeout(function() {
  bob123Element.hide();
}, 3000);

Bob

Ted

Mike

Joe

A: I'd just use ID and save a programmatic reference for future access so you don't have to keep traversing the DOM.
var users = {
    bob123: $('#user_bob123'),
    tedddd: $('#user_tedddd')
};

Then for future access, without traversing the DOM again:
users.bob123.hide();


text:
Q: Sorting an ArrayObject in php I get the following error with this code -

Warning: sort() expects parameter 1 to be array.

$array1 = new ArrayObject();

$array1->append("50");
$array1->append("30");
$array1->append("60");

sort($array1); // Should sort to 30, 50, 60.

Can anyone create a solution?

A: sort() only works on arrays. ArrayObject is an object and not an array.
Use the asort method instead ( $array1->asort(); )

A: Instead, you need to try this way:
$array1->asort();

See arrayobject.asort for more info!

A: You are seeing this issue because you are trying to sort an object. Despite its name, ArrayObject is an object not an array (see manual).
Your options are:
$array1 = new ArrayObject();

$array1->append("50");
$array1->append("30");
$array1->append("60");

$array1->asort();

or by using just an array
$array1 = array();

$array1[] = "50";
$array1[] = "30";
$array1[] = "60";

sort($array1);

You were effectively trying to use a procedural function on an object.

A: If you wish to use the sort function, you have to change the way you create your array to the following:
$array1 = array();
$array1 = array_push(array1, "50");
$array1 = array_push(array1, "30");
$array1 = array_push(array1, "60");
sort(array1);

Or even simpler:
$array1 = array("50","30","60");
sort(array1);


text:
Q: When inheriting a control in Silverlight, how to find out if its template has been applied? When inheriting a control in Silverlight, how do I find out if its template has already been applied?
I.e., can I reliably get rid of my cumbersome _hasTemplateBeenApplied field?
public class AwesomeControl : Control
{
    private bool _hasTemplateBeenApplied = false;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        this._hasTemplateBeenApplied = true;
        // Stuff
    }

    private bool DoStuff()
    {
        if (this._hasTemplateBeenApplied)
        {
            // Do Stuff
        }
    }

}

A: Nope that is the standard way to track whether the template has been applied.


text:
Q: Finding and removing html tags with PHP Simple HTML DOM Parser This is the code I am using:
include 'simple_html_dom.php';
$html = file_get_html('index.html');
echo $html->find('tr', 15);

This will find the row 15 of the table. What I want to do is to remove that row completely.
I have already tried
$html->find('tr', 15)=null;

But that does not seem to work. I have tried finding the info on the SimpleHTMLDom documentation but it does no contain much information.

A: simple_html_dom does not seems to allow the deletion.
Try with this instead:
$html = new DOMDocument();
$html->loadHTMLFile('index.html');
$element = $html->getElementsByTagName('tr')->item(15);
$element->parentNode->removeChild($element);

A: here you have a working example (works as is in Linux, but is easily adaptable).
File dom_test.php:
#!/usr/bin/php
<?php
    $html = new DOMDocument();
    $html->loadHTMLFile('index.html');
    $element = $html->getElementsByTagName('tr')->item(1);
    $element->parentNode->removeChild($element);

    echo $html->saveHTML();
?>

Where the index.html contains:

 hi 	there

                 HELLO
                 there

 hi 	there

Put both files in the same directory and execute this in the console:
php dom_test.php

The output will appears without the "HELLO there" row.
I hope that helps you.

A: You can do this with simple_html_dom, just set the outertext to the value of innertext
foreach($html->find('div') as $div) {
    $div->outertext = $div->innertext;
}


text:
Q: What's a good structure for an edit function in which all parameters are optionals? Let's get it simple, a table with three parameters (A, B and C). A is the key and is not editable, but B and C can be modified.
What's the best way of defining an editing function? Because what I have so far is...
function edit($b, $c){
    if {($b != "") && ($c != "")){
        update($b, $c);
    }elseif ($b != ""){
        update($b);
    }elseif ($c != ""){
        update($c);
    else {
        die("Anything to edit")
    }
}

In this case it's not kind of a big deal, but what if instead of two parameters there are 10 optional parameters? I'm pretty sure there must be some better way of defining such function.

A: I would run a loop on the value array (not sure how you are getting the values)
<?php

    $a = "A";
    $b = "B";
    $c = "C";
    $d = "D";
    $e = "E";

    $param = [$b, $c, $e];

    foreach($param as $value){

        // If $variable isset and not empty
        if(isset($value) && !empty($value)){

            echo ($value."<br/>");
            // update($value);

        }
    }

?>


text:
Q: Using Spring & Eureka Client in a separate project I have a project (projectA) that uses Spring-cloud Eureka and Ribbon:
@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableEurekaClient
public class ClassA extends AbstractClassA

I use it in another project (I have projectA as a maven dependency) which is a spring boot project and it works perfectly, Eureka and all. All Dependencies are injected normally. But I have some other projects that use ProjectA but don't use spring boot, just typical spring-mvc/web and I get the following error, even when I don't explicitly use ClassA, occurring at runtime:
WARN Exception encountered during context initialization - cancelling  refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [projectA.impl.ClassA]; nested exception is java.lang.IllegalStateException: Annotation @EnableDiscoveryClient found, but there are no implementations.  Did you forget to include a starter?
    at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:437)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:183)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:306)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:239)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at projectB.App.main(App.java:39)
Caused by: java.lang.IllegalStateException: Annotation @EnableDiscoveryClient found, but there are no implementations.Did you forget to include a starter?
    at org.springframework.cloud.util.SpringFactoryImportSelector.selectImports(SpringFactoryImportSelector.java:75)
    at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:429)
    ... 10 more

These are some of the dependencies in the project that failed, no parent:
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-parent</artifactId>
            <version>Angel.SR3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>com.netflix.eureka</groupId>
        <artifactId>eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>com.netflix.ribbon</groupId>
        <artifactId>ribbon-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>com.netflix.ribbon</groupId>
        <artifactId>ribbon-loadbalancer</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.netflix.ribbon</groupId>
        <artifactId>ribbon</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-commons</artifactId>
        <version>1.0.3.RELEASE</version>
    </dependency>
    .....

Any advice on what could be the issue? I looked into @EnabkeEurekaClient on github and it requires I have Eureka on the classpath, which I should given the above pom.


text:
Q: Use CreativeSDK below API level 14? For some reason the original Aviary framework has stopped working and this has forced me to migrate our code to use the new CreativeSDK instead.
Unfortunately this new SDK has a minSdkVersion of 14 = Android 4.0, but a lot of our customers still use older versions (a little over 20 % according to Googles statistics for our app).
We cannot release an app update that cuts away that many users, but is there a way to compile the app with a lower api level and then just disable the image editing for the "old api" users?

A:
is there a way to compile the app with a lower api level and then just disable the image editing for the "old api" users?

Tricky question. You can try build the app with api lv < 14 but then the creativeSDK will not be able to compile, resulting in a build error, so no.
Android 4.0 is already ~4 years old. It happens more and more that libraries drop support for older android versions (for good reason I think. Just update already!), as is the case with the creativeSDK. The minSDK requirement went from 2.3 in the aviary framework to 4.0 in the creativeSDK.
Adobe has to have done this for a reason. It is too much of a hassle to provide compatibility for 'old' versions of android, especially for complex functionality.
It is mentioned here, here and here that the creativeSDK now really requires api 14, and compatibility for older versions is not mentioned anywhere, meaning it very much likely doesn't exist.
To come back to your question, I think what would be a solution for you is to create multiple APKs for different API levels. There is some work to be done, but it is officially supported by Android, and the steps on how to achieve it are described clearly in the documentation I linked to.
Other than that, you have two options:

*

*Drop the SDK and use another library.

*Contact support and ask if they had forseen this issue and how they suggest you go about solving it.

A: As noted by Tim, the Adobe Creative SDK supports Android API 14 and up. It won't work for anything lower than that.
If you're using the Image Editor UI component, it's also worth noting that for APIs 14 and 15, the AviaryIntent.Builder will not work.
There is a workaround for that issue documented here.
Update: Note that starting in version 0.9.7 of the Creative SDK, the Image Editor supports Android API 16 and up only. This is noted in the Getting Started guide.


text:
Q: how to pass local state value to store without having an event I'm very new to redux+React. I need to pass localstate to store. I was able to do it with mapDispatch and using a click event to trigger it
 <div className="form-group">
 <button onClick={()=>this.props.onValueClick(this.state)}  type="button" className="btn btn-primary">Button</button>
   </div>

const mapDispatchToProps = (dispatch) => {

    return {

        onButtonClick: () => dispatch({type:'UP'}),
        onValueClick: (data) => dispatch({type:'SET',value:data.Value})
    }
}

This code working fine. But What i need is i need to trigger this (pass local state to store whenever local state is changed. (in this example i have to click on a button..
How can i achieve this?


text:
Q: std::ofstream sometimes fails to open file in a 'for' loop Here is the minimal reproducible code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const string TEST_FILE_PATH = "output.txt";

void write_to_file(string path, string line);
void generate_passwords(string file);

int main()
{
    generate_passwords(TEST_FILE_PATH);
    return 0;
}

void generate_passwords(string file)
{
    int count = 1;
    for (int len = 1; len <= 100; len++)
    {
        for (int i = 0; i < 100; i++)
        {
            write_to_file(file, to_string(count) + " : ");
            count++;
        }
    }
}

void write_to_file(string path, string line)
{
    ofstream file;
    file.open(path, ios::out | ios::app);

    cout << "writing line : " << line << endl;

    if (file.is_open())
    {
        cout << "file is open " << endl;
        file << line << '\n';
        cout << "written..." << endl;
    }
    else {
        cout << "FILE NOT OPEN" << endl;
    }

    file.close();
}

This is a stripped-down version of my full code, and it reproduces the same error.
With this code, I expect exactly 10,000 lines to be written to output.txt. However, it sometimes skips a random number of lines:

See how it skips numbers 6466 to 6509.
The console prints "FILE NOT OPEN" for these numbers.
This rarely happens with fewer iterations, but occurs very often with large numbers of iterations.
What could be the issue?


text:
Q: Vscode intellisense not working with pillow I can't seem to get intellisense to work on an Image object.
Image
I have tried resetting my settings and reinstalling.
The example is using pipenv but i have tested without it and it still does not work.


text:
Q: Low pass to high pass filter conversion Ripples from Mutable Instruments (open hardware) is a low pass 4th order filter. The schematic is found here https://mutable-instruments.net/modules/ripples/downloads/ripples_v40.pdf
Can I swap resistors and capacitors in the signal chain to create a high pass filter?
eg R10, C7 swapped with R8, C6
I would do this is Sallen and Key configuration but the inclusion of the OTA and VCA ICs makes me question what would be the right conversion.

A: Below shows a high pass sallen key filter on the left, and a low pass sallen key filter on the right. The resistors and capacitors are swapped. (Both high and low pass filters form a band pass). If you want to convert one sallen key configuration to the other, then swap resistors and caps

Source:


text:
Q: Use '&' to create pointer to member error I am creating a game in c++ and I have called a function, however I am getting an error saying i need to insert an ampersand to create a pointer to a member. However, I am unsure where this needs to go...
string MouseAndCatGame::prepareGrid(){
    //prepare a string that holds the grid information
    ostringstream os;
    for (int row(1); row <= SIZE; ++row)    //for each row (vertically)
    {
        for (int col(1); col <= SIZE; ++col)    //for each column (horizontally)
        {
            if ((row == cat_.getY) && (col == cat_.getX))
            {
                os << cat_.getSymbol(); //show cat
            }
            else
                if ((row == mouse_.getY()) && (col == mouse_.getX()))
                    os << mouse_.getSymbol();   //show mouse
                else
                {
                    bool holePresent(underground_.findHole(col, row));
                    if (holePresent == true) // If there is a hole at that location
                    {
                        os << HOLE; // Show hole symbol
                    }
                    else
                    {
                        if ((row == nut_.getY()) && (col == nut_.getX()))
                        {
                            os << nut_.getSymbol(); //show mouse
                        }
                        else
                        {
                            os << FREECELL;//show free grid cell
                        }
                    }
                }
        } //end of col-loop
        os << endl;
    } //end of row-loop
    return os.str();
} //end prepareGrid

The error is specifically the following:
Cat::getY': non-standard syntax; use '&' to create a pointer to member

A: It looks like you don't want a pointer to member.  You just forgot the parentheses on your function call.
            if ((row == cat_.getY()) && (col == cat_.getX()))

A: assuming getY/getX are methods of cat_ and not poorly named public variables,
this
if ((row == cat_.getY) && (col == cat_.getX))

should be
if ((row == cat_.getY()) && (col == cat_.getX()))


text:
Q: Redirect stdin to stdout while waiting for background process I have the following code:
cmd cmd_args & WAIT_PID=$!

trap "kill -s SIGTERM $WAIT_PID" SIGTERM SIGINT SIGKILL

wait $WAIT_PID

With this I want to be able to kill any background process whenever someone tries to kill this script.  However, I still want stdin to be redirected to the background process, which is not happening.
I would like to grab wait's stdin and redirect it to the background process. For that, I've tried:
wait $WAIT_PID 0>&1 1> named_pipe

But without any luck.

A: As mentioned, you can't trap SIGKILL (or SIGSTOP).
Other than that, try this:
#!/bin/bash
cmd cmd_args <&0 &
wait_pid=$!
trap "kill -s SIGTERM $wait_pid" SIGTERM SIGINT
wait $wait_pid

The <&0 will tell bash that you want cmd's stdin to be the script's stdin.
Slightly off topic, but another interesting method of dumping bytes into a running process' stdin is to send them directly to it's /proc file descriptor, as in:
echo "Stuff to send to the process" >/proc/$wait_pid/fd/0


text:
Q: Lower Semicontinuous functions and Countable Compactness Is it true that, if for any lower semicontinuous function $f : X \rightarrow (0,\infty)$, there exist $\varepsilon > 0$ such that $\varepsilon \leq f(x)$ for all $x \in X$, then $X$ is countably compact?

A: Yes. If $X$ is not countably compact, let $D=\{x_n:n\in\Bbb N\}$ be a countably infinite closed, discrete subset of $X$. Define $f:X\to(0,\to)$ by $f(x)=1$ if $x\in X\setminus D$, and $f(x)=2^{-n}$ if $x=x_n$; then $f$ is lower semicontinuous, and $\inf f[X]=0$.


text:
Q: If Vue transition-group shows no impact, what am I doing wrong? I'm still pretty new to Vue but I'm trying to apply a transition-group wrapper to a v-for group of divs and there is no impact at all after adding the following.
Is anyone able to see something wrong here?
This is a simplified version of the template:
<template>

            <transition-group name="sort" tag="div" appear>

                <SinglePost :post="post" />

            </transition-group>

</template>

And the styles tag:


text:
Q: Special Command and Caption I use the following code excessivle,
\makeatletter
\def\ifinstr#1#2{%
  \def\@ifinstr##1#2##2\@nil{%
    \ifstrempty{##2}{\@secondoftwo}{\@firstoftwo}}%
  \@ifinstr#1\@@nil#2\@nil
}

\def\popleft#1#2{%
  \edef\@tmpa{#1}%
  \expandafter\@popleft\expandafter{\@tmpa}{#1}{#2}}
\def\@popleft#1#2#3{%
  \ifinstr{#1}{|}
    {\@@popleft{#2}{#3}\q@nil#1\q@stop}
    {\@@popleft{#2}{#3}\q@nil#1|\q@stop}}
\def\@@popleft#1#2\q@nil#3|#4\q@stop{\edef#1{#4}\edef#2{#3}}

\DeclareRobustCommand*\assignvalues[2]{\@assignvalues{#1}{#2}}
\def\@assignvalues#1#2{%
  \edef\@tmpb{#1}\edef\@tmpc{#2}%
  \popleft\@tmpb\currentvalueA
  \popleft\@tmpc\currentvalueB
  \csedef{\currentvalueA}{\currentvalueB}%
  \ifdefempty\@tmpb{}{\assignvalues\@tmpb\@tmpc}%
}
\makeatother

But this piece of code doesn't work if i use the caption command in this way...
\assignvalues{bcaption}{Äußere Restfeuchte}

....
\end{pspicture}
\caption[Warscheinlichkeitsverteilung~\protect\bcaption]{\space~\protect\bcaption\space (AD)}

The first compile works, but the second one generates an entry in the lof file the following entry will be shwon as
\contentsline {figure}{\numberline {1.12}{\ignorespaces Wahrscheinlichkeitsplot Äu\T 1\ss ere Restfeuchte Rohstoff C}}{11}{figure.caption.18}

Has anybody an idea what the problem could be, for sure its a combination of the code above and the caption argument, which has to be robust. But I cannot solve the problem at the moment.
Any ideas?
Update 1: MWE (non Working more than one times)
\documentclass{scrreprt}
\usepackage[T1]{fontenc}
\usepackage[ansinew]{inputenc}
\usepackage{lmodern}
\usepackage{textcomp} % Euro-Zeichen etc...
\usepackage{etoolbox}
\usepackage{graphicx}
\usepackage{caption}[2008/08/24]
\usepackage{pstricks}
\usepackage{pst-all}
\usepackage{pstricks-add}

\makeatletter
\def\ifinstr#1#2{%
  \def\@ifinstr##1#2##2\@nil{%
    \ifstrempty{##2}{\@secondoftwo}{\@firstoftwo}}%
  \@ifinstr#1\@@nil#2\@nil
}

\def\popleft#1#2{%
  \edef\@tmpa{#1}%
  \expandafter\@popleft\expandafter{\@tmpa}{#1}{#2}}
\def\@popleft#1#2#3{%
  \ifinstr{#1}{|}
    {\@@popleft{#2}{#3}\q@nil#1\q@stop}
    {\@@popleft{#2}{#3}\q@nil#1|\q@stop}}
\def\@@popleft#1#2\q@nil#3|#4\q@stop{\edef#1{#4}\edef#2{#3}}

\DeclareRobustCommand*\assignvalues[2]{\@assignvalues{#1}{#2}}
\def\@assignvalues#1#2{%
  \edef\@tmpb{#1}\edef\@tmpc{#2}%
  \popleft\@tmpb\currentvalueA
  \popleft\@tmpc\currentvalueB
  \csedef{\currentvalueA}{\currentvalueB}%
  \ifdefempty\@tmpb{}{\assignvalues\@tmpb\@tmpc}%
}
\makeatother

\newcommand{\blankimageX}{
\begin{figure}[!ht]
\begin{center}
\psset{xunit=\scalex cm,yunit=\scaley cm, runit=\scaler cm}
\psCancel{\begin{pspicture}(\xstart,\ystart)(\xend,\yend)
% Achsen
% X-Achse
\psline(\xstart,\yistart)(\xend,\yistart)
% Y-Achse
\psline(\xstart,\yistart)(\xstart,\yend)
\psline(\xend,\yistart)(\xend,\yend)
\psline(\xstart,\yend)(\xend,\yend)
\end{pspicture}}
\caption[Wahrscheinlichkeitsplot \bcaption]{Wahrscheinlichkeitsplot \bcaption nach Anderson-Darling}
    \label{\lab}
\end{center}
\end{figure}
}

\begin{document}
\tableofcontents
\listoffigures

\chapter{Chapter A}
\assignvalues{scalex|scaley|scaler|xstart|xend|ystart|yend|yistart}{1|1|1|0|8|0|5|-1}
\assignvalues{bcaption|lab}{Äußere Restfeuchte|fig:picdesc}

\bcaption

\section{Section A}
\chapter{Chapter B}

\blankimageX

\section{Section B}
\end{document}

LG Goldnas

A: It's quite hard to follow the code; but the problem is in the fact that you're using \edef on input such as Äußere which is very dangerous as it produces all the instructions to print the characters.
Use \protected@edef instead for the token lists that can contain these "high bit set" characters; etoolbox provides also \protected@csedef.
Here's the amended code with a minimal example:
\documentclass{scrreprt}
\usepackage[T1]{fontenc}
\usepackage[ansinew]{inputenc}
\usepackage{lmodern}
\usepackage{etoolbox}

\makeatletter
\def\ifinstr#1#2{%
  \def\@ifinstr##1#2##2\@nil{%
    \ifstrempty{##2}{\@secondoftwo}{\@firstoftwo}}%
  \@ifinstr#1\@@nil#2\@nil
}

\def\popleft#1#2{%
  \protected@edef\@tmpa{#1}%
  \expandafter\@popleft\expandafter{\@tmpa}{#1}{#2}}
\def\@popleft#1#2#3{%
  \ifinstr{#1}{|}
    {\@@popleft{#2}{#3}\q@nil#1\q@stop}
    {\@@popleft{#2}{#3}\q@nil#1|\q@stop}}
\def\@@popleft#1#2\q@nil#3|#4\q@stop{\protected@edef#1{#4}\protected@edef#2{#3}}

\DeclareRobustCommand*\assignvalues[2]{\@assignvalues{#1}{#2}}
\def\@assignvalues#1#2{%
  \protected@edef\@tmpb{#1}\protected@edef\@tmpc{#2}%
  \popleft\@tmpb\currentvalueA
  \popleft\@tmpc\currentvalueB
  \protected@csedef{\currentvalueA}{\currentvalueB}%
  \ifdefempty\@tmpb{}{\assignvalues\@tmpb\@tmpc}%
}
\makeatother

\begin{document}
\tableofcontents
\listoffigures

\chapter{Chapter A}
%\assignvalues{scalex|scaley|scaler|xstart|xend|ystart|yend|yistart}{1|1|1|0|8|0|5|-1}
\assignvalues{bcaption|lab}{Äußere Restfeuchte|fig:picdesc}

\begin{figure}
\caption[Wahrscheinlichkeitsplot \bcaption]{Wahrscheinlichkeitsplot \bcaption{} nach Anderson-Darling}
    \label{\lab}
\end{figure}

\end{document}


text:
Q: Find vertex coordinates of a square given their distances $p,\>s,\>q,\>r$ to an inner point
The figure represents a square, with P a point inside the square. The four segments are drawn from P to the four vertices of the square and they are named p, q, r, s.
If the bottom-left vertex is at origin and the sides of the square are parallel to the axes (square is drawn in the first quadrant), find the co-ordinates of other three vertices if the measures of p, q, r, s are given.
I'm seeking your help.

A: Well, as it,s a square $C=(0,0); A=(0,w); E=(w,w); D=(w,0)$ where $w$ is the side of the square.
Law of cosines applied to $\triangle APE$ says that $q^2 = r^2 + w^2 - 2rw \cos \angle PAE$.
Applied to to $\triangle APC$ we have $p^2 = r^2+ w^2 - 2rw \cos (90 -\angle PAE)$.
By my reckoning   that should be enough to solve.  If not we can keep going
$r^2 = p^2 + w^2 -2pw \cos(\angle ACP)$.
etc.
If you are into that whole symmetry thing but not into a $w$ coefficient in quadratic equation jazz you can do the interior angles.
$w^2 = r^2 + q^2 - 2rq\cos \theta$
$= r^2 + p^2 - 2rp \cos \eta$
$= p^2 +s^2 - 2ps\cos \zeta$
$= s^2 +q^2 - 2sq\cos \beta$
$\theta + \eta + \zeta + \beta = 360^\circ$.

A:
Let $P(x,y)$ and $a$ the side length of the square. Then,
$$x^2+y^2=p^2, \>\>\>
(a-x)^2+y^2=s^2,\>\>\> x^2+(a-y)^2=r^2
$$
The 2nd and 3rd equations leads to
$x= \frac{a^2+p^2-s^2 }{2a}$ and $y= \frac{a^2+p^2-r^2}{2a}$.
Substitute them into the 1st equation to get
$$ a^4 -(s^2+r^2)a^2 +\frac12[(s^2-p^2)^2+ (r^2-p^2)^2]=0
$$
Solve for $a$ to obtain the vertex coordinates $(0,a)$, $(a,0)$ and $(a,a)$ with
$$a= \left(\frac{s^2+r^2}2 +\left( p^2(s^2+r^2)-p^4 -\frac14(s^2-r^2)^2 \right)^{1/2} \right)^{1/2}
$$
Note that $q^2 = s^2+r^2-p^2$ can not be separately specified. For example, $p=3$, $s=7$ and $r=9$ result in $q=11$ and $a=\sqrt{65+7\sqrt{17}}=9.7$.


text:
Q: Removing all nodes with specific value in firebase My firebase real time database structure looks like this:
"aHB1ASJ895Adsws2": { // User id
    "lat": "48.023288102" // Users lat
    "lng": "-122.3324202" // and lng values

Before adding another of these to the parent node I would like to delete all nodes that have the current users id.
For example, if the current user id is 123 and there are 2 nodes which have a user id value of 123 then these nodes should be deleted before adding a new location for the current user into the firebase real time database.
How can I remove nodes with the same user id as the current user with the firebase real time database?


text:
Q: Retrive data of today and last trhee days and calculate average in mysql I need to Retrive data of today and last trhee days and calculate average in mysql.
My query is
select  aqi_id,
r_aqi_id,
avg(aqi_value),
added_date
from
sfr_aqi
 order by
ra.added_date desc
limit 0,3

Please suggest me better way.

A: Try this one NOW() - INTERVAL 3 DAY for last three days
select  aqi_id,
r_aqi_id,
avg(aqi_value),
added_date
from
sfr_aqi
where ra.added_date >= NOW() - INTERVAL 3 DAY
group by aqi_id /* you can also use group by ra.added_date */
order by
ra.added_date desc
limit 0,3


text:
Q: how to test jquery-ui datepicker with Qunit I'm kind of new to Qunit, and would like to ask a question.
I have created a JavaScript file to simply use datepicker like below, and created a test-code using Qunit.
What I want to do is to show the calendar and select a date, and assert that date has been selected.
My problem here is that I was able to show the calendar, by .trigger("focus") but couldn't select anything.
Does anyone know how I can do this??
datepicker-basic.js

$(function () {
  $('#jquery-ui-datepicker').datepicker();
});

test-datepicker.html

<!DOCTYPE html>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>test datepicker.js</title>
   <link rel="stylesheet" href="jquery-ui/jquery-ui.css">
   <link rel="stylesheet" href="qunit/qunit-2.0.1.css">

   <input type="text" id="jquery-ui-datepicker">

test-datepicker.js

QUnit.test( "basic", function( assert ) {
  // initiate input value
  $("#jquery-ui-datepicker").val("");

  // focus on input-textbox and select date on calendar
  $("#jquery-ui-datepicker").trigger("focus").
   simulate( "keydown", { keyCode: $.ui.keyCode.ENTER } );

  // get selected date from input-textbox
  var actual = document.getElementById("jquery-ui-datepicker").value;
  // create expected value
  var today = new Date();
  var expected = formatDate(today);

  // assert
  assert.ok(actual === expected, "selected value from calendar correctly");
});

A: Oh, I think I found the answer.
I had to add a trigger.("focus").
Here's what I changed, and it worked.
before:
  // focus on input-textbox and select date on calendar
  $("#jquery-ui-datepicker").trigger("focus").
      simulate( "keydown", { keyCode: $.ui.keyCode.ENTER } );

after:
  // focus on input-textbox
  $("#jquery-ui-datepicker").trigger("focus");
  // select date on calendar
  $("#jquery-ui-datepicker").trigger("focus").
      simulate( "keydown", { keyCode: $.ui.keyCode.ENTER } );


text:
Q: SyncFailed Error:Cause: org/jetbrains/plugins/gradle/tooling/ModelBuilderService I have a project which I try to open in Android Studio however when the project is imported I receive an error

Error:Cause: org/jetbrains/plugins/gradle/tooling/ModelBuilderService

I searched on google and found that this is a common issue faced on windows. However all the solutions provided are:

*

*Delete .gradle.

*Invalidate Cache/Restart from File in Android Studio.

*Delete debug folders and files.

Here's what I've tried in addition to the above list.

*Reinstalled Android Studio.

*Deleted Android Studio Settings manually from C:/Users/<username>/.android<> old directories.

*Deleted %temp% folder.

This project works well in all PCs with Android Studio except this one.

A: So the problem was solved by deleting the .gradle folder. Unfortunately none of the answers that I referred to described which .gradle folder I was supposed to delete.
What I did was deleted the .gradle folder inside the project structure. What you have to do is delete the .gradle folder located in
Windows:
C:/Users/<username>/.gradle.

MacOS:
~/Users/<username>/.gradle

To view hidden files on Mac press command+shift+.

A: Here is a very simple solution,open your gradle-wrapper.properties file in your project and change your distributionUrl by downgrading/upgrading it.
For example, if gradle 5.1 is giving you problems, you can downgrade to 4.9
distributionUrl=https://services.gradle.org/distributions/gradle-4.9-all.zip

A: On mac use this command to delete .gradle folder.
rm -rf ~/.gradle

A: You may try the following steps:

*

*Close Android Studio

*Rename .gradle folder

*Open project again

After that Android studio will automatically download .gradle folder

A: Your Android Studio must be 3.4 or above Latest Version.
And Gradle file should be:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-5.4.1-all.zip
These error comes when you used below Android Studio 3.4 Version.

A: Upgrade the IDE to an updated version and remove it as versions that are not available in Android Studio that are on your computer. eg. AndroidStudio2.1 located in C:\Users\

A: I had also this problem with android studio 3.1.1, it resolved by deleting latest gradle(for me 5.1.1) in .gradle folder
I have to mention that gradle 5.1.1 is not compatible with 3.2 and older

A: This one works for me.

*

*Check your build gradle classpath version

*Open the file gradle>wrapper>gradlegradle-wrapper.properties in your project

*Check the version

*Use this version in build gradle and sync the project

A: The steps below helped me get out of this situation:
Goto -> File -> Invalidate Caches / Restart -> Invalidate and Restart

if necessary cleans project and re-build
Thanks!


text:
Q: Is there any convinient way to check the values of the member variables of a class in Eclipse? I am writing some code that makes use of the std::vector class to store objects of a user-defined class. For debugging, I need to keep watch on a few particular member variables of this class. Towards this end, I went to the variables view in my debugger perspective and put the relevant member variables on watch. However, in the expressions view, I ended up with variables that looked something like this:

((((((class std::_Vector_base >::_Vector_impl_data) ((((class std::_Vector_base >) ((baseExpression).baseExpression)))._M_impl)))._M_start))->expressionPtr)

Needless to say, this is pretty annoying to look at.
I tried editing the names of the variables under the "expression" column in the expressions view, however that seemed to remove the entire variable from the watch window. For example, I would try to set the above name to simply "expressionPtr" only to be greeted by the following errors:

Multiple errors reported.

1) Failed to execute MI command:
-var-create - * expressionPtr
Error message from debugger back end:
-var-create: unable to create variable object

2) Unable to create variable object

3) Failed to execute MI command:
-data-evaluate-expression expressionPtr
Error message from debugger back end:
No symbol "expressionPtr" in current context.

4) Failed to execute MI command:
-var-create - * expressionPtr
Error message from debugger back end:
-var-create: unable to create variable object

Is there a way to assign unique identifiers to member variables while debugging to make it a bit easier on the eyes? Also, since the vector class will hold an indefinite number of objects during run-time, I would also like to keep track of the member variables of each object. For example, consider the following code:
class Foo
{
public:
    int a_var;
    int b_var;
};

int main ()
{
    Foo a;
    Foo b;
    //some code to work with Foo::a_var and Foo::b_var
}

I would like keep track of the member variables of both a and b as and when they are allocated.
Some help will be really appreciated. Thanks in advance!

A: After messing around a bit, I figured out the solution to this and it was stupidly simple. All I had to do was add the member object variable of my vector object that contained my class objects to the watch list. I, however, was trying to add each member variable to the watch list individually like a complete idiot.
Anyway, after putting the object titled std::_Vector_base<Expression, std::allocator<Expression> >::_Vector_impl_data<Expression> >::_Vector_impl_data of the type std::_Vector_base<Expression, std::allocator<Expression> >::_Vector_impl_data on watch, my problem was solved. After that, all I have to do was expand this object which would now be listed in the expressions view and viola! I had all my required member variables right where I could see them.


text:
Q: Why we take two focuses in concave and convex lenses before the lens and behind the lens
 we take f(one) and 2f(one) before the lens  and f(two) and 2f(two) behind the lens.

A: You can place an object anywhere you like with respect to the lens. In one diagram, the author simply chose the separation to be twice the focal length. In this case, the rules for ray tracing tell you the image will also happen to be the same distance from the lens. This doesn't work with any other separation.
Also note that the one place you would have trouble placing the object is at the focal point itself. The standard rules for drawing light rays may lead to problems in that case.


text:
Q: Can't set tabIndex more than once in IE8 I've got a large HTML data entry table, implemented as a large matrix of input fields. I'm trying to implement a JavaScript-based feature that dynamically switches between a row-wise and column-wise tab order.
The approach I'm using seems to only work "once" in IE8. That is, once the tab index has been set using JavaScript, any subsequent changes are ignored - and the tab ordering reverts to its default state.
The table inputs have classnames like so:
.row-0 .col-0 | .row-0 .col-1 | .row-0 .col-2 | ...
--------------+---------------+---------------+----
.row-1 .col-0 | .row-1 .col-1 | .row-1 .col-2 | ...

My JavaScript looks like this:
nCols = ...;
nRows = ...;

function setTabOrder(byCol) {
    var max = byCol ? nCols : nRows;
    var selector = byCol ? '.col-' : '.row-';
    var tabIndex = 1;
    for (var i = 0; i < max; i++) {
        $(selector + i).each(function () {
            this.tabIndex = tabIndex++;
            //this.value = this.tabIndex;
        });
    }
}

Actually, it seems I can only tab by column if I invoke setTabOrder(true); when the page loads, i.e.:
$(function () {
    setTabOrder(true);
});

Any ideas why this isn't working as I expect it to?

A: I would recommend you do this a different way, which is the put an event handler for tab keys on all the entry items and then use that key's event to look for the next item in the row or column, depending on what you want, and then call setFocus() on that input. You can do the opposite for shift+tab if you want.
This avoids your problem and doesn't really answer your question, but it also could eliminate the need for this .col- and .row- naming scheme you have which will probably result in an easier to maintain design.


text:
Q: Width equal to content I'm experiencing some trouble with the width property of CSS. I have some paragraphs inside a div. I'd like to make the width of the paragraphs equal to their content, so that their green background looks like a label for the text. What I get instead is that the paragraphs inherit the width of the div father node which is wider.

#container {
  width: 30%;
  background-color: grey;
}

#container p {
  background-color: green;
}

Sample Text 1

Sample Text 2

Sample Text 3

A: set width attribute as: width: fit-content
demo: http://jsfiddle.net/rvrjp7/pyq3C/114

A: Using display:inline-block; will not work for long sentences without spaces like HiHowAreYouHopeYouAreDoingGood...etc to fix this consider using word-wrap: break-word; instead
it's made to allow long words to be able to break and wrap onto the next line., also Facebook using it
Example

#container {
    width: 40%;
    background-color: grey;
    overflow:hidden;
    margin:10px;
}
#container p{
    display:inline-block;
    background-color: green;
}
.flex{
    display: flex;
}

#wrap {
    width: 30%;
    background-color: grey;
    overflow:hidden;
    margin:10px;
}
#wrap p{
   word-wrap: break-word;
    background-color: green;
}

 display:inline-block;

With spaces

Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1

No specaes (not working )

HiHowAreYouHopeYouAreDoingGoodHiHowAreYouHopeYouAreDoingGoodHiHowAreYouHopeYouAreDoingGood

  word-wrap: break-word;

With spaces

Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1

No specaes (working )

HiHowAreYouHopeYouAreDoingGoodHiHowAreYouHopeYouAreDoingGoodHiHowAreYouHopeYouAreDoingGoodHiHowAreYouHopeYouAreDoingGood

A: Set display:inline-block and then adjust your margins.
fiddle here: http://jsfiddle.net/Q2MrC/

A: You can use either of below :-
1) display : inline-block :
http://jsbin.com/feneni/edit?html,css,js,output
Uncomment the line
 float:left;
 clear:both

and you will find that parent container has collapsed.
2) Using display : table
http://jsbin.com/dujowep/edit?html,css,js,output

A: You can use flex to achieve this:
.container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

flex-start will automatically adjust the width of children to their contents.

A: I set width as max-content and it worked for me.
width: max-content;

A: Try using a  element instead. Or if you prefer, try display:inline

A: If you are using display: flex for whatever reason and need on browsers like Edge/IE, you can instead use:

display: inline-flex

With ~97% browser support for inline-flex.

A: By default p tags are block elements, which means they take 100% of the parent width.
You can change their display property with:
#container p {
   display:inline-block;
}

But it puts the elements side by side.
To keep each element on its own line you can use:
#container p {
   clear:both;
   float:left;
}

(If you use float and need to clear after floated elements, see this link for different techniques: http://css-tricks.com/all-about-floats/)
Demo: http://jsfiddle.net/CvJ3W/5/
Edit
If you go for the solution with display:inline-block but want to keep each item in one line, you can just add a
 tag after each one:

Sample Text 1

Sample Text 2

Sample Text 3

New demo: http://jsfiddle.net/CvJ3W/7/

A: The solution with inline-block forces you to insert
 after each element.
The solution with float forces you to wrap all elements with "clearfix" div.
Another elegant solution is to use display: table for elements.
With this solution you don't need to insert line breaks manually (like with inline-block), you don't need a wrapper around your elements (like with floats) and you can center your element if you need.
http://jsfiddle.net/8md3jy4r/3/

A: Adding display: inline-block; to the p styling should take of it:
http://jsfiddle.net/pyq3C/
#container p{
    background-color: green;
    display: inline-block;
}

A: Despite using display: inline-block. My div would fill the screen width when the children elements had their widths set to % of parent. If anyone else is looking for a solution to this and doesn't mind using screen proportion instead of parent proportion, replace the % with vw for width (Viewport Width), or vh for height (Viewport Height).

A: just use  display: table; on your case.

A: You can use CSS property like this:
div {
    display: inherit;
}

I hope this helps.


text:
Q: If I know the lambdas for each manifest variable, how would I calculate the correlation matrix in factor analysis? I had a question as it relates to factor analysis. If I know the lambdas for each manifest variable. For example:
$\left\{\begin{array}{l}
X_{1}=0.7 \xi_{1}+0.1 \xi_{2}+\varepsilon_{1} \\
X_{2}=0.9 \xi_{1}+0.5 \xi_{2}+\varepsilon_{2} \\
X_{3}=0.3 \xi_{1}+0.2 \xi_{2}+\varepsilon_{3}
\end{array}\right\}$
How would I derive the correlation matrix? If you would like to solve it in order to help with the explanation that would be great, but I'm more just asking for a bit of an explanation on how you would calculate when you are given the factor loadings/lambdas as it pertains to factor analysis.
As per the comments the above is of the form:
$\left\{\begin{array}{l}
X_{1}=\lambda_{11} \xi_{1}+\lambda_{12} \xi_{2}+\cdots+\lambda_{1 m} \xi_{m}+\varepsilon_{1} \\
X_{2}=\lambda_{21} \xi_{1}+\lambda_{22} \xi_{2}+\cdots+\lambda_{2 m} \xi_{m}+\varepsilon_{2} \\
X_{3}=\lambda_{31} \xi_{1}+\lambda_{32} \xi_{2}+\cdots+\lambda_{3 m} \xi_{m}+\varepsilon_{3}
\end{array}\right\}$
This is why I state that I know the lambdas. My apologies if this wasn't clear.

A: The formula you want is:
$\Sigma = \Lambda\Phi\Lambda' + \varepsilon$
Where:
$\Sigma$ is the implied covariance matrix.
$\Lambda$ is the loading matrix (and $\Lambda'$ is the transposed loading matrix).
$\varepsilon$ is the error matrix
$\Phi$ is the factor covariance matrix. If your solution is orthogonal and standardized, then $\Phi$ is an identity matrix, and you can ignore it.


text:
Q: Does SCP lock the file it is transfering? Have a situation where we have an application log sitting out on an AIX server.  The log is being continually written to from the application, and we have users on Windows who want to view the file.  What they've been doing is using WinSCP to transfer the file to their desktop and they open it using a text editor.
What I think might be happening is scp is locking the file for the duration of the transfer, and the application ceases to be able to write to the file.  The reason I believe this is the log file will stop growing at random points during the day.
Is that what perhaps is going on?

A: Why don't you try this.  Start scp'ing a large file then run lsof /path/to/file on the AIX server and see what the FD column says.
From the lsof man page:

   FD         is the File Descriptor number of the file or:
                   cwd  current working directory;
                   Lnn  library references (AIX);
                   err  FD information error (see NAME column);
                   jld  jail directory (FreeBSD);
                   ltx  shared library text (code and data);
                   Mxx  hex memory-mapped type number xx.
                   m86  DOS Merge mapped file;
                   mem  memory-mapped file;
                   mmap memory-mapped device;
                   pd   parent directory;
                   rtd  root directory;
                   tr   kernel trace file (OpenBSD);
                   txt  program text (code and data);
                   v86  VP/ix mapped file;
              FD is followed by one of these characters, describing the mode under which the file is open:
                   r for read access;
                   w for write access;
                   u for read and write access;
                   space if mode unknown and no lock
                        character follows;
                   `-' if mode unknown and lock
                        character follows.
              The mode character is followed by one of these lock characters, describing the type of lock applied to the file:
                   N for a Solaris NFS lock of unknown type;
                   r for read lock on part of the file;
                   R for a read lock on the entire file;
                   w for a write lock on part of the file;
                   W for a write lock on the entire file;
                   u for a read and write lock of any length;
                   U for a lock of unknown type;
                   x for an SCO OpenServer Xenix lock on part of the file;
                   X for an SCO OpenServer Xenix lock on the entire file;
                   space if there is no lock.
              See the LOCKS section for more information on the lock information character.
              The FD column contents constitutes a single field for parsing in post-processing scripts.

If you do this, on Linux at least, you'll see that the FD column is "3r" which means it has some sort of read lock but I'm not sure what the 3 in front of it means.

A: Most Unix programs don't use locking or when they use it, it's not mandatory, so I doubt locking is stopping your log from growing. More likely the SCP transfer is slowing down the log writing.


text:
Q: Why is zero-initialization not the default for non-initialized variables in c++? Is there a compiler option to force it? In most languages I know, scalar-type variables are zero-initialized by default, if they were not initialized in the code.
Why doesn't this happen in c/c++? The only reason I could think of is performance, but

*

*is it really that performance-consuming, if I do initialize it?

*is it preferable to have undefined behavior?

*if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?

Wouldn't it be easier to explicitly tell the compiler somehow not to zero-initialize a variable, if this might be a performance issue?
An finally my question:
Is there a gcc option to tell the compiler to zero-init by default?

A: The down-side: Potential errors because of uninitialized values.
The up-sides:

*

*Efficiency. You don't pay for it if you don't need it.

*The compiler doesn't add assumptions about the right init value. Per @chris in the comments to the OP, you can get a false sense of security since 0 is not always the right initialization value. If it should start as -1, then 0 is wrong.

The mitigations:

*

*Use constructors to initialize your non-POD types

*Use "Almost Always Auto" to enforce initialization at declaration time. (Or as @Peter notes in the comments, use explicit types but don't declare a variable until you can properly initialize it. This is implied by AAA, but AAA makes it harder to get wrong since you can't accidentally forget to initialize because the initialization carries the type information also.)

*Crank up compiler warnings. For gcc, use -Wall -Werror, which includes -Wuninitialized and then will error on uninitialized values.

The origin: In the hoary old days of C, all declarations came first before initialization. Compare this example from the K&R book:
int main(void)
{
  double sum, atof(char s[]);
  char line[MAXLINE];
  int getline(char line[], int max);

  sum = 0;
  while (getline(line, MAXLINE) > 0)
    printf("\t%g\n", sum += atof(line));
  return 0;
}

C++ retained compatibility with C in this regard, but that came with what is an unfortunate default behavior.

A: One of the founding principals of c++ is to not force developers to pay for what they don't use. If you write something like int x; x = 1; then you shouldn't have to pay for the zero initialization of x, even if that cost happens to be very tiny.
Edit : Regarding your other two points

is it preferable to have undefined behavior?

Undefined behavior is not necessarily a bad thing to have in the language (you can argue both ways). It's definitely a bad thing if you write code that causes it. Notably it gives more freedom to implementers and  enables important optimizations.

if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?

It's not undefined behavior to have an uninitialized variable. It's undefined behavior to try to read from one.

A: The problem with zero initializing variables automatically is that not all your variables should have zero as their initial value. If you forget to initialize a variable with its correct value, the compiler can easily warn you that you used an uninitialized variable.
However if the compiler initialized every variable to zero whether it was your intention or not, then you would never know when you forgot to give them their correct value because the compiler would be unable to tell you.
Example:
std::string some_input = "27";

// ...

int i;
std::istringstream(some_input) >> i; // give i a value

// ...

std::cout << "stuff: " << i << '\n'; // use i here

Now what if I forget to give i a value?
int i;
// whoopsie I forgot to give i its value

// ...

std::cout << "stuff: " << i << '\n'; // COMPILER WARNING uninitialized!

Now what happens if the compiler (or I) zero initializes it?
int i = 0;
// whoopsie I forgot to give i its value

// ...

std::cout << "stuff: " << i << '\n'; // oopsie, output the wrong value, undetectable!

Zero initializing can seem like your friend but, if the variable should not contain zero, making it zero is giving it the wrong value. That is a silent corrupting influence on your data that is hard to spot.

A:
is it really that performance-consuming, if I do initialize it?

Performing zero initialisation is potentially more performance-comsuming than not performing it, yes.

is it preferable to have undefined behavior?

It is preferable to let the programmer decide whether they want performance (no zero initalisation before assigning the value later) and potential for UB in case of a bug or whether they want deterministic behaviour upon such bug (by explicitly value-initialising even when it is unnecessary).
At least, it was preferred by the people who designed C++ (and C before that). I'm sure it is still preferred by many who choose to use C++, considering there exists languages which don't have UB that could have been chosen instead.

if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?

Sometimes you don't have the value to which the value should be initialised to until after the object is created. In such case, you can assign the value later. By not initialising to zero, you win not having to set the value more than once.

A:
is it really that performance-consuming, if I do initialize it?

Tiny overhead is still overhead, hence yes it is.

is it preferable to have undefined behavior?

If the alternatives are worse performance or declaring something as not valid code then yes it is preferable to declare wrong usage as undefined behaviour.

if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?

Usually you declare variable only when you use them, but consider this contrived example
int a,x;
if (some_condition) {
    x = foo();
} else {
    a = foo();
    x = foo(a);
}
return x;

It is a bit contrived (you would probably declare a only when you need it), but if every variable would get initialized, then this code would suffer some overhead for no good reason.

A: I personally would find this useful - as a convenience - if it was optional.  Perhaps:
class MyClass
{
    ...
} = 0;

Then, for example, if I add members to my class, I don't have to mess around zero initialising them.

A: These are from C++ Core Guidelines:

*

*ES.20 : Always initialize an object

*ES.21: Don't introduce a variable (or constant) before you need to use it

*ES.22: Don't declare a variable until you have a value to initialize it with

More can be found here.
As far as I know, global variables will be explicitly 0, but locals will have a different value (in case of a bool variable, this will lead to true).
Visual Studio(just an example), in DEBUG mode, explicitly initializes variables to given values(which can be noticed easily, usually cause an out of bound error or access violation). In RELEASE mode, memory is not explicitly initialized and it just keeps the content that was there before.


text:
Q: Where's error in implementation of minimax algorithm? There is one little problem with it's implementation for a Tic-Tac-Toe game. For the following combination:
['x', 'o', 'e',
 'o', ' e', 'e',
 'e', ' e', 'e']

the best choice would be
['x', 'o', 'e',
 'o', ' x', 'e',
 'e', ' e', 'e']

but it returns as I suppose the nearest suitable one:
['x', 'o', 'x',
 'o', ' e', 'e',
 'e', ' e', 'e']

And in this case AI loses.
Here is the code:
var board = ['x', 'o', 'e', 'o', 'e', 'e', 'e', 'e', 'e'];
var signPlayer = 'o';
var signAI = (signPlayer === 'x') ? 'o' : 'x';

game = {
    over: function(board) {
        for (var i = 0; i < board.length; i += 3) {
            if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
                return board[i] !== 'e' ? board[i] : false;
            }
        }
        for (var j = 0; j < 3; j++) {
            if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
                return board[j] !== 'e' ? board[j] : false;
            }
        }
        if ((board[4] === board[0] && board[4] === board[8]) ||
        (board[4] === board[2] && board[4] === board[6])) {
            return board[4] !== 'e' ? board[4] : false;
        }
        return ( board.every(function(element) {
            return element !== 'e';
        }))
    },
    winner: function(board) {
        return game.over(board);
    },
    possible_moves: function(board, sign) {
        var testBoard = [],
        nextBoard;
        for (var i = 0; i < board.length; i++) {
            nextBoard = board.slice();
            if (nextBoard[i] === 'e') {
                nextBoard[i] = sign;
                testBoard.push(nextBoard);
            }
        }
        return testBoard;
    }
}

function moveScore(board) {
    var result = game.winner(board);

    if (result === signPlayer) {
        return -100;
    }
    if (result === signAI) {
        return +100;
    }
    return 0;
    //Game is a draw
}

function max(board) {

    if (game.over(board)) {
        return board;
    }
    var newGame = [];
    var bestMove = [];
    var score;
    var best_score = -Infinity;
    var movesArray = game.possible_moves(board, signAI);

    for (var i = 0; i < movesArray.length; i++) {
        newGame = movesArray[i].slice();
        score = moveScore(min(newGame));
        if (score > best_score) {
            best_score = score;
            bestMove = newGame;
        }
    }
    return bestMove;
}

function min(board) {

    if (game.over(board)) {
        return board;
    }
    var newGame = [];
    var worstMove = [];
    var score;
    var worst_score = +Infinity;
    var movesArray = game.possible_moves(board, signPlayer);

    for (var i = 0; i < movesArray.length; i++) {
        newGame = movesArray[i].slice();
        score = moveScore(max(newGame));
        if (score < worst_score) {
            worst_score = score;
            worstMove = newGame;
        }
    }
    return worstMove;
}

max(board);

A: There are the following issues:

*

*The over method gives wrong output for some boards, like for instance for this board:
['e', 'e', 'e', 'o', 'o', 'o', 'x', 'x', 'e']

It will actually stop looking after it finds the three e values in the first three elements and return false, i.e. it does not see the win on the second row for o. To fix, change this line:
return board[i] !== 'e' ? board[i] : false;

to:
if (board[i] !== 'e') return board[i];

This will make the function continue with the other checks if it finds three e in a row. Similar fixes are necessary in the other loops (except the very last one).

*Although the minimax algorithm visits the nodes in the search tree succesfully, it does not carry the found leaf-score (0, -100 or 100) back up in the search tree. Instead you recalculate each position's score by just looking at a static board configuration, ignoring the best/worst score you could get from the recursive call. To fix this, let the min and max function not only return the best move, but also the score associated with it. So replace this:
return bestMove;

with:
return [best_score, bestMove];

And then you pick up the score from the recursive call, if you replace this:
score = moveScore(min(newGame));

with:
score = min(newGame)[0];

You need to do a similar change for the case where the game is over. Replace this:
if (game.over(board)) {
    return board;
}

with:
if (game.over(board)) {
    return [moveScore(board), []];
}

Note that this is the only right moment to call moveScore. The second element of the array should be the best move, but as there is no move, it is better to just use an empty array for that.

*This is a minor issue: you don't actually use the best move you get from the main call to max. With the above change, you could get both the best move and its score in the main call:
[score, nextBoard] = max(board);

Here is your corrected code, with some additional code at the end to allow a game to be played by clicking on a 3x3 grid. For that purpose I have changed the code e to a space, as it looks better on a printed board:

var board = ['x', 'o', ' ', 'o', ' ', ' ', ' ', ' ', ' '];
var signPlayer = 'o';
var signAI = (signPlayer === 'x') ? 'o' : 'x';

var game = {
    over: function(board) {
        for (var i = 0; i < board.length; i += 3) {
            if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
                //return board[i] !== ' ' ? board[i] : false;
                if (board[i] !== ' ') return board[i];
            }
        }
        for (var j = 0; j < 3; j++) {
            if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
                //return board[j] !== ' ' ? board[j] : false;
                if (board[j] !== ' ') return board[j];
            }
        }
        if ((board[4] === board[0] && board[4] === board[8]) ||
                (board[4] === board[2] && board[4] === board[6])) {
            //return board[4] !== ' ' ? board[4] : false;
            if (board[4] !== ' ') return board[4];
        }
        return ( board.every(function(element) {
            return element !== ' ';
        }))
    },
    winner: function(board) {
        return game.over(board);
    },
    possible_moves: function(board, sign) {
        var testBoard = [],
        nextBoard;
        for (var i = 0; i < board.length; i++) {
            nextBoard = board.slice();
            if (nextBoard[i] === ' ') {
                nextBoard[i] = sign;
                testBoard.push(nextBoard);
            }
        }
        return testBoard;
    }
}

function moveScore(board) {
    var result = game.winner(board);

    if (result === signPlayer) {
        return -100;
    }
    if (result === signAI) {
        return +100;
    }
    return 0;
    //Game is a draw
}

function max(board) {
    //if (game.over(board)) {
    //    return board;
    //}
    if (game.over(board)) {
        return [moveScore(board), []];
    }
    var newGame = [];
    var bestMove = [];
    var score;
    var best_score = -Infinity;
    var movesArray = game.possible_moves(board, signAI);
    for (var i = 0; i < movesArray.length; i++) {
        newGame = movesArray[i].slice();
        //score = moveScore(min(newGame));
        score = min(newGame)[0];
        if (score > best_score) {
            best_score = score;
            bestMove = newGame;
        }
    }
    //return bestMove;
    return [best_score, bestMove];
}

function min(board) {
    //if (game.over(board)) {
    //    return board;
    //}
    if (game.over(board)) {
        return [moveScore(board), []];
    }
    var newGame = [];
    var worstMove = [];
    var score;
    var worst_score = +Infinity;
    var movesArray = game.possible_moves(board, signPlayer);

    for (var i = 0; i < movesArray.length; i++) {
        newGame = movesArray[i].slice();
        //score = moveScore(max(newGame));
        score = max(newGame)[0];
        if (score < worst_score) {
            worst_score = score;
            worstMove = newGame;
        }
    }
    //return worstMove;
    return [worst_score, worstMove];
}

// Extra code for adding a simple GUI

var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var score = null;

var tds = Array.from(document.querySelectorAll('td'));
var table = document.querySelector('table');
var span = document.querySelector('span');

function display(board, score) {
    board.forEach( (v, i) => tds[i].textContent = v );
    span.textContent = score;
}
display(board);

table.onclick = function (e) {
    var i = tds.indexOf(e.target);
    if (i == -1 || board[i] !== ' ' || game.over(board)) return;
    board[i] = signPlayer;
    display(board);
    [score, board] = max(board, 1);
    display(board, score);
}
td { border: 1px solid; width: 20px; text-align: center; cursor: hand }
tr { height: 25px; v-align: middle }

Score:

Final note
I have just made the corrections to make it work, but note there are several ways to improve the efficiency. This you can do by using an alpha-beta search, tracking scores for already evaluated boards, while mapping similar boards by translations (turning, mirroring), and mutating boards instead of creating a new board each time you play a move.


text:
Q: Asynchronous programming using async/await I am having a tough time understanding async / await. Lets say I have a class A and class B. Class A returns a ActionResult from wcf service method. Before that it calls a async method from another class using await. Does this mean that await obj.method(param1) will be running asynchronously and without waiting for the completion of its execution, wcfservice method will execute ? or does it wait until it gets completed?
I wanted that somemethod() should continue its execution without waiting for the result of the method in classB. How will I be able to achieve this?
public async classA
{
    public async IHttpActionResult  somemethod
    {
        classB obj  = new classB();
        await obj.method(param1);
        returnok(somewcfservice.method());
    }

public classB
{
    public async Task method(param)
    {
        obj.somebuiltinmethod(param)
    }
}

A: 1. Does this mean that await obj.method(param1) will be running aysnchronously and without waiting for the completion of its execution, wcfservice method will execute ? or does it wait until it gets completed?
await obj.method(param1); will wait until the obj.method finishes execution before resuming the execution flow. Thi means the obj.method(param1); finishes and then the web service method will be called.
2.  I wanted that somemethod() should continue its execution without waiting for the result of the method in classB. How will I be able to achieve this?
you can do something like this :
var task = obj.method(param1);
var result = somewcfservice.method()
Task.WaitAll(task);
returnok(result);


text:
Q: postgis table - shapefile - mapinfo file I have a .tab file with a ridiculous amount of columns (96). One of my colleagues at my new job wanted to update them manually one by one. I told him I could do that in an easier way using PostGIS. So I told him to give me the data and let me do my thing.
I converted the .tab file to a shapefile, uploaded the shapefile to PostGIS, uploaded a table to PostGIS with the data which was needed for the update. I updated all the 96 columns at once and achieved the wanted ending in a table in PostGIS. He wanted it back in a .tab file.
I exported the file as a shapefile, which went perfect. Then I export the file as a .tab file using QGIS. So I figured I had the end result and have send it to my colleague. He checks it and reports back to me that the last 10 columns are empty, which they should not be. Also the coordinates differ and the polygons are not in the same location as they were in the original file in MapInfo, which he uses.
I checked it in QGIS and there is no problem at all. The columns are filled, the polygons overlap with the original data. I am totally perplex.
I know that my coordinate system RD new sometimes differs in code. I remember adding a small line of text in the formula to align it once. So I guess the movement of the coordinates is something I can fix myself. But why do columns appear empty while they are not in QGIS?
And why can some .tab files I export in QGIS not be opened in MapInfo? It gives an error the moment I open the .tab file.
I am researching myself, but I need some guidance to find the right direction to research further to. I'd love some help and that is why I ask the question here.

A: Based on your comments to MappaGnosis's answer, it looks like you're just trying to join 2 tables. This is easily done in MapInfo and would save you a whole load of grief trying to move the data between systems.
Let's say you have Table1 which has the ID and map objects in it, and Table2 which holds all the attribute information you want to apply to Table1. All you need to do is go to Query > SQL Select:
Enter the following (amended to your table and column names):
Select Columns: *
From Tables: Table1, Table2
Where: Table1.ID = Table2.ID
Into: MyJoinedTable
Then it's just a case of saving off the query results as a native MapInfo table.

A: Without seeing the data, it is difficult to say for certain why it is not working for you but here are a couple of things to consider:

*

*The reason the polygons could appear misplaced sounds very much like one of projection.  It is possible that the MapInfo file has lost its projection along the way and QGIS is maybe coping better with reprojecting on the fly.  Did you give ALL the files to your colleague including the PRJ if there was one?

*I wonder if the encoding of the data in the final columns is not compatible with MatInfo (e.g. UTF vs LATIN) but readable by QGIS and Postgresql??

Finally, you appear to have 'gone round the houses' during your conversion process and each additional step is a potential source of error or loss of projections (especially where a shapefile is concerned).  I'd prefer to do this conversion in two fewer steps and use OGR2OGR to go straight to Postgres and then OGR2OGR again to go straight from PG back to MapInfo.
That said - while I am not a MapInfo user I am very surprised that MapInfo doesn't have some facility to do bulk edits on the columns.  You can in both QGIS and ArcGIS (which possibly precludes the need to even convert to PostGIS, though you may need a little Python magic).  I'd always understood MapInfo to be a very capable GIS and would have expected that this could all be done using MapBasic


text:
Q: default values(Client IP) in schema is there a way to put the client IP as default value in my schema?7
i already looked on the python-eve.org homepage in the section configuration, but i coulndt find anything ;(
thanks
Harald

A: Currently default only accepts static values. Support for callables and lambdas is planned. Actually, at this very moment there's a pending pull request waiting to be merged.
Until then, you could probably use a callback function to achieve your payload. Something like:
from flask import request

def before_insert(resource_name, documents):
    if resource_name == 'myresource':
        for document in documents:
            document['field'] = request.remote_addr

app = Eve()
app.on_insert += before_insert

app.run()


text:
Q: Effective way to make a system tray application This is my first post on Stack Overflow and I'm just wondering on the options of making a system tray application. The application would run primary from the system tray while still operating, and could be brought up into a window when clicked on. It is also needed to have some support for global keystroke tracking, to bring up a window.
I'm curious on what options I have available to me, as I'm sure that there are many ways to do this. I'm most familiar with with Java though I have some experience with C++. I'm willing to explore other languages if they have some definite perks to them, though it would be nice to work with what I know in a way.
Thank you

A: Java 6 has new functionality which allows for the creation of applications which use the system tray.
The New System Tray Functionality in Java SE 6 article goes into the details, and provides some sample code as well.
The newly added SystemTray and TrayIcon classes of the java.awt package can be used to add icons to the system tray. The icons can respond to mouse clicks and use pop up menus as well. However, this new functionality is a part of AWT, so it doesn't do a very good job integrating with Swing components.
Here's an example of a little clock that shows up in the system tray which was made using the SystemTray and TrayIcon classes in Java 6:

(source: coobird.net)

A: Plain old Winforms would get my vote.
If you are familiar with Java you should have little difficulty using one of the managed languages to create a simple tray app with .NET.
Here is some advice on the correct way to create a tray app.

A: Be carefully with manged applications and Java here.   Tray applications run all the time.   So, if they are poorly written then they can use enough system resources to interfere with other things.
There is nothing wrong with manged code or Java in general, but it can be more difficult to keep managed or java apps frugal with memory, I/O and CPU time.
I'm saying this as a dev manger on the Windows perf team - we've seen lots and lots of very piggy tray applications.    Yes, some are even windows or MSFT applications.
It may be a better approach to write a very small light weight tray app that launches a richer process when the user needs it.   You can write your try app in simple C++ right on top of the low level Win32 APIs.   If you don't want to use the Win32 APIs directly, you can use the Windows Template Library.


text:
Q: JQuery: Ckeditor and autosuggestion not working together in one page?

     <link rel="stylesheet" type="text/css" href="css/auto/auto.css">

     <link rel="stylesheet" type="text/css"href="css/auto/jquery.tagin.css">

     <link href="css/editor.css" type="text/css" rel="stylesheet"/>

A: You need to change your code multiple jQuery or jquery-ui become problematic:

     <link rel="stylesheet" type="text/css" href="css/auto/auto.css">

     <link rel="stylesheet" type="text/css"href="css/auto/jquery.tagin.css">

     <link href="css/editor.css" type="text/css" rel="stylesheet"/>

Try this.


text:
Q: D3D12 Use backbuffer surface as unordered access view (UAV) Im making a simple raytracer for a schoolproject were a compute shader is supposed to be used to shade a triangle or some other primitive.
For this I'd like to write to a backbuffer-surface directly in the compute shader, to then present the results imideatly. I know for certain that this is possible in DX11 though i can't seem to get it to work in DX12.
I couldn't gather that much information about this, but i found this gamedev thread discussing the exact same problem I try to figure out and they seem to come to the conclusion which was my go to workaround: writing to an intermediate texture and then sampling in a pipeline.
I can't fully accept that this would be impossible to achieve in dx12. Why would that feature be removed? Could it be that the queuing-systems removes some overhead that makes it unnecessary to have this feature?
Is there any way to achieve a raytracer without writing to a separate texture and then sampling in a pipeline or copy it onto the back-buffer? What are my best alternatives for achieving performance?

A: You will have to access the answer. They removed the capability to create an UAV the same way they removed the capability to use multisample surface in the swapchain.
The problem with authorizing UAV on the swapchain surface is that they would have to forfeit tracking of what is happening to it. DX12 rely on descriptor heaps that are 100% volatile at runtime for UAVs ( render targets are CPU side only and can be tracked ).
Microsoft need to track the swapchain surface status strongly in order to guarantee behavior with the desktop presentation and for that reason, they choose to deny the UAV binding.


text:
Q: Dynamically generate SVG with images inside? AngularJS app.
Basically I've to make an horizontal arrow-like drawing with images that will be repeating inside depending on the array of items i sent to the html(ng-repeat).
I got told the best would be svg so here I am, but my knowledge of svg is pretty low. So I managed to make a little arrow with fixed witdh and height. But now I need it a lot bigger.
So I read about viewBox online. It scales the  items I have in the SVG, but I have two problems so far.

*

*Images don't work.

*All  items are stacked up and don't follow the space in between them that I had before.

This code is the working code I have right now, so you get an idea of the element I'm trying to draw. I use the  element so I can ng-repeat it with tooltips and text inside, this code is simplified.

.container {
    display: flex;
}

.justaclass {
    fill: #9b3d9c;
    background-color: #9b3d9c;
}

.justaclass-group {
    display: inline-block;
    position: relative;
}

.justaclass-image {
    padding: 2px;
}

  <svg width="8" height="34">
      <path class="justaclass"
            d="M 0 0 L 7 17 L 0 34 L 17 34 L 17 0 z">
      </path>
  </svg>
  <svg width="33" height="34" class="justaclass justaclass-image">

      <image x="0" y="3" width="33" height="25" href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"></image>

  </svg>

      <svg width="50" height="34" class="justaclass image">

          <image width="45" height="30"
                 x="0" y="0"
                 href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg">
          </image>

      </svg>

  <svg width="10" height="34">
      <path class="justaclass"
            d="M 0 0 L 0 34 L 10 17 z">
      </path>
  </svg>

The code isn't perfect pixel-wise here, but that's not my main issue.
Now that I try to make it bigger with viewBox, I can draw the 4 elements but they are misplaced. So If I add display:flex or display:table I quite cannot get the elements aligned horizontally, the  elements just disappear.
Anyone got any idea of how to dinamically resize all this elements plus making them all in the same line just like display flex would do?
My first try at doing the above image with viewBox
But If I add display:flex into the container, the svg's are gone and I only see images.

.container {}

.justaclass {
    fill: #9b3d9c;
    background-color: #9b3d9c;
}

    <svg viewBox="0 0 150 50">
        <path class="justaclass"
              d="M 0 0 L 7 17 L 0 34 L 17 34 L 17 0 z">
        </path>
    </svg>

    <svg viewBox="0 0 150 50">
        <image width="150" height="50" href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"></image>
    </svg>

    <svg viewBox="0 0 150 50">
        <image width="150" height="50" href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"></image>
    </svg>

    <svg viewBox="0 0 150 50">
        <path class="justaclass"
              d="M 0 0 L 0 34 L 10 17 z">
        </path>
    </svg>

A: There are a lot of things that need to change here. First lets talk about viewBox. This attribute describes how the numbers inside the <svg> tag relate to those outside. It gives a rectangle into which the inside content is rendered. Then, this rectangle is scaled such that it fits into the size given by width and height. That means, giving a viewBox without also defining width and height makes not much sense, as the size the content should be scaled to is missing.
What happens if the aspect ratio of the viewBox and that of the width and height do not match? As a default, the content is set into the middle and scaled such that it just fits. Other values can be given with the preserveAspectRatio attribute. For example, to get the left "arrow" part to the right of its rectangle (so there is no gap), set preserveAspectRatio="xMaxYMid meet".
width and height can be given as attributes for SVG content or as CSS properties. It makes sense to define them as styles if they are to be changeable.
Your linked images do not need to have a concrete size. Giving them width="100%" height="100%" scales them to the containing SVG element, without distorting them (unless you define so with preserveAspectRatio="none".

.container {
    display: flex;
}

.container svg {
    width: 50px;
    height: 50px;
}

.container .justaclass {
    fill: #9b3d9c;
    background-color: #9b3d9c;
    width: 150px;
}

    <svg width="50" height="50" viewBox="0 0 8 34" preserveAspectRatio="xMaxYMid meet">
        <path
              d="M 0 0 L 7 17 L 0 34 L 17 34 L 17 0 z">
        </path>
    </svg>

    <svg class="justaclass">
        <image width="100%" height="100%" href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"></image>
    </svg>

    <svg class="justaclass">
        <image width="100%" height="100%" href="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"></image>
    </svg>

    <svg viewBox="0 0 10 34" preserveAspectRatio="xMinYMid meet">
        <path
              d="M 0 0 L 0 34 L 10 17 z">
        </path>
    </svg>

A: viewBox defines the size of the contents of the svg before being scaled. You need to set them to the original size of your image and then scale the elements up either with the width and height tags you used before or with css. Here's a fiddle of everything scaled up to double size: https://jsfiddle.net/ohnqbufa/
You can see here that the viewport of your first element is set to the original size and the width and height are set to double.
<svg width="16" height="68" viewBox="0 0 8 34">
    <path class="justaclass"
          d="M 0 0 L 7 17 L 0 34 L 17 34 L 17 0 z">
    </path>
</svg>


text:
Q: "IOException: too many authentication attempts. Limit: 3" when using JDK HttpClient with wrong credentials I have simple code basically copy-paste from javadoc. It works well in general but in case of incorrect credentials, instead of getting proper error code I get exception:
Caused by: java.io.IOException: too many authentication attempts. Limit: 3
    at java.net.http/jdk.internal.net.http.AuthenticationFilter.response(AuthenticationFilter.java:326)
    at java.net.http/jdk.internal.net.http.MultiExchange.responseFilters(MultiExchange.java:248)
    at java.net.http/jdk.internal.net.http.MultiExchange.lambda$responseAsyncImpl$6(MultiExchange.java:413)
    at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1150)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.postFire(CompletableFuture.java:614)
    at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:653)
    at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:482)
    at java.net.http/jdk.internal.net.http.HttpClientImpl$DelegatingExecutor.execute(HttpClientImpl.java:157)
    at java.base/java.util.concurrent.CompletableFuture$UniCompletion.claim(CompletableFuture.java:572)
    at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:642)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at java.net.http/jdk.internal.net.http.Http1Response$HeadersReader.handle(Http1Response.java:695)
    at java.net.http/jdk.internal.net.http.Http1Response$HeadersReader.handle(Http1Response.java:621)
    at java.net.http/jdk.internal.net.http.Http1Response$Receiver.accept(Http1Response.java:612)
    at java.net.http/jdk.internal.net.http.Http1Response$HeadersReader.tryAsyncReceive(Http1Response.java:668)
    at java.net.http/jdk.internal.net.http.Http1AsyncReceiver.flush(Http1AsyncReceiver.java:233)
    at java.net.http/jdk.internal.net.http.common.SequentialScheduler$LockingRestartableTask.run(SequentialScheduler.java:205)
    at java.net.http/jdk.internal.net.http.common.SequentialScheduler$CompleteRestartableTask.run(SequentialScheduler.java:149)
    at java.net.http/jdk.internal.net.http.common.SequentialScheduler$SchedulableTask.run(SequentialScheduler.java:230)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:833)

As I said, the code is fairly mundane:
HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_1_1)
        .followRedirects(HttpClient.Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(10))
        .authenticator(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(name.asString(), password.toCharArray());
            }
        })
        .build();

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(HttpApiUrl))
        .timeout(Duration.ofSeconds(10))
        .GET()
        .build();

try {
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() / 100 != 2) {
        logger.info("Authenticated");
        return true;
    } else {
        logger.error("Authentication failed");
    }
} catch (IOException | InterruptedException ex) {
    logger.error(""Authentication failed", ex);
    return false;
}

I don't get why HttpClient uses retry logic if there is authenticator set (https://github.com/openjdk/jdk/blob/master/src/java.net.http/share/classes/jdk/internal/net/http/AuthenticationFilter.java#L324)... Without .authenticator(new Authenticator() {} I get nice "Not authorized" / 401. How can I disable this retry "feature"? IMHO it doesn't make much sense - if the credentials are invalid, retrying couple of times won't change it... Or at least make it return correct error code when retires fails instead of throwing an exception?