text:
Q: Laravel VueJS testing TypeError: _vm._ssrEscape is not a function I've been piecing together a few different tutorials to try and get Mocha tests working for Laravel 7 Vue Components.
I can successfully run a basic test
expect(0).toBe(0);
But as soon as I try and mount a component I get the following error
TypeError: _vm._ssrEscape is not a function
      at Proxy.render (public/main.js:154:13)
      at VueComponent.Vue._render (node_modules/vue/dist/vue.runtime.common.dev.js:3538:22)
      at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4054:21)
      at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4465:25)
      at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4454:12)
      at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4061:3)
      at VueComponent.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8392:10)
      at init (node_modules/vue/dist/vue.runtime.common.dev.js:3112:13)
      at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:5958:9)
      at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5905:9)
      at VueComponent.patch [as __patch__] (node_modules/vue/dist/vue.runtime.common.dev.js:6455:7)
      at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3933:19)
      at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4054:10)
      at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4465:25)
      at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4454:12)
      at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4061:3)

I'm running Node 12.18.2.
My test file contains
import { mount } from '@vue/test-utils';
import Counter from '../../resources/js/components/Counter';

describe ('Counter', () => {

    it ('defaults to a count of 0', () => {
        const wrapper = mount(Counter);
    });

});

And my component contains
<template>

        <button @click="count++"></button>

</template>

The test command is
mochapack --webpack-config node_modules/laravel-mix/setup/webpack.config.js --require tests/Vue/setup.js tests/Vue/**/*.spec.js
And the setup.js file contains
require('jsdom-global')()
global.expect = require('expect');

Thanks for any help

A: I've got this working now.
Using parts of this https://dev.to/tuandm/how-to-test-vue-components-with-laravel-mix-and-mocha-3kgc/
Rather than install mcocha-webpack then uninstalling I went straight to installing mochapack
npm install --save-dev webpack vue-template-compiler @vue/test-utils mocha mochapack jsdom jsdom-global expect


text:
Q: Communication between javascript and GWT code I've created a map using google maps v3 api for GWT. I'm trying to present a kml over this map, but this is not possible because it is stored locally. So, I'm trying to use geoxml3 in order to parse my local kml.
I need the javascript code to be able to "see" the map I created using GWT. How can I do this?
I create the map using
map = GoogleMap.create(Document.get().getElementById("map_canvas"), myOptions);
(map_canvas is a div in my html page)
I want to call a Javascript function in order to parse the KML file and present it on my map. I know how to call a JS function but I don't know what to write in its body.,,

A: This is the way I plotted local kml files in gwt/gxt google maps api v3
Find and download geoxml3.js and ProjectedOverlay.js on the internet.
in your html put:<
script type="text/javascript"
 src='YourServicePath/geoxml3.js'>

Add some procedures to call the kml operations to your client entry java file:
public final native JavaScriptObject createKmlParser(JavaScriptObject mapId) /*-{
var myParser = new $wnd.geoXML3.parser({map: mapId});

    return myParser;
}-*/;

public final native void showKml(JavaScriptObject parser, String kml) /*-{
    parser.parseKmlString(kml);
}-*/;

public final native void hideKml(JavaScriptObject parser) /*-{
    parser.hideDocument();
}-*/;

Because ProjectedOverlay.js needs Google maps connected we'll inject it after we connect to Google maps.
mapWidget = new MapWidget(opts);

ScriptInjector.fromUrl(
    GWT.getHostPageBaseURL() + "YourServicePath/ProjectedOverlay.js").setCallback(new Callback() {

@Override
public void onFailure(Object reason) {
    System.out.println("Script load failed");
}

@Override
public void onSuccess(Object result) {

}
}).setWindow(ScriptInjector.TOP_WINDOW).inject();

To show the KML:
public JavaScriptObject parserGeoXml3;

if (mapWidget != null) {
    JavaScriptObject jsoParser = createKmlParser(mapWidget.getJso());
         parserGeoXml3 = jsoParser;
    try {
        showKml(jsoParser, kmlStr);
        } catch (JavaScriptException jse) {

        }
}
To hide:
try {
    hideKml(parserGeoXml3);
} catch (JavaScriptException jse) {

}

A: Here is coding basics of JSNI from GWT documentation.  This definitely help you how to write body of the function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysqld throws error, ignores --tmpdir switch I'm using the MySql Server which comes with Cygwin. No matter whether I start it like this:
 mysqld --tmpdir=/cygdrive/c/temp start

or like this:
mysqld start --tmpdir=/cygdrive/c/temp

I always get the error message
151104 15:50:48 [Note] mysqld (mysqld 5.5.45) starting as process 8784 ...
151104 15:50:48 [Warning] Can't create test file /var/lib/mysql/CMTCL033974.lower-test
151104 15:50:48 [Warning] Can't create test file /var/lib/mysql/CMTCL033974.lower-test

It looks as if the --tmpdir option would be ignored.
BTW, the directory /cygdrive/c/temp exists and is writeable.

A: It seems to be easy: --tmpdir does not affect the location of these files. They always have to be under /var/lib, so I manually created /var/lib/mysql, and the error message disappeared.
However, mysqld now complains about the start parameter, but this is an unrelated issue, where I will open a separate thread for it, if I can't figure it out by myself....


text:
Q: Why is Ruby throwing a syntax error whenever I use the gem command? This is the first time I've attempted to work with Ruby. I wanted to install sass so I updated gem and attempt to install sass but was thrown an error. I then realized that the syntax error was raised whenever I ran gem - I can't figure out what could be causing this and all other similar cases happen to people in their code, not when they just run the command.
I haven't touched the source code or even used the gem command up to this point. The error is a syntaxerror, specifically:
$ gem
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': /Library/Ruby/Gems/2.0.0/gems/psych-3.0.0/lib/psych/scalar_scanner.rb:146: syntax error, unexpected tIDENTIFIER, expecting ')' (SyntaxError)
      klass.new(yy, m, dd, hh, mm, ss+us/(1_000_000r), offset)
                                                    ^
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/psych-3.0.0/lib/psych/nodes/node.rb:4:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/psych-3.0.0/lib/psych/nodes.rb:2:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/psych-3.0.0/lib/psych.rb:14:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems.rb:585:in `load_yaml'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/config_file.rb:314:in `load_file'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/config_file.rb:191:in `initialize'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/gem_runner.rb:66:in `new'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/gem_runner.rb:66:in `do_configuration'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/gem_runner.rb:46:in `run'
    from /usr/bin/gem:21:in `<main>'

A: This is a known bug in the gemspec of Psych 3.0.0, which lists the required Ruby version as >= 1.9.2, even though Psych 3.0.0 actually requires Ruby 2.2.2 (the specific syntax that causes the error in your case was introduced in Ruby 2.1):

s.required_ruby_version = Gem::Requirement.new(">= 1.9.2")

The problem has been fixed in the repository, but there has not yet been a release incorporating that fix.
The necessary steps to fix your problem are mentioned in the bug report, basically you need to delete the b0rked Psych 3.0.0 gem directory manually, then you can uninstall Psych 3.0.0, and after that, you need to ensure that you don't install 3.0.0 again:

FYI, for anyone landing on the issue as described in the first post, where even the gem command won't even work:

*

*You must rm -rf psych 3.0.0's gem directory. (after that, the gem command should work)

*Then you can do gem uninstall psych -v 3.0.0.

*Then, until version 3.0.0 gets fixed, you must add gem 'psych', '< 3.0.0' to your Gemfile.

*You might have to run bundle update for it to accept your change of psych's version.


text:
Q: How to set enviroment variable from shell script script file set_env:
#!/bin/bash
export LD_LIBRARY_PATH=some_path/openssl/lib/

I run it from the terminal: ./set_env
but variable is not established:
printenv | grep "LD_LIBRARY_PATH"

prints nothing.
So it should be?

A: A child process cannot change the environment of the parent.
The only way to do this is to have the parent environment source the script.
It's all in how your "run" it.
./set_env   # won't work creates a child process that evaporates
. ./set_env # reads the script in the *CURRENT* environment, loads the vars


text:
Q: Include a dailymotion video in Cornerstone I have a video on Dailymotion that I'd like to display on my Wordpress website (X-Theme with Cornerstone).
I use a Video Player element and when I paste the URL of the video in the SRC & Poster field no video is being displayed.

I don't know much about this so I am open to any suggestions. (Is there maybe an other element which is more appropriate for this ? )
I chose DailyMotion rather than Youtube because I need an annotation linking to a page from my website.

A: You need to use Embedded video feature of the x theme to integrate/add the dailymotion video:
Use the following code inside the Embedded video in the embed code section and replace the video ID.
<iframe frameborder="0" width="480" height="270"
src="//www.dailymotion.com/embed/video/xwr14q?autoplay=1&mute=1"
allowfullscreen></iframe>

Screenshot


text:
Q: Trying to save data from a class into localStorage I'm very new to programming, very new to Javascript. The professor is not any help, and I'm doing this with a friend (who is also a beginner) and we're both stuck.
We're trying to make a simple game and we're told that we have to use a save and loading feature using localStorage.
My friend handles the game logic while and I'm doing the save and load.
Problem is, I can't figure out how to get the game and player data that I need to put into an object literal that i can stringify and save it into localStorage.
Every time I inspect element in firefox, it says no data present for selected host.
This is my friend's code:

class Game {
    constructor(level, score)
    {
        // game logic truncated to not clutter..

        this.levelNum = level;

        this.total = score;
        this.hits = 0;
        this.misses = 0;
        this.time = 0;
    }
    // Game methods

    // truncated...
}

class Player
{
    constructor(fName, playerAge)
    {
        this.firstName = fName;
        this.age = playerAge;
    }
    displayInfo()
    {
        return `${this.firstName}, AGE ${this.age}`;
    }
}

// Creating player one
function createPlayer ()
{
    let playerName = document.querySelector("#textbox").value;
    let playerAge = parseInt(document.querySelector("#selectBox").value);

    return new Player(playerName, playerAge);
}
let playerOne = createPlayer();
clickPlay.addEventListener("click", createPlayer());

var playGame;
var gameLevel = 1;

function showLevel()
{
    playGame = new Game(gameLevel);
    let currentLevel = document.querySelector("#levelNum");
    let levelName = document.querySelector("#mathType");
    let playerID = document.querySelector("#playerName");
    let ageID = document.querySelector("#playerAge");

    currentLevel.innerHTML = `${playGame.levelNum}`;
    levelName.innerHTML = `${playGame.mathType}`;
    playerID.innerHTML = `${playerOne.firstName}`;
    ageID.innerHTML = `${playerOne.age}`;

}

clickPlay.addEventListener("click", showLevel());

This is what I've tried and I inserted this at the very end of the above code:
let save_button = document.querySelector("#savBut");

function createUserData(){
  var userData =
  {
    nName: playerOne.firstName,
    nAge: playerOne.age,
    nLevel: playGame.levelNum,
    nMisses: playGame.misses,
    nHits: playGame.hits,
    nSecs: playgame.time
  };
}

clickPlay.addEventListener("click", createUserData();

function saving() {
    // stringify first before storing to userInfo
  localStorage.setItem("userInfo", JSON.stringify(userData));
}

save_button.addEventListener("click", saving);

A: instead of creating the userData on start of the game, you should create it periodically. For testing I would create it when you click the save button and console out the userData to see if the data is in your object before saving. I would also suggest naming the keys the same as from the objects they came from to make loading the data back easier.
function saving() {
  // stringify first before storing to userInfo
  const userData =
  {
    firstName: playerOne.firstName,
    age: playerOne.age,
    levelNum: playGame.levelNum,
    misses: playGame.misses,
    hits: playGame.hits,
    time: playgame.time
  };
  console.log(userData);
  localStorage.setItem("userData", JSON.stringify(userData));
}

you have probably already been saving your data correctly and it will show up in the developer console under the main tab Application in the local storage list.


text:
Q: Cause of delay in multi-threading I wrote a program in Java to print 10 hundred thousand in a for loop.
for (int i =0;i<1000000;i++){
     System.out.println(i);
}

It took around 7.5 seconds.
I wrote a custom class in Java that implements Runnable interface, it takes 2 parameters as a limit to print the values between 2 values.
public class ThreadCustom implements  Runnable {

    int start;
    int end;
    String name;

    ThreadCustom(int start, int end, String name){
        this.start = start;
        this.end = end;
        this.name = name;

    }
    @Override
    public void run() {
       for(int i =start; i<=end;i++){
            System.out.println(i);
        }
    }
}

I created 10 objects of my custom thread class, assigned each object a chunk of 100k numbers to print so at the end I get all the 10 hundred thousands printed (not in order definitely) but it takes around 9.5 seconds.
What's the reason for this 2 seconds delay? Is that because of time slicing and context switching that takes place between threads? I am executing a java process and it spawns 10 threads. Am I thinking in the right direction?
Updated: commented System.out.println to see how it performs when there is an iteration.
Printed time without threads
2019-04-14 22:18:07.111   // start
2019-04-14 22:18:07.116 // end

Using ThreadCustom  class:
2019-04-14 22:26:42.339
2019-04-14 22:26:42.341

A: The extra time is spent in two ways:
1) the overhead involved in setting up each threads execution context
2) the likely scenario that you are spawning more threads than there are logical processors available in your main processor
Since the amount of processing required to increment a loop and print an integer is minimal, this will, in the majority of cases result in degraded performance in a parallel environment.
If you were however to do something like count the distinct pixel colors on any given image during each iteration, you would see a significant performance advantage when using multiple threads.

A:
I wrote a program in Java to print [1 million] in a for loop... I created 10 objects of my custom thread class, ... but it takes around 9.5 seconds.  What's the reason for this 2 seconds delay?

Threads are only faster if they can work independently.  In the case of printing numbers to System.out, all of the threads are trying to contest for access to the same resource System.out which is a synchronized PrintStream.  This means that most of the time is wasted waiting for another thread to release the lock on System.out.  Any additional "delay" with threaded programs is most likely because of the lock contention and the context switching between the threads.
To test thread speed appropriately, you need to run some sort of independent CPU task in each thread.  Calculating Math.sqrt(...) a bunch of times is a better example.  On my newer Macbook, I can do 1 billion (with a b) Math.sqrt(...) calls in ~8.1 seconds but 10 threads can each do 100 million in ~1.1 seconds in parallel.  But wait, you might say, 10 * 1.1 > 8 seconds of total CPU.  I have 4 cores, so with 10 threads running, there is a lot of in and out of the CPUs.    4 threads doing 250m each take 2.1 seconds which is a lot closer to 8.1 secs with the single thread example.
Lastly, Java performance testing is really hard.  I bet if you ran your two programs a number of times you would see some different results.  Any program that runs quickly is really not a good judge of speed or at best is a very rough approximation.  Also, you need to be careful else the hotswap compiler might optimize your loops away at runtime so you need to try to do actual work.


text:
Q: Convert hexString to unicode string I need a code, to convert @"043b" to @"л"
Here is what I tried
// get a hex string (@"0x043b")
NSString *hexString = [@"0x" stringByAppendingString:@"043b"];

// scan an unsined int from it (1083 as expected)
NSScanner* pScanner = [NSScanner scannerWithString:hexString];
unsigned int iValue;
[pScanner scanHexInt: &iValue];

// get a unichar from it (';')
NSNumber *number = [NSNumber numberWithUnsignedInt:iValue];
unichar character = [number unsignedCharValue];

// get a string (@";")
NSString *result = [NSString stringWithFormat:@"%C", character];

but I get @";" instead of @"л"
I also tried
// get a char (';')
char character = [number charValue];

// get a string (@";")
NSString * result = [NSString stringWithFormat:@"%c", character];

Please, help!

A: Here you go:
unsigned long hexBytes = 0x3b04;
NSString *theString = [[NSString alloc] initWithBytes:&hexBytes length:sizeof(hexBytes) encoding:NSUnicodeStringEncoding];
NSLog(theString, @"");

Important point: you have to reverse your bytes so it's 0x3b04 instead of 0x043b.

A: This worked for me
int value = 0;
sscanf([@"043b" cStringUsingEncoding:NSUTF8StringEncoding], "%x", &value);

NSString *result = [NSString stringWithFormat:@"%C", value];

But the compiler is warning me on the last line, so the answer is not that clean
Format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'

Tested both on the 32- and 64-bit processors


text:
Q: How to prevent "+" from escaping in go-echo I am using https://github.com/labstack/echo in one of the projects. I am using c.QueryParam to parse the query parameter and its values. One of the values contains a + symbol in it and it converts them to a space character (which is correct). However, I would like to retain the + character in the value.
Ex: http://localhost:8080?param=test+test
fmt.Println(c.QueryParam("param"))

Right now it outputs test test. However, I am expecting the output as test+test. Is it possible to achieve it using c.QueryParam?

A: You can get the raw query and then parse the parameter and it's value
func hello(c echo.Context) error {
    //to get the raw query
    fmt.Println(c.Request().URL.RawQuery)
    return c.String(http.StatusOK, "Hello, World!")
}

Then you can use strings.split(rawQuery,"=") to get the parameter and it's value.

A: You can write a custom helper function like below -
func CustomQueryParam(c echo.Context, name string) string {
    qParams := make(map[string]string)
    for _, singleQueryParamStr := range strings.Split(c.QueryString(), "&") {
        val := strings.Split(singleQueryParamStr, "=")
        qParams[val[0]] = val[1]
    }
    return qParams[name]
}

func TestGet(c echo.Context) error {
    param := CustomQueryParam(c, "param")
    fmt.Println(param)

    return c.JSON(http.StatusOK, map[string]interface{}{
        "message": "request is successful",
    })
}

Now, the output is as your expection. It prints test+test. But what actually CustomQueryParam do?
Okay, let's explore the insight. Suppose, the api call is -
http://localhost:8080?param=test1+test2&param2=test3
The CustomQueryParam function will take an echo.Context instance and the query param name as function parameters.
Then, inside for loop the whole query string i.e. in our case which is param=test1+test2&param2=test3 is split by & and stored into string slice made by each query param string ([]string{"param=test1+test2", "param2=test3"}).
After that, we iterate over each query param string and again split into a string slice of two values having first value as param name and second value as param value. For example, for first query param string, the resultant output is like below -
"param=test1+test2" => []string{"param", "test1+test2"}
Then, the first value (param name) is assigned as map key and second value (param value) as map value.
After finishing above process for every query string, the map value by query param name (which is the parameter of this function) is returned.
One of the interesting fact about this custom function is that it returns empty string if query param is not found.


text:
Q: Find the Frenet Frame of a curve
Find the Frenet Frame of $\alpha(t)=(2t,t^2,\frac{t^3}{3})$ for $t\in\mathbb{R}$

First finding $\alpha'=(2,2t,t^2)$ and $\alpha''=(0,2,2t)$
$||\alpha'||=\sqrt{4+4t^2+t^4}=\sqrt{(t^2+2)^2}=t^2+2 \neq 1$ so not arc length parameterized
$T=\frac{\alpha'}{||\alpha'||}=(\frac{2}{t^2+2}, \frac{2t}{t^2+2}, \frac{t^2}{t^2+2})$
$N=\frac{T'}{||T'||}$
However I am struggling from here:
$T'=(\frac{-4t}{(t^2+2)^2}, \frac{4-2t^2}{(t^2+2)^2}, \frac{4t+2t^3-2t^4}{(t^2+2)^2})$
$$||T'||=\sqrt{\frac{16t^2+16-16t^2+4t^3+16t^2+8t^4-8t^5+8t^4+4t^6-4t^7-8t^5-4t^7+4t^8}{(t^2+2)^4}}=\sqrt{\frac{16+20t^2+16t^4-16t^5+4t^6-8t^7+4t^8}{(t^2+2)^4}}$$
Providing my calculation is correct, how do I simplify this crazy expression?

A: So using $B=\frac{\alpha' \times  \alpha''}{||\alpha' \times \alpha''||}$
$\alpha' \times \alpha'' = (2t^2, -4t, 4)$
$||\alpha' \times \alpha''||=\sqrt{4t^4+16t^2+16}=2\sqrt{(t^2+2)^2}=2(t^2+2)$
$B=(\frac{t^2}{t^2+2}, \frac{-2t}{t^2+2}, \frac{2}{t^2+2})$
$N=-(T \times B)=(\frac{-2t^3-4t}{(t^2+2)^2}, \frac{-t^4+4}{(t^2+2)^2}, \frac{2t^3+4t}{(t^2+2)^2})$


text:
Q: MiniTest Tutorials in rails are there any good tutorials on MiniTest in rails.
was searching for a while bt without much success.
any help would be really welcome...

A: Check out Announcing Minitest Rails to get started.
After you've picked up the basics and some syntax, I recommend reading the RSpec book. It uses RSpec but really teaches you general testing techniques which can be applied in multiple testing frameworks.
And when you forget something, you can refer to cheatsheets.


text:
Q: Extract words from a List in C Shell I am working on a really old version of UNIX. I have a list such as
x="abc xyz"

stored in a variable x. Now i want to store the individual strings in separate variables. Like
x1="abc" and x2="xyz".

How do I split the original string into words ? I am using sh, so I can not create arrays here.
I tried this approach
  col_list=`cat $outf`

    col=""
    tab=""

    for coltab in $col_list
    do
            j=0

    echo $coltab

        for ct in `echo $coltab`
            do

    echo $ct
                    case $j in
                    0)
                            col=$ct
                    ;;

                    1)
                            tab=$ct
                    ;;
                    esac

                    j=`echo "$j + 1" | bc`

         done

    echo "Column is $col"
    echo "Table is $tab"

  done

But this does not work. Please help
Thanks

A: I haven't any idea how it will work in your ancient sh but can:
x="abc xyz"
read x1 x2 <<EOF
$x
EOF
echo $x1
echo $x2

prints
abc
xyz

BTW, your script isn't C-shell syntax. but vanila sh.
In csh, should arrays works
set x = "a b c"
set arr = ($x)
echo $arr[1]


text:
Q: In rake task, execute command, read stdout until a certain line is matched, then detach and continue task I want to launch a java servlet, observe its stdout until I see that it has fully loaded, and then go back to the rest of my rake task while keeping that process running. Currently I have something like this:
IO.popen "java -jar ./tools/tests/servlet.jar" do |io|
  io.each do |line|
    puts line
    Process.detach(io.pid) if line.include? 'Server ready.' # need help here
  end
end

puts "Ready..."

How do I exit this IO block to continue with the task, while keeping the process running? Thank you!
Edit: Temporary Bad Solution
def with_server_running
  IO.popen "java -jar ./tools/tests/servlet.jar" do |io|
    io.each do |line|
      puts line
      yield if line.include? 'Server ready.'
    end
  end
end

with_server_running do
  puts "Ready..."
  # rest of task
end

A: If I understand you correctly, try this:
if(line.include? 'Server ready.')
  Process.detach(io.pid)
  exit(0)
end


text:
Q: Disable Advanced Options entry automatic generation in GRUB Is it possible to instruct GRUB to not include the Advanced Options entry while it routinely updates? I mean this snippet in /boot/grub/grub.cfg which I forced to remove manually every time some package update is requesting GRUB config recreation:
submenu 'Advanced options for Debian GNU/Linux' $menuentry_id_option 'gnulinux-advanced-7abbf46a-25c1-4ac5-b8fc-eff98778e924' {
        menuentry 'Debian GNU/Linux, with Linux 3.16.0-4-amd64' --class debian --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.16.0-4-amd64-advanced-7abbf46a-25c1-4ac5-b8fc-eff98778e924' {
                load_video
                insmod gzio
                if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
                insmod part_msdos
                insmod lvm
                insmod ext2
                set root='lvmid/iLJBEP-k39n-9Orf-iYFY-szXc-GiFC-hw19FQ/R5kb0j-PEbc-THWn-fH8a-rECU-z7x2-Mr200e'
                if [ x$feature_platform_search_hint = xy ]; then
                  search --no-floppy --fs-uuid --set=root --hint='lvmid/iLJBEP-k39n-9Orf-iYFY-szXc-GiFC-hw19FQ/R5kb0j-PEbc-THWn-fH8a-rECU-z7x2-Mr200e'  7abbf46a-25c1-4ac5-b8fc-eff98778e924
                else
                  search --no-floppy --fs-uuid --set=root 7abbf46a-25c1-4ac5-b8fc-eff98778e924
                fi
                echo    'Loading Linux 3.16.0-4-amd64 ...'
                linux   /boot/vmlinuz-3.16.0-4-amd64 root=/dev/mapper/debianvg-mainlv ro  quiet
                echo    'Loading initial ramdisk ...'
                initrd  /boot/initrd.img-3.16.0-4-amd64
        }

The system is Debian Stable (Jessie 8.5) with GRUB version 2.02~beta2-22+deb8u1 installed.

A: *

*Add GRUB_DISABLE_SUBMENU=y to /etc/default/grub

*Regenerate the grub configuration: grub-mkconfig -o /boot/grub/grub.cfg
See Arch Linux wiki for more explanations:

If you have multiple kernels installed, say linux and linux-lts, by default grub-mkconfig groups them in a submenu. If you do not like this behaviour you can go back to one single menu by adding the following line to /etc/default/grub:
GRUB_DISABLE_SUBMENU=y


text:
Q: What exactly is the relationship between weak* convergence and sequential convergence? I am studying Banach algebras, and the theory frequently makes use of the weak* topology which I am not very familiar with. As I understand it, the weak* topology is defined as follows: let $X$ a normed vector space (or a topological vector space), and let $X^*$ be the dual space to $X$. Define the weak* topology on $X^*$ to be the coarsest topology such that the maps $T_x:X^*\to \mathbb{C}$ defined by $\phi\mapsto\phi(x)$ are continuous for all $x\in X$. On the Wikipedia page, convergence in the weak* topology is defined in terms of nets or sequences, saying that $\phi_\lambda\to\phi$ if $\phi_\lambda(x)\to\phi(x)$ for all $x\in X$ where $\lambda$ is a net, or in the case of sequences, $\phi_n\to\phi$ if $\phi_n(x)\to\phi(x)$ as $n\to\infty$ for all $x\in X$.
Now, on Wikipedia, they make the statement that "Weak-* convergence is sometimes called the simple convergence or the pointwise convergence. Indeed, it coincides with the pointwise convergence of linear functionals."
I have a couple questions about this:

*

*I know nothing about nets, so I am wondering if I can say the following: if $\phi_\lambda\to\phi$ in the weak* topology with $\lambda$ a net, may I assume that there is a sequence so that $\phi_n\to\phi$? For example, if I wanted to prove that the set of characters on a unital abelian Banach algebra are closed, here is how I might try to prove it. Suppose $\phi_n$ is a sequence of characters of the unital abelian Banach algebra $X$ converging to $\phi\in X^*$, then $X$ being unital implies that $\phi$ is not the $0$ functional. Then $\phi_n(ab)=\phi_n(a)\phi_n(b)$ so taking limits on both sides yields $\phi(ab)=\phi(a)\phi(b)$. Thus the limit is nonzero and multiplicative, so is a character on $X$. Is this correct?

*If the above is true, i.e. that you can see every weak* limit as a sequential limit in the above sense, then what information are nets providing about the space? Is there any reason to consider nets when using the weak* topology?
Apologies if the questions are rather basic, I would just like to know how much I need to know about nets before proceeding on with my study of Banach and C$^*$ algebras.


text:
Q: Static analysis tool groovyParser cannot scan console log output, please define a file pattern - Jenkins Warnings Next Generation Plugin How to set the Report File Pattern with Jenkins Warnings Next Generation Plugin when using a groovy parser as a post build action with static analysis tool (Report file pattern has to come for the empty input field in bellow image)
I have tried various methods but none of them worked. Appreciate any valuable input.

A: This parser examine within the jenkins work space of the project. Therefore when I gave a log file (or any other file type) in the workspace that worked properly. If anyone in the future came across with the same issue hope this could benefit you somehow.


text:
Q: React: Call to external API from localhost using axios not working I'm working on a simple CRUD app with Nextjs. The app is currently local, not deployed anywhere yet. I'm trying to make an API call to an external API:
import axios from "axios";

let headers = {
    "token": process.env.NEXT_PUBLIC_BARCODELOOKUP_API_KEY,
};

export const getRecordInfoByBarcode = async (barcode) => {

    const searchByBarcode = `https://api.barcodelookup.com/v3/products?upc=${barcode}&formatted=y`;

    if (barcode === "" || barcode === undefined) {
        throw "Barcode cannot be empty!";
    }

    const res = await axios.get(searchByBarcode, { headers })
        .then(response => {
            console.log("response from barcodelookup");
            console.log(response);
        })
        .catch(e => console.log(e))
}

but I'm getting the following error:

Access to XMLHttpRequest at 'https://api.barcodelookup.com/v3/products?upc=724381033210&formatted=y' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

According to the API's documentation (https://devapi.barcodespider.com/documentation) you can either send the token in the header or as part of the URL:
https://api.barcodelookup.com/v3/products?token=XXXXXXXXXXXXXXXXXX&upc=029667003315
I've tried both ways and none worked. Also tried the same call from my backend app (which is written in Go) but I'm getting the same results.
I can perform the call from a REST client such as POSTMAN.
The API docs do not offer a way to register my app.

A: Have you tried logging process.env.NEXT_PUBLIC_BARCODELOOKUP_API_KEY to the console? If you have created your app using Create React App then you need to prefix the environment variables with REACT_APP like REACT_APP_NEXT_PUBLIC_BARCODELOOKUP_API_KEY


text:
Q: Sum of column values of dataframes with date time index I have two dataframes like this:
df1:
Timestamp    Consumption
2017-03-21    2903
2017-03-22    2982
2017-03-23    3011
2017-03-24    2964
2017-03-25    2961
2017-03-26    2967
2017-03-27    2967
2017-03-28    2903
2017-03-29    2923
2017-03-30    3032

df2:
Timestamp             Consumption
2017-03-21 23:00:00    2000.0
2017-03-22 23:00:00    2005.0
2017-03-23 23:00:00    2026.0
2017-03-24 23:00:00    1919.0
2017-03-25 23:00:00    1933.0
2017-03-26 23:00:00    2006.0
2017-03-27 23:00:00    1995.0
2017-03-28 23:00:00    1998.0
2017-03-29 23:00:00    2002.0
2017-03-30 23:00:00    1730.0

I want to add the values of Consumption column with respective date but i couldn't able to do that.
Desired output:
Timestamp    Consumption
2017-03-21    4903
2017-03-22    4987
2017-03-23    5037
2017-03-24    4883
2017-03-25    4894
2017-03-26    4973
2017-03-27    4962
2017-03-28    4901
2017-03-29    4925
2017-03-30    4762

I tried this:
sum = df1['Consumption'] + df2['Consumption'][match(df1.index,df2.index)]

Output:
Timestamp           Consumption
2017-03-21 00:00:00   NaN
2017-03-21 23:00:00   NaN
2017-03-22 00:00:00   NaN
2017-03-22 23:00:00   NaN
2017-03-23 00:00:00   NaN
2017-03-23 23:00:00   NaN
2017-03-24 00:00:00   NaN
2017-03-24 23:00:00   NaN
2017-03-25 00:00:00   NaN
2017-03-25 23:00:00   NaN
2017-03-26 00:00:00   NaN
2017-03-26 23:00:00   NaN
2017-03-27 00:00:00   NaN
2017-03-27 23:00:00   NaN
2017-03-28 00:00:00   NaN
2017-03-28 23:00:00   NaN
2017-03-29 00:00:00   NaN
2017-03-29 23:00:00   NaN
2017-03-30 00:00:00   NaN
2017-03-30 23:00:00   NaN

Help me achieve this.

A: You can create indexes for align data, column Timestamp in df2 is converted to date:
df1 = df1.set_index('Timestamp')
s = df2.set_index(df2.Timestamp.dt.date)
df1['Consumption'] = df1['Consumption'].add(s['Consumption'])
#if necessary convert to int
df1['Consumption'] = df1['Consumption'].astype(int)
df1 = df1.reset_index()
print (df1)
   Timestamp  Consumption
0 2017-03-21         4903
1 2017-03-22         4987
2 2017-03-23         5037
3 2017-03-24         4883
4 2017-03-25         4894
5 2017-03-26         4973
6 2017-03-27         4962
7 2017-03-28         4901
8 2017-03-29         4925
9 2017-03-30         4762


text:
Q: How to flush interpreters list cache? I initialized a virtualenv with a python 2.7 interpreter, and then selected it as the interpreter in VSCode.
I then changed the virtualenv interpreter to python 3.7, and the VSCode interpreter list does not reflects the change: it still shows the virtualenv interpreter as being python 2.7.
How can I force the cached interpreter list to be updated or flushed?
This is related to this issue.

A: At last I found a way to remove no-longer existing interpreters from the cache :

*

*close VSCode

*delete the virtualenv

*launch VSCode and try to select the no-longer existing interpreter

I guess the lookup is only done at launch, and not upon interpreter selection...

A: Running those 2 commands in the command palette worked for me.

*

*Python: Clear Workspace Interpreter Setting

*Python: Reset Stored Info for Untrusted Interpreters

As mentioned in the GitHub issue here
Kudos to ericsnowcurrently

A: Python: Clear Cache and Reload Window

A: According to this comment, as of October 2021 it is possible to refresh the list of interpreters by doing F1, typing "Python: Select interpreter", and clicking on the circular arrow icon in the top-left corner of the menu.


text:
Q: Передача строки из Receiver в MainActivity Подскажите пожалуйста как мне правильно передать строку из Receiver в MainActivity и в остальные классы, есть ресирвер который принимает данные, подставляет их в строку и должен передать в другие 3 класса, но передает строку только в один или максимум два класса, в третий не дает, как исправить данный код? Программа используется на ТСД, лазер считывает штрих или DataMatrix код.
public class ScanTestReceiver extends BroadcastReceiver {

private static final String TAG = "ScanTestReceiver";
private NotificationManager mNm = null;
private static final String SCANKEY = ScanUtil.SCANKEY;
private static final String SCAN_DECODING_BROADCAST = ScanUtil.SCAN_DECODING_BROADCAST;
public String scancode, keycode;

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    String action = intent.getAction();
        Bundle extras = intent.getExtras();

        for (String key : extras.keySet()) {
            String v = intent.getStringExtra(key);
            Log.d("~~~~~myApplication", "~~~~~" + key + " is a key in the bundle with value " + v);
        }
        int scanKey = intent.getIntExtra(SCANKEY, -1);
        mNm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (SCAN_DECODING_BROADCAST.equals(action) /* && isScanKeyEnable(context,scanKey) */) {
            Intent serviceIntent = new Intent(context, ScanTestService.class);
            context.startService(serviceIntent);
            scancode = intent.getStringExtra("EXTRA_BARCODE_DECODING_SYMBOLE");
            keycode = intent.getStringExtra("EXTRA_BARCODE_DECODING_DATA");

            Log.i(TAG, "Сработало событие EXTRA_BARCODE_DECODING_DATA__" + scancode + "_" + scanKey + "_" + keycode);

            if (scancode.equals("Code 128")) {
            try {

                MainActivity  .getInstace().updateTheTextView(scancode+ "_" + keycode);
                ScanPriemSKoles .getInstace().updateTheTextView(scancode+ "_" + keycode);

            } catch (Exception e) {

            }
            } else if (scancode.equals("Data Matrix")) {
                try {
            MainActivity  .getInstace().updateTheTextView(scancode+ "_" + keycode);
                    Log.i(TAG, "Data Matrix------------------------------------для приема на склад" + action);
            RetirementScan  .getInstace().updateTheTextView(scancode+ "_" + keycode);
                    Log.i(TAG, "Data Matrix------------------------------------для выдачи в отделения" + action);
            ScanPriemSKoles .getInstace().updateTheTextView(scancode+ "_" + keycode);
                    Log.i(TAG, "Data Matrix------------------------------------для выдачи с колес" + action);
                } catch (Exception e) {

                }

            } else {
                try {
                    MainActivity  .getInstace().updateTheTextView( "Ошибка_1");
                    RetirementScan  .getInstace().updateTheTextView( "Ошибка_1");
                   // ScanPriemSKoles .getInstace().updateTheTextView( "Ошибка_1");
                } catch (Exception e) {

                }
            }
            ToneGenerator ToneGenerator1 = new ToneGenerator(STREAM_MUSIC, 30);
            ToneGenerator1.startTone(TONE_DTMF_6, 100);
    }
}

}
код MainActivity
public static MainActivity  getInstace(){
    return ins;
}

public void updateTheTextView(final String t) {

    MainActivity.this.runOnUiThread(new Runnable() {
        public void run() {

            String[] words = t.split("_");
            for(String word : words) {
            }

            x = words[0];
            z = words[1];
        }
    });


text:
Q: How does Mac OS keep track of moved files? An application I was using had a .dockset file stored in my home directory. I moved this file, and the application automatically updated the location of the file. I notice a similar effect when moving files that I'm currently editing in apps like Xcode, TextEdit, BBEdit, Preview, iWork, etc.
How does Mac OS keep track of these file movements?

A: Most Apps don't use the Bookmarks (mentioned by Matthieu) for this purpose, because Bookmarks are meant to locate a file after the app has been quit in between), but rather either keep the file open while the app runs, or reference the file using its File ID (aka CNID or objID), or simply by using a NSURL object that keeps track of the file.
The secret to this working is that HFS(+) volumes assign each file and folder a unique number (the CNID), and so even if the file is renamed or moved, it can be looked up by that number again. Bookmarks also make use of this number by storing it for this purpose.
This also means that if you place your file on a file system that does not support file IDs, e.g. on a SMB network volume or a FAT formatted disk, renaming and moving of such files may NOT be detected by those apps, because there's no alternative tracking mechanism in this case.
See also Apple's Technical QA1113: The /.vol/ dir and volFS.
APFS, Apple's new volume format, does support File IDs as well, BTW.

A: From a higher point of view (in opposite to the low level implementation) this is probably related to NSURL's bookmark capabilities.

A bookmark provides a persistent reference to a file-system resource. When you resolve a bookmark, you obtain a URL to the resource's current location. A bookmark's association with a file-system resource (typically a file or folder) usually continues to work if the user moves or renames the resource, or if the user relaunches your app or restarts the system.


text:
Q: Co-relate cpu & mem usage from kubectl top pods and top command inside respective pod I wish to understand co-relation between "kubectl top pods" output and linux command "top" executed inside POD.
How do they co-relate ?
While top shows current load/usage status along with 5-min & 15-min details, do we have any such functionality for kubectl top pods command ?
Thanks in advance.

A: Kubectl top - Allows you to see the resource consumption for nodes or pods. This command requires Metrics Server to be correctly configured and working on the server.
The top command is used to show the Linux processes. It provides a dynamic real-time view of the running system
If you run top inside the pod, it will be like you run it on the host system because the pod is using the kernel of the host system. Unix top uses the proc virtual filesystem and reads /proc/meminfofile to get actual information about current memory status. Containers inside pods partially share /proc with the host system include a path about memory and CPU information.
For more  information refer to top command in linux and Kubernetes Top pod/node authored by Kasper Siig.


text:
Q: removing ' delimiters from a string hello i am trying to split a string using the split method of string
 string toSplit = "hello how 'are u"
 string[] arr = toSplit.Split('''); // that code doesnt compile
 for (int i=0 ; i < arr.Length ; i++)
      Console.write("arr[i]="+ arr[i]);

my output is:
arr[0] = hello
arr[1]=how, // i get this output by removing the split ofc , it doesnt compile
arr[2]='are
and arr[3]=u

and what i want is to remove this ' delimiter from arr[2]
thanks in advance for you kind help.

A: string toSplit = "hello how 'are u";
string[] arr = toSplit.Split('\'');
var arr=arr.Split(' ');
 for (int i=0 ; i < arr.Length ; i++)
      Console.Write("arr[i]="+ arr[i]);

Mistakes in code:

*

*No semi colon in the string declaration line

*You were not escaping ' Use escape character \

*Console.Write and not write

A: You can just do
toSplit = toSplit.Replace("'", "");

before you split
But I am not quite understanding your question. Your title says you want to remove ' from a string.
I am also unsure how your code gets 4 objects in an array by splitting by ' since there is only one in your string.
The array would look like that if you did a split with a space character.
So do this to get the output you want:
string toSplit = "hello how 'are u";
toSplit = toSplit.Replace("'", "");
string[] arr = toSplit.Split(' ');
for (int i=0 ; i < arr.Length ; i++)
    Console.Write("arr[i]="+ arr[i]);


text:
Q: PHP Regexp Help I'm going to be working with regular expression's a lot in a new project,
I don't have much experience with them and was wondering of a good way of converting HTML to a regular expression.
Anybody know of any good tutorials, or perhaps a generator?
At the moment I need to convert this:
IMPORTANT

Thanks!

A: $text = 'IMPORTANT';
preg_match('|IMPORTANT|', $text, $match);

there's nothing to be "converted" if you're not looking for specified title for example
to pick that important you would use
$text = 'IMPORTANT';
preg_match('|(.*?)|', $text, $match);
echo $match[1]; //IMPORTANT

A: If you want to just get rid of all the html around some values, you can just use strip_tags()
Edit: moved the comment into the answer because it was copy/pasting out bad.
<?php
$html = 'IMPORTANT';
preg_match_all("/]+>(.*?)]+>/i", $html, $matches);
var_dump($matches);
?>

Also, please note that just like said in the comments above, using a regex to parse html is considered bad practice. You should be able to load the html into an instance of DOMDocument and use the getElementsByTagName method to get all spans. Then you can loop through those and validate the attributes/text inside.

A: It's worth noting that Regular Expressions are not a great solution for parsing HTML. I think they are fine if you have a small chunk of HTML with a guaranteed format, though.
Please see the following great StackOverflow thread:
RegEx match open tags except XHTML self-contained tags


text:
Q: Transform a dataframe without looping? I would like to analyse and transform the following DataFrame
import random
import string
import numpy as np
import pandas as pd

# generate example dataframe
df=pd.DataFrame()
df['Name']=[str(x) for x in np.random.choice(['a','b','c'],10)]
df['Cat1']=[str(x) for x in np.random.choice(['x',''],10)]
df['Cat2']=[str(x) for x in np.random.choice(['x',''],10)]
df['Cat3']=[str(x) for x in np.random.choice(['x',''],10)]

df.head(10)

This produces a DataFrame like this:
Sample DataFrame
The task is to count the 'x' in columns Cat1, Cat2, Cat3 for each unique entry in column 'Name'. This can be achieved wth help ofthe groupby() function:
grouped=df.groupby(['Name'])
dfg=grouped['Cat1','Cat2','Cat3'].sum()
dfg

Result of analysis
And the result is this almost what I wanted. Now, I needed to replace the 'x' by a number, e.g., 'xxxx' by 4, 'x' by 1, and so forth. The solution uses a loop over all columns:
for col in range(0,len(dfg.columns)):
    dfg[dfg.columns[col]]=list(map(lambda x: len(x), dfg[dfg.columns[col]]))
dfg

Final result.
Now, I wonder how I can avoid that loop and achieve the same final result?
Thanks a lot for sharing your ideas and guidance.

A: Try:
df.set_index('Name').eq('x')\
  .groupby('Name')['Cat1','Cat2','Cat3'].sum()\
  .astype(int).reset_index()

Output:
  Name  Cat1  Cat2  Cat3
0    a     5     3     4
1    b     1     1     0
2    c     1     1     1

A: Depending on your source of data, this could be easily solved by replacing the "x" with a 1 and setting the empty cells to 0. So you also had to change the datatype of the column to integer.
Calling sum() then on your group will already give you the numeric answer.


text:
Q: When to use the fifth normal form (5NF)? I am new at this form of normalization. I have worked before with the 4NF, but at the moment the 5NF it seems messy and I want to know if there is any rule that says when it is proper to apply this kind of structure or if I have to start thinking and working with it from now on.
PS: I have read about it and I kind of understand it; I just want to know if there are scenarios when it's better to use it or not, and if it so, when to.

A: This is more or less a subjective topic. But my subjective opinion is that the 5NF is really more of a theoretical concept than a practical one. I've been developing databases for 20+ years and have never gone to that extent, or ever wanted to.
In practice it means that your database is already in 4NF and cannot be further decomposed without loss of data.

A:
When to use the fifth normal form (5NF)?

Only during interviews, not in real. That's extreme. Even during interview you are asked to explain database normalization, you are really not expected to go till 5th one. First 3 and you will be selected. :)


text:
Q: how can i unzip a zip file with creating a new folder on the given path in linux i have to unzip a file, i don't want to CD and then run mkdir newfolder then come again to the folder where i have the zip file and then run unzip file.zip /home/user/newfolder
i want to simply run the command from the whichever directory i am it will create the folder for me or ask me that on location /home/user there's no newfolder directory exist do you want to create one (Y/n)? and chose it to y
(doesn't matter if this operation need root access)
i have checked unzip swtiches and google but in all the exmaples they make a directory then unzip the file in it
i am using Debian Buster

A: man unzip says:
 unzip [-Z] [-cflptTuvz[abjnoqsCDKLMUVWX$/:^]] file[.zip] [file(s) ...]  [-x xfile(s) ...] [-d exdir]

[-d exdir]
                An optional directory to which to extract files.  By default, all files and subdirectories are recreated in  the  current  directory;  the  -d
                option  allows  extraction  in  an  arbitrary  directory (always assuming one has permission to write to the directory).  This option need not
                appear at the end of the command line; it is also accepted before the zipfile specification (with the normal options), immediately  after  the
                zipfile specification, or between the file(s) and the -x option.  The option and directory may be concatenated without any white space between
                them, but note that this may cause normal shell behavior to be suppressed.  In particular, -d ~ (tilde) is expanded by Unix C shells  into
                the name of the user's home directory, but -d~ is treated as a literal subdirectory ~ of the current directory.

Alternatively, 7zip (7z command) supports the ZIP format and has a -o parameter for the same purpose

A: The -d in situation (fish shell), where the folder name is derived from the archive name:
for i in *.zip ; unzip $i -d (basename $i .zip) ; end

Only issue, when the archive already embeds a folder, you end up with a superfluous level.
Hence, I want to mention that unar does the right thing (tm): automatically creates a folder, but only when the root of the archive isn't one.
This behavior can be overriden with the same -d option.
Plus, unar handles zip, rar, etc...
What's not to love?


text:
Q: Python/PIL Resize all images in a folder I have the following code that I thought would resize the images in the specified path
But when I run it,  nothing works and yet python doesn't throw any error so I don't know what to do. Please advise. Thanks.
from PIL import Image
import os, sys

path = ('C:\Users\Maxxie\color\complete')

def resize():
for item in os.listdir(path):
    if os.path.isfile(item):
        im = Image.open(item)
        f, e = os.path.splitext(item)
        imResize = im.resize((200,200), Image.ANTIALIAS)
        imResize.save(f + ' resized.jpg', 'JPEG', quality=90)

resize()

A: John Ottenlips's solution created pictures with black borders on top/bottom i think because he used
  Image.new("RGB", (final_size, final_size))

which creates a square new image with the final_size as dimension, even if the original picture was not a square.
This fixes the problem and, in my opinion, makes the solution a bit clearer:
from PIL import Image
import os

path = "C:/path/needs/to/end/with/a/"
resize_ratio = 0.5  # where 0.5 is half size, 2 is double size

def resize_aspect_fit():
    dirs = os.listdir(path)
    for item in dirs:
        if item == '.jpg':
            continue
        if os.path.isfile(path+item):
            image = Image.open(path+item)
            file_path, extension = os.path.splitext(path+item)

            new_image_height = int(image.size[0] / (1/resize_ratio))
            new_image_length = int(image.size[1] / (1/resize_ratio))

            image = image.resize((new_image_height, new_image_length), Image.ANTIALIAS)
            image.save(file_path + "_small" + extension, 'JPEG', quality=90)

resize_aspect_fit()

A: In case you want to keep the same aspect ratio of the image you can use this script.
from PIL import Image
import os, sys

path = "/path/images/"
dirs = os.listdir( path )
final_size = 244;

def resize_aspect_fit():
    for item in dirs:
         if item == '.DS_Store':
             continue
         if os.path.isfile(path+item):
             im = Image.open(path+item)
             f, e = os.path.splitext(path+item)
             size = im.size
             ratio = float(final_size) / max(size)
             new_image_size = tuple([int(x*ratio) for x in size])
             im = im.resize(new_image_size, Image.ANTIALIAS)
             new_im = Image.new("RGB", (final_size, final_size))
             new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
             new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
resize_aspect_fit()

A: #!/usr/bin/python
from PIL import Image
import os, sys

path = "/root/Desktop/python/images/"
dirs = os.listdir( path )

def resize():
    for item in dirs:
        if os.path.isfile(path+item):
            im = Image.open(path+item)
            f, e = os.path.splitext(path+item)
            imResize = im.resize((200,200), Image.ANTIALIAS)
            imResize.save(f + ' resized.jpg', 'JPEG', quality=90)

resize()

Your mistake is belong to full path of the files. Instead of item must be path+item

A: Expanding on the great solution of @Sanjar Stone
for including subfolders and also avoid DS warnings you can use the glob library:
from PIL import Image
import os, sys
import glob

root_dir = "/.../.../.../"

for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
    print(filename)
    im = Image.open(filename)
    imResize = im.resize((28,28), Image.ANTIALIAS)
    imResize.save(filename , 'JPEG', quality=90)

A: This code just worked for me to resize images..
from PIL import Image
import glob
import os

# new folder path (may need to alter for Windows OS)
# change path to your path
path = 'yourpath/Resized_Shapes' #the path where to save resized images
# create new folder
if not os.path.exists(path):
    os.makedirs(path)

# loop over existing images and resize
# change path to your path
for filename in glob.glob('your_path/*.jpg'): #path of raw images
    img = Image.open(filename).resize((306,306))
    # save resized images to new folder with existing filename
    img.save('{}{}{}'.format(path,'/',os.path.split(filename)[1]))

A: For those that are on Windows:
from PIL import Image
import glob

image_list = []
resized_images = []

for filename in glob.glob('YOURPATH\\*.jpg'):
    print(filename)
    img = Image.open(filename)
    image_list.append(img)

for image in image_list:
    image = image.resize((224, 224))
    resized_images.append(image)

for (i, new) in enumerate(resized_images):
    new.save('{}{}{}'.format('YOURPATH\\', i+1, '.jpg'))

A: Heavily borrowed the code from @Sanjar Stone. This code work well in Windows OS.
Can be used to bulky resize the images and assembly back to its corresponding subdirectory.
Original folder with it subdir:
..\DATA\ORI-DIR
├─Apolo
├─Bailey
├─Bandit
├─Bella

New folder with its subdir:
..\DATA\NEW-RESIZED-DIR
├─Apolo
├─Bailey
├─Bandit
├─Bella

Gist link: https://gist.github.com/justudin/2c1075cc4fd4424cb8ba703a2527958b
from PIL import Image
import glob
import os

# new folder path (may need to alter for Windows OS)
# change path to your path
ORI_PATH = '..\DATA\ORI-DIR'
NEW_SIZE = 224
PATH = '..\DATA\NEW-RESIZED-DIR' #the path where to save resized images

# create new folder
if not os.path.exists(PATH):
    os.makedirs(PATH)

# loop over existing images and resize
# change path to your path
for filename in glob.glob(ORI_PATH+'**/*.jpg'): #path of raw images with is subdirectory
    img = Image.open(filename).resize((NEW_SIZE,NEW_SIZE))

    # get the original location and find its subdir
    loc = os.path.split(filename)[0]
    subdir = loc.split('\\')[1]

    # assembly with its full new directory
    fullnew_subdir = PATH+"/"+subdir
    name = os.path.split(filename)[1]

    # check if the subdir is already created or not
    if not os.path.exists(fullnew_subdir):
        os.makedirs(fullnew_subdir)

    # save resized images to new folder with existing filename
    img.save('{}{}{}'.format(fullnew_subdir,'/',name))

A: Expanded the answer of Andrei M. In order to only change the height of the picture and automatically size the width.
from PIL import Image
import os

path = "D:/.../.../.../resized/"
dirs = os.listdir(path)

def resize():
    for item in dirs:
        if item == '.jpg':
            continue
        if os.path.isfile(path+item):
            image = Image.open(path+item)
            file_path, extension = os.path.splitext(path+item)
            size = image.size

            new_image_height = 190
            new_image_width = int(size[1] / size[0] * new_image_height)

            image = image.resize((new_image_height, new_image_width), Image.ANTIALIAS)
            image.save(file_path + "_small" + extension, 'JPEG', quality=90)

resize()

A: If you want to resize any image from a folder where without images files, other files also exist, then you can try this:
from genericpath import isdir
from PIL import Image
import os, sys

path = "C://...//...//....//...//"
save_path = "C://...//..//...//...//"
images = os.listdir(path)

if not os.path.isdir(save_path):
    os.makedirs(save_path)

for image in images:
    image_path = os.path.join(path, image)
    iamge_save_path = os.path.join(save_path, image)
    if image.split(".")[1] not in ["jpg", "png"]:
        continue
    if os.path.exists(image_path):
        im = Image.open(image_path)
        image_resized = im.resize((224,224))
        image_resized.save(iamge_save_path, quality=90)
        # print("saved")

A: Safer to use pathlib
As jwal commented on a similar question, use the object-oriented counterparts for os of pathlib:

*

*p = Path('images') to define the path instance (here as directory relative to current)

*Path.iterdir() to find files in the path instance

*Path.absolute() to get the absolute-path for file-IO functions

*Path.joinpath(*other) to add subfolders or filenames

*Path.mkdir(parents=True, exist_ok=True)

*Path.name to return the basename of the file (like picture.png)

from pathlib import Path

# folder = 'images'
# new_dimension = (width, height)
def resize(folder, new_dimension, new_subdir):

    images_folder = Path(folder)
    for child in images_folder.iterdir():
        print("Found image:", child)
        image_path = child.absolute()

        image = Image.open(image_path)
        resized_image = image.resize()  # could also add Image.ANTIALIAS

        # create if the subdir not exists
        subdir = images_folder.join(new_subdir)
        if not subdir.exists():
            subdir.mkdir(parents=True, exist_ok=True)

        to_path = subdir.joinpath(child.name)  # join adds the path-separators
        print("Saving resized to:", to_path)
        resized_image.save(to_path)  # could also add save-options like 'JPEG', quality=90


text:
Q: CRUD with Lithium & MySQL I just started to play with the PHP framework lithium (v 0.10).
I followed the quick start manual which uses MongoDB as database.
To learn a bit more about lithium, I wanted to switch the DBMS from MonogoDB to MySQL.
The problem I'm having that when I open /posts/ in the browser lithium only shows a blank page with no error messages. Also, when I go to /posts/add/, the correct form is displayed, but after submitting the data (which is correctly written to the DB), lithium also just displays a blank page. What's going wrong?
Also, after reading the lithium docs on models in lithium, I'm still not quite sure what logic (in this case) belongs to the model.
UPDATE 1:
I looks like it there is a problem with the APC caching. After installing APC and renaming the folder containing the lithium, the application worked without an error. When leaving the name of the folder containing lithium unchanged, I got an cache error:
Warning: include(/var/www/web/frameworks/lithium/app/resources/tmp/cache/templates/template_views_layouts_default.html_886_1308416958_798.php) [function.include]: failed to open stream: No such file or directory in /var/www/web/frameworks/lithium/libraries/lithium/template/view/adapter/File.php on line 111

Warning: include() [function.include]: Failed opening '/var/www/web/frameworks/lithium/app/resources/tmp/cache/templates/template_views_layouts_default.html_886_1308416958_798.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/web/frameworks/lithium/libraries/lithium/template/view/adapter/File.php on line 111

END UPDATE 1
I manually set a up a MySQL table posts with the rows id, title and body.
My Posts.php model in /app/models:
<?php
namespace app\models;

class Posts extends \lithium\data\Model {

}
?>

My PostsController.php controller in /app/controllers:
<?php

namespace app\controllers;

use app\models\Posts;

class PostsController extends \lithium\action\Controller {

    public function index() {
        $posts = Posts::all();
        return compact('posts');
        var_dump($posts);
    }

    public function add() {
        if($this->request->data) {
            $post = Posts::create($this->request->data);
            $success = $post->save();
        }
        return compact('success');
    }
}
?>

And finally my views index.html.php in /app/views/posts/:
<?php foreach($posts as $post): ?>

<?=$post->title ?>

<?=$post->body ?>

<?php endforeach; ?>

And also add.html.php in /app/views/posts/:
<?=$this->form->create(); ?>
    <?=$this->form->field('title');?>
    <?=$this->form->field('body', array('type' => 'textarea'));?>
    <?=$this->form->submit('Add Post'); ?>
<?=$this->form->end(); ?>

<?php if ($success): ?>

Post Successfully Saved

<?php endif; ?>

A: A couple of tips ...
1) Are you sure Lithium is running correctly in general? I'm confused as to what your actual question / problem is.
2) There is no need to make the change to your PostsController, Posts::all(); is just shorthand for Posts::find('all');
3) You may need to change your Model for Posts, Lithium (with MySQL) will expect an id column in your table to use as a key, if you don't have a coloum named id you might need to add one to your model.
For example, if you have a table with columns like postid, title, body, date ... add this to your model
<?php
 namespace app\models;

 class Posts extends \lithium\data\Model {
   public $_meta = array('key' => 'postid');
 }

?>

Note the 'key' => 'postid' that will let lithium know to use postid as the key for the table instead of looking for id
4) Here's how to actually construct a MySQL query in your controller ...
public function locations($companyid,$state=null) {

 /* removes null or false values with array_filter() */
 $conditions = array_filter(array('companyid' => $companyid, 'state' => $state));

 /* pass $conditions array to the Locations model, find all, order by city */
 $locations = Locations::find('all', array(
       'conditions' => $conditions,
       'order' => array('city' => 'ASC')
 ));

 return compact('locations');

}

Check out the Lithium Manual for more help: http://li3.me/docs/manual
Models
http://li3.me/docs/manual/working-with-data/using-models.md
Controllers
http://li3.me/docs/manual/handling-http-requests/controllers.md
Views
http://li3.me/docs/manual/handling-http-requests/views.md


text:
Q: How to access the computation result of an Akka Stream? I'm attempting to return the result of a stream operation which in this case is:

*

*sum a list

*square the value

*square the value

which is represented as:
        .fold(0, (aggr, next) -> aggr + next)
        .map(x -> x * x)
        .map(x -> x * x)

To access the value I use
final AtomicInteger returnValue = new AtomicInteger();

followed by :
        .to(Sink.foreach(x -> {
            returnValue.set(x);
            System.out.println("got: " + x);
        }))

Which requires a blocking call to allow the stream to complete which is not acceptable:
Thread.sleep(2000);

If I use:
    CompletableFuture<Object> futureValue =
            ask(actorRef, Done.done(), Duration.ofMillis(5000)).toCompletableFuture();
    System.out.println(futureValue.toCompletableFuture().get().toString());

an error is returned :
Caused by: akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://StreamsExamples/system/Materializers/StreamSupervisor-0/$$a-actorRefSource#1663100910]] after [5000 ms]. Message of type [akka.Done$]. A typical reason for `AskTimeoutException` is that the recipient actor didn't send a reply.

The recipient actor in this case is Source and returns the following on a Done.done message:
return Optional.of(CompletionStrategy.immediately());

Can an Akka stream be used to return the computed value from the stream? The only alternative is to store the computed value in a DB or send it to a Kafka topic when the value is computed in :
.to(Sink.foreach(x -> {

?
Complete src:
import akka.Done;
import akka.actor.ActorRef;
import akka.stream.CompletionStrategy;
import akka.stream.OverflowStrategy;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;

import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

public class GetStreamValue {

    final static akka.actor.ActorSystem system = akka.actor.ActorSystem.create("StreamsExamples");

    public static void main(String args[]) throws InterruptedException, ExecutionException {

        int bufferSize = 100;
        final Source<Integer, ActorRef> source =
                Source.actorRef(
                        elem -> {
                            // complete stream immediately if we send it Done
                            if (elem == Done.done()) {
                                return Optional.of(CompletionStrategy.immediately());
                            }
                            else {
                                return Optional.empty();
                            }
                        },
                        // never fail the stream because of a message
                        elem -> Optional.empty(),
                        bufferSize,
                        OverflowStrategy.dropHead());

        final AtomicInteger returnValue = new AtomicInteger();

        final ActorRef actorRef = source
                .fold(0, (aggr, next) -> aggr + next)
                .map(x -> x * x)
                .map(x -> x * x)
                .to(Sink.foreach(x -> {
                    returnValue.set(x);
                    System.out.println("got: " + x);
                }))
                .run(system);

        Arrays.asList(1, 2, 3).forEach(i -> actorRef.tell(i, ActorRef.noSender()));
        Arrays.asList(1,2).forEach(i -> actorRef.tell(i, ActorRef.noSender()));
        actorRef.tell(Done.done(), ActorRef.noSender());

        Thread.sleep(2000);

        System.out.println("returnValue is "+returnValue);

    }
}

A: I think what you may be missing is to understand the concept of materialized value in Akka Streams. Scan through this part of the documentation especially around combining materialized values. I also had a go at trying to explain this concept here (search for Materialized value). If you grok materialized value, then perhaps what I write here will make more sense.
A call to Source.actorRef(..) returns Source<T, ActorRef> where T is data type of elements flowing through the stream (in your case it's Integer) and ActorRef is the materialized value of that Source. You get the materialized value synchronously when you call run  on RunnableGraph which is what to(...) call returns.
That ActorRef is how you can "drive" the stream as per Source.actorRef(...) semantics.
Now the question is how you get your hands on the data that passes through the stream. In your case you're reducing all Integers into one, so instead of using Sink.foreach(...) which is good for side effects, you can use Sink.head. You see,Sinks can also produce materialized values and in case of Sink.head it materializes to CompletionStage of the first element in the stream, which in your case is the only element. So let's try that:
final ActorRef actorRef = source
                                .fold(0, (aggr, next) -> aggr + next)
                                .map(x -> x * x)
                                .map(x -> x * x)
                                .to(Sink.head())
                                .run(system);

Ok, that didn't help too much. You still are getting just the materialized value of the Source. To get the materialized value of the Sink we need to explicitly ask for it:
final Pair<ActorRef, CompletionStage<Integer>> matVals =
      source
        .fold(0, (aggr, next) -> aggr + next)
        .map(x -> x * x)
        .map(x -> x * x)
        .toMat(Sink.head(), Keep.both())
        .run(system);

Now we get both Source and Sink materialized values. You can drive your stream via the ActorRef as before:
final ActorRef actorRef = matVals.first();

Arrays.asList(1, 2, 3).forEach(i -> actorRef.tell(i, ActorRef.noSender()));
Arrays.asList(1,2).forEach(i -> actorRef.tell(i, ActorRef.noSender()));
actorRef.tell(Done.done(), ActorRef.noSender());

and also you can use CompletableStage API to get your value out of the stream. Like say this:
Integer folded = matVals.second().toCompletableFuture().join();

Yes, this is blocking, but you need somehow to stop the main thread from finishing before the streams runs to completion.


text:
Q: Tomcat Auto Deploy Feature is this good? I downloaded and setup my Apache Tomcat 6 in our production server. I then started it to see if it's running, and found out that its okay.
It runs and then I place my project war file there.  I am about to restart the tomcat service when I notice that that my web archive file was already unzipped and my project web file is already set at the web apps folder.
I think, my setup has an auto-deploy feature but I kept on thinking if this is a good thing?
I have these questions in mind:

*

*Does Tomcat really auto deploys web archive file and what is the frequency that it does?

*Is this a nice feature?

*So what if I leave my war file there, does that mean that Tomcat will reload or unzip the archive file every now and then?

*Is what Tomcat does to my war file the same as when I properly restart my tomcat and let the tomcat service deploy my war file?

A: Have a look at the manual. It says:
If the Host autoDeploy attribute is "true", the Host will attempt to deploy and update web applications dynamically, as needed, for example if a new .WAR is dropped into the appBase
Whether this is a nice feature depends on your requirements. None of the projects I worked on needed this, but hey - your story might be different.
Autodeploy is the same feature as if you would restart Tomcat and it would find a .war sitting around, the only difference is that there has to be a polling thread which looks for changes in the appBase folder.

A: Be careful when using this autoDeploy feature. It will first 'undeploy' the application if an existing version exists and it will delete the context configuration file as well ($CATALINA_HOME/conf/[engine-name]/[host-name]/[app-name].xml).


text:
Q: How to add standard Django models to fixtures output? I try to test extended version of Django flatpages and need to create fixture for it. It's incredibly straightforward to create one for a custom model. For example, to create a fixture for a auth.User model, I should execute the following command in terminal:
$ python manage.py dumpdata auth.User > /path/to/fixture.json

How can I do the same thing for the django.flatpages module? (see the explanation below)

I extended the django.contrib.flatpages.models.FlatPage model as follows:
from django.db import models
from django.contrib.flatpages.models import FlatPage

class FooProject(models.Model):
    pass

class FooFlatPage(FlatPage):
    project = models.ForeignKey(FooProject)

The code above will create 4 tables in a database when I execute the migrate command (1 for FooProject, 1 for FooFlatPage and 2 for Django Flatpages).
Now when I try to execute dumpdata for my module:
$ python manage.py dumpdata my_module > /path/to/fixture.json

...I'll get dump of only 2 tables (except flatpages tables). The fixture.json file:
[
  {
    "model": "my_module.fooproject",
    "pk": 1
  },
  {
    "model": "my_module.fooflatpage",
    "pk": 1,
    "fields": {
      "project": 1
    }
  }
]

Question: How I can create a data dump for all (4) tables?

When I try to add --verbosity=3 argument the same output.


text:
Q: Why is my debug data unformatted? var_dump and print_r are displayed are not formatted when using Laravel 4. How do I format the data to be more readable?

A: Use kint
we use should  s() instead of print_r()
use should d() instead of var_dump()
ex:
sd($arr); like same print_r($arr); die();
Ref: http://raveren.github.io/kint/#configuration

A: Add Kint to your composer.json by running this on the command line:
composer require raveren/kint "dev-master"

And then try it:
dd( new Controller );

You should see this:

Better, huh?

A: You can use the pre tag to format align your answear
http://www.w3schools.com/tags/tag_pre.asp


text:
Q: Asterisk hangs up calls after 10 seconds I am having some trouble with my asterisk install hanging up calls.
Initially I was having no audio on my calls so I opened up the ports to my gsu gateway which is on a different network then my asterisk box. I opened up the port on the gsm gateway side with is behind not and that resolved the audio issues
Now the issue is that asterisk drops the calls. I have checked and the rtp packets stream is only sending packets and doesn't seem to be getting anything back.
The asterisk box is hosted on vultr with Ubuntu server.
Any idea on whats going on?

A: Hangup in 10-12 seconds after call started usually issued by incorrect nat settings. Asterisk can't send back response to softphone/hardphone and hangup line(it think no internet connection to device).
See http://www.voip-info.org/wiki/view/Asterisk+SIP+NAT+solutions
In your case it also can be firewall or bad virtualization setup.


text:
Q: Get the type with specified name in the different assemblies but the same namepsace I need to get the type with specified class name which have the same namespace in the different assemblies.
For example:
Assembly1
namespace ABCSolution.MyProject.MyCode
{
    public class Class1
    {
    }
}

Assembly2
namespace ABCSolution.MyProject.MyCode
{
    public class Class2
    {
    }
}

In my cases, I don't know which assembly a specified class belongs to at runtime. So I am using the code below
private Type GetType(string typeName)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            assemblies = assemblies.Where(x => x.FullName.StartsWith("ABCSolution.MyProject.MyCode.", StringComparison.InvariantCulture)).ToArray();

            foreach (var assembly in assemblies)
            {
                Type type = Type.GetType(typeName + ", " + assembly);

                if (type != null)
                {
                    return type;
                }
            }

            return null;
        }

var myType = GetType("ABCSolution.MyProject.MyCode.Class1");

My solution works fine most of times, however sometimes a null value is returned. I am not sure what happened and if I am using the correct approach.


text:
Q: Compare Excel rows within a table I have an Excel table (which is formatted as table and named as "table 1"). So the table columns are named like @LastName, @FirstName and so on.
This table contains information on when people attended a seminar. They're able to attend a number of seminars but also can attend a single seminar twice or more often.
I now want to find out, when the last date was , when a person attended a special seminar.
Lets give an Example:
Table:
@FirstName  @LastName @Seminar     @Date
Frank       Mayer     Workshop 1   2017/01/15
Frank       Mayer     Workshop 2   2019/05/27
Sabine      Adams     Workshop 1   2017/01/15
Volker      Mueller   Workshop 1   2017/01/15
Frank       Mayer     Workshop 1   2018/04/23

As you can see from this simple example, Frank Mayer attended Workshop 1 2x. All others attended each Workshop only once.
Goal is to have a list of Name, Workshop and last attendance. So the final list should look like:
@FirstName  @LastName @Seminar     @Date
Frank       Mayer     Workshop 2   2019/05/27
Sabine      Adams     Workshop 1   2017/01/15
Volker      Mueller   Workshop 1   2017/01/15
Frank       Mayer     Workshop 1   2018/04/23

I really have no idea how to solve this with Excel Formulas, since there is not only comparing dates, but also find double entry which differ only with the date. If possible, I'd like to NOT use VBA programming.
Do you guys have any idea? My table has 1500 lines, so doing that by hand is not an option...
Maybe there is a way to create a new sheet or table with the results?
Best Regards
Olaf

A: There are a thousand and one ways to do this and you might be surprised how easy it is to do manually too.
If you're reducing the table, meaning, removing rows from the table; then you could...

*

*Add a helper column which concatenates the first name, last name, and workshop.

*Then sort by this column and by date decreasing values.

*Remove duplicates based only in the helper column.

*Remove the helper column

*Sort as desired
The trick is the sort.  Sorting the helper column groups the repeat names per workshop and including the date by decreasing values ensures the most recent is at the top.  So when you remove duplicates, the first occurrence will be the most recent and will be retained but subsequent entries well be removed.

A: A more dynamic approach
(i.e. you would not have to go through the entire process each time more data is added.)

*

*Add a helper column with name+last name+workshop per cell named e.g. "ID". Use either Concatenate or =Name & Lastname & Workshop to consolidate

*Create a pivot table from your table with the following field-list:Rows: Add "ID" , Values: Add "Date" and change the value field settings (right-click) to "Max of Date"

*Remember to refresh the pivot table when adding new data or change the pivot settings to update automatically when opening the workbook.

A: I'd advise you to use the "Subtotals" Excel feature, choosing the Max function.
You might encouter problems as you need to give a single column in the first entry of the dialog, but this can be solved, creating an extra column, appending first name and last name, and basing your that (hidden) column (sorry for the Dutch, I don't have an English Excel):

The corresponding entries for the other columns can be found using basic search formulas (Match, VLookup, ...).

A: I would recommend using PIVOT as the simplest and fastest way:


text:
Q: Pairwise test of 2x3 contingency table in R Var1 <- c("Yes", "No", "Unsure", "Yes", "No", "Unsure")
Var2 <- c("Observation 1", "Observation 1", "Observation 1",
    "Observation 2", "Observation 2", "Observation 2")
Freq <- c(719, 212, 33, 624, 238, 102)
df <- data.frame(Var1, Var2, Freq)

I have the above repeated measures, paired data and I'm working in R. A table of the aggregated data can be created in R via above, but essentially I have two observations for each participant and the observations are categorical (yes, no, unsure). I understand I can run chi-squared or fisher exact test to test for overall differences between O1 and O2. What I am interested in is whether the number of Yes's in Observation-1 is significantly different than Observation-2, and No's vs No's etc. Unfortunately, when I run pairwise comparison tests using pairwise.fisher.test() or pairwiseNominalIndepence() or pairwise.table() I get comparisons like Yes vs. No, but nothing gives me Yes vs Yes. If I transpose the data I just get one overall comparison of O1 vs O2.

A: The comment by @dipetkov is spot-on.  Usually, if you have paired data like this, you want to capture if e.g. Participant 1 changed their answer from "Yes" to "No", and so on.  The data could then be summarized in the following manner:
Before = c("No", "Unsure","Yes")
After  = c("No", "Unsure","Yes")

Table = xtabs( ~ Before + After)

Table[1:3,1:3] = rep("-", 9)

Table

   ###         After
   ### Before   No Unsure Yes
   ###   No     -  -      -
   ###   Unsure -  -      -
   ###   Yes    -  -      -

Note that the labels on the rows are the same as the labels on the columns, and that the table is square.
Also note that for your data, this table will sum to 964 observations, which is the number of individuals you have.  Your table sums to 1928.
Usually this kind of table would be analyzed with an extension of McNemar's test for tables larger than 2 x 2.
A post-hoc analysis might examine the component 2 x 2 tables, for example to see if there was a significant change from "Yes" to "No" or from "Yes" to "Unsure".
Addition:
The following is an example that matches your data.  But your actual data, arranged this way, will likely differ.
The omnibus test is conducted with the mcnemar.test() function. And the post-hoc is conducted with the nominalSymmetryTest() function from the rcompanion package, with the caveat that I wrote the function.
Here, the omnibus test is significant, as is the change from "Yes" to "Unsure" and the change from "Yes" to "No".
Before = c("No", "Unsure","Yes")
After  = c("No", "Unsure","Yes")
Table  = xtabs( ~ Before + After)

Table[1, 1:3] = c(159, 11,  42)
Table[2, 1:3] = c(  5, 25,   3)
Table[3, 1:3] = c( 74, 66, 579)

Table

sum(Table[1,]) # NO BEFORE
sum(Table[2,]) # UNSURE BEFORE
sum(Table[3,]) # YES BEFORE
sum(Table[,1]) # NO AFTER
sum(Table[,2]) # UNSURE AFTER
sum(Table[,3]) # YES AFTER

mcnemar.test(Table)

library(rcompanion)

nominalSymmetryTest(Table, exact=TRUE)

###         After
### Before    No Unsure Yes
###   No     159     11  42
###   Unsure   5     25   3
###   Yes     74     66 579

### NO BEFORE
### 212
### UNSURE BEFORE
### 33
### YES BEFORE
### 719
### NO AFTER
### 238
### UNSURE AFTER
### 102
### YES AFTER
### 624

### McNemar's Chi-squared test
###
### McNemar's chi-squared = 68.599, df = 3, p-value = 8.514e-15

### $Global.test.for.symmetry
###   Dimensions p.value
###        3 x 3      NA
###
### $Pairwise.symmetry.tests
###                Comparison  p.value p.adjust
###     No/No : Unsure/Unsure     0.21 2.10e-01
###           No/No : Yes/Yes  0.00381 5.72e-03
###   Unsure/Unsure : Yes/Yes 1.86e-16 5.58e-16
###
### $p.adjustment
###   Method
###      fdr
###
### $statistical.method
###          Method
###   binomial test


text:
Q: ionic doesn't run on device I'm trying to run an Ionic exemple app, but i'm just no able to make it works with run and emulate.
I'm able to run some Android Studio examples in my device without problems and able to run it with $ ionic serve but when I try to run it with run android, the answer is this:
$ ionic cordova run android --device
Running app-scripts build: --platform android --target cordova
[13:54:25]  build dev started ...
[13:54:25]  clean started ...
[13:54:25]  clean finished in 8 ms
[13:54:25]  copy started ...
[13:54:25]  deeplinks started ...
[13:54:25]  deeplinks finished in 59 ms
[13:54:25]  transpile started ...
[13:54:31]  transpile finished in 5.63 s
[13:54:31]  preprocess started ...
[13:54:31]  preprocess finished in 1 ms
[13:54:31]  webpack started ...
[13:54:31]  copy finished in 6.18 s
[13:54:39]  webpack finished in 8.41 s
[13:54:39]  sass started ...
Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.
[13:54:41]  sass finished in 1.72 s
[13:54:41]  postprocess started ...
[13:54:41]  postprocess finished in 24 ms
[13:54:41]  lint started ...
[13:54:41]  build dev finished in 16.39 s
> cordova run android --device
Android Studio project detected

ANDROID_HOME=/Users/<user>/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
studio
Subproject Path: CordovaLib
Subproject Path: app
chmod: File not found: /Users/<me>/cutePuppyPics/platforms/android/gradle/wrapper/gradle-wrapper.properties

sed: no such file or directory: /Users/<me>/cutePuppyPics/platforms/android/gradle/wrapper/gradle-wrapper.properties

(node:10706) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: /Users/<me>/cutePuppyPics/platforms/android/gradlew: Command failed with exit code ENOENT
(node:10706) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

[OK] Your app has been deployed.
     Did you know you can live-reload changes from your app with --livereload?

[13:54:46]  lint finished in 5.50 s

running cordova requirements it shows me that I have gradle installed:
$ cordova requirements
Android Studio project detected

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-27,android-26,android-24,android-23
Gradle: installed /usr/local/lib/node_modules/gradle/bin/gradle

Thanks a lot! :)

A: It may be that your gradle configuration needs to be updated so you can try this.
npm install -g cordova
cd my_project
cordova platform update android

A: *

*Delete all .gradle files from project dir.

*add android platform. If exist rm it and add again. cordova platform add android@6.3.3

*try cordova build again.

*have success


text:
Q: Mapping muti-level embedded collection gives exception I do have an entity Root
@Entity
public class Root {
    @Id
    String id;

    @ElementCollection
    @CollectionTable
    List<Col> cols ;

The Collection Item 'Col' has an embedded object itself
@Embeddable
public class Col {

    @Embedded
    private Emb emb;

The 'Emb' Object is quite simple
@Embeddable
public class Emb {

    String embField;

I would expect the database tables to be like that
Table: ROOT
Fields: ID
Table: ROOT_COLS
Fields: ROOT_ID, EMB_FIELD
Starting this Spring Boot application gives me an ArrayIndexOutOfBoundsException
How can I fix this problem?
hibernate version: 5.0.12
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at ch.admin.estv.map.Application.main(Application.java:33) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.MappingException: Could not instantiate collection persister org.hibernate.persister.collection.BasicCollectionPersister
    at org.hibernate.persister.internal.PersisterFactoryImpl.createCollectionPersister(PersisterFactoryImpl.java:167) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.persister.internal.PersisterFactoryImpl.createCollectionPersister(PersisterFactoryImpl.java:140) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:399) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
    at org.hibernate.persister.collection.AbstractCollectionPersister.initCollectionPropertyMap(AbstractCollectionPersister.java:1914) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.persister.collection.AbstractCollectionPersister.initCollectionPropertyMap(AbstractCollectionPersister.java:1891) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.persister.collection.AbstractCollectionPersister.(AbstractCollectionPersister.java:592) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.persister.collection.BasicCollectionPersister.(BasicCollectionPersister.java:57) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_121]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_121]
    at org.hibernate.persister.internal.PersisterFactoryImpl.createCollectionPersister(PersisterFactoryImpl.java:152) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 26 common frames omitted

A: The problem is that the default access for entities is field, but for embedded objects the default access is property.
So the Col class should be
@Embeddable
@Access(AccessType.FIELD)
public class Col {
    @Embedded
    private Emb emb;

and the Emb class
@Embeddable
@Access(AccessType.FIELD)
public class Emb {
    String embField;

I would have loved a better error message then an ArrayIndexOutOfBoundsException!


text:
Q: Want to show pin points in MKMapView every 5 seconds I have three locations.  I want to show them one by one randomly in each 5 seconds.
I have used this code:
-(IBAction)onMap:(id)sender
{
    [NSTimer scheduledTimerWithTimeInterval:10.0
                                     target:self
                                   selector:@selector(loadMap)
                                   userInfo:nil
                                    repeats:YES];
}

-(void)loadMap
{
    [mapView1 removeAnnotations:mapView1.annotations];

    int i = random()%3;

    location.latitude = [[lat_Array objectAtIndex:i] doubleValue];
    location.longitude =[[long_Array objectAtIndex:i] doubleValue];

    CLLocationCoordinate2D center = coordinate;
    [mapView1 setCenterCoordinate:center];

    NSMutableArray *marketLocations =[[NSMutableArray alloc]init];

    MapAnnotation *addAnnotation = [[MapAnnotation alloc] initWithCoordinate:location];

    [addAnnotation setTitle:@"name"];

    [marketLocations addObject:addAnnotation];

    [mapView1 addAnnotations:marketLocations];

    // region.center = location;

    span.latitudeDelta = 150.0f;
    span.longitudeDelta = 150.0f;

    region.span=span;

    [mapView1 setRegion:region animated:FALSE];
    [mapView1 regionThatFits:region];
}

#pragma mark - Mapview delegate
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyPin"];

    annView.animatesDrop=FALSE;
    annView.canShowCallout = YES;
    annView.pinColor = MKPinAnnotationColorPurple;

    //annView.rightCalloutAccessoryView = rightButton;

    return annView;
}

It shows the locations correctly but in each load, it focuses to Africa from user's scroll.
I don't want that. I just want to remain in the point where the user scrolled to.


text:
Q: Scroll won't work on Chrome The scroll will not work on a few pages of my site.  I am not exactly sure why.
Here is an example of a page that does not work:
https://gmatanswers.com
While the scroll works fine here:
https://gmatanswers.com/posts
Everything seems to work fine on Firefox, it is just chrome.
Any help would be appreciated.

A: I had the same problem.
Try to disable Smooth Scroll on about:flags
Works for me.