text:
Q: Find rows that are not in a set of values (similar to SQL Except) What I'm trying to do is delete several rows of an Excel-Files (with pandas) and then save the File without those rows to .xlsx (with pyexcelerate module).
I'm aware that I can remove rows of a data frame by dropping them (I already got that to work). But I have read in several posts that when there are many (in my case > 5000) rows that should be deleted it's much faster to just get the indexes of the "to delete" rows from the data frame and then slice the data frame (just as a SQL Except statement for example would do).
Unfortunately I can't get it to work, even though I've tried several methods.
Here are my "source posts":
Slice Pandas dataframe by labels that are not in a list - Answer from User ASGM
How to drop a list of rows from Pandas dataframe? - Answer from User Dennis Golomazov
And here is a part of the function, that should delete the rows and save the created file:
for index, cell in enumerate(wb_in[header_xlsx]):
    if str(cell) in delete_set:
        set_to_delete.append(index)
        print str(cell) + " deleted from set: " + str(len(set_to_delete))
wb_out = Workbook()
data_out = wb_in.loc[set(wb_in.index) - set(set_to_delete)]
ws_out = wb_out.new_sheet('Main', data=data_out)
wb_out.save(file_path + filename + "_2.xlsx")

Here is an example of the data frame:
               sku  product_group                      name  \
0  ABCDb00610-23.0           ABA1        Anti
1  ABCDb00610-10.0           ABA1        Anti
2   ABCDb00610-1.1           ABA1         Anti
3  ABCDb00609-23.0           ABA1         Anti
4  ABCDb00609-10.0           ABA1         Anti
5   ABCDb00609-1.1           ABA1         Anti
6  ABCDb00608-23.0           ABA1         Anti
7  ABCDb00608-10.0           ABA1         Anti
8   ABCDb00608-3.3           ABA1         Anti
9   ABCDb00608-3.0           ABA1         Anti

Delete_set is a set that contains only skus (e.g.: ABCDb00608-3.3 or ABCDb00609-1.1).
Btw: I have tried many solution suggestions!
Thanks in advance!

A: Use pd.Series.isin:
df = df[~df.sku.isin(delete_set)]

print(df)
               sku product_group                   name
0  ABAAb00610-23.0          ABA1  Anti-Involucrin [SY5]
1  ABAAb00610-10.0          ABA1  Anti-Involucrin [SY5]
2   ABAAb00610-1.1          ABA1      Anti-EpCAM [AUA1]
3  ABAAb00609-23.0          ABA1      Anti-EpCAM [AUA1]
4  ABAAb00609-10.0          ABA1      Anti-EpCAM [AUA1]
5   ABAAb00609-1.1          ABA1      Anti-EpCAM [AUA1]
6  ABAAb00608-23.0          ABA1      Anti-EpCAM [AUA1]
7  ABAAb00608-10.0          ABA1      Anti-EpCAM [AUA1]
8   ABAAb00608-3.3          ABA1      Anti-EpCAM [AUA1]
9   ABAAb00608-3.0          ABA1      Anti-EpCAM [AUA1]

print(delete_set)
('ABAAb00608-3.3', 'ABAAb00609-1.1')

m = ~df.sku.isin(delete_set)
print(m)
0     True
1     True
2     True
3     True
4     True
5    False
6     True
7     True
8    False
9     True
Name: sku, dtype: bool

print(df[m])
               sku product_group                   name
0  ABAAb00610-23.0          ABA1  Anti-Involucrin [SY5]
1  ABAAb00610-10.0          ABA1  Anti-Involucrin [SY5]
2   ABAAb00610-1.1          ABA1      Anti-EpCAM [AUA1]
3  ABAAb00609-23.0          ABA1      Anti-EpCAM [AUA1]
4  ABAAb00609-10.0          ABA1      Anti-EpCAM [AUA1]
6  ABAAb00608-23.0          ABA1      Anti-EpCAM [AUA1]
7  ABAAb00608-10.0          ABA1      Anti-EpCAM [AUA1]
9   ABAAb00608-3.0          ABA1      Anti-EpCAM [AUA1]


text:
Q: Copying the same directory from multiple parent directories to a multiple destinations What I want to do is copy a directory that exists in multiple parent directories, to a destination while preserving the \Parent\child structure. The source directories are versioned software releases, and the directory that I want contains hot-fixes for each of those versions.
Source directory structure
\Releases\app_26.6.1.123\Patch\
\Releases\app_26.6.2.456\Patch\
etc etc

The last two numbers change, but the format is always #.## or #.###, with the first # incrementing from 1 to 7.
And what I'm trying to do is something like this:
copy \Release\app_26.6.[1-7].*\Patch\ to C:\Temp\eureka\app_26.6.[1-7].*\Patch\

I think that I'll have to use a for loop iteration, but my brain is hurting trying to think of a way to do this in powershell; and that's why I'm here.
This post is pretty close to what I want to do, but wrong platform:
Copying multiple directories into multiple destination directories
Thank you

A: I'm assuming you have multiple destinations per source patch? Try something like this where you wildcard up the version number in the name:
Foreach ($src in (Get-Item "\Releases\app_*\Patch")) {

  # Split off the last version number on the parent folder
  $baseVersion = ($src.parent.name -split '\.')[0..2] -join '.'

  # Get each destination folder using * wildcard
  $destinations = Get-Item "c:/Temp/eureka/$baseVersion*/"

  # Copy folders
  Foreach ($dst in $destinations) {
    Copy-Item $src.FullName $dst.FullName -Recurse
  }

}

This should create the following source and destination structure:
# src
\Releases\app_26.6.1.123\Patch\1
\Releases\app_26.6.2.456\Patch\2

# dst
c:/Temp/eureka/app_26.6.1.100/Patch/1
c:/Temp/eureka/app_26.6.1.200/Patch/1

c:/Temp/eureka/app_26.6.2.300/Patch/2
c:/Temp/eureka/app_26.6.2.400/Patch/2

If you don't want a wildcard but specifically need [1-7], you can use regex:
$destinations = Get-Item "c:/Temp/eureka/*/" |
  Where Name -match "$baseversion.[1-7]"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make Microsoft Lync instant messenger open reliably? Often I try to open Lync 2010, but nothing happens. On inspection in task manager, there are several communicator.exe processes in task manager. How can I stop this happening, so Lync window opens reliably?
Tedious workaround: kill and the communicators and try opening Lync again.

A: I have been encountering this problem for the last few months. I am not sure whats causing the problem and how to avoid it completely.
Earlier when I would open MS Office/Outlook or SharePoint which are integrated with Lync because of Single Sign On, I noticed that Lync would run into this issue.
The workaround which has worked for me is that I first open Microsoft Lync after starting my computer and only then open any other programs like Microsoft Outlook/SharePoint.
Try this approach.

A: Yes, in Lync options, uncheck the box that says not to start Lync during Windows Startup.


text:
Q: Is there a Google DFP api to check whether an ad units is active or not? Is there a Google DFP api to check whether an ad unit is active or not ?
Any suggestions are appreciated! Thanks

A: The google publisher console can help check for active ad units, https://support.google.com/dfp_sb/answer/2462712?hl=en.

A: It depends on what you mean by "whether an ad unit is active or not". In general it's best to be as descriptive as posible in questions and to include what you've already tried, it saves time in the answers. I'll do my best.
If you're trying to debug whether it was properly loaded on the site, then I'd suggest you debug using the DoubleClick Publisher Console, which you can activate by adding ?googfc to the end of the URL. In there you can check which ad units are called and their status, and you can also follow the execution on the History tab inside the console.
You could also use the Google Publisher Toolbar chrome extension, which has some more information on the ad being rendered, the line item, etc.
Moreover, you could set up an event listener and render information to the developer console.
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
        console.info(event);
    }
});

This code should be included inside the googlgoogletag.cmd.push(function() {}) and below the slot definitions (e.g.: the method defineSlot()).
However, if you want to do is programatically check if an ad unit is active prior to calling it or defining it, then I think you should rephrase the question to be a bit more specific.


text:
Q: Refer to a loop variable in an argument I have a script (myscript.sh) loop that greps some strings in many different files, stores them in a new file, and then cats the content of this file to the terminal:
for i in {1..201..5}; do
        grep "Pitch" filename-$i.log | cut -d" " -f25
done > pitch.txt
echo "========Pitch==========="
cat pitch.txt

Here's what I'd like to do instead from the command line:
./myscript.sh filename-$i.log

This then runs myscript.sh, looping over the variable i that I refer to in the argument to myscript.sh.
I hope I have explained my goal here properly!

A: If you want to pass the base part of thew different filenames as the first parameter to your script, change the loop to:
for i in {1..201..5}; do
        grep "Pitch" "${1}-${i}" | cut -d" " -f25
done > pitch.txt

(assuming the dash is always there, and not passed as part of the parameter, and the variable part of the filenames is always at the end)

A: Use this syntax:
for ((i=0; i<=$1; i=(($i + 5)) ))
        grep "Pitch" filename-$i | cut -d" " -f25
done > pitch.txt
echo "========Pitch==========="
cat pitch.txt

A: It's not exactly clear what you are after, but from what I get is that you have 6 directories but each directory has files named in a similar fashion of having numbers at their end. Then you could do this like this:
for arg
do
   for i in {1..201..5}; do
      grep "Pitch" "$arg-$i" | cut -d" " -f25
   done > $arg/pitch.txt
   echo "========Pitch==========="
   cat $arg/pitch.txt
done

A: This bash function should work:
foo() {
    searchstring="$1"
    shift 1
    echo "========${searchstring}===========" ;
    grep --no-filename "${searchstring}" "$@" | \
    cut -d" " -f25 | tee "${searchstring,,}".txt
    }

Invoke like so:
foo Pitch filename-{1..201..5}

How it works.  Since grep allows multiple file names from the command line, and bash allows prefixing a string to code like {1..10}, there's no need to pass file names one a time through a for loop.  The cat and > can both be replaced by a single tee.
The first argument of foo is the search string, (e.g. "Match"), which the shell sets to "$1" -- that gets moved to a temporary variable $searchstring, then "Match" is removed with shift 1, so that "$@" contains only the filenames.


text:
Q: Limit point alternative definition I have a question, why isn't an alternative definition of a $p \in X$ being a limit point of a set $E$  : $\forall r>0 N_r(p) \cap E \neq \emptyset$, why does it have to be the punctured neighborhood?
Note that $E$ is a subset of $X$ and $X$ is a metric space.
Note that the definition of a limit point of a set E is a point $p \in X$ such that every neighborhood contains a point $q$ such that $q\neq p$ and $ q\in E$.

A: The definition of a limit point uses punctured neighborhoods to intentionally exclude isolated points of $E$ from being limit points. To see this just consider any closed set $E$ with an isolated point $p$. And notice that if we didn't use punctured neighborhoods, then the isolated point $p$ would be considered a limit point of $E$ (hypothetically).
We typically say $p \in \text {Cl}(E)$ if and only if $p$ is an adherent point of $E$. An adherent point of $E$ is either a limit point of $E$ or an isolated point of $E$.
To summarize:

*

*$p$ is a limit point of $E$ means there is a sequence of points $\{p_n\}_{n=1}^\infty$ with $p_n \in E$ and $p_n \neq p$ for every $n \in \mathbb N$ and such that $\lim_{n \to \infty} p_n = p$. Notice how an isolated point of $E$ can't possibly be the limit of such a sequence.

*$p$ is an adherent point of $E$ means there is no open neighborhood $U_p$ such that $U_p \cap E=\emptyset $. More informally, $p$ sticks to $E$ in the sense that we cannot find a open set containing $p$ that is disjoint from $E$.

I hope this helps to clarify things.


text:
Q: How do I enumerate through a JsonElement Array and then convert it to a List? Note that JsonElement is nullable (for a reason elsewhere in my project):
JsonElement? json = JsonSerializer.Deserialize<JsonElement?>(jsonData);
List<JsonElement?> itemsArray = json?.EnumerateArray().ToList();

The error in this code says:

Cannot convert from List to List<JsonElement?>

A: Working with .Select() from System.Linq to casting each element to Nullable<JsonElement> type.
using System.Linq;

List<JsonElement?> itemsArray = json?.EnumerateArray()
    .Select(x => x as Nullable<JsonElement>)
    .ToList();

Or with .Cast<T>().
List<JsonElement?> itemsArray = json?.EnumerateArray()
    .Cast<JsonElement?>()
    .ToList();


text:
Q: I don't know how to fix my update code, vb.net to access database
This is the error I get
I don't know how to fix my update code, vb.net to access database I don't understand the error, though the database/connection notifies me it's opened

A: "& My.txtSearchMyID.Text &" ---> '" & My.txtSearchMyID.Text & "'


text:
Q: Preloading sprite kit textures So I was reading the apple documentation for best sprite kit practices. I came across this:
For example, if your game uses the same textures for all its gameplay, you might create a special loading class that runs once at startup. You perform the work of loading the textures once, and then leave them in memory. If a scene object is deleted and recreated to restart gameplay, the textures do not need to be reloaded.
And this would significantly help performance in my application.  Can someone point me in the right direction to how I would go about achieving this?
I presume I would call a function to load up texture's in my View Controller? And then access that texture atlas?

A: The thing is, do you really want to cache the resources like that? Can't say I ever found a need for something of that nature. Anyways, if doing that somehow helps with your app's performance, then you can make a TextureManager class which would be a singleton (create separate file for TextureManager class), like this:
class TextureManager{

    private var textures = [String:SKTexture]()

    static let sharedInstance = TextureManager()

    private init(){}

    func getTexture(withName name:String)->SKTexture?{ return textures[name] }

    func addTexture(withName name:String, texture :SKTexture){

        if textures[name] == nil {
            textures[name] = texture
        }
    }

    func addTextures(texturesDictionary:[String:SKTexture]) {

        for (name, texture) in texturesDictionary {

            addTexture(withName: name, texture: texture)
        }
    }

    func removeTexture(withName name:String)->Bool {

        if textures[name] != nil {
            textures[name] = nil
            return true
        }
        return false
    }
}

Here you are using dictionary and associate each texture with its name. Pretty simple concept. If there isn't a texture with the same name in a dictionary, then add it. Just beware of premature optimization.
The usage:
 //I used didMoveToView in this example, but more appropriate would be to use something before this method is called, like viewDidLoad, or doing this inside off app delegate.
    override func didMoveToView(view: SKView) {

        let atlas = SKTextureAtlas(named: "game")

        let texture = atlas.textureNamed("someTexture1")

        let dictionary = [
             "someTexture2": atlas.textureNamed("someTexture2"),
             "someTexture3": atlas.textureNamed("someTexture3"),
             "someTexture4": atlas.textureNamed("someTexture4"),

        ]

        TextureManager.sharedInstance.addTexture(withName: "someTexture", texture: texture)
        TextureManager.sharedInstance.addTextures(dictionary)

    }

As I said, you have to put TextureManager implementation in a separate file, to make it real singleton. Otherwise, if you define it in GameScene for example, you will be able to call that private init, and then TextureManager will not be a real singleton.
So, with this code you can create some textures at the very beginning of the app lifecycle, like it is said in the docs:

For example, if your game uses the same textures for all its gameplay,
  you might create a special loading class that runs once at startup.

and fill the dictionary with them. Later on, whenever you need a texture, you will not use atlas.textureNamed() method, but rather load it from a dictionary property of a TextureManager class. Also, when transitioning between scenes, that dictionary will survive scene's deinits, and will persist while app is alive.


text:
Q: Invalid argument supplied for foreach in Symfony Controller Im trying to add products to current logged in user cart in my CartController, but when i click the "Add To Cart" Button it throws the following exception: Warning:

Invalid argument supplied for foreach()

Here's my addToCart Function:
/**
     * @Route("/cart/add", name="cart_add")
     */
    public function addToCartAction(Request $request)
    {
        $manager = $this->getDoctrine()->getManager();
        $currentUserId = $this->get('security.token_storage')->getToken()->getUser();
        $session = $this->get('session');
        $id_cart = $session->get('id_cart', false);

        if (!$id_cart) {
            $cart = new Cart();
            $cart->setUserId($currentUserId);
            $cart->setDateCreated(new \DateTime());
            $cart->setDateUpdated(new \DateTime());

            $manager->persist($cart);
            $manager->flush();
            $session->set('id_cart', $cart->getId());
        }

        $cart = $this->getDoctrine()->getRepository('AppBundle:Cart')->find($session->get('id_cart', false));

        $products = $request->get('products');

        foreach ($products as $id_product) {
            $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($id_product);

            if($product) {
                $cartProduct = new CartProduct();
                $cartProduct->setCart($cart);
                $cartProduct->setProduct($product);
                $cartProduct->setQuantity(1);

                $manager->persist($cartProduct);
            }
        }
        $cart->setDateUpdated(new \DateTime());
        $manager->persist($cart);
        $manager->flush();

        return $this->redirectToRoute('cart_list');
    }

A: You should add a default value when you get a parameter to avoid those kind of errors:
$products = $request->get('products', []);


text:
Q: Wicket 1.5 compared to 1.4 What are the wicket 1.5 new features in short as compared to the most recent 1.4 release?
The first release candidate will be released very soon. We're thinking about the introduction of wicket in one of our projects, so for me it's relevant to see what's coming up in 1.5 and if it's worth to build our software on top of the upcoming 1.5 release or based on the stable 1.4.

A: There's a work in progress wiki page that answers this question over here: https://cwiki.apache.org/WICKET/migration-to-wicket-15.html

A: There's a Wicket 1.5 wishlist here. Some items have been scored out, suggesting that this list more or less accurately represents what's in 1.5.


text:
Q: Is there a way to change a php URL with htaccess? I am trying to change:
example.com/profile.php?id=abcdefgh

To simply:
example.com/abcdefgh

I searched here on StackOverflow and I understood that I need to do something with my .htaccess, I tried this code:
RewriteEngine On

RewriteRule ^([^/]*)$ /profile.php?id=$1 [L]

But it seems nothing changes, when type this URL (example.com/profile.php?id=abcdefgh) it doesn't get rewritten.
P.S. I don't know if the above code is right, i tried it because where I got it from had a similar problem to mine.

A: This should work.
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ profile.php?id=$1 [QSA,L]

A: You should be requesting the "pretty" URL, ie. /abcdefgh. Your mod_rewrite directive in .htaccess then internally rewrites this to the "real" URL that actually handles the request (ie. /profile.php?id=$1). That directive is expecting a URL of the form /abcdefgh. However, in its current state I should expect a rewrite loop:

*

*Request /abcdefgh

*Request is rewritten to /profile.php?id=abcdefgh.

*Processing starts over...

*Request is rewritten to /profile.php?id=profile.php (because the regex ^([^/]*)$ matches the profile.php part of the rewritten URL.

*GOTO #3

In this example you can avoid the rewrite loop by simply making the RewriteRule pattern (regex) more restrictive. eg. Include a dot (.) in the negated character class (assuming your new "pretty" URLs do not contain a dot).
For example:
RewriteRule ^([^/.]+)$ /profile.php?id=$1 [L]

You then need to actually change the URLs on your website to the new "pretty" URLs.
However, if you are currently getting a 404 then maybe this directive isn't being processed at all? Are .htaccess files enabled? Do you have other directives in your .htaccess file?

UPDATE: in the id the only characters allowed are A-Z

In that case you should be more specific with the regex and match just the characters required. This helps to avoid conflicts and avoids the need for filesystem checks (to some extent) - which are relatively "expensive". Note, however, that you've stated "A-Z" but your example includes lowercase letters. For the sake of argument I'll assume the id can include a-z and A-Z.
So, this now becomes:
RewriteRule ^([a-z]+)$ /profile.php?id=$1 [NC,L]

No other filesystem checks (preceding RewriteCond directives) are necessary. The NC (nocase) makes the regex match case-insensitive.
There is no need to check that the request does not map to a file (with a preceding condition), since the regex ^([a-z]+)$ could never match a file (that includes a file extension).
There is also no need to check that the request does not map to a directory, unless you are requesting directories in the document root directly - which is probably "unlikely". However, therein lies an inherent conflict with this URL structure. If you needed to be able to access a directory then those directory names become invalid IDs - so you would need other checks elsewhere in your system to ensure no IDs were generated that map to physical directories in the document root.


text:
Q: Profile C code execution percentage (line-by-line annotation) I need to profile a couple of C codes and get an annotated file with percentage of exeuction time taken by each line or atleast each block(while/if-else/for-functions) etc.
So far I have looked into valgrind(callgrind) and gperf and some other tools. So far what I get is

*

*Count of each function or line of source Code like how many times it is execution.

*Or Percentage of Count.

*Or execution time taken by each funtion call.

What I do need however if percentage of execution time not the count and that should be for each line of source code or atleast all blocks(while/if-else/for-functions).
Can someone let me know of a way I can do it ?
Thanks,

A: I believe perf(1) (part of the linux-tools-common package in Ubuntu) will get you what you want. It makes use of a kernel-based subsystem called Performance counters for Linux, included in newer kernels. More information can be found here.
Simple usage example below. Make sure to compile with debugging symbols.
$ perf record ./myprogram arg1 arg2
$ perf report

Cachegrind might be worth looking into too.

A: You need something that samples the stack, either on CPU time, or wall-clock time if you want to include I/O.
You don't need particularly high frequency of sampling.
Each stack sample is a list of code locations, some of which can be traced to lines in the code.
The inclusive percentage cost of a line of code is just the number of stack samples that contain it, divided by the total number of stack samples (multiplied by 100).
The usefulness of this is it tells you what percentage of total time you could save if you could get rid of that line.
The exclusive percentage is the fraction of samples where that line appears at the end.
If a line of code appears more than once in a stack sample, that's still just one sample containing it. (That takes care of recursion.)
What tools can do this? Maybe oprofile. Certainly Zoom.


text:
Q: Get All Connected Users (Laravel 5) How to display all connected users in my home?

A: This is a very basic, but hopefully an efective way to detect both Guest and Registered users on your Laravel5 application.
Step 1
Open the file config/session.php and change the driver to database.
Step 2
We need to create the sessions table, so use the following artisan command php artisan session:table to generate the migration file.
Step 3
On this newly generated migration, you need to add a new user_id column, this is so we can relate the session to a user, if that user is logged in of course.
Open the file migrations/xxxx_xx_xx_xxxxxx_create_session_table.php and add the following inside the Schema::create:
$t->integer('user_id')->nullable();
Here is how the full migration should look:
<?php

use Illuminate\Database\Migrations\Migration;

class CreateSessionTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sessions', function($t)
        {
            $t->string('id')->unique();
            $t->text('payload');
            $t->integer('last_activity');
            $t->integer('user_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('sessions');
    }

}

Step 4
Run composer dump-autoload and php artisan migrate.
Note: If you don't have Composer installed globally, just use php composer.phar dump-autoload.
Step 5
Save the Eloquent Model somewhere on your application as Session.php.
Note: The recommended place to save this is on the app directory.
Step 6
Now you just need to know how to use it.
.
.
.
Usage
Place the following Session::updateCurrent(); somewhere on your code, as this will make sure that the session entry for the current user get's updated, just an example, you can place it on your app/routes.php file.
Get all users (Guests + Registered)
$all = Session::all();
If you need to check all users online for a certain period, like 10 minutes, you need to call the activity(:limit) method, like so:
$all = Session::activity(10)->get();
Note: This method can be used in combination with the guests() and/or registered() methods.
Guest Users
Grab all
$guests = Session::guests()->get();
Get the # of Guest users

$total = Session::guests()->count();

Registered Users
Grab all
$registered = Session::registered()->get();

foreach ($registered as $online) {
    // You can retrieve the user information using something like:
    var_dump($online->user->email);
}

Get the # of Registered users
$total = Session::registered()->count();
Eloquent model:

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Session;
use Illuminate\Database\Eloquent\Builder;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;

class Session extends Model
{
    /**
     * {@inheritdoc}
     */
    public $table = 'sessions';

    /**
     * {@inheritdoc}
     */
    public $timestamps = false;

    /**
     * Returns the user that belongs to this entry.
     *
     * @return \Cartalyst\Sentinel\Users\EloquentUser
     */
    public function user()
    {
        return $this->belongsTo('Cartalyst\Sentinel\Users\EloquentUser');
    }

    /**
     * Returns all the users within the given activity.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $limit
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActivity($query, $limit = 10)
    {
        $lastActivity = strtotime(Carbon::now()->subMinutes($limit));

        return $query->where('last_activity', '>=', $lastActivity);
    }

    /**
     * Returns all the guest users.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeGuests(Builder $query)
    {
        return $query->whereNull('user_id');
    }

    /**
     * Returns all the registered users.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeRegistered(Builder $query)
    {
        return $query->whereNotNull('user_id')->with('user');
    }

    /**
     * Updates the session of the current user.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeUpdateCurrent(Builder $query)
    {
        $user = Sentinel::check();

        return $query->where('id', Session::getId())->update([
            'user_id' => $user ? $user->id : null
        ]);
    }
}

Alternatively you can try this.


text:
Q: Libvirt guest destroyed after shutdown I have created a VM withLibvirt and when I shut it down whether forcefully or with ACPI, it gets deleted. I create it:
<domain type='kvm'>
    <name>deneme2</name>
    <memory>2097152</memory>
    <vcpu>1</vcpu>
    <os>
        <type>hvm</type>
        <boot dev="hd" />
    </os>
    <features>
       <acpi/>
    </features>
    <on_poweroff>preserve</on_poweroff>
    <on_reboot>restart</on_reboot>
    <on_crash>restart</on_crash>
    <on_lockfailure>poweroff</on_lockfailure>
    <devices>
        <graphics type='vnc' port='-1'/>
        <disk type='file' device='disk'>
            <driver name='qemu' type='qcow2'/>
            <source file='/home/mustafa/buki/vms/deneme2/disk0.img'/>
            <target dev='vda' bus='virtio'/>
        </disk>
        <disk type='file' device='disk'>
            <source file='/home/mustafa/buki/vms/deneme2/cloud-init.img'/>
            <target dev='vdb' bus="virtio"/>
        </disk>
        <interface type='network'>
            <source network='br0-bridge'/>
            <mac address='00:16:3e:5a:41:9c'/>
            <model type="virtio" />
        </interface>

    </devices>

However although I use on_poweroff event properly, it gets deleted immediately.
$ virsh dumpxml deneme2 | grep "on_poweroff"
  <on_poweroff>preserve</on_poweroff>

$ virsh shutdown deneme2 --mode acpi
Domain deneme2 is being shutdown

$ virsh list --all
 Id    Name                           State
----------------------------------------------------

What is the reason of this?

A: You created your guest with virsh create (or its equivalent). This creates transient domains, which are deleted when they power off.
To create persistent domains, use virsh define instead. These remain defined after they are powered off or destroyed, and can be started again at any time.


text:
Q: Is "sans" a drop-in replacement for "without"? I keep hearing people use the word sans in place of without which causes me to cringe. Can sans really be used as a drop-in replacement?
Examples:

"I prefer cheeseburgers sans pickles."
"I went to the store sans my brother."
"I typed my essay sans using a sans serif font."

A: The Oxford English Dictionary describes it as archaic.

A: As others said, sans does mean without.  However, in my experience it is used only to modify a noun, not a verb phrase.  So your "sans using" example feels very wrong to me, but "sans serif", "sans pickles", etc are fine.  (Another answer commented on the oddness of "sans my brother", though "sans Dave" feels more natural.)
So sans is best used with an unmodified noun, might be ok with a modified noun ("my brother") but will sound "off", and is not advised with verbs.

A: I limit myself to using it as a de facto prefix and in no other way. That is, to mean the antithesis of what immediately follows as otherwise generally understood. Sans serif as opposed to the more common Roman font; sans soda because going with soda is more common...
@jwpat7: Which is probably why "sans my brother" sounds clumsy.

A: Your three examples of use are all correct, although the "my brother" one is clumsy and I'd only expect to hear that example with a name; e.g. "I went to the store sans Billy."
Another Shakespeare example: "Last scene of all /.../
Sans teeth, sans eyes, sans taste, sans everything."
A Horace Walpole example, regarding Frederick the Great:

Have you seen the works of the philosopher of Sans Souci, or rather, of the man who is no philosopher, and who has more Souci than any man now in Europe? How contemptible they are!

[As in ohne-sorgen-polka notes, Sans Souci can translate as Without worry, or more hiply as no sweat, "Ohne Sorge" being the German for Sans Souci.]

A: "sans" might come from French: "sans" is the French word that exactly means "without".
For instance:

*

*"J'y suis allé sans mon frère" is translated into "I went there without my brother"

*"Soda sans glace" is "Soda, no ice"

*"sans importance" is "not important"

*"sans plomb" is "unleaded"

For these reasons, I suspect "sans" would be a little more higher language, less common, and sounding old-fashioned compared to "without"/"-less/"no"/"free"

A: Well, Merriam-Webster considers sans a word (meaning without). Sans-serif is definitely correct; that is simply what sans-serif fonts are called. Shakespeare used it like this:

My love for thee is sound, sans crack or flaw.

I think it's safe to assume that if Merriam-Webster and Shakespeare use it, it's probably a safe word to use; the words that weren't words when Shakespeare used them became words anyways.
As for how much one should use the word, I would suggest limiting its use, despite the fact that it may be legitimate; using it could make you sound silly (awkward wording sounds silly, IMO) or pretentious.


text:
Q: ajax timeout only works for 1 second hi i have an ajax call and the timeout error that only works if the timeout is set to 1000 if i change this value to 5000 for example it gets ignored and then the error event wont fire
 $.ajax({
    method: 'GET',
    url: raspberry_url+'/stop_training',
    contentType: "application/json; charset=utf-8",
    processData: false,
    dataType: 'json',
    headers: {"Authorization": "Bearer "+localStorage.getItem('token')},
    complete: function(data) {
        localStorage.setItem('SmartSailing',true);
        data = JSON.stringify(data.responseJSON);
        data = JSON.parse(data);
        if (data.status == '200'){
            localStorage.setItem('token',data.new_token);

        }else{
            mui.viewport.showPage("try-again-page", "FADE");
        }
    },
    timeout: 5000,
    error: function(jqXHR, textStatus, errorThrown) {
        localStorage.setItem('SmartSailing',false);
        if(textStatus==="timeout") {
            swal({
                title: "Connection Failed!",
                text: "Please check your connection to the SmartSailing network",
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "OK",
                closeOnConfirm: true,
            });
        }
    }
});

A: Manage to solve the problem. The thing was that I try to make an ajax request to a server, but the server was down, it seems that the ajax request reaches the server but returns with an error. Its different when i try to request to another IP which doesnt exists in my network and the request doesnt "find where to go" so that is when the timeout takes place.


text:
Q: K-means clustering algorithm in TensorFlow I was looking for the k-means clustering algorithm in TensorFlow. Does anyone know if TensorFlow has support for it?

A: Here you have it: https://www.tensorflow.org/api_docs/python/tf/contrib/factorization/KMeansClustering.
It may also be helpful: https://www.tensorflow.org/api_docs/python/tf/contrib/factorization/KMeans.
Note that all code under tf.contrib is volatile or experimental. Furthermore, note that you could easily have found what I did using the search box in the TensorFlow website.


text:
Q: How do port forwarding work in big video games with a lot of traffic? Please consider the following scenario,
Let's suppose there are two roommates having the same game installed. For the sake of this question let's assume that the game is DoTA2.
Both the roommates are connected to the same router and thus have the same public IP essentially. (router's IP)
Now, let's assume that someone else on the outside i.e. public internet outside of the router wants to connect to the roommate1, then the router will have a simple port forwarding within the NAT rule that may go like follows,
If the request comes from outside on port ABC(game owned port) forward it to roommate1.
Now, if we assume that the roommate2 is also online in the game and another public computer wants to connect to them, then how would the port forwarding work?
How will the router know which private computer(roommate) the connection request be forwarded to?
Please do not give answers like, DoTA has multiple ports allotted or any game-specific answer, use of DoTA is just an example.
You can even consider a scenario where there are two private computers running a simple HTTP server on port number 80, how would an outside computer know which one to connect?
I have googled DMZ, and port forwarding but do not clearly understand the solution.

A: It's kinda rude to tell us on what kind of answers we can give, specially when you have asked an off topic question yourself.
Getting to the answer to your question, port forwarding is done based on the combination of private IP and port; roomate1 and roommate2 have different private IP addresses but using the same port, on your router(assuming it's a generic one) only one forwarding rule can be used at any point.
A possible solution is to use a proxy server like HAProxy after your router on the private network side and use TCP association based policy to forward packets to roomates.

A: In short, NO is not possible. You can only NAT from 1 public address to an internal IP on X port.
In long, companies does this, but they have 2 or 3 public address then you can map to a different internal IP.
Public IP 1 > Internal IP:port
Public IP 2 > Internal IP:port
You can map from an external IP to multiple internal IP addresses but since you are using the same service(game) they probably use the same port or ports.


text:
Q: Issues with using d2l remote plugins (insert stuff cim) example not working I am new to Brightspace and been fiddling with the remote plugins sample (logo). I can load the sample logo project, but cannot get it to insert into the page. I have uploaded the file but get a 404 error on submit.  Can someone `

   $( document ).ready(function() {
            $('#submitFormButton').click( function() {
                 $.ajax({
                    url: "/getisfdetails",
                    data: {
                        image: $("input[name='image']:checked").val()
                    },
                    success: function(response){
                        $("input[name='lti_message_type']").val(response.lti_message_type);
                        $("input[name='lti_version']").val(response.lti_version);
                        $("input[name='content_items']").val(response.content_items);
                        $("input[name='oauth_version']").val(response.oauth_version);
                        $("input[name='oauth_nonce']").val(response.oauth_nonce);
                        $("input[name='oauth_timestamp']").val(response.oauth_timestamp);
                        $("input[name='oauth_consumer_key']").val(response.oauth_consumer_key);
                        $("input[name='oauth_callback']").val(response.oauth_callback);
                        $("input[name='oauth_signature_method']").val(response.oauth_signature_method);
                        $("input[name='oauth_signature']").val(response.oauth_signature);
                        $("#isfForm").prop('action', response.lti_return_url);
                        $("#isfForm").submit();
                    }
                });
            });

    });

            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>

Select an logo:

        <input type="radio" name="image" value="brightspace-logo.png">

        <input type="radio" name="image" value="d2l-logo.png">

            <form id="isfForm" method="POST">
                <input type="hidden" name="lti_message_type" />
                <input type="hidden" name="lti_version" />
                <input type="hidden" name="content_items" />
                <input type="hidden" name="oauth_version" />
                <input type="hidden" name="oauth_nonce" />
                <input type="hidden" name="oauth_timestamp" />
                <input type="hidden" name="oauth_consumer_key" />
                <input type="hidden" name="oauth_callback" />
                <input type="hidden" name="oauth_signature_method" />
                <input type="hidden" name="oauth_signature" />
            </form>

        <button id="submitFormButton">Submit</button>

` how do you set this cookie in the javascript? I believe a cookie needs to be set??? and I do not see how to set it? or maybe I am missing something else that is not noted in the documentation.

A: I would highly recommend you consider using LTI Advantage/1.3 instead of Remote Plugins. LTI provides a standards-based integration approach & a better developer experience.
https://community.brightspace.com/s/article/LTI-Integration-Guide

A: If you are working with a partner of D2L please get in touch with the partner team and technical assistance is available. Your information here is appreciated but we are glad to examine the full context and use case as these errors are not hugely uncommon during dev. Otherwise, I echo Paul's suggestion, but I understand if it is not immediately possible.
partners@d2l.com or talk with your team that knows D2L!

A: Depending on which browser you are in you might be seeing the recent effects of the third-party cookie blocking that the browsers are adopting.  Because LTIs (both 1.1 and 1.3/Advantage) typically launch into iframe any access to those cookies are regarded as third party.  This effectively means two things

*

*You need to be aware of the cookie access routines where a user action must be taken to request access to the browser storage API using document.requestStorageAccess()

*You need to be marking your cookies appropriately with the new SameSite cookie directives
Without these the browser will mark your cookie request as a 'Tracking cookie' and refuse to serve it along with the request or make it accessible via javascript.
An alternative is also to detect that the LTI launch is happening inside the an iframe and to bust that iframe out to a new window, or alternatively configure the launch inside Brightspace to not use a iframe at all.


text:
Q: Dynamically length/sized char array in c I am attempting to create a dynamic char array (vector) in c with dynamic length/size.
Here is my attempt:
#include <stdio.h>
#include <stdlib.h>

void push_back(char **arr, char *element, int *counter) {
    if (*counter > 0) {
        arr = realloc(arr, *counter * sizeof(char *));
    }
    arr[*counter] = element;
    (*counter)++;
}

int main() {
    char **arr = malloc(1 * sizeof(char *));
    int counter = 0;

    push_back(arr, "element", &counter);
    push_back(arr, "element2", &counter);
    push_back(arr, "element3", &counter);
    push_back(arr, "element4", &counter);
    push_back(arr, "element5", &counter);
    push_back(arr, "element6", &counter);

    for (int i=0; i<counter; i++) {
        printf("%s <-\n", (char *)arr[i]);
    }

    free(arr[i]);
    return 0;
}

I receive the following error from stdout:
realloc(): invalid next size
Aborted

What am I doing wrong?

A: you need triple pointer *** (wrrrr.....) or just return realloced pointer back.
char ** push_back(char **arr, char *element, int *counter) {
    *counter += 1;

    arr = realloc(arr, *counter * sizeof(char *));
    arr[*counter - 1] = element;
    return arr;
}

int main() {
    char **arr = NULL;
    int counter = 0;

    arr = push_back(arr, "element", &counter);
    arr = push_back(arr, "element2", &counter);
    arr = push_back(arr, "element3", &counter);
    arr = push_back(arr, "element4", &counter);
    arr = push_back(arr, "element5", &counter);
    arr = push_back(arr, "element6", &counter);

    for (int i=0; i<counter; i++) {
        printf("%s %d <-\n", arr[i], counter);
    }

    free(arr);
    return 0;
}

You do not need to malloc and then check the value of the counter.
https://godbolt.org/z/xnaxKo
PS Yuo shiuld always check the result of the malloc (and friends).


text:
Q: Block php files except in one directory I'm trying to block all calls to php files in a specific folder and subfolders except for one specific folder and its subfolders.
I've tried a number of different regex permutations and I can get the regex to match properly, it's implementing in htaccess where I have a problem.
This is the htaccess file as it is now:
<FilesMatch "\.(?i:php)$">
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
</FilesMatch>

and this is the regex expression that matches properly outside of htaccess:
^(?!.*(thedirectory)).*(?i:php)$

When I check that regex against index.php it matches. When I check against /thedirectory/index.php it does not match. When I check against /someotherdirectory/style.css it does not match.
How I'd like it to work is:
domain.com/folder/index.php -> 404 Error
domain.com/folder/thedirectory/index.php -> resolves
domain.com/folder/someotherdirectory/index.php -> 404 Error
domain.com/folder/someotherdirectory/afunction.php -> 404 Error
domain.com/folder/someotherdirectory/style.css -> resolves

A: Turned out to be a lot more straightforward than I thought it would be:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^(?!.*(thedirectory)).*(?i:php)$ [NC]
    RewriteRule "(.*)" /404.php
</IfModule>

A: The <Files> and <FilesMatch> sections match just the filename, not the directory path. So attempting to do so will naturally fail.
An alternative approach is to simply create an additional .htaccess file in the directory you want to allow access, which will override the parent:
Require all granted


text:
Q: Character Handling on Mac in Java So I recently finished a program for a colleague that wanted a quick quizzing system with very loose encryption.
I emphasize very because the encryption is merely adding a flat number to each character in the file, thus resulting in (easily decryptable, but these are grad students in a completely unrelated field) a jarbled mess.
This works as intended in Windows and Linux, it encrypts and decrypts fine.
However, on Mac it does not.
On Mac it encrypts fine, but then when decryption kicks in, it becomes an assortment of the occasional letter and several blank spaces. I currently think it's because I have not set what charset the character array is, but is it possible to set an array (not a string) to a specific charset?
I'm currently not in a position to post code, but if people need further information before suggesting anything, I will be able to later.

A: Are you talking about a Caesar cipher? It changes each char into an ascii number, adds a flat number to each ascii number, then reverts each char to the respective chars. If this is your encryption, you simply need to subtract your flat number in the loop for decryption.


text:
Q: Repeated Measures ANOVA? I am an undergraduate student studying psychology using SPSS to analyse my data.
I have 2 conditions of the IV of treatment (treatment or no treatment) to test pain tolerance levels which is measured by the DV of pulse rate to measure pain.
The study used a repeated measrures design using a counterbalancing approach (e.g. 20 particpants in treatment condition first, wheras other 20 in no treatment condition first, and then in alternate condition in second part of experiment. The sample is two-thirds consisting of females and one-third of males, although i want to analyse gender differences anayway.
I've used paired samples t-tests to test for significant differences between both conditions, but now i want to test it for gender differences, to see if whether male or female particpants got higher scores.
Is there any ANOVA's i would use for this and how would i interpret it using what tests?


text:
Q: Moving .lproj file inside Resources I'm trying to begin localization on a project, and I've already got an English version of Localizable.strings going. I'm now trying to add French to that file, which is creating an fr.lproj folder, as I'd expect. However, it's putting it in my project root, and I'd like it inside my project's Resources directory.
Xcode seems to have no interest in letting me move the file, and if I move it in Finder, it goes red in Xcode as expected, but doesn't let me click to locate the file.
I've tried moving it in Finder, then editing project.pbxproj in a text editor to add Resources/ in front of the only line in there that mentions fr.lproj/Localizable.strings, and that has worked, but after doing that, the project's targets also turned red in Xcode, and building the app doesn't change that fact. Very odd.. any idea what could be going on, or how to get this going?

A: This can be a real pain. I even had XCode crash on me when trying to correct unwanted file locations. I found that the best way is to create the localized file (be it .strings or .xib) as a copy of the source language version outside of XCode, then drag and drop it into XCode. If you do this then XCode will display it correctly and your targets' Build Phases > Copy Bundle Resources settings will include it with its correct location.  I don't know why your targets are displayed in red, perhaps you could look under Copy Bundle Resources in case anything is wrong there, or also select your project and click Validate Settings in case you haven't already done so.
Also, if you have been testing in the simulator beware of how XCode does not clean up the files in your app bundle--you may want to delete the app and run it again to make sure it's working with your new location.


text:
Q: Java Strategygame: Units-Coordination and Behaviour on a 100x50 orthogonal tilegrid with 32x32 tiles, i created some animated Units, which are moved by A* (like in many strategy games usual) with a rightclick on the mouse.
The collision detection works by using a two dimensional booleanarray i gave the grid in the constructor and this says whether a tile is an obstacle or not.
Thats what i have so far and it works.
I am now figuring out, some Kind of Units coordinationsystem, which simply doesnt allows the Units to walk into each other. All of this just should be in this 32x32 tilesized RASTER not more for the moment.
I just thought this should be easy, but the grid is loaded once just like the obstacles, while the Units positions are always different and the Problem here is, that if i define each unit as an obstacle at Runtime, the obstacle at its Position stays stored in the gridarray and it stay some Kind of invisible obstacle, although it shouldnt be one. The result is, that the unit cant go the way back, where it cames from. Another Problem is of Course, that a unit can stand still or move arround(so far) and if it moves arround ist not rastered anymore.
My question now is: How can i implement a movable obstacle or do i have to implement a separate collision detection for my Units here?
PS: The Programm is quite big and i dont like to post the whole Code, although that would make all easier for u guys to help me, but if somebody understand what i mean, i can post the relevant Code snippets here on the Forum.


text:
Q: Math puzzle I have been stuck on Have had this math puzzle that I have been unable to solve for a while.
Each leter is a number between 1-9. No letter uses the same number twice (aka if B is 3 D can't be 3 also). The ? mark represents an unknown letter (as in it could be any letter).
$$A + B + C + D = EF$$
$$G + F + E + H = CJ$$
$$B + G + J = \;?D$$


text:
Q: Plotting all-time risk of a variable with ggplot2 after adjusting a survival model I am working with survival analysis and the smoothHR package, after modeling I'd like to plot the relative risk vs a variable, thing that is quite easy with
plot(dataset, predictor)

But I'd like to do it using the ggplot package. Any idea how to?
#the library
library(smoothHR)

#the artificial dataset
surv.days<- runif(n = 200, min = 100, max = 500)
censor<- sample(c(0,1), 200, replace=TRUE)
surv.var<- surv.days/10 + rnorm(200, mean = 0, sd = 3)
surv.var[which(surv.days>250)]<- surv.days[which(surv.days>250)]/5 + rnorm(length(which(surv.days>250)), mean = 0, sd = 10)

survdata<- data.frame(surv.days, censor, surv.var)

rm(censor, surv.days, surv.var)

#using smoothHR package to adjust a model
variabledf<-dfmacox (time = "surv.days", status = "censor",
                    nl.predictor = c ("surv.var"),
                    smoother = "ns",
                    method = "AIC",
                    data = survdata)

coxmodel<- coxph(Surv(surv.days, censor) ~ ns(surv.var, variabledf$df[1]), data = survdata, x = TRUE)

c.smoothhr<-smoothHR (data = survdata, coxfit = coxmodel)

After that, I can plot the risk as a function of the survival variable
plot (c.smoothhr, predictor = "surv.var", conf.level = 0.95, ref.label = "", main = "", xlab = "surv.var")

I would like to generate this plot using the ggplot2 package, for storing and customization purposes; but I am simply clueless about how to proceed.


text:
Q: Signin Soap request and unrecognized path attribute I am using Web Services Enhancements 1.0 for Microsoft .NET to sign my Soap request. With wireshark I can see the Soap request, which looks to be signed.
I have written a test server with well-known HelloWorld() method. But an error occured, saying that "path" attribute is not recognized.
This in an extract of the Soap request, in <soap:Header> section:
<wsrp:path soap:actor="http://schemas.xmlsoap.org/soap/actor/next" soap:mustUnderstand="1" xmlns:wsrp="http://schemas.xmlsoap.org/rp">
<wsrp:action wsu:Id="Id-177d0898-4b52-4807-8042-34c2107414ee" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility">http://tempuri.org/HelloWorld</wsrp:action>
<wsrp:to wsu:Id="Id-bd6f000f-c2e9-40c4-8ae5-7316dcb08295" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility">http://xxxx/yyyy.asmx</wsrp:to>
<wsrp:id wsu:Id="Id-9ceacb6a-d758-4ab5-9e4a-2c25b77005f7" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility">uuid:e4e7eda7-b4a3-4661-91c6-42ee17fb6b61</wsrp:id>
</wsrp:path>

It looks like that "path" attribute it used to relay the request (??). But why the server don't understand this attribute?

A: MWSE assembly has to be declared in server too (web.config).


text:
Q: Is it safe to return a structure of strings? I am writing a function parser which needs to recursively split data, i.e.
aba$(2)cd$(5)efg
returns aba, $(2), and $(5)efg
I need to make a structure that can hold three strings,
struct split3 {
   std::string before, middle, after;
};

If I assign the strings in the structure then return them, is this safe? If its not, what should I do? I don't really think its safe, because there is no copy constructor for the structure, and the strings would exist on the stack, which wouldn't exist (for long, anyway) after returning?
i.e.
split3 func(...) {
s = split3();
... do stuff to s.before, s.middle, s.after;
return s;
}

A: Yes, it's safe. split3 will be given a default copy constructor, which will just call the copy constructor for string 3 times. Which sounds like it's what you want.
It's true that the original strings you created on the stack inside func() will no longer be valid after it returns, but the copies inside the split3 object that is returned will be ok.

A: Yes, it is safe (in the correctness meaning). There is no need for explicit copy constructor as default copy constructor will suffice. Your structure will be copied by correctly copying all the 3 strings.

A: It is safe like others have said. Just remember that it is making a copy. That means if you have a really large structure it is going to have to make a copy of the whole thing. If it's something small like this it doesn't really matter.


text:
Q: Cluster behavior on worker crash I'm using cluster to fork workers that process files received over http/express. I'm currently testing the recovery when processing a file that makes the worker crash (I detect the crash with on('exit',... and re-fork a new worker).
I'm witnessing a strange behavior: in the case of a poisoned file that would make a worker crash, my logs show that all workers receive the file and crash (whereas normally, only a single worker would process a non-poisoned file). And on the client-side, it shows that the HTTP request has only been sent once. Any reason that would explain that odd behavior?
EDIT: code extract
if (cluster.isMaster) {
    cluster.on('exit', function(worker, code, signal) {
        var worker = cluster.fork();
        worker.on('message', function(filename) {
            console.log('worker ' + worker.process.pid + ' processing ' + filename);
        });
    });

    for (var i = 0; i < numCPUs; i++) {
        var worker = cluster.fork();
        worker.on('message', function(filename) {
            console.log('worker ' + worker.process.pid + ' processing ' + filename);
        });
    }
} else {
    var app = express();
    app.use('/', express.static('public'));
    app.use(multer({ inMemory: true }));

    app.post('/detect', function(req, res) {
        var image = req.files.image;
        if (!image) {
            res.status(400).send({ error: 'missing image' });
            return;
        }

        process.send(image.originalname);

        // some code that may crash
    });

    var server = app.listen(nconf.get('port'), "0.0.0.0", function () {
        var host = server.address().address;
        var port = server.address().port;
    });
}

Thanks


text:
Q: simple dense optical flow program calcOpticalFlowFarneback() openCV 3.2 cpp I can't run this simple code. I'm trying to calculate the optical flow between 2 pictures.
Please check the attached pictures

OpenCV Error: Assertion failed (prev0.size() == next0.size() &&
  prev0.channels() == next0.channels() && prev0.channels() == 1 &&
  pyrScale_ < 1) in
  cv::`anonymous-namespace'::FarnebackOpticalFlowImpl::calc, file
  C:\Users\krato\Desktop\OpenCV\opencv-master\modules\video\src\optflowgf.cpp,
  line 1114

#include <Windows.h>
#include "opencv2\highgui.hpp"
#include "opencv2\imgproc.hpp"
#include "opencv2\objdetect\objdetect.hpp"
#include "opencv2/video/tracking.hpp"
#include <vector>
#include <stdio.h>
#include <Windows.h>
#include <iostream>
    using namespace std;
    using namespace cv;

    // Display the results of the matches
    //
    int main(int argc, char* argv[])
    {
        cv::Mat img1 = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
        cv::Mat img2 = cv::imread(argv[2], cv::IMREAD_GRAYSCALE);
        cv::Mat res;

        cv::calcOpticalFlowFarneback(img1,img2,img1,.4,1,12,2,8,1.2, 0);

        cv:imshow("cat", res);
        cv::waitKey(0);

    }

A: The assertion is due to img1 and img2 having different sizes. In the first image that you gave it can be clearly seen that img1 has 762 rows and img2 has 768 rows.
Try using cv::resize to make img2 of the same size as img1. Add the following line before cv::calcOpticalFlowFarneback().
cv::resize(img2, img2, img1.size());

A: Thanks to shawshank
The final version of the code is:
#include "opencv2\highgui.hpp"
#include "opencv2\imgproc.hpp"
#include "opencv2\objdetect\objdetect.hpp"
#include "opencv2/video/tracking.hpp"
#include <vector>
#include <stdio.h>
#include <Windows.h>
#include <iostream>
using namespace std;
using namespace cv;

// Display the results of the matches
//
int main(int argc, char* argv[])
{
    cv::Mat res, img1, img2, img2Original, img2OriginalC;
    cv::VideoWriter writer;

    cv::VideoCapture cap;
    cap.open(std::string(argv[1]));
    //cv::cap.open(0);

    cv::namedWindow("cat", cv::WINDOW_AUTOSIZE);

    cap >> img1;
    cvtColor(img1, img1, COLOR_BGR2GRAY);
    double fps = cap.get(cv::CAP_PROP_FPS);
    cv::Size tamano((int)cap.get(cv::CAP_PROP_FRAME_WIDTH), (int)cap.get(cv::CAP_PROP_FRAME_HEIGHT));
    writer.open("mouse.avi", CV_FOURCC('M', 'J', 'P', 'G'), fps, tamano);

    for (;;) {
        cap >> img2;
        if (img2.empty()) break;

        img2.copyTo(img2OriginalC);
        cvtColor(img2, img2, COLOR_BGR2GRAY);
        img2.copyTo(img2Original);
        cv::calcOpticalFlowFarneback(img1, img2, res, .4, 1, 12, 2, 8, 1.2, 0);
        for (int y = 0; y < img2.rows; y += 5) {
            for (int x = 0; x < img2.cols; x += 5)
            {
                // get the flow from y, x position * 3 for better visibility
                const Point2f flowatxy = res.at<Point2f>(y, x) * 1;
                // draw line at flow direction
                line(img2OriginalC, Point(x, y), Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), Scalar(255, 0, 0));
                // draw initial point
                circle(img2OriginalC, Point(x, y), 1, Scalar(0, 0, 0), -1);
            }
        }
        img2Original.copyTo(img1);
        imshow("cat", img2OriginalC);
        //writer << img2OriginalC;
        if (cv::waitKey(1) == 27) break;
    }
    cap.release();
    return 0;
}

Video that shows the code in action:
https://www.youtube.com/watch?v=rfuP-z2OR8I


text:
Q: Parsing String Arrays in JSON with Retrofit For moderator: It's not duplicate question, because in other quiestions there are DIFFERENT format of JSON-responce!
In my case, proposed approaches don't useful, unfortunatly :(
For example, in first case - I haven't string of responce (because i use gson), and in second I have error when I try to use List<String> (Unable to create converter for java.util.List<java.lang.String>) :(

I have a JSON-answer in such format (with many string arrays):
{
"marketdata": {
 "columns": [
  "SECID",
  "BID",
  "OFFER",
  "SPREAD",
  "LCURRENTPRICE",
  "UPDATETIME",
  "TIME",
  "SYSTIME"
],
"data": [
  [
    "AFLT",
    121.4,
    121.5,
    0.1,
    121.5,
    "12:25:45",
    "12:25:34",
    "2018-07-25 12:40:45"
  ],
  [
    "KRKNP",
    11400,
    11430,
    30,
    11400,
    "12:25:00",
    "12:16:12",
    "2018-07-25 12:40:00"
  ],
  [
    "LKOH",
    4347,
    4349.5,
    2.5,
    4349.5,
    "12:25:46",
    "12:25:40",
    "2018-07-25 12:40:46"
  ]
 ]
 }
}

I created simple pojo file (https://pastebin.com/PQvnQCRb) and it's doesn't work even for "columns" field. And, of course, I need to parse "data" fields too... Where is my mistakes? Thanks.


text:
Q: How to call cloudfront distribution with wrong Host header Prerequisites
I have configured a custom domain for an API Gateway. The endpoint type is edge, as the API Gateway (RestApi) is edge.
I also issued a certificate through cdk. This is some of the code used:
  const zone = route53.HostedZone.fromLookup(stack, 'Z0557019************', {
    domainName: 'sub.example.com' // changed for SO post
  })

  const certificate = new DnsValidatedCertificate(stack, 'lws-api-certificate', {
    domainName: 'mysub.sub.example.com', // changed for SO post
    region: 'us-east-1',
    hostedZone: zone
  })

  const api = new apigateway.RestApi(stack, 'legacy-wrapper-api', {
    restApiName: 'My API',
    domainName: {
      domainName: 'mysub.sub.example.com',
      certificate: certificate,
      endpointType: EndpointType.EDGE

    },
    policy: apiResourcePolicy
  })

  new route53.ARecord(stack, 'ApiGatewayAliasRecord', {
    zone: zone,
    recordName: 'mysub',
    target: route53.RecordTarget.fromAlias(new targets.ApiGateway(api))
  })

So, I understand that a Cloudfront distribution is created. However, it is not listed in CloudFront.
In ApiGateway console:

What works
The custom domain was successfully created and applied and I am able to access my API gateway through mysub.sub.example.com.
What is not working
My issue is the following. I have clients which send a wrong Host Header. We can call our api fine when Host Header is mysub.sub.example.com. However, one client sends erroneously sub.another-example.com.
I know that this is a wrong header. But there is nothing we can do about this client sending the wrong header. Unfortunately!
What are my options?

*

*switch to http

*add foreign Host to allowed Hosts (certificate)?

*Create some sort of proxy instance which allows incoming traffic from sub.another-example.com and redirect to

Regarding 1.
How can I allow http? I am seeing an option to set a minimum security level, but the minimum is TSL1.0. Can I even create a CloudFront distribution that accepts http? Again, in console I cannot see the distribution so I have to do it via CDK.
Regarding 2.
How can I do that, specifically in CDK?
Regarding 3.
Any creative ideas?
Help is much appreciated.
Additional resource:
A curl call to the custom domain with wrong header brings this:
$ curl --header "Authorization: Bearer 9c904d3##########################" --header "Host: sub.another-example.com" -v https://mysub.sub.example.com/v2.2/api/posts/list
* TCP_NODELAY set
* Connected to mysub.sub.example.com (18.66.###########) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_128_GCM_SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=mysub.sub.example.com
*  start date: May 27 00:00:00 2022 GMT
*  expire date: Jun 25 23:59:59 2023 GMT
*  subjectAltName: host "mysub.sub.example.com" matched cert's "mysub.sub.example.com"
*  issuer: C=US; O=Amazon; OU=Server CA 1B; CN=Amazon
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x5627934cd8c0)
> GET /v2.2/api/posts/list HTTP/2
> Host: sub.another-example.com                    <----------------- This is the problematic value
> user-agent: curl/7.68.0
> accept: */*
> authorization: Bearer 9c904d3##########################
>
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 403
< server: CloudFront
< date: Mon, 30 May 2022 11:21:50 GMT
< content-type: text/html
< content-length: 915
< x-cache: Error from cloudfront
< via: 1.1 f7d063##########################.cloudfront.net (CloudFront)
< x-amz-cf-pop: FRA56-P5
< x-amz-cf-id: _KTRiNK8z74PB4qCwS##################################################==
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>

403 ERROR

The request could not be satisfied.

Bad request.
We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.

If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.

Generated by cloudfront (CloudFront)
Request ID: _KTRiNK8z74PB4qCwS##################################################==

<ADDRESS>
</ADDRESS>
* Connection #0 to host mysub.sub.example.com left intact

A: As often when the questions are so specific I found a solution myself.
It is option 2! All with CDK.
Those are the steps:

*

*As I mentioned the Cloudfront distribution created for the custom domain is hidden in console, so you need to create an new one.

*you want an "Alternate domain name" with the value of "sub.another-example.com" to be appearing on the distributions settings

*In order for that to work, you will need to create a certificate which also includes the foreign domain

*for that certificate to validate you will need to put a CNAME to the DNS settings of that domain (so you need to be able to do that).

*your certificate will not auto-validate by DNS of course! I found a hack for that which requires deploying two times.

Cloudfront distribution with alternate domain and cert
This is the final code.
import { CloudFrontToApiGateway } from '@aws-solutions-constructs/aws-cloudfront-apigateway'

let certificate
if (buildConfig.isFirstDeploy) {
  // This is a helper for an otherwise manual step. Unfortunately, there is no better fix for foreign host certs.
  // The first deploy will fail with message '*.another-example.com. is not permitted in zone *.sub.example.com
  // However, you can then manually validate the *.another-example.com domain and use the ARN for following deploys
  // https://stackoverflow.com/questions/58101817/cdk-dnsvalidatedcertificate-can-create-a-certificate-in-a-linked-aws-account-w
  certificate = new DnsValidatedCertificate(stack, 'api-certificate', {
    domainName: `mysub.sub.example.com`,
    region: 'us-east-1', // required for edge https://docs.aws.amazon.com/acm/latest/userguide/acm-services.html
    hostedZone: zone,
    subjectAlternativeNames: ['*.another-example.com']
  })
} else {
  certificate = Certificate.fromCertificateArn(
    stack,
    'api-certificate',
    'arn:aws:acm:us-east-1:#############:certificate/#################' // you only know that after first deploy, copy from console
  )
}

const cloudfront = new CloudFrontToApiGateway(stack, 'MyCloudFrontDistribution', {
  existingApiGatewayObj: api,
  cloudFrontDistributionProps: {
    certificate: certificate,
    domainNames: [
      `mysub.sub.example.com`,
      '*.another-example.com'
    ]
  }
})


text:
Q: Submit Button on InfoPath Does anyone know if a 'submit button' in infopath can be progammed to email and update a sharepoint list at the same time?
Thanks.

A:
Does anyone know if a 'submit button' in infopath can be progammed to
  email and update a sharepoint list at the same time? Thanks

Me. I know.
A 'submit button' can certainly be programmed to email and update. But how to do it depends on many unspecified in question details:

*

*is Infopath 2003? 2010?,

*which type/compatibility of template?

*

*Sharepoint List Form?

*Workflow Form?

*Web Browser Form (and it it is web enabled one)

*Filler

*published to/stored where

*

*sharepoint form library?

*network share?

*on client machine?

*etc., etc.

So, it does not have a concrete answer in its currently undefined context, i.e. it is a guessing game. From the other side, the concrete answers are multiple variants per each concrete possible (known only to topic starter) context and are   available by search on internet.
Update (answer to comment):

I have Infopath 2010. I created the form from a sharepoint list and
  want it to publish/store to the same sharepoint list (not library -
  that option is available on infopath). I'm not sure if I answered
  everything??

No, your comment does not answer how you created the Infopath form, with which options, data connections and options of fata connections (what is its compatibility and how you connected a sharepoint list to it).
It is a guessing game with distorted initial data.
For example, if I create Infopath 2010 form (by pressing Customize Form button on ribbon in browser) of Sharepoint List Form type (in Infopath Designer 2010, File > Info > Form Options > Compatibility ? Form Type:),

I see that it has options to submit to its sharepoint list (in Infoapth Designer 2010, File > Info > Submit Options button):

as well as it has clear instructions how to do it if you wish to choose submission it to more than one/single location, for example. both to email and sharepoint list:

*

*Perform Custom actions using Rules
To set rules that will run when a user submits the form, on the Data tab, in the Rules group, click Form Submit

A: I have never tried it but it should be doable. Change the button option from Submit to Rules and Code. Add rules to the button to first use the data connection to submit via email and then submit via your SharePoint connection and then if you wanted the button to also close have it do that as well.


text:
Q: How to import self-written python files from other paths? Yes, there are lots of questions asked about this, I read all of them, but none of them helped.
So I have db and registration packages in project package. The structure looks like this:

*

*project

*

*db

*

*db.py

*__init__.py

*registration

*

*registration.py

*__init__.py
I want to import my db.py file to registration.py file. Tried almost everything but it is still not working.

A: Make the toplevel directory a module too
project/
  __init__.py       << add this
  db/
    __init__.py
    db.py
  registration/
    __init__.py
    registration.py

then use
from ..db import db

A: You can also do it with this
import sys
sys.path.insert(1, '/path/to/db.py')

Then you can now import functions if any from db.py

A: You should create a setup.py in your project folder with something like :
from setuptools import setup, find_packages

setup(
    name='project',
    version='1.0.0',
    use_scm_version=True,
    packages=find_packages(),
    package_data={'': ['*.json']},
    include_package_data=True,
    classifiers=[
        'Programming Language :: Python :: 3.7'
    ]
)

You can then install from the command line with :
pip install -e .

Finally to import db into registration it'll be :
from db.db import * # or whatever you want to import


text:
Q: Firebase Google sign in: get user location Is it possible to access a Google user's location once they've signed in (using GIDSignIn)?
I have no trouble accessing a user's name, email, and photo.

A: I believe it is possible,
you can set it as profile properties.
so you get user location normally and set it to users profile in your database

A: I am not 100% sure if user location is accessible through GIDSignIn but according to their documentation, you can request for additional scope of information; aside from the basic info, from the user. Here's even more info about it.
Here's the extensive list of Google's current OAuth 2.0 API Scopes


text:
Q: batch script to find a particular folder in a drive am a newbie to the batch script, i have many folders called LIB in my drive
say it can be as LIB_data,lib,lib_ac anything that starts with lib or LIB... i want to list all these directories and sort them in which they have created in the pc and copy the latest directory contents to BATCH_LATEST_LIB_FILES folder,that will be a new folder created by this batch file.i want this new folder to be created in the path where this batch file is present. please help me with a batch script.

A: You might look at FOR, DATE, TIME, SORT, IF, GOTO and XCOPY.
This site is a great resource for batch files.


text:
Q: Passing multiple parameters of different type in HTTP Post Request causes InvalidArgument Exception I am in need to pass multiple parameters of type String and NSData. So I added all the details as Dictionary. First I tried with postString.percentEncoding.But I caught Exception.So I tried with the following.With this I am getting NSInvalidArgumentException.
func receiptValidation()
    {

             let SUBSCRIPTION_SECRET = mySecretKey
         let defaults = UserDefaults.standard
             let receiptPath = Bundle.main.appStoreReceiptURL?.path
             if FileManager.default.fileExists(atPath: receiptPath!){
                 var receiptData:NSData?
                 do{
                     receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped)
                 }
                 catch{
                     print("ERROR: " + error.localizedDescription)
                 }

                 let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)

                 print(base64encodedReceipt!)

                let requestDictionary = ["receipt-data":base64encodedReceipt!,"password":SUBSCRIPTION_SECRET]

                 guard JSONSerialization.isValidJSONObject(requestDictionary) else {  print("requestDictionary is not valid JSON");  return }
                 do {
                     let requestData = try JSONSerialization.data(withJSONObject: requestDictionary)

                    let URLForApplication:String = String(format:"%@/api/validate-receipt-data",opcodeDetails["apiProxyBaseUrl"]!)                         SwiftyBeaver.info("URLForApplication Path:\n\(URLForApplication)")
                     let url:URL! = URL.init(string: URLForApplication)
                    var request = URLRequest.init(url: url)
                     request.httpMethod = "POST"
                    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                    let configure = URLSessionConfiguration.background(withIdentifier: Bundle.main.bundleIdentifier!)

                    var postString:[String:Any]=[
                        "receiptData":requestData,
                        "deviceType":"IOS",
                        "subscriberId":encodeString(normalString: defaults.array(forKey: "userDetails")?.first as! String),
                        "password":encodeString(normalString: defaults.array(forKey: "userDetails")?.last as! String),
                        "productId":PurchaseManager.instance.productId,

                        "code":opcodeDetails["opCode"]!
                    ]
                     do {
                           request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
 } catch let error {
                           print(error.localizedDescription)
                       }

                     let task = session1?.uploadTask(with: request, from: requestData) { (data, response, error) in
                         if let data = data , error == nil {
                             do {
                                 let appReceiptJSON = try JSONSerialization.jsonObject(with: data)
                                 print("success. here is the json representation of the app receipt: \(appReceiptJSON)")

                             } catch let error as NSError {
                                 print("json serialization failed with error: \(error)")
                             }
                         } else {
                             print("the upload task returned an error: \(error)")
                         }
                     }
                    task?.resume()
                 } catch let error as NSError {
                     print("json serialization failed with error: \(error)")
                 }

             }

    }

Why I am getting NSInvalidArgumenException???? Can anyone please help me? Thanks in advance.


text:
Q: The sum modulo $1$ on the unit circumference Let $X=[0,1)$. For every $x,y\in X$ we define
$$
x\dot{+}y:=
\begin{cases}
x+y
& \text{if $x+y<1$} \\
x+y-1 & \text{if $x+y\ge1$}
\end{cases}
$$
I do not understand the following statement:

This operation can be displayed as an sum of angles $\text{mod}\;2\pi$: the sum ($\text{mod}\;1$) of $y$ corresponds to the rotation ($\text{mod}\;2\pi$) of an angle $2\pi y.$

Could someone help me to understand this? Thanks!

A: Let $R_\theta$ be the rotation by angle $\theta$ around the origin.
Verify that it's a linear transformation of the plane $\Bbb R^2$.
Let $GL(\Bbb R^2)$ denote the group of invertible linear transformations of $\Bbb R^2$.
Now (one version of) the precise statement is that $(X,+) \to GL(\Bbb R^2),\ \ t\mapsto R_{2\pi t}$ is an (injective) group homomorphism.
Note also that $X$ is (isomorphic to) the quotient group $\Bbb R/\Bbb Z$.


text:
Q: Using CArrayDataProvider to populate a CGridView in Yii CArrayDataProvider Object
(
    [keyField] =>
    [rawData] => Array
        (
            [24] => Array
                (
                    [ids] => 24
                    [name] => trillia
                )

            [25] => Array
                (
                    [ids] => 25
                    [name] => ahestina
                )

            [28] => Array
                (
                    [ids] => 28
                    [name] => piyas
                )

            [59] => Array
                (
                    [ids] => 59
                    [name] => sitesrs
                )

            [60] => Array
                (
                    [ids] => 60
                    [name] => simons
                )

            [70] => Array
                (
                    [ids] => 70
                    [name] => Mahesh Raj
                )

            [71] => Array
                (
                    [ids] => 71
                    [name] => kathetrine
                )

            [72] => Array
                (
                    [ids] => 72
                    [name] => babig
                )

            [73] => Array
                (
                    [ids] => 73
                    [name] => symons
                )

        )

    [caseSensitiveSort] => 1
    [_id:CDataProvider:private] =>
    [_data:CDataProvider:private] =>
    [_keys:CDataProvider:private] =>
    [_totalItemCount:CDataProvider:private] =>
    [_sort:CDataProvider:private] =>
    [_pagination:CDataProvider:private] => CPagination Object
        (
            [pageVar] => page
            [route] =>
            [params] =>
            [validateCurrentPage] => 1
            [_pageSize:CPagination:private] => 10
            [_itemCount:CPagination:private] => 0
            [_currentPage:CPagination:private] =>
            [_e:CComponent:private] =>
            [_m:CComponent:private] =>
        )

    [_e:CComponent:private] =>
    [_m:CComponent:private] =>
)

from the above array i populate the cgridview , using the following code in view file
 <?php
                             $this->widget('zii.widgets.grid.CGridView', array(
                                'id'=>'unen-custom-module-grid',
                                'dataProvider'=>$unenrollProvider,
                                //'dataProvider'=>Yii::app()->globals->getUsersByStandardnSection(1,3),
                                'itemsCssClass'=>'table table-striped flip-scroll',
                                'ajaxUpdate'=>true,
                                'template'=>'{summary}{pager}{items}{summary}{pager}',
                                'pager'=>array(
                                 'header'         => '',
                                 'firstPageLabel' => '<<',
                                 'prevPageLabel'  => 'PREVIOUS',
                                 'nextPageLabel'  => 'NEXT',
                                 'lastPageLabel'  => '>>',
                                 ),
                                // 'selectableRows' => 2,
                                'columns'=>array(
                                   array(
                                     'header'=>'#',
                                     'value'=>'++$row',
                                     'htmlOptions'=>array(
                                     'style'=>'width:50px;'
                                     )
                                 ),
                                   'name',
                                   array(
                                  'id' => 'unselectedIds',
                                //  'name' => 'ids',
                                  'selectableRows' => 2,
                                  'class' => 'CCheckBoxColumn',
                                   //'value'=>'$this->ids'
                                  ),
                                ),
                             ));
                             ?>

its working fine , but whenever i click the pagination the cgridview is automatically hiding , im not using $model->search() here ,

A: every time cgridview pagination sends get requests only,  with out form post data you cant able to populate the cgrid again and again , so try to store the values in session and access it , i hope its usefull to you , try it

A: CGridView requires the result returned by CActiveDataProvider so try to do this in your search method in the corresponding model using CActiveDataProvider

A: I think you're experiencing a problem here for not having specified a keyField in your data provider. Try array('keyField'=>'ids) when creating the data provider instance. See also this answer.


text:
Q: Running code whenever a notebook opens I would like to run some code whenever I open a notebook in iPython notebook, basically I would like to specify a file or a couple lines of code to be executed before anything in that notebook is executed. The code is global, ie. should be executed for all notebooks when the iPython notebook server is started with this specific profile.
I have found settings to specify such startup script for the interactive shell, but not for the notebook part. Can somebody point me in the right direction?


text:
Q: SQLite: select max index for each group What I'm trying to do:
SELECT MAX(index), scr FROM history WHERE state = "TQA" GROUP BY scr

So, for every 'scr' in the table, I want a row showing the maximum index where the 'state' of that row = 'TQA'.
For some reason this gives me a syntax error near "index".

A: INDEX is a reserved keyword in SQLite. If you want to use that as a field name, you'll need to quote it;
SELECT MAX("index"), scr FROM history WHERE state = "TQA" GROUP BY scr


text:
Q: Listview performance issue in Xamarin.Android? I am new to Xamarin.Android and I made a very simple app and I compared it to the same app developed in Java and got results that I can't believe in.
Everything that this app is doing is populating ListView with 10000 items on a button click.
C# code:
private void Button_Click(object sender, System.EventArgs e)
{
    var list = new List<String>();

    for (int i = 0; i < 10000; i++)
        list.Add(i.ToString());

    var adapter =
     new ArrayAdapter<String(this,Android.Resource.Layout.SimpleListItem1, list);
    listView.Adapter = adapter;
}

Java code:
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final ArrayList<String> list = new ArrayList<>();
            for(int i = 0; i < 100000; i++)
                list.add(Integer.toString(i));

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, list);
            listView.setAdapter(adapter);
        }
    });

I measured the performance and these are the results:
Xamarin.Android: approx. 950 ms
Java: less than 1 ms
How and why? What am I doing wrong?
I think that in Java not all items are populated at the same time but in Xamarin.Android are, if that is the case how can I avoid it and make populating ListView a lot faster?

A:
Xamarin.Android: approx. 950 ms Java: less than 1 ms.

When you use new ArrayAdapter(..) method to populate ListView, if you just populate a small amount of data(less then about 100), it has little difference between Xamarin.Android and Java. With the increase of the data, the performance has little change in Java, but in Xamarin.Android, the time spend to loaded time is proportional to the amount of data.
In my M6 with Android 7.0, when I populate ListView with 100,000 data, Xamarin.Android : approx. 4200 ms, Java : approx. 42 ms.

If that is the case how can I avoid it and make populating ListView a lot faster?

For a better performance you can create a custom Adapter to populating ListView. If you want to populating mass of data, it is suggested to use RecyclerView. I use it in my device to populate 100,000 data, both of them has a good performance in Xamarin.Android : approx. 200 ms.


text:
Q: Excel : Data Validation of Mac Address using Custom I'm new to Excel  custom data validaiton . I want to prevent users from inserting wrong mac-address format . Correct Mac-Address format which I need to allow as input  is show below :
aabc.1234.acbc

9978.a8f6.2c3a

As you know mac-add can be from number "0-9",letter a-f or A-F .  I doing some google searches I was able to do this :
=ISNUMBER(SUMPRODUCT(FIND(MID(K1,ROW(INDIRECT("1:"&LEN(K1))),1),"0123456789abcdefABCDEF")))

This  validate  without the dot "." after 4 characters , however I need to check for  dot "." after 4 characters. Above  works fine  for below data :
aabc1234aacd

1234ac3d1209

Any help will be appreciated.


text:
Q: Computation of the hom-set of a comodule over a coalgebra: $Ext_{E(x)}(k, E(x)) = P(y)$. First of all, since every other book somehow mentions that this is trivial, I apologize if it turns out that I am just misunderstanding something in the definitions. So here goes:
The motivation for this is the proof that $Ext_{\Gamma}(k, k) = P(y_1, y_2, ...)$ where $\Gamma$ is a commutative, graded connected Hopf algebra of finite type over a field $k$ found in Ravenel's green book Chapter 3, page 62. With this, let me set up my question.
Let $P[x]$ and $E[x]$ be the polynomial and exterior algebra on one generator over a field $k$ respectively. With $x$ as the primitive element (that is to say, $\Delta(x) = 1 \otimes x + x \otimes 1$), they are both coalgebras over $k$.
I would like to understand the following computation: $Ext_{E(x)}(k, E(x)) = P(y)$.
(The earlier question was wrong oops)
The way one does this is to take an injective resolution $0 \rightarrow k \rightarrow E(x) \rightarrow E(x) \rightarrow ...$ where the maps are $d_i(x) =1,  d_i(1) = 0$ then applying $Hom_{E(x)}(k, )$ to get a complex with zero differentials. It then suffices to compute each term $Hom_{E(x)}(k, E(x))$. These $Hom$-sets are what I am interested in knowing an explicit computation of.
Thanks!

A: Maybe it would help to work with algebras rather than coalgebras: since everything is finite-dimensional, we can dualize. The dual to the coalgebra $E(x)$ is again the exterior algebra $E(x)$, and we can work with $E(x)$-modules rather than comodules.
In this case, the goal is to show that $\mathrm{Ext}^{\bullet}_{E(x)}(k, k)$ is a polynomial algebra, generated by a nontrivial map $k \to k[1]$ in the derived category of $E(x)$-modules (which corresponds to the extension $0 \to k \to E(x) \to k \to 0$).
One can write down a minimal resolution of $k$ as an $E(x)$-module that looks like
$$ \dots \to E(x) \to E(x) \to E(x) \to 0 ,$$
where each of the successive maps is given by multiplication by $x$. This computes $\mathrm{Ext}^\bullet_{E(x)}(k, k)$ as a  graded vector space (there's one element in each dimension as desired). The main point is that all the products (compositions) of the element in degree zero are nontrivial. One way to do this computation is to write down compositions of maps of chain complexes: it suffices to show that the maps of chain complexes of the form
$$ \dots \to E(x) \to E(x) \to E(x) \to 0 \\
\dots \to E(x) \ \to 0 \ \   \to 0 \ \   \to 0
$$
which are the identity or zero degreewise, are not nullhomotopic.
In fact, one can't construct a homotopy even at the first level.
But if you work with coalgebras, one way to see this is to use the cobar complex which is discussed in Ravenel's book: in this case, the cobar complex has entirely zero differentials and gives the polynomial algebra as desired.
(Note also that the analogous construction applied to a polynomial algebra yields an exterior algebra. It's probably worth pointing out that this connection between polynomial and exterior algebras is a special case of Koszul duality for associative algebras.)


text:
Q: How can i put two variables into blade view in laravel It is just for learning purposes.
But how do one put two different tables into one view in Laravel.
So far i tried with use DB;
As its just to learn and havent done the model for that table.
Here is my code.
public function view($id, $slug = null){

    $first = DB::table('first')->get();
    $second = Second::where('id',$id)->where('status','active')->firstOrFail();

    $uriCampaign = $this->request->path();

    if( str_slug( $second->title ) == '' ) {
            $slugUrl  = '';
        } else {
            $slugUrl  = '/'.str_slug( $second->title );
        }

        $url_second = 'second/'.$second->id.$slugUrl;

        $uriCanonical = $url_second;

        if( $uriCampaign != $uriCanonical ) {
            return redirect($uriCanonical);
        }

    return view('test.view')->withResponse($second,$first);

}

So i can get the $second into blade, but not the $first.
How can i get them both that i can show, {{ $second->name }}. and also {{ $first->name }}
It doesnt have to be anything frome this code, but just in general.
If i dont want to use model, is it possible with just use DB or there has to be a model to support it?


text:
Q: VSCode IntelliSense for commonJS modules using path.join() In an Adobe CEP panel that I am working on which also uses NodeJS, I have been using the following approach to require other modules:
require('path');
const moduleA = require(path.join(__dirname, "/*PATH-TO*/module_A.js"));
const moduleB = require(path.join(__dirname, "/*PATH-TO*/module_B.js"));

My problem is that VSCode doesn't parse those files and I am not getting IntelliSense autocomplete after requiring those modules.
Is there a way to make IntelliSense work with such code?
--
Note:
That's the only way I could get After-Effects to find those modules, using relative paths gives me errors: Uncaught Error: Cannot find module './module_A'. I have also tried using paths relative to the project folder.
(Alternatively, I would love to know how to make require() work with relative paths in an After-Effects CEP panel, but in this case my project is already full of these requires statements)


text:
Q: Laravel Eloquent use nested relationship to construct eloquent collection I would like to pull the record subscription detail record and the plans and cheats that the particular user subscribes. Aside from that, I also included all my relationship that is available in my model(s).
User Model
// Columns: id, username, email

public function plans(){
    return $this->belongsToMany(Plan::class,"subscriptions","user_id","plan_id");
}

Subscription Model
// Columns: id, plan_id, user_id, expiry,dll_type

Plan Model
// Columns: id, cheat_id, currency_code, country,amount

public function cheatinfo($val){
    return $this->hasOne(Cheat::class,'cheat_id','id');
}

Cheats Model
// Columns: id, internal_subscription_name, cheat_name, isActive

public function plans(){
    return $this->hasMany(Plan::class)->select(['id','cheat_id','country','currency_code','amount']);
}

This is my attempt and this is my current function caller, by the way, I am new for Laravel Eloquent at the moment.
User::whereId(2)->with(["plans"])->first();

Current output:
{
    "resp": {
        "id": 2,
        "name": "qx.wong",
        "email": "user@gmail.com",
        "email_verified_at": null,
        "created_at": "2021-05-23T07:05:13.000000Z",
        "updated_at": "2021-05-23T07:05:13.000000Z",
        "plans": [
            {
                "id": 5,
                "country": "MY",
                "amount": 40,
                "currency_code": "MYR",
                "cheat_id": 3,
                "created_at": "2021-05-23T04:43:04.000000Z",
                "updated_at": "2021-05-23T04:43:04.000000Z",
                "pivot": {
                    "user_id": 2,
                    "plan_id": 5
                }
            }
        ]
    }
}

Expected output:
{
    "resp": {
        "id": 2,
        "name": "qx.wong",
        "email": "user@gmail.com",
        "email_verified_at": null,
        "created_at": "2021-05-23T07:05:13.000000Z",
        "updated_at": "2021-05-23T07:05:13.000000Z",
        "subscription": {
            "expiry":"2020-05-04",
            "dll_type":"2021",
            "plans":[
                {
                    "id": 5,
                    "country": "US",
                    "amount": 10,
                    "currency_code": "USD",
                    "cheat_id": 3,
                    "created_at": "2021-05-23T04:43:04.000000Z",
                    "updated_at": "2021-05-23T04:43:04.000000Z",
                    "pivot": {
                        "user_id": 2,
                        "plan_id": 5
                    },
                    "cheats":{
                        "id":3,
                        "internal_subscription_name":"pubg-ultimate-02",
                        "cheats_name":"PUBG Ultimate 2",
                        "isActive":1
                    }
                }
            ]
        }
    }
}

A: You can access using nested relationship with dot operator like below
User::whereId(2)->with(["plans","palns.cheatinfo"])->first();