text:
Q: Limit size of diffable data source snapshots after calling performFetch Problem
After executing an NSBatchBatchInsertRequest and calling fetchedResultsController.performFetch(), the frc's delegate method controller(_:didChangeContentWith:) is called with a NSDiffableDataSourceSnapshot<Section, NSManagedObjectID> that unexpectedly contains all data in Core Data (even though I've only just inserted new data).
Code
Here's how the NSFetchedResultsController is created:
    let fetchedResultsController = NSFetchedResultsController<MyManagedObject>(
        fetchRequest: fetchRequest,
        managedObjectContext: persistentContainer.viewContext,
        sectionNameKeyPath: nil,
        cacheName: nil
    )

The NSFetchRequest:
    let fetchRequest = MyManagedObject.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "value", ascending: true)]
    fetchRequest.fetchBatchSize = 10

The snapshot is applied in this NSFetchedResultsControllerDelegate method below.
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
    dataSource.apply(snapshot as NSDiffableDataSourceSnapshot<Section, NSManagedObjectID>, animatingDifferences: false)
}

Details

*

*The sample app receives 10,000 Item instances every 5 seconds and runs an NSBatchInsertRequest on a new background context with performAndWait to convert and store the Items as MyManagedObject instances.

*performFetch() is then called on main.

*Calling performFetch() ensures a new snapshot is provided in controller(_:didChangeContentWith:), which the data source can apply(_:animatingDifferences:completion:) to update the UI.

*The items populate a UICollectionView, which is hooked up to a UICollectionViewDiffableDataSource<Section, NSManagedObjectID>.

*

*When the data source is asked to make a cell for a specific NSManagedObjectID, the right MyManagedObject for that NSManagedObjectID using fetchedResultsController.managedObjectContext.object(with:).

*Then the MyManagedObject is converted into an Item, which is finally used to configure the cell.

Attempt at a solution
The most obvious solution to me was implementing this delegate method only, but that method doesn't seem to get called:
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith diff: CollectionDifference<NSManagedObjectID>) {
    print(diff)
}

I don't want the UI to stutter and hang when I'm fetching the data. I think that the reason that's happening is because my snapshots are huge. My guess why they're huge is because my fetch request fetches all the data (but I only want to add new data to the snapshot). To fix that, I've tried to setting fetchLimit to a small number like 2, but that just causes only 2 items to be fetched at all. I think I could workaround that by updating fetchOffset, but that approach could get messy as I scroll around. Adjusting fetchBatchSize doesn't make a difference. Memory is not leaking either. And FWIW, I'm applying the snapshots in a background queue, but that also doesn't seem to improve the UI stuttering.
I want to store items to Core Data as I get them, and then only fetch from the persistent store when scrolling to off-screen cells. That appears to be happening because I can see the data source only requests cells for index paths near the visible range when the snapshot is applied (even though the vertical scroll bar of the collection view is shrinking over time). But the size of snapshots (= the total number of items received until now) is ever increasing.
I can get the current snapshot and only append the items missing from the new snapshot, but that will still require me to go through a snapshot of unbounded size. How can I avoid doing that and load lots of data without the UI stuttering? I'm only inserting new data into Core Data, so why am I getting all the data in the snapshots?


text:
Q: SAP instance definition Could someone explain to me what SAP instance is? Is it also installed on the SAP application server?

A: The role of a SAP instance is to deliver SAP Processes (DIA, BGD, UPD, ...).
A SAP System (SID) can be made of 1 CI (Central Instance) and 1,n DIALOG instances.
You can get the list of SAP Instances using of your SAP System using
SM66 t-code.
CI (Central Instance) hosts Enqueue and Message server.

A: The term instance is used in SAP when you have a lot of clients.
If you see ADM100 pdf manual, they specify an instance as a group of multiple clients(more than 50...).
Don't confuse an instance with developing a program, they are two different things.
Call it server,call it client,you can install SAP on a machine.
Machine,Server, Client, they are the same, but are used in different contest.

Also you could have a single machine with a lot of instance virtualized, where in every virtual system is installed sap, then you could say that this machine holds an instance.
Be careful Dirk,On a sap system you can have Abap based sap systems or Abap+Java based sap system, I would be careful to use the word instance.

A: Sanaz,
In addition to the responses of Dirk, Admin2017 and Fedoco, I can advise SM51 t-code.
AS (Application Server) Instances of SAP Server.
You can find in this transaction information about:

*

*Application Server Instance (or Instances),

*Host (server address)

*Instance Services (List of instance services)

*State (eg:Active)

A: In SAP environments, an Instance usually means a SAP Netweaver instance. Netweaver is the server software that runs SAP applications like ERP, CRM, PI and others, both Java and ABAP. You can have several instances configured on a single server - they share a few common directories, other directories are instance specific. A Netweaver application server would be one instance running on your server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serialize nested user defined class from Q_PROPERTY in QT faced with following problem: I can't serialize user defined object from Q_PROPERTY
I try to serialize RegistersSettings class to QDataStream. The idea is to be able to serialize it to text file (using << operator) and later be able to read it (using >> operator). It should verify that fields that was readed from file are still valid. So I inspect property for that.
The issue is that Q_PROPERTY(QList groups MEMBER groups) is not work as expected.
It looks like it's possible to create such functionality, but it looks that it's not so easy.
Could anyone help with the common way how to serialize user defined class from Q_PROPERTY?
The code is simplifyed to be more readable, but the main idea is in place.
class RegisterGroupSettings:SettingsItem<RegisterGroupSettings>
{
private:
    Q_GADGET
    Q_PROPERTY(QString name MEMBER name)
    Q_PROPERTY(int interval MEMBER interval)

public:
    QString name;
    int     interval;
};
Q_DECLARE_METATYPE(RegisterGroupSettings)

class RegistersSettings:SettingsItem<RegistersSettings>
{
private:
    Q_GADGET
    Q_PROPERTY(QList<RegisterGroupSettings> groups MEMBER groups)
    Q_PROPERTY(int code MEMBER code)

public:
    QList<RegisterGroupSettings> groups;
    int code;
};
Q_DECLARE_METATYPE(RegistersSettings)

SettingsItem is a helper fo unification
template <typename T> class SettingsItem
{
public:
    friend QDataStream & operator << (QDataStream &arch, const T & object)
    {
        const QMetaObject &mo = object.staticMetaObject;
        int cnt = mo.propertyCount();
        QString prop_name;
        QVariant prop_value;
        arch << cnt;
        while (cnt>0)
        {
            prop_name = mo.property(cnt-1).name();
            prop_value = mo.property(cnt-1).readOnGadget(&object);
            arch << prop_name;
            arch << prop_value;
            cnt--;
        }
        return arch;
    }

    friend QDataStream & operator >> (QDataStream &arch, T & object)
    {
        const QMetaObject &mo = object.staticMetaObject;
        int cnt=0;
        QString prop_name;
        QVariant prop_value;
        int prop_index;
        arch >> cnt;
        while (cnt>0)
        {
            arch >> prop_name;
            arch >> prop_value;
            prop_index = mo.indexOfProperty(prop_name.toStdString().c_str());
            if (prop_index > -1)
            {
                mo.property(prop_index).writeOnGadget(&object, prop_value);
            }
            cnt--;
        }
        return arch;
    }

    friend bool operator == (const T &first, const T &second)
    {
        const QMetaObject &mo = first.staticMetaObject;
        int cnt = mo.propertyCount();
        QString prop_name;
        QVariant oProp_value;
        QVariant dProp_value;
        while (cnt>0)
        {
            prop_name = mo.property(cnt-1).name();
            oProp_value = mo.property(cnt-1).readOnGadget(&first);
            dProp_value = mo.property(cnt-1).readOnGadget(&second);
            if (oProp_value == dProp_value)
            {
                cnt--;
                continue;
            }
            return false;
        }

        return true;
    }

    friend bool operator != (const T &first, const T &second)
    {
        return !( first == second );
    }
};

A: The solution is to extend template with constructor
SettingsItem()
{
    qRegisterMetaType<T>();
    qRegisterMetaTypeStreamOperators<T>(T::staticMetaObject.className());
}

and register nested type in class constructor
RegistersSettings()
{
    qRegisterMetaTypeStreamOperators<QList<RegisterGroupSettings>>("QList<RegisterGroupSettings>");
}


text:
Q: Map the first element of each array of an array of arrays in Javascript I have an array of arrays like this:
myData = [
          ["name1", 34.1, 43.1, 55.2],
          ["name2", 5.3, 23.6, 40.9],
          ["name3", 43.5, 77.8, 22.4]
         ];

I want to get an array containing only the first element of each array like this: ["name1", "name2", "name3"].
I tried to do it like this but doesn't work:
var arrayTitle = myData.map(function(x) {
    return [myData[x][0]];
});

Any suggestions?

A: You could return just the first elementn of x, an element of the outer array.

var myData = [["name1", 34.1, 43.1, 55.2], ["name2", 5.3, 23.6, 40.9], ["name3", 43.5, 77.8, 22.4]],
    arrayTitle = myData.map(function(x) {
        return x[0];
    });

console.log(arrayTitle);

A: Your x itself is an array. So you need not to touch myData again inside.
var arrayTitle = myData.map(function(x) {
    return x[0];
});

or with a traditional loop

myData = [
          ["name1", 34.1, 43.1, 55.2],
          ["name2", 5.3, 23.6, 40.9],
          ["name3", 43.5, 77.8, 22.4]
         ];

var arrayTitle = [];

for(var k in myData)
 arrayTitle.push(myData[k][0]);

 console.log(arrayTitle);

A: With your actual code return [myData[x][0]], you are returning undefined, because x  is the iterated item, so it's an array and not an index.
And using the wrapping [] is useless here, it's a destructing syntax, we don't need it here.
You should only return item[0] in each iteration:
var res = myData.map(function(arr) {
  return arr[0];
});

Demo:

myData = [
  ["name1", 34.1, 43.1, 55.2],
  ["name2", 5.3, 23.6, 40.9],
  ["name3", 43.5, 77.8, 22.4]
];

var res = myData.map(function(arr) {
  return [arr[x][0]];
});
console.log(res);

A: This could be the shortest answer:
var res = myData.map(a => a[0])


text:
Q: Erasing an elemnt from a 3D vector in C++ So, I have a vector, containing vectors which contain vectors which contain integers, essentially acting as a 3D array. I have declared it as so:
vector<vector<vector<int>>> maxtrix;
...
int size = 16;
vector<int> intial;
inital.assign(size, 0); // fill a vector with 0s depending on size
vector<vector<int>> secondInitial;
secondInitial.assign(size, initial); // so now the 2d array holds the inital empty vector
matrix.assign(size,secondInitial); // an array of the 2d arrays -> 3d array.

I can therefore only access the matrix via
matrix[x][y][z];

but I need to be able to erase elements like:
initial.erase(0)

However I have tried an am unable to in the way of :
matrix.erase([a][b][c]);

I am not sure how else I could access the 'deepest' level of the vector to remove elements without it being declared.
I have tried to search how to do it for a 2D vector an extrapolate out for a 3D vector but I am stuck. Thanks.

A: I would guess something like this would work:
matrix[x][y].erase(matrix[x][y].begin() + z);

And then you substitute in whatever numbers you want for x, y, and z.


text:
Q: How to construct & solve a linear programming problem using lpsolve in r? I'm new to linear programming and trying to solve in R using lpsolve package.
I have taken this from a Youtube tutorial done in excel and below is the problem Constrains:

I have tried below code to construct this problem but I am getting error on running lpsolve:
library(lpSolve)
library(tidyverse)

options(scipen = 999)

*

*ROI which need to be maximized
Channel <- c("tv","seo","adwords","facebook")
ROI <- c(.09, .14, .10, .05)

cbind(Channel,ROI)

# --------------- output ---------------
     Channel    ROI
[1,] "tv"       "0.09"
[2,] "seo"      "0.14"
[3,] "adwords"  "0.1"
[4,] "facebook" "0.05"

*Creating Problem Constrains

budget_constr <- 1000000
seo_budg_60_per <- .60 * 1000000
fb_budg_20_per <- .20 * 1000000
tv_min_200grand <- 200000
fb_min_cont_80grand <- 80000
seo_min_cont_60grand <- 60000
seo_max_cont_220grand <- 220000
adwords_max_cont_3xseo <- 0
Market_size <- 1300000

const.rhs <- c(budget_constr,seo_budg_60_per,fb_budg_20_per,tv_min_200grand,fb_min_cont_80grand,
  seo_min_cont_60grand,seo_max_cont_220grand,adwords_max_cont_3xseo,Market_size)

constraint_descr <- c("Budget 1 Million","Seo adwords atleast 60% of the budget","Facebook max 20% of budget",
                   "Tv is min 200000","Facebook min contract 80000","Seo min contract 60000","Seo max contract 220000",
                   "Adwords max contract is 3 times SEO","Allocate Money <= Market Size (which is 1300000)")

cbind(constraint_descr, const.rhs)

# --------------- output ---------------
      constraint_descr                                   const.rhs
 [1,] "Budget 1 Million"                                 "1000000"
 [2,] "Seo adwords atleast 60% of the budget"            "600000"
 [3,] "Facebook max 20% of budget"                       "200000"
 [4,] "Tv is min 200000"                                 "200000"
 [5,] "Facebook min contract 80000"                      "80000"
 [6,] "Seo min contract 60000"                           "60000"
 [7,] "Seo max contract 220000"                          "220000"
 [8,] "Adwords max contract is 3 times SEO"              "0"
 [9,] "Allocate Money <= Market Size (which is 1300000)" "1300000"

*Creating Constrain direction

const.dir <- c("<=",">=","<=",">=",">=",">=","<=",">=","<=")

*Creating Matrix

const.mat <- rbind(c(1,1,1,1),
                c(0,1,0,0),
                c(0,0,0,1),
                c(1,0,0,0),
                c(0,0,0,1),
                c(0,1,0,0),
                c(0,1,0,0),
                c(0,1,3,0),
                c(1,1,1,1))

*Using lpsolve

lpSolve::lp(direction = "max", objective.in = ROI,
            const.mat, const.dir, const.rhs)

Error: no feasible solution found

A: I prefer to use the linprog package.
Your example:
library(linprog)

Channel <- c("tv","seo","adwords","facebook")
ROI <- c(.09, .14, .10, .05)
cbind(Channel,ROI)

budget_constr <- 1000000
seo_budg_60_per <- .60 * 1000000
fb_budg_20_per <- .20 * 1000000
tv_min_200grand <- 200000
fb_min_cont_80grand <- 80000
seo_min_cont_60grand <- 60000
seo_max_cont_220grand <- 220000
adwords_max_cont_3xseo <- 0
Market_size <- 1300000

const.rhs <- c(budget_constr,
               seo_budg_60_per,
               fb_budg_20_per,
               tv_min_200grand,
               fb_min_cont_80grand,
               seo_min_cont_60grand,
               seo_max_cont_220grand,
               adwords_max_cont_3xseo,
               Market_size)

constraint_descr <- c("Budget 1 Million",
                      "Seo adwords atleast 60% of the budget",
                      "Facebook max 20% of budget",
                      "Tv is min 200000",
                      "Facebook min contract 80000",
                      "Seo min contract 60000",
                      "Seo max contract 220000",
                      "Adwords max contract is 3 times SEO",
                      "Allocate Money - Market Size (which is 1300000)")

cbind(constraint_descr, const.rhs)

const.mat <- rbind(c(1,1,1,1),
                   c(0,1,0,0),
                   c(0,0,0,1),
                   c(1,0,0,0),
                   c(0,0,0,1),
                   c(0,1,0,0),
                   c(0,1,0,0),
                   c(0,1,3,0),
                   c(1,1,1,1))

solveLP(ROI, const.rhs, const.mat, const.dir = c("<=",">=","<=",">=",">=",">=","<=",">=","<="), maximum = TRUE)

Result:
Results of Linear Programming / Linear Optimization

Objective function (Maximum): 102800


text:
Q: SKPhysics not working properly? struct PhysicsCategory {
    static let None      : UInt32 = 0
    static let All       : UInt32 = UInt32.max
    static let planet    : UInt32 = 0b1
    static let rocket    : UInt32 = 0b10 }

planet.physicsBody = SKPhysicsBody(circleOfRadius: planet.size.width / 2)
planet.physicsBody?.dynamic = true planet.physicsBody?.categoryBitMask = PhysicsCategory.planet
planet.physicsBody?.contactTestBitMask = PhysicsCategory.rocket
planet.physicsBody?.collisionBitMask = PhysicsCategory.None

func planetCollidedWithRocket(rocket: SKSpriteNode, planet: SKSpriteNode) {
    println("collision planet") }

 func didBeginContact(contact: SKPhysicsContact) {
        var firstBody: SKPhysicsBody
        var secondBody: SKPhysicsBody
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
        } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA }

        if ((firstBody.categoryBitMask & PhysicsCategory.planet != 0) &&
            (secondBody.categoryBitMask & PhysicsCategory.rocket != 0)) {
            planetCollidedWithRocket(firstBody.node as! SKSpriteNode, planet: secondBody.node as! SKSpriteNode)}

I'm currently using this to add collision detection to my game (I've taken only taken out the bits of code I think are relevant). The first time I ran the game on the simulator it worked fine, and I added a game over scene to the planetCollidedWithRocket method. But I tested it again today and for some reason the game is detecting a collision between the rocket and the planet when they aren't colliding! Can anyone see what Ive done wrong??

A: Your contact isn't set up correctly. This is what you have, and what it translates to:
if((firstBody.categoryBitMask & PhysicsCategory.planet !=0)
// This is checking if the firstBody *has* a categoryBitMask, but it is not evaluating what it is.
// In addition to that, it is requiring that the PhysicsCategory.planet does not equal zero, which it doesn't.
// This would evaluate to true every time, no matter what.
// It is also requiring that...

&& (secondBody.categoryBitMask & PhysicsCategory.rocket != 0))
// This is checking if the secondBody *has* a categoryBitMask, but it is not evaluating what it is.
// In addition to that, it is requiring that the PhysicsCategory.planet does not equal zero, which it doesn't.
// This would evaluate to true every time, no matter what.

What you need to do is check that you categoryBitMask equals one of your PhysicsCategory variables, such that when a planet and a rocket contact, something evaluates to true. Try this:
if ((firstBody.categoryBitMask == PhysicsCategory.planet) &&
    (secondBody.categoryBitMask == PhysicsCategory.rocket)){

// Code Here

}

Alternatively, since you know the hard-coded numbers in your PhysicsCategory struct, you can evaluate to hard numbers:
if ((firstBody.categoryBitMask == 1) &&
    (secondBody.categoryBitMask == 2)){

// Code Here

}

What this will do is check to see if the physicsBody's categoryBitMask equals certain numbers when they contact. If they do, something happens, if not, nothing happens.


text:
Q: cannot update ftp credentials even when group owner has write access Why doesn't update work for wp?
_www has write permission to everything as you can see.
But it always asks for ftp credentials. Only way is to have wp dir owned by _www. Why?


text:
Q: how to create input search word with jQuery I have one input and one ul that has many li like this :
input
<input type="text" placeholder="searching friends ..." id="search-friends">

this is list of my friends:

        <button class="conver-link">

 Janatan

        </button>

        <button class="conver-link">

 andy

        </button>

        <button class="conver-link">

 Anna

        </button>

        <button class="conver-link">

 fred

        </button>

        <button class="conver-link">

 john

        </button>

        <button class="conver-link">

 cristian

        </button>

I want when type any word hide ul and show me related li that is like typing name .....

A: $('#search-friends').on('keyup', function() {
    $('.friend-name span').each(function(){
        if ($(this).html().indexOf($('#search-friends').val()) != -1 {
            //SHOW/HIGHLIGHT/OR WHATEVER THE li's you are looking for
        })
    });
});

A: I would suggest the use of a tried and tested autocomplete plugin like jQuery UI Autocomplete, but in case you want a no-frills approach, you can try this:
var $list = $('#friend-list');

//Hide the list items initially
$list.find('li').hide();

$('#search-friends').on('keyup', function() {
    $list.find('li').hide();

    //Select only elements that contain the query string and show it
    $list.find('li:contains("' + this.value.toLowerCase() + '")').show();
});

Here's the working demo: http://jsfiddle.net/tfMZg/4/

A: $(document).ready(function () {
    $("#search-friends").keyup(function (){
        searchFriendsByPattern($("#search-friends").val());
    });
});

function searchFriendsByPattern(pattern){
    $("#friend-list").children("li").each(function () {
        var liText = $(this).find("span").text().toLowerCase();
        if (liText.indexOf(pattern.toLowerCase()) == -1){
            $(this).hide();
        }
        else{
           $(this).show();
        }
    });
}

jsFiddle


text:
Q: Web Scrape IMDB using Beautiful Soup in Python I'm working on a project that requires me to web scrape IMDB and builds a pd dataframe.
This is the url I am currently working on: https://www.imdb.com/list/ls031674317/
Everything went smoothly until I tried to get the Director on html page into my movie_director list. The website looks like this with some movies having a director while some others don't:

The html code looks like this:

I wrote a function that uses Beautiful Soup to get each director from the html (text_muted is just the part of code on my screen shot):
def getDirector(text_muted):
    try:
        return text_muted.find("a").getText()
    except:
        return 'NA'

text_muted_stuff = movie.find_all("p", {"class": "text-muted text-small"})[1]
director = getDirector(text_muted_stuff) # Need to seperate director and actor
movie_director.append(director)

I managed to get all the directors and stars in a single list, but I want to be more specific and just fill the list with directors only (append NA if no director for any movie). I am not sure if I can achieve this with Beautiful Soup or any hard code.
Thanks

A: EDIT: diggusbickus comment is mutch more strict, so you do not have to check twice - nice. Changed full example to it´s approache, result is the same.
[x.text for x in d] if (d := item.select('a[href*="_dr_"]')) else None

Attribute selectors
[href*="_dr_"] - represents elements with an attribute named href whose value containing the substring _dr_.

First approach
You can select the director with css selector and a condition that also checks the href.
[x.text for x in d if '_dr_' in x['href']] if (d := item.select('p:-soup-contains("Director:") a')) else None

*

*Select all <a> in a <p> that contains Director:
item.select('p:-soup-contains("Director:") a')

*Check if element is not None else set value of director to None

*Check if there is _dr_ in the href, to be sure its a director
if '_dr_' in x['href']

Example (https://www.imdb.com/search/title/?genres=action)
import requests
from bs4 import BeautifulSoup
url = 'https://www.imdb.com/search/title/?genres=action'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}
page = requests.get(url,headers=headers)
soup = BeautifulSoup(page.text, 'html.parser')

data = []
for item in soup.select('.lister-item'):
    data.append({
        'title':item.h3.a.text,
        'url':'https://www.imdb.com'+item.a['href'],
        # if you do not like lists in your data frame, simply join ','.join([x.text for x in d])
        'director': [x.text for x in d] if (d := item.select('a[href*="_dr_"]')) else None,
        'stars':[x.text for x in s] if (d := item.select('a[href*="_st_"]')) else None
    })

pd.DataFrame(data)

Output

title
url
director
stars

Das Rad der Zeit
https://www.imdb.com/title/tt7462410/?ref_=adv_li_i

['Rosamund Pike', 'Daniel Henney', 'Madeleine Madden', 'Zoë Robins']

Arcane
https://www.imdb.com/title/tt11126994/?ref_=adv_li_i

['Kevin Alejandro', 'Jason Spisak', 'Hailee Steinfeld', 'Harry Lloyd']

Hawkeye
https://www.imdb.com/title/tt10160804/?ref_=adv_li_i

['Jeremy Renner', 'Hailee Steinfeld', 'Florence Pugh', 'Tony Dalton']

Cowboy Bebop
https://www.imdb.com/title/tt1267295/?ref_=adv_li_i

['John Cho', 'Mustafa Shakir', 'Daniella Pineda', 'Elena Satine']

Red Notice
https://www.imdb.com/title/tt7991608/?ref_=adv_li_i
['Rawson Marshall Thurber']
['Dwayne Johnson', 'Ryan Reynolds', 'Gal Gadot', 'Ritu Arya']

Spider-Man: No Way Home
https://www.imdb.com/title/tt10872600/?ref_=adv_li_i
['Jon Watts']
['Zendaya', 'Benedict Cumberbatch', 'Tom Holland', 'Marisa Tomei']

Dune
https://www.imdb.com/title/tt1160419/?ref_=adv_li_i
['Denis Villeneuve']
['Timothée Chalamet', 'Rebecca Ferguson', 'Zendaya', 'Oscar Isaac']

Shang-Chi and the Legend of the Ten Rings
https://www.imdb.com/title/tt9376612/?ref_=adv_li_i
['Destin Daniel Cretton']
['Simu Liu', 'Awkwafina', 'Tony Chiu-Wai Leung', 'Ben Kingsley']

James Bond 007: Keine Zeit zu sterben
https://www.imdb.com/title/tt2382320/?ref_=adv_li_i
['Cary Joji Fukunaga']
['Daniel Craig', 'Ana de Armas', 'Rami Malek', 'Léa Seydoux']

Eternals
https://www.imdb.com/title/tt9032400/?ref_=adv_li_i
['Chloé Zhao']
['Gemma Chan', 'Richard Madden', 'Angelina Jolie', 'Salma Hayek']

Venom: Let There Be Carnage
https://www.imdb.com/title/tt7097896/?ref_=adv_li_i
['Andy Serkis']
['Tom Hardy', 'Woody Harrelson', 'Michelle Williams', 'Naomie Harris']

A: The easiest way I can see to separate directors and stars whilst remaining in bs4, even if there is no director listed, is to use the href differences between them.
The href tag for the director contains "dr_0", which is probably the same for all titles (should check this), movies with multiple directors will probably follow the same pattern as the stars, and advance in such as "dr_1", "dr_2", ...
So to get only directors and only stars from the html source, you can use:
import re

# could do with a copy of the html source to test this,
# please provide a test html string of the element if this doesn't work first time
def get_directors(text_muted) -> list:
  # find all 'a' tags in that small element, if the href contains "dr_%d" then include the name in the returned list. return empty list if no directors.
  names = text_muted.find_all("a")
  return [element.string for element in names if re.search("dr_[0-9]", element.get("href", ""))]

def get_stars(text_muted) -> list:
  # find all 'a' tags in that small element, if the href contains "st_%d" then include the name in the returned list. return empty list if no stars.
  names = text_muted.find_all("a")
  return [element.string for element in names if re.search("st_[0-9]", element.get("href", ""))]

This should be safe enough, but if the hrefs aren't as predictably as they look, then you could dump the element string and split that on the patterns "Director:" and "Stars:".
Btw, I tend to use manual string searches/regex when html-scraping as for the cost of just a little more effort getting the tags split correctly the speed improvement over bs4 is around 100-200x, so that's worth considering.


text:
Q: String value in Object I need to use obj to store string values, inside of the string, there is a comma, but this is not working in the project.
const resizedUrl ={
    'mobile': "'images','400x/images'",
    'tablet': "'images','700x/images'",
    'desktop': "'images','1000x/images'",
};

function imageUrlResizer(para) {

    console.log(11111, resizedUrl.tablet);

    if(!!isMobile()) {
        para = para.replace(resizedUrl.mobile);
    } else if(!!isTablet()) {
        para = para.replace(resizedUrl.tablet);
    } else {
        para = para.replace(resizedUrl.desktop);
    }
    return para;
}

I want to use 'images', '700x/images' inside the replace. But when it is running, the value becomes '\'images\', \'700x/images\' . I have tried this code inside codesandbox, it works fine.
This code is running in the backend, with node.js
Could anyone helps?

A: if you just want a quick fix this will work:
const resizedUrl ={
    'mobile': ['images','400x/images'],
    'tablet': ['images','700x/images'],
    'desktop': ['images','1000x/images'],
};

function imageUrlResizer(para) {
    if(!!isMobile()) {
        para = para.replace.apply(para, resizedUrl.mobile);
    } else if(!!isTablet()) {
        para = para.replace.apply(para, resizedUrl.tablet);
    } else {
        para = para.replace.apply(para, resizedUrl.desktop);
    }
    return para;
}

the replace method expects 2 arguments, your code was only providing one.
for information on how apply works, see here.
A better approach would be to restructure your resizedUrl object so it's usage and purpose are straightforward.


text:
Q: Javascript function not defined, for audio on click Im trying to make a game in HTML5 and JavaScript. I created a function to play audio onclick (the sound is a gunshot). For some reason the error report says the playSound(volume) is not defined and I'm not sure how to fix it. I would like to find a solution to this. I'm pretty new to coding HTML5/Java in general and this is for an assignment, So I'd really appreciate it if i could get some help :)
I tried using the code from here but its not working properly for me so far : HTML5 audio - play sound repeatedly on click, regardless if previous iteration has finished
Here is the whole code for what I'm using so far so you don't get confused.
 <!DOCTYPE html>
 <html>

 <head>
 <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
 <style type="text/css">
.cvs { background-image:url('Game/Backdrop.jpg');}

body
 {
 background-position: left 40px;
 background-attachment: fixed;
 background-repeat: repeat;
 background-color:#131516;
 }

 </style>

<script type="text/javascript">
/* Global Var*/
var posX = 0;
var posY = 0;
var sound = new Audio("Game/fire.WAV");
sound.preload = 'auto';
sound.load();

/* end of global var*/

function handleClick(event)
{
    console.log('handleclick');
    console.log('BANG');
    drawBlood();
    playSound(volume);

}

function playSound(volume)
{

var click = sound.cloneNode();
click.volume = volume;
click.play();

}

function moveTarget(event)
{
    //console.log('moveTarget');
    var mCanvas = document.getElementById("myCanvas");
    var mContext = mCanvas.getContext('2d');
    clearCanvas();
    drawTarget();

}

function drawTarget()
{

    var mCanvas = document.getElementById("myCanvas");
    var mContext = mCanvas.getContext('2d');
    var mTarget = new Image();

    var mouseX = getXCoords(event);
    var mouseY = getYCoords(event);

    var offSetX = leftOffSet(event);
    var offSetY = scrollOffset(event);

    var posX = mouseX - offSetX;
    var posY = mouseY - offSetY;

    var targetX = 31;
    var targetY = 33;

    posX = posX - targetX;
    posY = posY - targetY
    mTarget.src="Game/target.png";
    mTarget.onload=function()
    {
        //clearCanvas();
        mContext.drawImage(mTarget,posX,posY);
    }
}

function getXCoords(event)
{
    var x = event.clientX;
    return(x);
}
function getYCoords(event)
{
    var y = event.clientY;
    return(y);
}

function clearCanvas()
{
    var mCanvas = document.getElementById("myCanvas");
    var mContext = mCanvas.getContext('2d');
    mContext.clearRect(0,0,mCanvas.width,mCanvas.height);
}

function leftOffSet(event)
{
    var mCanvas = document.getElementById("myCanvas");
    var winX = mCanvas.offsetLeft - mCanvas.scrollLeft;
    return(winX);
}
function scrollOffset(event)
{
    var mCanvas = document.getElementById("myCanvas");
    var winY = mCanvas.offsetTop - mCanvas.scrollTop;
    return(winY);
}

function drawBlood()
{

    var mCanvas = document.getElementById("myCanvas");
    var mContext = mCanvas.getContext('2d');
    var mBlood = new Image();

    var mouseX = getXCoords(event);
    var mouseY = getYCoords(event);

    var offSetX = leftOffSet(event);
    var offSetY = scrollOffset(event);

    var posX = mouseX - offSetX;
    var posY = mouseY - offSetY;

    var bloodX = 133;
    var bloodY = 44;

    posX = posX - bloodX;
    posY = posY - bloodY

    mBlood.src="Game/blood.png";
    mBlood.onload=function()
    {
        console.log(posX, posY);
        console.log("This is where blood is drawn");
        mContext.drawImage(mBlood,posX,posY);
        //clearCanvas();
    }
}

</script>
<audio src="Game/wolverine.mp3" autoplay="autoplay"></audio>
<audio src="Game/Deadpool Game - Main Menu Theme.mp3" autoplay="autoplay" loop="loop"> </audio>
<!--<BGSOUND src="Game/wolverine.mp3"
        balance =  0
        delay   = 100
        loop    = 1
        volume  = -500>

<BGSOUND src="Game/Deadpool%20Game%20-%20Main%20Menu%20Theme.mp3"
        balance =  0
        delay   = 10
        loop    = -1
        volume  = -500>
-->
</head>

<body>

<div style="width:1200px; height:900px; margin:0 auto;">
<canvas id="myCanvas" width="1200px" height="900px" class="cvs" onclick="handleClick(event)" onmousemove="moveTarget(event)"></canvas>


text:
Q: force cmake specific sh path I have incompatible sh.exe and make.exe in my path due to multiple toolchains for embedded development. I want to force use of the one not in my path.
cmake used the wrong make (the one in the path) to check GCC functionnality and I could force the correct make with SET(CMAKE_MAKE_PROGRAM .../make.exe)
How to do the same for sh.exe ?

A: Turning my comment into an answer
To make CMake to ignore the toolchain in your path you can utilize CMAKE_IGNORE_PATH with something like:
cmake -DCMAKE_IGNORE_PATH="/path/to/your/toolchain/bin" ..

Just be aware that the path has to be exact string match for the path (in CMake format with / slashes and it's case sensitive).
For more details: Environment variable used by CMake to detect Visual C++ compiler tools for Ninja


text:
Q: Sheaf associated to sheaf on basis Statement: If we have a basis $B$ for a topological space $X$, then a sheaf defined on $B$ defines uniquely a sheaf on $X$.
I was wondering if the following proof is correct:
Let $\mathcal{F}$ be a sheaf on $B$, then this gives a presheaf $\mathcal{G}$ on $X$ if we give some abelian groups for open sets $U\subseteq X$ not in $B$ and the needed restriction maps, such that they satisfy the presheaf axioms.
Then sheafification of $\mathcal{G}$ gives an unique sheaf $\mathcal{F}^+$ on $X$.
It follows from the construction of the sheaf $\mathcal{F}^+$ that the abelian groups we chose for $\mathcal{G}$ have no influence on the construction because stalks on $B$ and $X$ are the same.

A: Assume you want to have a sheaf of rings. Let $X=\{u,v\}$ be a set consisting of two points with the discrete topology. A base is given by $U:=\{u\}$ and $V:=\{v\}$. Declare $\mathscr F$ on this base by $\mathscr F(U)=\mathscr F(V)=\mathbb Z$, then you will not be able to decree $\mathscr G(X)=\mathbb Q$, because there is no ring homomorphism $\mathbb Q\to\mathbb Z$. If you want a sheaf of abelian groups, you will similarly not be able to decree $\mathscr G(X)$ as a cyclic group. This is just a very simple example, much more problems can arise as hinted to in the comments above. The point here is that the restriction maps are a very important part of the data that constitutes a presheaf.


text:
Q: how do i resolve the issue of no reverse match found?
django.urls.exceptions.NoReverseMatch: Rever\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 694, in _reverse
se for 'user_login' not found. 'user_login'
is not a valid view function or pattern name

I think the main problem is at the URL mapping as i am really new to this, I am just practicing by watching video lectures and that guy is using some older version of django and the URL mapping used by that guy involves resular expressions i.e ^ and $ sign. He has put dollar sign at the end of a url link for the first time and i can not find any alternate of that in django 3+ as i am using Path function for the mapping instead of regular expressions.
Views.py
def user_login(request):

if request.method == 'POST':
    username = request.POST.get('username')
    password = request.POST.get('password')

    user = authenticate(username=username, password=password)

    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))

        else:
            return HttpResponse("Account not Active")

    else:
        print("Someone tried to login and failed")
        print("Username: {} and Password {}".format(username,
password))
        return HttpResponse("invalid login details supplied!")

else:

    return render(request, 'basicapp/login.html',{})

urls.py from basicapp
from django.conf.urls import url
from django.urls import path
from basicapp import views

 app_name = 'basicapp'

urlpatterns = [
    path('register/', views.register, name= 'register'),
    path('user_login/', views.user_login, name= 'login'),
]

urls.py from project
from django.contrib import admin
from django.urls import path, include
from basicapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path ('',views.index, name ='index'),
    path ('basicapp/', include('basicapp.urls')),
    path ('logout/', views.user_logout, name='logout'),
    path ('special/', views.special, name = 'special'),
]

base template call

DJANGO

Admin

Register

      {% if user.is_authenticated %}

Logout

      {% else %}

Login

      {% endif %}

A: Import reverse_lazy and try replacing
reverse('index')

With
reverse_lazy('index')


text:
Q: Fetch a Model's associations in Laravel to simplify creation/update I have a Movie model with the following associations (belongsToMany):
Actor
Country
Genre
...
When a form is posted, I have this data (skipping a lot of details here):
'actors' => array(
    'Cary Grant',
    'Grace Kelly',
    ...
),
'genres' => array(
    'Drama',
    ...
),
...
I'd like my update()/store() controller function to easily associate these Models.
An actor with the name 'Cary Grant' may or may not exist and may or may not be already associated with the movie I'm editing. Also I could remove him from this movie, so I'd need to remove the association. Same with Genre and everything else.
So I thought I'd do a BaseModel and do all of this only once in there, like this:
1. get the Movie Model's defined associations.
2. check if POST data contains those associations.
3. for each of them, check if they exist (if not create them) and return an array of ids. the column I'm checking is 'name', but it could be configurable.
4. sync() those ids.
For now, I don't need to add more stuff to the related model from the movie form (ex. an actor's birthdate).
I'm stuck at n.1 ($movie->getRelations() only works for existing movies) and in general I'm not sure if this is the right approach. Hints?

A: use direct relations: $model->actors
http://laravel.com/docs/4.2/eloquent#relationships
All sync() stuff will be done by ORM, so the most complex thing you should do is n.3. You must create diff between $model->actors and $_POST['actors'] and understand what actors you need to insert (create new actors).

A: I've met the same problem and this is what I do in my project:

*

*Instead of retrieving all defined relations of the models, I white-listing  relations that can be updated by adding a static member
Movie::$editableRelations = ['actors', 'genres', 'countries'];

*Loop through the post data, and match with the $editableRelations arrays. If the data of a relation exists, following below steps, otherwise we simply do not touch this relation.
Step 3 and step 4 are the same as yours.


text:
Q: keep getting ERR.SWS.CLIENT.VALIDATION_FAILED exception when calling TravelItineraryReadRQ i am facing ERR.SWS.CLIENT.VALIDATION_FAILED exception in my code
my Request to Sabre
<?xml version="1.0" encoding="utf-16"?>
<TravelItineraryReadRQ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="3.9.0">
  <MessagingDetails xmlns="http://services.sabre.com/res/tir/v3_10">
    <SubjectAreas>
      <SubjectArea>DEFAULT</SubjectArea>
    </SubjectAreas>
  </MessagingDetails>
  <UniqueID ID="XXXXXX this is changed" xmlns="http://services.sabre.com/res/tir/v3_10" />
  <ReturnOptions xmlns="http://services.sabre.com/res/tir/v3_10" />
</TravelItineraryReadRQ>

Kindly Help me in this exception

A: The one below works for me:
<TravelItineraryReadRQ Version="3.9.0" TimeStamp="2012-09-19T10:00:00-06:00"
xmlns="http://webservices.sabre.com/sabreXML/2011/10">
 <MessagingDetails>
 <SubjectAreas>
 <SubjectArea>FULL</SubjectArea>
 </SubjectAreas>
 </MessagingDetails>
 <UniqueID ID="XXXXXX"/>
<ReturnOptions UnmaskCreditCard="false"/>
</TravelItineraryReadRQ>

Did you also set the headers correctly?


text:
Q: How to JSON encode an array with French accents? There are many threads about this but none of them helped me solve this problem.
$array=array(
"dépendre"=>"to depend",
"dire"=>"to say",
"distraire"=>"distracted",
"être"=>"to be (being)",
);

Gets encoded like this with json_encode :
"d\u00e9pendre":"to depend","dire":"to say","distraire":"distracted","\u00eatre":"to be (being)"

So far I have tried this:
array_walk_recursive($array,function($value,$key) {
     $key = urlencode(utf8_decode($key));
});

A: Try this,
json_encode($array, JSON_UNESCAPED_UNICODE);
You should get this result;
{
  "dépendre":"to depend",
  "dire":"to say",
  "distraire":"distracted",
  "être":"to be (being)"
}

A: Please check the result from the following code:
<?php
$x=array(
    "dépendre"=>"to depend",
    "dire"=>"to say",
    "distraire"=>"distracted",
    "être"=>"to be (being)",
);

$encoded = json_encode($x);

var_dump($x);

var_dump(json_decode($encoded, true));

The string you get in your question is a correctly escaped JSON and could be successfully decoded.


text:
Q: How to add authorization on header using Swift 3.0 + Alamofire 4.0 Am trying to add authorization to my header using a return apikey of my login user am trying like this but it seems to not working because am getting an error that apikey is missing (is a return error from the webservices)
 func getFavourites ()
{

    let headers = ["Content-Type": "application/x-www-form-urlencoded", "authorization" : user.apiKey ]

    Alamofire.request("http://localhost:8888/food_pin/v1/restaurantToFavourites", method: HTTPMethod.get,  encoding: URLEncoding.default, headers: headers).responseJSON { (response:DataResponse<Any>) in

        if response.result.value != nil
        {
            print(response.result.value!)
            print(response.response!)
            self.returnAllFavourites(data: response.data!)
        }

        else
        {
            print(response.result.error!)
        }
    }

}

A: Use Authorization as your header key.
However, you shouldn't need to do it, considering HTTP header keys are case-insensitive, the issue is probably on the server.


text:
Q: Paste in the last column ( using variable in range) vba I am trying to copy one column from different excel sheets in one folder and paste in the last column of another excel sheet.
I have a problem using variable in range function for the destination worksheet column
I tried to use my i counter or the m as the last column
I appreciate if some one can help or give me guidance
Sub LoadColumn()

Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Dim m As Integer
Dim val As Variant
Dim x As Workbook
Dim y As Workbook

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\Users\ ....")
Set y = Workbooks.Open("C:\Users.... .xlsm")

For Each oFile In oFolder.Files

Set x = Workbooks.Open(oFile.Path)
x.Sheets("example").Range("AF:AF").Copy

m = Range("A1").End(xlToRight).Column + 1

y.Sheets("summary").Range("i", "i").PasteSpecial Paste:=xlPasteValues

Application.CutCopyMode = False

x.Close

i = i + 1

Next oFile

End Sub

A: Try this (using value assignment, rather than the clipboard):
Sub LoadColumn()

    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object
    Dim i As Integer
    Dim m As Integer
    Dim val As Variant
    Dim x As Workbook
    Dim y As Workbook

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder("C:\Users\ ....")
    Set y = Workbooks.Open("C:\Users.... .xlsm")

    m = y.Sheets("Summary").Cells(1, Columns.Count).End(xlToLeft).Column + 1
    For Each oFile In oFolder.Files

    Set x = Workbooks.Open(oFile.Path)

    y.Sheets("summary").Columns(m).Value2 = x.Sheets("example").Range("AF:AF").Value2

    x.Close

    m = m + 1

    Next oFile

End Sub


text:
Q: A minority has or a minority have? I wrote:

a minority of pairs has (...)

A native speaker corrected this with:

a minority of pairs have (...)

Which one is correct?  I thought it should be the former, because minority is singular.  But English is funny sometimes with collective nouns.  What is the case here?

A: You are using 'minority' to mean 'a small number of' which can mean more than one.  A similar sentence to illustrate this would be:

A small number of pairs have

If you meant a single pair and want to use 'has', you should sign-post this explicitly e.g.

A pair has or A single pair has


text:
Q: When we send any videos or music in whatsapp how it is resuming when it is interrupted by any circumstances? When we send any media in whatsapp to our friends how it is resuming upload when we are interrupted by any call or some internet problem ? The retry button will resume the upload

A: It is likely to work something like this:

*

*Whatsapp client will send the size of the upload to the server so the server knows how many bytes to expect.

*When upload begins, the server will send an acknowledgement for a batch of bytes it has successfully uploaded.

*The server will know the upload has complete when it has received all the bytes.
Point 2 means that the Whatsapp client will know exactly what bytes have been sent to the server, so that when connectivity resumes, it knows exactly where to resume sending bytes from.
The server will also have a mechanism to handle receiving the same bytes more than once just incase the acknowledgement didn't reach the client.


text:
Q: How do ASP.NET Identity framework (forms) with bootstrap I'm doing an ASP.NET Web Application with Identity with this tutorial:
http://www.asp.net/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project
But I would like to the form with bootstrap like that:

  <input type="text" class="form-control" placeholder="Username">

But the form with .aspx is so:
    <asp:Literal runat="server" ID="StatusMessage" />

    <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>

        <asp:TextBox runat="server" ID="UserName" />

How it should be?
Thanks.

A: The idea is to add the css class's of bootstrap to the asp.net controls, and what other attributes you may like as:

    <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
    <asp:TextBox runat="server" ID="UserName" CssClass="form-control" placeholder="Username" />


text:
Q: Why is LaTeX producing a normal sentence as one long word? When I type:
Now divide both sides by 154 so we have 1 on the right side of the equal side, and you get:

into LaTeX, and then look at it in PDF view it combines that whole line into one long word with no spaces, so it looks like:
Nowdividebothsidesby154sowehave1ontherightsideoftheequalside,andyouget:

This is the MWE
\documentclass{article}
\usepackage[utf8]{inputenc} % not essential, but I'll leave it (GuM)

\begin{document}

To start you have to complete the square for 2x^2 - 12x + y^2 + 6y + 26 = 0. \\\\
Start by subtracting 26 from both sides to get: 2x^2 - 12x + y^2

\end{document}

A: From your comments, I gather your MWE looks something like this:
\documentclass{article}
\usepackage{graphicx,subfigure}
\usepackage{here}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{amssymb,amsmath,amsthm}

\begin{document}

To start you have to complete the square for 2x^2 - 12x + y^2 + 6y + 26 = 0.
\\\\
Start by subtracting 26 from both sides to get: 2x^2 - 12x + y^2

\end{document}

The problem you are having is that in LaTeX there are basically three modes (to keep things simple), paragraph mode, math mode and left-to-right mode (LR mode). Don't worry about it too much, the point is that we must distinguish between math mode and text mode (paragraph mode and LR mode are the two text modes). Maths must go in math mode, text needs to be in text mode.
Now, there are two types of math mode, inline math and display math. Display math is for when we want to highlight a formula or an equation or something, setting it off from the main body and displaying it to the reader. Inline math mode is for maths that appears as part of a sentence which is what you have here. For inline math, you need to put all of your maths inside $ ... $ or \( ... \) like so:
To start you have to complete the square for $2x^2 - 12x + y^2 + 6y + 26 = 0.$

Start by subtracting 26 from both sides to get: $2x^2 - 12x + y^2$

Now one thing is that some commands, such as ^ only work in math mode. Your problem was that you have ^ in text mode, you hadn't entered math mode at all. This would have caused a couple of
! Missing $ inserted.

errors. What's happened is LaTeX's got as far as your ^, and it's had a problem, because it needs to be in math mode and it's not. So it inserts the missing $ to put itself in math mode. Which is fine. Problem solved. Only, it doesn't know where the math mode should end. So what happens is LaTeX keeps going until it finds a closing $ to make the pair. In your MWE there isn't one, so LaTeX gets all the way to the end, finds there is no $ and inserts one. As a result, everything gets put in math mode, including the sentence that follows. And in math mode, letters like abc are treated as variables being multiplied (this is math mode after all), not as letters of a word. Spaces are ignored in math mode because LaTeX handles it all for us, giving us beautiful typographical results, with a lot of the spacing taken care of for us, without us having to do anything. But that does mean that text in math mode does not look good.
So there's your explanation. Also \\\\ is very very bad, do not do this, paragraphs should be ended by a blank line, much as you would be used to in a word processor in fact.


text:
Q: How to provide music streaming on ethereum blockchain I have some queries for ethereum blockchain.
1 - I was looking through some requirements of a project. They wanted to have music streaming on ethereum blockchain. I mean how that can be possible. I mean first pushing the data on ethereum and then retrieving that back would cost a lot of transactions. How can a music streaming be possible on ethereum.
2 - If I have an array of structs than pushing into an array is easy and possible but while retrieving back the whole array is not comming. I can have a specific index of that array. But I want the whole array, which is not getting retrieved. If it is not possible for EVM to give the whole array. Than what can be the alternative of the same.
3 - Lets say I am storing a reference link to blockchain. Now I can retrieve the link but, can I redirect to that link internally from blockchain only. I mean is it possible if I want to create a smart contract in which when a user gives some requirements than it automatically creates an account in mist or etherwallet.
Thanks in advance.

A: *

*The purchases, rights, ownership, etc. can be stored on the blockchain. The media itself would be stored offchain on something like IPFS.

*Using an index is the preferred way to go. Retrieving the entire array can be problematic if the size of the array is unbounded (you can start hitting out of gas exceptions). See a more detailed answer here on returning an array of structs and this answer for more information on gas usage with loops needed to decompose your array of structs.

*I'm not sure I understand this question. You can trigger something to occur by activity on the blockchain by throwing an event on the blockchain and clients listening for those events can then perform some action. If you're attempting to do something within a contract, you can use an oracle to retrieve external information for use in the contract. But, you can't do something like create a new EOA account from inside a contract. This requires a private key that should not be on the blockchain.


text:
Q: Find all de.wv articles that are not Wikidata-linked to a en.wv article How to find all German-Wikivoyage articles that are not Wikidata-linked to an English-Wikivoyage article?
For instance:

*

*https://de.wikivoyage.org/wiki/Calabash_Bay (not even present on Wikidata)

*https://de.wikivoyage.org/wiki/Cecina https://www.wikidata.org/wiki/Q157762
Could be in Python, but bash or any tool or even HTTP request is fine, the simpler the better.

A: I think the best way would be to access the SQL database for that.
For that, you can either get an account on Tool Labs or you can download the dump of the necessary tables of the database (here, that would be langlinks and page) and then import those into a local MySQL database.
The query would look something like:
select page_title
from page
where not exists
    (select * from langlinks where ll_from = page_id and ll_lang  = 'en')
and page_namespace = 0
and page_is_redirect = 0

This list also wouldn't contain pages that have a language link to English Wikivoyage using the old (in-page) method, but I believe those should be rare.

A: Magnus Manske's Not in the other language can do this and outputs a tidy PagePile with around 12k items.
There are related tools if you also want to include the few articles not yet on Wikidata.


text:
Q: Random TimeOuts in vb.NET Thread Code (Task Factory) I am working with a big application. It starts at the beggining of the form declaring and starting some threads:
      Thread1 = New Thread(AddressOf Thread1Sub)
      Thread1.Start()

      Thread2= New Thread(AddressOf Thread2Sub)
      Thread2.Start()

Ok. The program can be running without a problem for several minutes, hours, days. But then
randomly we start getting  an exception performing trivial database jobs like getting one registry.
I doubt that the GetRegistry database operation is faulty because it can be executed a thousand times, even more before I start getting the timeoutException.
Since this hangs started, I changed the  problematic function call and I am currently starting a new task as follows:
Dim TokenCancel As New CancellationTokenSource
Dim taskConta = Tasks.Task(Of DataSet).Factory.StartNew(
Function() myFunc(param1, param2),
     TokenCancel.Token, Tasks.TaskCreationOptions.LongRunning)

If taskConta.Wait(ThreadTimeOut) Then
 datos = taskConta.Result
Else
 Throw New TimeoutException("TimeOut")
End If

The function I am calling is real simple:
Private Function myFunc(ByVal param1 As Decimal, ByRef param2 As DatabaseObject) As DataSet
        DatabaseObject= New DatabaseObjectClass

         Dim datos As DataSet = DatabaseObject.GetRegistry(param1)
         Return datos

End Function

Randomly, I start getting timeout emails because that task who recovers a simple DataSet from database is getting timeout (Who is configured in 50000 milliseconds and it's very weird.
Im starting to thing it could be network related problems, because the function fails and it is caught by an exception but the next time if executes it works nice.
I would be glad if you give me some ideas.


text:
Q: Load XML data with same value in SQL Server Can anyone help me to load the following XML into my SQL Server database:
declare @learnxml varchar(5000);

set @learnxml = '
      <alerts>
          <alert id="XYQ">
             <alertTime>2020-01-06T09:49:59.999-0500</alertTime>
           <participants>
                  <item marketCode="CC">MAIN</item>
                  <item marketCode="CC">PASS</item>
           </participants>
        </alert>
     </alerts>';

DECLARE @xml XML = @learnxml
PRINT @learnxml;

SELECT
    xData.value('../../@id','Varchar(100)') AlertId,
    xData.value('../../alertTime[1]','Varchar(50)') AlertTime,
    xData.value('../item[1]', 'varchar(50)') ParticipantHouse,
    xData.value('(.)/@marketCode', 'varchar(20)') HouseMarketCode
FROM
    @xml.nodes('./alerts/alert/participants/item') AS x(xData)

Because of the same market code for both the items, the above query populates same value 'Main' instead of populating 2 rows with 2 different values Main and Pass.
What needs to be changed in above query to have 2 different values for the same market code?

A: Following query returns correct values:
SELECT xData.value('../../@id','Varchar(100)') AlertId,
xData.value('../../alertTime[1]','Varchar(50)') AlertTime,
xData.value('.', 'varchar(50)') ParticipantHouse,
xData.value('@marketCode', 'varchar(20)') HouseMarketCode
FROM @xml.nodes('./alerts/alert/participants/item') as  x(xData)


text:
Q: UWP - Automatic if statement with sequence condition I have a condition where if file = 2016, then folder_id = 1, if file = 2015 then folder_id = 2, like so on. How do I apply the if statement automatically (instead of entering one by one) with C# language?

A: Assuming files and folder ids are sequential...
var increment = 1;

var currentFile = 2016;
var currentFolder = 1;
var minFile = 2000;//change this to whatever you need

while(minFile <= currentFile){
    //do your work

    currentFile -= increment;
    currentFolder += increment;
}


text:
Q: When to use Instruction Set Extensions Technology from Intel When does it make sense to use Instruction Set Extensions Technology from Intel and what exactly does it do?
My scenario: I want to do ~500.000 matrix vector multiplications as fast as possible.
matrix size: [4x4] | vector size: [1x4]

A: If you can guarantee your clients have a certain level of SIMD support I don't see what's holding you back.
SIMD has been around for a long enough time it's not unreasonable to require your clients to have it.
As an example:
https://learn.microsoft.com/en-us/cpp/build/reference/arch-x86?view=vs-2019
https://learn.microsoft.com/en-us/cpp/build/reference/arch-x64?view=vs-2019
x86-64 guarantees that SSE2 is available, so compilers always use that for 64-bit builds.  (And in some sense it's not an extension anymore, just a baseline part of the x86-64 ISA).
EDIT:
Thank you for the edit Peter Cordes!
But I also wanted to point out to users if they are interested in SIMD they might want to look into OpenCL.
https://en.wikipedia.org/wiki/OpenCL
OpenCL helps users write very efficient SIMD programs.


text:
Q: Meteor setTimeout in method I have a collection called Games with method updateGame. I want to start game on client if playersCount = 4, so I want to update field hasStarted after 4 seconds. I tried it with bluebird promises, but got this error: "Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment."
export const updateGame = new ValidatedMethod({
  name: 'games.updateGame',
  validate: new SimpleSchema({
    gameId: { type: String },
  }).validator(),
  run({ gameId }) {
    const game = Games.findOne(gameId);
    let playersCount = game.playersCount + 1;
    let isRunning = false;
    if (playersCount === 4) {
      isRunning = true;
      startAfterDelay(gameId, 4000);
    }
    Games.update(gameId, {
      $set: {
        playersCount,
        isRunning
      },
    });
  },
});

const startAfterDelay = function(gameId, delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Meteor.wrapAsync(
        Games.update(gameId, {
          $set: {
            hasStarted: true
          },
        })
      );
    }, delay)
  })
}


text:
Q: Symfony2 dynamic queryBuilder I'm making a tool in which a user can view data from an entity, where they can choose what data and how they see the records.
I created a form with two date fields (start and end) and a list of fields that correspond to data counts and sums of the entity.
My question is:
How I can create a dynamically QueryBuilder that allows me to add fields based on what the user wants to see?
EDIT for Symfony2 dynamic queryBuilder
public function reportData($fields, $dateStart, $dateFinish)
{
    $em = $this->getEntityManager()
        ->getRepository('AcmeBundle:Entity');
    $query = $em->createQueryBuilder('e');

    foreach($fields as $field)
    {
        switch($field)
        {
            case 'totalResults':
                $query->setect('SUM(e.id) AS '.$field);
                break;
        }
    }
    $query->addWhere('e.dateStart >= :dateStart');
    $query->addWhere('e.dateFinish <= :dateFinish');
    ...

A: Something like this ? You store all your select queries in an array, then pass the array to the query builder after testing each of your fields.
public function reportData($fields, $dateStart, $dateFinish)
{
    $em = $this->getEntityManager()
        ->getRepository('AcmeBundle:Entity');
    $query = $em->createQueryBuilder('e');

    $select_array = array();

    foreach($fields as $field)
    {
        switch($field)
        {
            case 'totalResults':
                $select_array[] = 'SUM(e.id) AS '.$field;
                break;
        }
    }

    $query->select($select_array);
    $query->addWhere('e.dateStart >= :dateStart');
    $query->addWhere('e.dateFinish <= :dateFinish');
    ....

A: Basically, you want to keep on adding the

Select Fields

based upon the conditions.
So, the solution is simple.
You can use,
$queryBuilder->addSelect();

See Doctrine Query Builder Documentation

A: I would do a regular full query then filter it into a not doctrine object (dao/dto) then display it.
This way you can do the complex and optimized query first, then filter the result on whatever you want, even if it's not related to the query itself


text:
Q: Can't display Image in PDF-File if height > 72px I created a PDF-File with XSL. What iam trying to do is displaying a image with
<fo:block >
 <fo:external-graphic src="url('{.//ImagePfad}')"  />
</fo:block>

Its working fine with that as long as the picture has a height of 72px. If i change for example the height to 73, the image is no longer displayed. What could be the problem? How can i display images with a higher height?
Can someone help please help me with that

A: I found the solutions on my self. I had to to set the region-before higher


text:
Q: AppDomain unloaded issue with service bus version 2.6.5 We have multiple projects that are making use of the service bus library. We are currently using v2.6.5 at the moment and we've been getting several warnings for unit tests that calls to the code in the library. This is the warning message:
System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen if the test(s) started a thread but did not stop it. Make sure that all the threads started by the test(s) are stopped before completion.
And we would get it everytime we invoke this method: TopicClient.CreateFromConnectionString(connectionString, topicName)
This warning will not appear if we use the built-in Visual Studio test runner (2012/2015) and it would appear if we opt to use the MSTest runner via the .runsettings file.
It will also not appear if I update my service bus to version 3.0.0 and above but that is not possible because we were having a separate issues with them so the only option now is the stick to version 2.6.5 and try to fix those warnings.
Any idea what could be wrong? If you guys need additional information I'm happy to come up with a simple project that is able to reproduce the warning.


text:
Q: Survival plot in shiny app I am trying to plot survival plots in a shiny app. Among other exploratory graphs, The UI has two selectInput() blocks where a user can select either the type of 'event' like Renal Failure, Plasmacytoma etc. and the second input is for calculation of the time interval. Part of the UI code is:
 selectInput(inputId="event",
             label = "Event",
             choices = c("RenalFailure","Plasmacytoma","RemissionStatusPreTx","RemissionStatusPostTx",
                                                    "TotalNoTherapy","ISS")
                          ),
                          selectInput(inputId="analysis",
                                      label="Period for analysis",
                                      choices=c("From date of transplant"="TD",
                                                "From date of relapse"="TD_R")

                          ),

In the server, the code that I am using is:
output$events <- renderPlot({
if(input$analysis=='TD'){
fit_RF <- survfit(Surv(TD,cenin_dead)~input$event,data=rlp_data)
ggsurvplot(fit_RF,risk.table = T,risk.table.height = 0.4,pval = T)
} else{
  fit_RF <- survfit(Surv(TD_R,relapse)~input$event,data=rlp_data)
  ggsurvplot(fit_RF,risk.table = T,risk.table.height = 0.4,pval = T)
}

})

This gives me an error Error in model.frame.default: variable lengths differ (found for 'input$event'). I Googled this error but honestly, couldn't make much of it. I tried providing the argument na.action=na.omit but no joy. If I hard code input$event to the actual value that it is returning (say, RenalFailure), the plot renders. Quite clueless here and would appreciate some guidance please.


text:
Q: SQL Concat int to string in mariadb Iam working in XAMP on a local database Mariadb and want to add/concat a word to an int
This is my query
Select 'id:' + cast(Cid as varchar) from table where Cid is 3747;

The result should be id:3747
What am I doing wrong here?

A: Use CONCAT.
And the IS operator is only used for [NOT] NULL.
F.e. select col from tbl where col IS NOT NULL
select concat('id:', Cid) as result
from table
where Cid = 3747

But you could use IN also
select concat('id:', Cid) as result
from table
where Cid in (3747)


text:
Q: Symfony2 kernel.controller event for single controller or bundle scope My question about a little, but significant detail that i discover while read this article: http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html
Manual says, that declared TokenListener will be executed on each request. So, if i have a big application with a lot of controllers (or bundles with own controllers), and a lot of any other kind of event listeners, this beaviour add an overhead: each of the event listeners will be executed in each request for each bundle! For example, i have default AppBundle and ApiBundle, and in given example, TokenListener executes in case of request to boths bundles, because defined in app specific config: app/config/services.yml
How to avoid this beaviour? How to define listeners only per bundle, or, better, per controller? Maybe,it can be defined in bundle specific services.yml, but this is also too wide scope for listener, that used in a few controllers.

A: Please note that there probably is only one requests each time you open a page (apart from subrequests). The listener is thus only called once.
If you also look at the code of the listener, you can see that it already does only perform the "complex logic" when the controller is instance of TokenAuthenticatedController. This means it already quite does what you said you wanted: only execute for some controllers.
The only overhead one has is the call of the listener. This doesn't add much overhead.
Doing something to prevent the listener from being called when controller isn't an instance of TokenAuthenticatedController means you're just shifting the instanceof check from listener to a method before listener, ending up with exactly the same overhead.


text:
Q: How can I get Firebase Notification Body when user clicks? When user clicks a Firebase Notification in Android, you can get the following keys

*

*google.sent_time (long)

*from (string)

*google.message_id (String)

*collapse_key (String)

with the following code:
if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                String value = getIntent().getExtras().getString(key);
                Log.d(TAG, "Key: " + key + " Value: " + value);
            }
        }

However, I need to get the Body from the message. Is it possible?

A: Not if the app is in the background, the values defined in the notification payload are really for the purposes of generating a notification. If you want access to the values that are defined in the notification payload of the message then you should repeat them in the data payload so when the user taps on the notification you will be able to retrieve them from the extras of the intent. Something like:
{
  "to": "/topics/sometopic",
  "notification": {
    "title": "some title",
    "body": "some body"
  },
  "data": {
    "noti_title": "some title",
    "noti_body": "some body",
    "other_key": "other value"
  }
}

A: You have to handle the notification manually, just follow this guide.
To get the notification body, call remoteMessage.getNotification().getBody() in the onMessageReceived method.
And then when showing the notification (look at this file), add the body as extra to the intent.
intent.putExtra("body", notificationBody);
intent.putExtra("title", notificationTitle);

Hope this helps :)


text:
Q: Can I specify mandatory arguments with optparse I am using the optparse package but cannot find out if I can specify mandatory arguments.
install.packages('optparse')
library('optparse')
library('data.table')

# example from vignette
option_list <- list(
  # those 2 are linked together by dest='verbose'
  # store_true makes sure it does not take any arg by storing TRUE (or default if specified)
  make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default %default]"),
  make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"),
  #
  make_option(c("-c", "--count"), type="integer", default=5L, help="Number of rgn [default %default]", metavar="number"),
  make_option("--generator", default="rnorm", help = "Function to generate random deviates [default \"%default\"]")
)
parser <- OptionParser(option_list=option_list)

# vanilla case
parsedArgs <- parse_args(parser, args = c("-c","100","--generator","fakeGen"))
setcolorder(setDT(stack(parsedArgs)),c('ind','values'))[]
#         ind  values
#1:   verbose    TRUE
#2:     count     100
#3: generator fakeGen
#4:      help   FALSE

Say I want the user to input a [-d --date SOMEDATE] it does not really make sense to provide a default date... how can I tell optparse that some args are mandatory ?

A: According to its documentation, it does not seem that mandatory functionality is implemented by optparse package.
However, as a workaround, you can always check for the parameter value and stop() the script execution in case the parameter is not set.
One approach could be like:
install.packages('optparse')
library('optparse')
library('data.table')

# example from vignette
option_list <- list(
  make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default %default]"),
  make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"),
  make_option(c("-c", "--count"), type="integer", default=5L, help="Number of rgn [default %default]", metavar="number"),
  make_option("--generator", default="rnorm", help = "Function to generate random deviates [default \"%default\"]"),
  make_option(c("-d", "--date"), action = "store", default = NA, type = 'character',
              help = "some date to be converted from character")
)
parser <- OptionParser(option_list=option_list)

# check date is provided
if (!is.na(parser$date)) {
  mydate <- as.Date(parser$date)
}
else {
  stop("date parameter must be provided. See script usage (--help)")
}

By setting date's default value as NA we can check later if it was supplied.
Note: since date will contain user's input you should do some checks and/or handle the likely error issued by as.Date() function if it is not able to parse the given parameter option.


text:
Q: Equivalent of thread.interrupt_main() in Python 3 In Python 2 there is a function thread.interrupt_main(), which raises a KeyboardInterrupt exception in the main thread when called from a subthread.
This is also available through _thread.interrupt_main() in Python 3, but it's a low-level "support module", mostly for use within other standard modules.
What is the modern way of doing this in Python 3, presumably through the threading module, if there is one?

A: Well raising an exception manually is kinda low-level, so if you think you have to do that just use _thread.interrupt_main() since that's the equivalent you asked for (threading module itself doesn't provide this).
It could be that there is a more elegant way to achieve your ultimate goal, though. Maybe setting and checking a flag would be already enough or using a threading.Event like @RFmyD already suggested, or using message passing over a queue.Queue. It depends on your specific setup.

A: If you need a way for a thread to stop execution of the whole program, this is how I did it with a threading.Event:
def start():
    """
    This runs in the main thread and starts a sub thread
    """

    stop_event = threading.Event()
    check_stop_thread = threading.Thread(
        target=check_stop_signal, args=(stop_event), daemon=True
    )
    check_stop_thread.start()
    # If check_stop_thread sets the check_stop_signal, sys.exit() is executed here in the main thread.
    # Since the sub thread is a daemon, it will be terminated as well.
    stop_event.wait()
    logging.debug("Threading stop event set, calling sys.exit()...")
    sys.exit()

def check_stop_signal(stop_event):
    """
    Checks continuously (every 0.1 s) if a "stop" flag has been set in the database.
    Needs to run in its own thread.
    """
    while True:
        if io.check_stop():
            logger.info("Program was aborted by user.")
            logging.debug("Setting threading stop event...")
            stop_event.set()
            break
        sleep(0.1)

A: You might want to look into the threading.Event module.


text:
Q: Deletar arquivo de imagem ao excluir do editor tinymce Estou usando Tinymce, para editar os textos do site e também fazer o upload de imagens.
O upload e seu aparecimento esta funcionando perfeitamente.

Questão
É possível enviar algum comando GET com o nome da imagem para que possa também ser apagada no diretório?
tinymce.init({
  selector: 'textarea',
  directionality: 'pt_BR',
  language: 'pt_BR',
  height: 400,
  menubar: true,
  plugins: [
    " advlist anchor autolink codesample image imagetools",
    " lists link media noneditable preview",
    " searchreplace table visualblocks wordcount paste code fullscreen"
  ],
  toolbar: "undo redo | bold underline italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | image paste | code | fullscreen",
  paste_as_text: true,
  paste_data_images: true,
  entity_encoding: "raw",
  images_upload_url: './upload_tinymce.php'
});

A: Se entendi (a pergunta está confusa) você quer deletar uma imagem do servidor que esteja embarcada dentro do tinymce acaso o usuário remova ela da área de edição?
Eu devo dizer que isso é uma má ideia, isto porque estes tipos de editores suportam Ctrl+Z, então se deletar no momento que remover a imagem da área de edição e o usuário resolver fazer um Ctrl+Z ele não terá mais a imagem do servidor, pode ser até que ela esteja em cache no navegador, mas do lado do servidor ela não existirá.
A solução que proponho é simplesmente resolver isto no back-end no momento que você salva os dados no servidor, é basicamente simples, ao enviar o conteúdo do tinymce para o servidor você poderá usar o o DomDocument do PHP para fazer o parse em HTML, mas isso só vai funcionar se este editor for para uma unica coisa, se não for o caso então o que você deve fazer é checar todas edições que usuários fizeram, supondo que você tenha uma tabela com algo como (vamos chamar de tabela "postagens"):

id
titulo
conteudo

1
titulo 1
foo bar  um

2
titulo 2
lorem y  dois

Então na hora de salvar você pode checar todas "postagens" e obter todas imagens (tudo isto é hipotético) e fazendo o parse DOM disto tudo para pegar todas imagens (segue pseudocódigo para entendimento, independente de PDO ou mysqli ou outros bancos):
if (!query('INSERT INTO postagens')) // OU UPDATE, depende de como você preparou a lógica
{
     die('Falhou ao salvar');
}

function pegar_imagens($doc)
{
     $imagens = array();

     forach ($doc->getElementsByTagName('img') as $img)
     {
          $path = $img->getAttribute('src');

          if (!$path) continue;

          $imagens[] = basename($path);
     }

     return $imagens;
}

$todas_imagens = array();

$data = query('SELECT conteudo FROM postagens');

while ($row = $data->fetch()) {
    $doc = new DOMDocument;
    $doc->loadHTML($row['conteudo']); //Faz o parse do HTML no php

    //Junta imagens de postagens diferentes no mesmo array
    $todas_imagens = array_merge($todas_imagens, pegar_imagens($doc));
}

//Remove imagens repetidas
$todas_imagens = array_unique($todas_imagens);

//Pega todas imagens da pasta no seu servidor
foreach (glob('upload/*.{jpg,png,gif,webp}', GLOB_BRACE) as $imagem)
{
      //Verifica se a imagem da pasta NÃO está em nenhuma postagem
      if (!in_array(basename($imagem), $todas_imagens)) {
           //Acaso não estiver deleta a imagem
           unlink($imagem);
      }
}

Vale lembrar que se muitos usuários estão editando postagens isto pode causar conflitos, a maneira que creio que ajudaria a amenizar, se realmente tiver mais de um usuário usando o sistema é separar as imagens para cada usuário, poderia separar por pastas, então o glob() deverá ser executado somente na pasta que pertence ao usuário especifico.
Outra maneira seria executar o script acima em um CRON (sem a parte do insert e update, já que é algo totalmente separado), isto claro, deverá ser feito em um horário ocioso, em um momento que de preferência ninguém esteja usando o editor, isto você poderia checar através do seu sistema de logins (se ele foi bem trabalhado) ou então definir um horário do qual o sistema entre em modo de manutenção e impeça o acesso somente ao editor de textos, então você agendaria o CRON para executar todo dia neste horário X, poderia até colocar a "limpeza" para um domingo, exemplo:
0 03 * * * /var/www/tarefas/limpar-imagens-em-desuso.php


text:
Q: Problems with Swipe Gesture in Landscape Mode I have been trying to figure out a way to fix this on my own, without any luck.
Programming Language is Objective-C and SpriteKit is the technology.
I'm trying to make an SKNode move around the screen using swipe gestures. (In a landscape mode app)
The problem is when I swipe left or any other sides, the node will move the opposite direction and use another method than it's supposed to. It looks like the iPhone thinks it is in portrait mode. What should I do?
Here's the code:
Inside .h Declaring the node
SKNode *Main_Character;

Inside .m
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    UISwipeGestureRecognizer *oneFingerSwipeLeft = [[UISwipeGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(SwipedLeft)] ;
    [oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [[self view] addGestureRecognizer:oneFingerSwipeLeft];

    UISwipeGestureRecognizer *oneFingerSwipeRight = [[UISwipeGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(SwipedRight)] ;
    [oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [[self view] addGestureRecognizer:oneFingerSwipeRight];

    UISwipeGestureRecognizer *oneFingerSwipeUp = [[UISwipeGestureRecognizer alloc]
                                                  initWithTarget:self
                                                  action:@selector(SwipedUp)] ;
    [oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionUp];
    [[self view] addGestureRecognizer:oneFingerSwipeUp];

    UISwipeGestureRecognizer *oneFingerSwipeDown = [[UISwipeGestureRecognizer alloc]
                                                    initWithTarget:self
                                                    action:@selector(SwipedDown)] ;
    [oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionDown];
    [[self view] addGestureRecognizer:oneFingerSwipeDown];
}

// Methods to make the node move when a swipe is called.
-(void)SwipedDown{
    SKAction *Move = [SKAction moveByX:0.00 y:-50 duration:2];

    [Main_Character runAction:Move];
}

-(void)SwipedUp{
    SKAction *Move = [SKAction moveByX:0.00 y:+50 duration:2];

    [Main_Character runAction:Move];
}

-(void)SwipedRight{
    SKAction *Move = [SKAction moveByX:+50 y:0.00 duration:2];

    [Main_Character runAction:Move];
}

-(void)SwipedLeft{
    SKAction *Move = [SKAction moveByX:-50 y:0.00 duration:2];

    [Main_Character runAction:Move];
}

A: Your copy/paste have failed you, you need to fix your setDirections, you only set left, when you want to set other directions.


text:
Q: return what after a ajax call I use spring-mvc and I have a ajax call which return void because i just update some data in the database. But in case of the user is not logged , i want to redirect him to a login page but i have to specify String as return not void so How can I handle this ?
@RequestMapping(value="/add_to_fav")
public @ResponseBody
void add_to_fav( ... ) {
    ....
    if(session.getAttribute("contact") == null)
        return "redirect:/login?next="+URLEncoder.encode(
                request.getRequestURL().toString() + "" + (request.getQueryString() != null ? "?" + request.getQueryString() : "")
                    ,"utf-8");

    ....

}

A: On this case you have some possibilities, like exposed below:
a
 - Change your return to a boolean and if false redirect the user to the login page.

*

*Change your return to a boolean and if false you call a modal to ask to the user the credentials

*Be sure previously that the user is logged or not, and if not, call the modal before the server call, so you will have less calls to server.

*If none of these options is fit to you, put more details about the application to help to think about.


text:
Q: Change where mouse is actually clicking Is it possible with CSS to tell the browser that with this new cursor that the click point is not actually at 0x0y but actually 3x-20y.
Looking though all of the options, I did not see one to do such a thing.
http://www.w3schools.com/cssref/pr_class_cursor.asp
This would be helpful to be used in conjunction with either
Javascript library to Change cursor color
OR
cursor: url();

A: css3 supports this... cursor: url(curser.cur) 3 -20, auto;
The .cur format also embeds the hotspot...
This has already been covered in length here: link


text:
Q: Add VBA Project to Visio Document by Using Code I've been asked to create a macro to update a few hundred or so Visio drawings, and keep them updated.
The update involves putting all objects of a certain type on their own layer - simple.
Now, this is easy enough to do, but when a user adds a new object some time in the future it will likely be on a default layer. So I had hoped to be able to include a VBA macro which is triggered by the Save event to re-assign objects to their layers.
The problem here is that I'd need to include this macro in every document since Visio doesn't have an application level VBA project.
Is there any way to introduce a VBA project to ALL Visio documents using code (VBA or otherwise)?? Or is there an alternative I might not have considered? Unfortunately an Add-in is not really an option due to available resources.

A: You have a couple options here:

*

*Force every user to allow programmatic access to the VBA project for their documents, and use VBA automation to add code.  This works nicely when you have programmatic access, but this can be difficult to assure.

*If you're not using Visio 2013, you can actually save a document as VDX (xml) and replace the data for the VBA project with your own (you'd save out a document as VDX manually, and copy out the chunk of data for the VBA project).  As I said, this wouldn't work with Visio 2013 since they seem to have eliminated the VDX format.  You probably can get away with something similar with the VSDX XML format for 2013.

*You can 'migrate' everyone's documents to a new VST file you provide.  This would just involve copying and pasting all the content from a document into the new document that has your code in it.  You have to be careful though to make sure all the document- and page-level data comes along, too (meaning DocumentSheet and PageSheet and any Document XML properties that may be important, and attributes like Author, Description, etc...)

Item 1 is the easiest, aside from the pain getting programmatic access to VBA Projects, unless you can have people send you documents to migrate.


text:
Q: How to solve this email sending error in codeigniter How can I solve this email sending error in codeigniter?
220 smtp.googlemail.com ESMTP g7sm4210473pgr.52 - gsmtp hello:
250-smtp.googlemail.com at your service, [49.34.9.27]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8

Failed to authenticate password. Error: 535-5.7.8 Username and Password not accepted.

Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials g7sm4210473pgr.52 - gsmtp
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
Date: Thu, 14 Nov 2019 04:57:55 +0100 From: "RK Dream Homes" <> Return-Path: <> To: rushiid123@gmail.com Subject: =?UTF-8?Q?Property=20Management?= Reply-To: <> User-Agent: CodeIgniter X-Mailer: CodeIgniter X-Priority: 3 (Normal) Message-ID: <5dccd0c3c0a25> Mime-Version: 1.0

Content-Type: multipart/alternative; boundary="B_ALT_5dccd0c3c0a3c"

This is a multi-part message in MIME format. Your email application may not support this format.

--B_ALT_5dccd0c3c0a3c Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit

A: You must check few things (Gmail SMTP)

*

*Verify Email and Password are correct.

*Enable Less Secure App Here

*Enable Display Unlock Captcha  here

*Use Host : smtp.gmail.com

*Use Port : 587 or 465 as per SSL or TLS setting

Also check newline as per below
$config['newline'] = "\r\n";

A: Please try to use below configuration in CI and make sure it's correct.
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_user'] = 'apple@gmail.com';
$config['smtp_pass'] = 'password';
$config['smtp_port'] = '465';
$config['mailtype'] = 'html';
$config['starttls'] = false;
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;
$config['smtp_timeout']='30';
$config['newline']="\r\n";

Also, please ensure that gmail is allowed to access by another app.
There are 2 steps to check in gmail account.

*

*Allow less secure app access.
https://myaccount.google.com/lesssecureapps

*Allow access to your Google account.
https://accounts.google.com/b/0/DisplayUnlockCaptcha


text:
Q: Elastic search Synonym completely eliminated by analyzer I am using synonym file to create synonyms in elasticsearch, My requirement is to show photo frames of different sizes.
For example-
6x9, 6 x 9 => 6x9

But when I close and re-open the index, I am getting following error.
{
"error": {
    "root_cause": [
        {
            "type": "illegal_argument_exception",
            "reason": "failed to build synonyms"
        }
    ],
        "type": "illegal_argument_exception",
            "reason": "failed to build synonyms",
                "caused_by": {
        "type": "parse_exception",
            "reason": "Invalid synonym rule at line 107",
                "caused_by": {
            "type": "illegal_argument_exception",
                "reason": "term: 6 x 9 was completely eliminated by analyzer"
        }
    }
},
"status": 400
}

It works fine for
8x10, 8 x 10 => 8x10

Which means it is only working if it has minimum 2 digits after x ie. 10 in 8 x 10 .
Regarding 6x9 it is working fine. The only issue is with 6 x 9 as it has spaces and the last digit is single. But it is working fine if I change it to 6 x 09.
Here are the Settings -
"analysis": {
"filter": {
    "synonym_filter": {
        "type": "synonym",
            "synonyms_path": "analysis/synonyms.txt"
    },
    "suggestions_shingle": {
        "max_shingle_size": "4",
            "min_shingle_size": "2",
                "type": "shingle"
    },
    "english_stemmer_filter": {
        "name": "minimal_english",
            "type": "stemmer"
    },
    "edgeNGram_filter": {
        "min_gram": "2",
            "side": "front",
                "type": "edgeNGram",
                    "max_gram": "20"
    }
},
"analyzer": {
    "whitespace_punc_analyzer": {
        "filter": [
            "lowercase",
            "asciifolding",
            "word_delimiter"
        ],
            "type": "custom",
                "tokenizer": "whitespace"
    },
    "edge_nGram_analyzer": {
        "filter": [
            "lowercase",
            "asciifolding",
            "synonym_filter"
        ],
            "type": "custom",
                "tokenizer": "edge_ngram_tokenizer"
    },
    "path_analyzer_lc": {
        "filter": [
            "lowercase"
        ],
            "tokenizer": "path_tokenizer"
    },
    "stemmer_synonym_analyzer": {
        "filter": [
            "synonym_filter",
            "lowercase",
            "english_stemmer_filter"
        ],
            "tokenizer": "standard"
    },
    "whitespace_analyzer": {
        "filter": [
            "lowercase",
            "asciifolding"
        ],
            "type": "custom",
                "tokenizer": "whitespace"
    },
    "synonym_analyzer": {
        "filter": [
            "synonym_filter",
            "lowercase",
            "edgeNGram_filter"
        ],
            "tokenizer": "standard"
    },
    "edge_nGram_shingle_analyzer": {
        "filter": [
            "lowercase",
            "asciifolding",
            "synonym_filter",
            "suggestions_shingle"
        ],
            "type": "custom",
                "tokenizer": "edge_ngram_tokenizer"
    },
    "path_analyzer": {
        "tokenizer": "path_tokenizer"
    }
},
"tokenizer": {
    "edge_ngram_tokenizer": {
        "token_chars": [
            "letter",
            "digit"
        ],
            "min_gram": "2",
                "type": "edgeNGram",
                    "max_gram": "6"
    },
    "path_tokenizer": {
        "ignore_case": "true",
            "type": "path_hierarchy",
                "delimiter": ">"
    }
}}

Thanks in advance!

A: It's because of the edge_ngram_tokenizer tokenizer that has min_gram set to 2, and hence, it cannot produce any tokens for single character input.
POST _analyze
{
  "text": "6 x 9",
  "tokenizer": {
    "token_chars": [
      "letter",
      "digit"
    ],
    "min_gram": "2",
    "type": "edgeNGram",
    "max_gram": "6"
  }
}

=> tokens: []
For 8 x 10, only the token 10 is produced, which is probably not what you want either:
POST _analyze
{
  "text": "8 x 10",
  "tokenizer": {
    "token_chars": [
      "letter",
      "digit"
    ],
    "min_gram": "2",
    "type": "edgeNGram",
    "max_gram": "6"
  }
}

=> tokens: [10]
So the reason you're getting this error message is because the tokenizer doesn't produce any tokens, and then token filters have nothing to chew on.


text:
Q: How to recognize the enumerate shortlabels in my custom environment? On How to create a enumerate list adding a custom prefix before each item number? I learned how to create a custom environment to create labels. But now, it is missing the enumitem shortlabels feature:
By taking the original example, I managed to pass the delimiter type to the nested environment list:

\documentclass{scrbook}

\usepackage{enumitem}
\usepackage{xparse}
\newcounter{enumerateoptionalcount}

\NewDocumentEnvironment{enumerateoptional}{O{)}}{%
    \setcounter{enumerateoptionalcount}{0}%
    \renewcommand*\descriptionlabel[1]{%
      \stepcounter{enumerateoptionalcount}%
      \normalfont\bfseries ##1~\arabic{enumerateoptionalcount}#1%
    }%
    \description%
  }%
  {\enddescription}

\begin{document}

\begin{enumerateoptional}[)]
   \item[Some first] item one
   \item[Some second] item two
   \item[Some third] item three
   \item[Some fourth] item four
   \item[Some Fifth] item five
\end{enumerateoptional}

\end{document}

But how can I also pass the number type as enumerate environment has, i.e.,

*

*If I call \begin{enumdescript}[1)], then, the number are 1) ..., 2) ...

*If I call \begin{enumdescript}[i)], then, the number are i) ..., ii) ...

*If I call \begin{enumdescript}[I)], then, the number are I) ..., II) ...

*...

I tried to look at the enumitem package source-code, but I cannot understand anything about it. For example, \ifx\enit@b\enit@c\else ... \enit@elt{##1}{##2}, what is enit? What does elt mean? What are enit@a, enit@b, enit@c doing?
\newcommand\SetEnumerateShortLabel[2]{%
  \let\enit@a\@empty
  \def\enit@elt##1##2{%
    \def\enit@b{#1}\def\enit@c{##1}%
    \ifx\enit@b\enit@c\else
      \expandafter\def\expandafter\enit@a\expandafter{%
        \enit@a
        \enit@elt{##1}{##2}}%
    \fi}%
  \enit@marklist
  \expandafter\def\expandafter\enit@a\expandafter{%
    \enit@a
    \enit@elt{#1}{#2}}%
  \let\enit@marklist\enit@a}

\SetEnumerateShortLabel{a}{\alph*}
\SetEnumerateShortLabel{A}{\Alph*}
\SetEnumerateShortLabel{i}{\roman*}
\SetEnumerateShortLabel{I}{\Roman*}
\SetEnumerateShortLabel{1}{\arabic*}

A: You can simplify the code in the OP by using tools from the enumitem package to create a customised enumerate environment. If you do this then you can change the labels in the enumerate in standard way provided by the enumitem package:
\begin{enumerateoptional}[label=\alph*]
   \item[Some first] item one
   \item[Some second] item two
   \item[Some third] item three
   \item[Some fourth] item four
   \item[Some Fifth] item five
\end{enumerateoptional}

to produce:

whereas by default, when you omit the [label=\alph*], you get:

The trick is to redefine the \item command to do what you want. To do this I make a "copy" of the real item command and then define a custom \optionalItem that gives your format. Then in the specifications for the custom enumerate environment you add before=\let\item\optionalItem to use the custom item command.
Here is the full code:
\documentclass{scrbook}

\usepackage{enumitem}
\newlist{enumerateoptional}{enumerate}{1}
\setlist[enumerateoptional]{
    before=\let\item\optionalItem,
    label=\arabic*,
    nosep,
    labelindent=20mm,
    leftmargin=*
}
\let\realItem\item

\newcommand\optionalItem[1][]{%
  \refstepcounter{enumerateoptionali}% increment the counter
  \realItem[\bfseries#1~\theenumerateoptionali)]%
}

\begin{document}

\begin{enumerateoptional}
   \item[Some first] item one
   \item[Some second] item two
   \item[Some third] item three
   \item[Some fourth] item four
   \item[Some Fifth] item five
\end{enumerateoptional}

\begin{enumerateoptional}[label=\alph*]
   \item[Some first] item one
   \item[Some second] item two
   \item[Some third] item three
   \item[Some fourth] item four
   \item[Some Fifth] item five
\end{enumerateoptional}

\end{document}


text:
Q: Bot Framework SDK4 C# - send proactive message to a user in Teams / REST response timeout Based on a GitHub sample, I created a dialog bot in Teams that collects information from a user and sends that to a Flow (Microsoft Flow/Power Automate) with a HTTP POST call.
After that the Bot waits for a response and sends it back to the user. This generally would be sufficient if the timeout for the call wasn't limited to 2 minutes - sometimes it takes longer to get the complete actions in Flow and get the response.
My question is how I could accomplish the same without getting the timeout. REST seemed the easiest as I'm not a programmer..
I checked the GitHub sample for proactive messaging (https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/16.proactive-messages), and that worked in the Emulator when I enter http://localhost:3978/api/notify, but I have no idea how to use it published to Azure. What would be the endpoint and how I could pass the message text?
Thanks

A: You should do some code modify if you want to send an message based on proactive-messages demo .
You can refer to my previous post which will meet your requirement.
After you modify the NotifyController.cs file , you can use send messages to a specific user with steps below :

*

*Connect to your bot get current user ID :

*Send message to this user by rest client tool or post man :

Result :

If you publish your bot to Azure , lets assume your Azure App service host is :https://xxxxxx.azurewebsites.net , then your bot message endpoint will be :https://xxxxxx.azurewebsites.net/api/messages and your /notify function endpoint will be : https://xxxxxx.azurewebsites.net/api/notify . In brief , just use your Azure App service endpoint to replace http://localhost:3978 will be fine .
Hope it helps . If there is anything unclear pls feel free to let me know .