text:
Q: match all variants of an enum that contain attached data I'm just learning and writing a small poker program with the following code:
enum Action {
    Fold,
    Check,
    Call(i32),
    Bet(i32),
    Raise(i32),
    Post(i32),
}

// ...

infors[seat] = match action {
    Action::Fold => Status::Out,
    Action::Check => infors[seat],
    Action::Call(x) => infors[seat].incr(x),
    Action::Bet(x) => infors[seat].incr(x),
    Action::Raise(x) => infors[seat].incr(x),
    Action::Post(x) => infors[seat].incr(x),
};

Is there a way to pattern match on all variants with the i32 field so that the final 4 lines can be combined, since they all do the same thing with x?
Something in the spirit of
Action::_(x) => // ...

A: You can do something like this:
match action {
    Action::Fold => Status::Out,
    Action::Check => infors[seat],
    Action::Call(x) | Action::Bet(x) | Action::Raise(x) | Action::Post(x) => infors[seat].incr(x),
}

And if you want to shorten everything, you can use Action::*
{
    // Only import in this block to avoid name conflicts
    use Action::*;
    match action {
        Fold => Status::Out,
        Check => infors[seat],
        Call(x) | Bet(x) | Raise(x) | Post(x) => infors[seat].incr(x),
    }
}

Rust Playground
Read the Rust Book Pattern Syntax Chapter for more information


text:
Q: Laravel redirect to home when I surf the backend panel I have a problem with laravel 5.4
Laravel redirect to /home when I surf the backend panel or I create new category or edit category.
I did composer dump-autoload and php artisan cache:clear but It is redirect to /home again.
.env
 BROADCAST_DRIVER=log
 CACHE_DRIVER=file
 SESSION_DRIVER=array
 QUEUE_DRIVER=sync

config/session.php
return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 1,

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc" or "memcached" session drivers, you may specify a
| cache store that should be used for these sessions. This value must
| correspond with one of the application's configured cache stores.
|
*/

'store' => null,

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

'cookie' => 'laravel_session',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => env('SESSION_DOMAIN', null),

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => env('SESSION_SECURE_COOKIE', false),

/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/

'http_only' => true,

 ];

routes.php
    Route::group(['middleware' => 'auth', 'prefix' => 'backend', 'as' => 'backend.'], function () {

        Route::get('/', 'Backend\DashboardController@index');
        Route::get('/dashboard', 'Backend\DashboardController@index');

        Route::resource('/category', 'Backend\CategoryController');

        Route::resource('/blog', 'Backend\BlogController');

    });

CategoryController.php
<?php

    namespace App\Http\Controllers\Backend;

    use App\Repositories\CategoryRepository as CategoryRepo;
    use League\Flysystem\Exception;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\Entity\Category;

    class CategoryController extends Controller
    {
        protected $category;

        public function __construct(CategoryRepo $categoryRepo)
        {
            $this->category = $categoryRepo;
        }

        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            $this->data["categories"] = $this->category->paginate(10);
            return view('backend.category.index', $this->data);
        }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            return view('backend.category.create');
        }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request $request
         * @return \Illuminate\Http\Response
         */
        public function store(Request $request)
        {
            $Result = $request->except(["path_info"]);

            $row = $this->category->create($Result);
            flash('Kayıt eklenmiştir', 'success');

            return redirect(route("backend.category.index"));
        }

        /**
         * Display the specified resource.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function show($id)
        {
            $this->data["result"] = $this->category->find($id);
            return view('backend.category.show', $this->data);
        }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {
            $this->data["result"] = $this->category->find($id);
            return view('backend.category.edit', $this->data);
        }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function update(Request $request, $id)
        {
            $PagesUpdate = $request->except(["path_info"]);
            $Pages = $this->category->find($id);
            $Pages->update($PagesUpdate);
            flash('Kayıt güncellenmiştir', 'info');

            return redirect(route("backend.category.index"));
        }

        /**
         * Remove the specified resource from storage.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function destroy($id)
        {

            try {
                $this->category->delete($id);
                flash('Kayıt silinmiştir', 'danger');
                return redirect(route("backend.category.index"));
            } catch (Exception $ex) {
                throw new Exception($ex);
            }

        }
    }

A: You should do something like this when you store the data:
public function store(Request $request)
{
    $Result = $request->except(["path_info"]);

    $row = $this->category->create($Result);
    flash('Kayıt eklenmiştir', 'success');

    return redirect('/dashboard');
}

When you update them redirect back at the same page:
    public function update(Request $request, $id)
    {
        $PagesUpdate = $request->except(["path_info"]);
        $Pages = $this->category->find($id);
        $Pages->update($PagesUpdate);
        flash('Kayıt güncellenmiştir', 'info');

        return back();
             //or
        return redirect ('/');
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Encoded JavaScript: How to decode? I recently bought a script from a guy that isn't replying anymore, and left me with the script obfuscated and not working. The thing is that everything works except the encoded part, which gives error.
I've tried every website on google to un-obfuscate this, with no luck.
How can I "decrypt" this part to make this script work?
var _0x4091 =
['.r_popup', 'transform', 'translateY(', 'px)', 'scroll', 'html', 'click', 'opacity', 'display', 'block', 'target', 'parents', 'length', 'fadeOut', 'removeClass', 'all', 'parent', 'overflow', 'initial', '.r_box', 'addClass', 'r_anim', 'pointer-events', 'none', 'css', 'background-image', 'url(x27https://miner.eu/svg/circle.svgx27)', '.r_popup_container', 'fadeIn', 'fast', 'r_pointer', 'fixed', 'top', 'body', 'scrollTop']; (function (a, c) { var b = function (b) { while (--b) { a['push'](a['shift']()); } }; b(++c); }(_0x4091, 0x12b)); var _0x1409 = function (a, c) { a = a - 0x0; var b = _0x4091[a]; return b; }; var shown = 0x0; function verify() { if (shown == 0x0) { $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0x2'))['css'](_0x1409('0x3'), _0x1409('0x4')); setTimeout(function () { $('.r_box')[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x7')); }, 0xfa); setTimeout(function () { $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa')); $(_0x1409('0x0'))[_0x1409('0x1')]('r_pointer'); $(_0x1409('0x0'))[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x4')); shown = 0x1; updatePos(); }, 0x730); } else { $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa')); $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x4')); } } function updatePos() { if (shown == 0x1 && $(_0x1409('0x8'))[_0x1409('0x5')]('position') != _0x1409('0xc')) { var a = $(_0x1409('0x8'))['offset']()[_0x1409('0xd')] - $(_0x1409('0xe'))[_0x1409('0xf')](); dist = a * -0x1; if (a < 0x0) { if (a > 0x14) { $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + dist + _0x1409('0x13')); } } else if (a >= 0x0) { if (a < 0xdc) { $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + dist + _0x1409('0x13')); } else { $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + -0xdc + _0x1409('0x13')); } } } else { $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + 0x0 + 'px)'); } } $(window)[_0x1409('0x14')](function () { if (shown == 0x1) { updatePos(); } }); $(_0x1409('0x15'))[_0x1409('0x16')](function (a) { if ($('.r_popup_container')[_0x1409('0x5')](_0x1409('0x17')) == '1' && $(_0x1409('0x8'))[_0x1409('0x5')](_0x1409('0x18')) == _0x1409('0x19')) { if (a[_0x1409('0x1a')]['id'] != _0x1409('0x8') && $(a[_0x1409('0x1a')])[_0x1409('0x1b')](_0x1409('0x8'))[_0x1409('0x1c')] == 0x0) { $(_0x1409('0x8'))[_0x1409('0x1d')](_0x1409('0xa')); $(_0x1409('0x0'))[_0x1409('0x1e')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x1f')); } } }); $('.r_all')['parent']()[_0x1409('0x20')]()[_0x1409('0x5')](_0x1409('0x21'), _0x1409('0x22'));

the error is:

ReferenceError: $ is not defined [Learn More] test.js:25:1942 The
  character encoding of the HTML document was not declared. The document
  will render with garbled text in some browser configurations if the
  document contains characters from outside the US-ASCII range. The
  character encoding of the page must be declared in the document or in
  the transfer protocol. a.html ReferenceError: $ is not defined [Learn
  More] test.js:25:685

Any ideas?

A: First, run it all through a beautifier, to get some proper indentation.

var _0x4091 = ['.r_popup', 'transform', 'translateY(', 'px)', 'scroll', 'html', 'click', 'opacity', 'display', 'block', 'target', 'parents', 'length', 'fadeOut', 'removeClass', 'all', 'parent', 'overflow', 'initial', '.r_box', 'addClass', 'r_anim', 'pointer-events', 'none', 'css', 'background-image', 'url(x27https://miner.eu/svg/circle.svgx27)', '.r_popup_container', 'fadeIn', 'fast', 'r_pointer', 'fixed', 'top', 'body', 'scrollTop'];
    (function(a, c) {
        var b = function(b) {
            while (--b) {
                a['push'](a['shift']());
            }
        };
        b(++c);
    }(_0x4091, 0x12b));

    var _0x1409 = function(a, c) {
        a = a - 0x0;
        var b = _0x4091[a];
        return b;
    };
    var shown = 0x0;

    function verify() {
        if (shown == 0x0) {
            $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0x2'))['css'](_0x1409('0x3'), _0x1409('0x4'));
            setTimeout(function() {
                $('.r_box')[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x7'));
            }, 0xfa);
            setTimeout(function() {
                $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa'));
                $(_0x1409('0x0'))[_0x1409('0x1')]('r_pointer');
                $(_0x1409('0x0'))[_0x1409('0x5')](_0x1409('0x6'), _0x1409('0x4'));
                shown = 0x1;
                updatePos();
            }, 0x730);
        } else {
            $(_0x1409('0x8'))[_0x1409('0x9')](_0x1409('0xa'));
            $(_0x1409('0x0'))[_0x1409('0x1')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x4'));
        }
    }

    function updatePos() {
        if (shown == 0x1 && $(_0x1409('0x8'))[_0x1409('0x5')]('position') != _0x1409('0xc')) {
            var a = $(_0x1409('0x8'))['offset']()[_0x1409('0xd')] - $(_0x1409('0xe'))[_0x1409('0xf')]();
            dist = a * -0x1;
            if (a < 0x0) {
                if (a > 0x14) {
                    $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + dist + _0x1409('0x13'));
                }
            } else if (a >= 0x0) {
                if (a < 0xdc) {
                    $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + dist + _0x1409('0x13'));
                } else {
                    $(_0x1409('0x10'))[_0x1409('0x5')]('transform', _0x1409('0x12') + -0xdc + _0x1409('0x13'));
                }
            }
        } else {
            $(_0x1409('0x10'))[_0x1409('0x5')](_0x1409('0x11'), _0x1409('0x12') + 0x0 + 'px)');
        }
    }
    $(window)[_0x1409('0x14')](function() {
        if (shown == 0x1) {
            updatePos();
        }
    });
    $(_0x1409('0x15'))[_0x1409('0x16')](function(a) {
        if ($('.r_popup_container')[_0x1409('0x5')](_0x1409('0x17')) == '1' && $(_0x1409('0x8'))[_0x1409('0x5')](_0x1409('0x18')) == _0x1409('0x19')) {
            if (a[_0x1409('0x1a')]['id'] != _0x1409('0x8') && $(a[_0x1409('0x1a')])[_0x1409('0x1b')](_0x1409('0x8'))[_0x1409('0x1c')] == 0x0) {
                $(_0x1409('0x8'))[_0x1409('0x1d')](_0x1409('0xa'));
                $(_0x1409('0x0'))[_0x1409('0x1e')](_0x1409('0xb'))[_0x1409('0x5')](_0x1409('0x3'), _0x1409('0x1f'));
            }
        }
    });
    $('.r_all')['parent']()[_0x1409('0x20')]()[_0x1409('0x5')](_0x1409('0x21'), _0x1409('0x22'));

_0x1409 seems to be a wrapper function to get a key from the _0x4091 array. We can replace all those with direct array access. Then we can remove the _0x1409 method.
All the 0x.. values can be replaced with their decimal equivalent using a deobfuscator:

var map = [".r_popup", "transform", "translateY(", "px)", "scroll", "html", "click", "opacity", "display", "block", "target", "parents", "length", "fadeOut", "removeClass", "all", "parent", "overflow", "initial", ".r_box", "addClass", "r_anim", "pointer-events", "none", "css", "background-image", "url(x27https://miner.eu/svg/circle.svgx27)", ".r_popup_container", "fadeIn", "fast", "r_pointer", "fixed", "top", "body", "scrollTop"];

(function(depMap, opt_attributes) {
  var setter = function(val) {
    for (;--val;) {
      depMap["push"](depMap["shift"]());
    }
  };
  setter(++opt_attributes);
})(map, 299);

var shown = 0;

function verify() {
  if (shown == 0) {
    $(map[0])[map[1]](map[2])["css"](map[3], map[4]);
    setTimeout(function() {
      $(".r_box")[map[5]](map[6], map[7]);
    }, 250);
    setTimeout(function() {
      $(map[8])[map[9]](map[10]);
      $(map[0])[map[1]]("r_pointer");
      $(map[0])[map[5]](map[6], map[4]);
      shown = 1;
      updatePos();
    }, 1840);
  } else {
    $(map[8])[map[9]](map[10]);
    $(map[0])[map[1]](map[11])[map[5]](map[3], map[4]);
  }
}

function updatePos() {
  if (shown == 1 && $(map[8])[map[5]]("position") != map[12]) {
    var a = $(map[8])["offset"]()[map[13]] - $(map[14])[map[15]]();
    dist = a * -1;
    if (a < 0) {
      if (a > 20) {
        $(map[16])[map[5]](map[17], map[18] + dist + map[19]);
      }
    } else {
      if (a >= 0) {
        if (a < 220) {
          $(map[16])[map[5]]("transform", map[18] + dist + map[19]);
        } else {
          $(map[16])[map[5]]("transform", map[18] + -220 + map[19]);
        }
      }
    }
  } else {
    $(map[16])[map[5]](map[17], map[18] + 0 + "px)");
  }
}

$(window)[map[20]](function() {
  if (shown == 1) {
    updatePos();
  }
});

$(map[21])[map[22]](function(options) {
  if ($(".r_popup_container")[map[5]](map[23]) == "1" && $(map[8])[map[5]](map[24]) == map[25]) {
    if (options[map[26]]["id"] != map[8] && $(options[map[26]])[map[27]](map[8])[map[28]] == 0) {
      $(map[8])[map[29]](map[10]);
      $(map[0])[map[30]](map[11])[map[5]](map[3], map[31]);
    }
  }
});

$(".r_all")["parent"]()[map[32]]()[map[5]](map[33], map[34]);

Then there's a little snippet directly following the map that shifts around the methods a little, resulting in a new map:

var map = [
    ".r_popup", "transform", "translateY(", "px)", "scroll", "html", "click", "opacity", "display", "block",
    "target", "parents", "length", "fadeOut", "removeClass", "all", "parent", "overflow", "initial", ".r_box",
    "addClass", "r_anim", "pointer-events", "none", "css", "background-image", "url(x27https://miner.eu/svg/circle.svgx27)", ".r_popup_container", "fadeIn", "fast",
    "r_pointer", "fixed", "top", "body", "scrollTop"];

(function(depMap, opt_attributes) {
  var setter = function(val) {
    for (;--val;) {
      depMap["push"](depMap["shift"]());
    }
  };
  setter(++opt_attributes);
})(map, 299);

console.log(map);

Now all that remains is replacing all occurrences of map[num] with their string equivalent, and replacing ["key"] with .key where possible, for this end result:
var shown = 0;

function verify() {
  if (shown == 0) {
    $(".r_box").addClass("r_anim").css("pointer-events", "none");
    setTimeout(function() {
      $(".r_box").css("background-image", "url('https://miner.eu/svg/circle.svg')");
    }, 250);
    setTimeout(function() {
      $(".r_popup_container").fadeIn("fast");
      $(".r_box").addClass("r_pointer");
      $(".r_box").css("background-image", "none");
      shown = 1;
      updatePos();
    }, 1840);
  } else {
    $(".r_popup_container").fadeIn("fast");
    $(".r_box").addClass("r_pointer").css("pointer-events", "none");
  }
}

function updatePos() {
  if (shown == 1 && $(".r_popup_container").css("position") != "fixed") {
    var a = $(".r_popup_container").offset().top - $("body").scrollTop();
    dist = a * -1;
    if (a < 0) {
      if (a > 20) {
        $(".r_popup").css("transform", "translateY(" + dist + "px)");
      }
    } else {
      if (a >= 0) {
        if (a < 220) {
          $(".r_popup").css("transform", "translateY(" + dist + "px)");
        } else {
          $(".r_popup").css("transform", "translateY(" + -220 + "px)");
        }
      }
    }
  } else {
    $(".r_popup").css("transform", "translateY(" + 0 + "px)");
  }
}

$(window).scroll(function() {
  if (shown == 1) {
    updatePos();
  }
});

$("html").click(function(options) {
  if ($(".r_popup_container").css("opacity") == "addClass" && $(".r_popup_container").css("display") == "block") {
    if (options.target.id != ".r_popup_container" && $(options.target).parents(".r_popup_container").length == 0) {
      $(".r_popup_container").fadeOut("fast");
      $(".r_box").removeClass("r_pointer").css("pointer-events", "all");
    }
  }
});

$(".r_all").parent().parent().css("overflow", "initial");

A:

var map = [
    ".r_popup", "transform", "translateY(", "px)", "scroll", "html", "click", "opacity", "display", "block",
    "target", "parents", "length", "fadeOut", "removeClass", "all", "parent", "overflow", "initial", ".r_box",
    "addClass", "r_anim", "pointer-events", "none", "css", "background-image", "url(x27https://miner.eu/svg/circle.svgx27)", ".r_popup_container", "fadeIn", "fast",
    "r_pointer", "fixed", "top", "body", "scrollTop"];

(function(depMap, opt_attributes) {
  var setter = function(val) {
    for (;--val;) {
      depMap["push"](depMap["shift"]());
    }
  };
  setter(++opt_attributes);
})(map, 299);

console.log(map);


text:
Q: Show that $\Gamma$ is $\kappa $-categorical for $\kappa>\aleph_{0}$ , but not $\aleph_{0}$-categorical. Let $\mathcal L=\{c_{i}:i<\omega\}$ be a language in first order logic, and:
$\Gamma =\{\forall x(x=x),\forall x\forall y(x=y\rightarrow y=x),\forall x\forall y\forall z(x=y\wedge y=z\rightarrow z=y)\}\cup\{c_{i}\neq c_{j}:i,j\in\omega ,i\neq j\}$
Show that $\Gamma$ is $\kappa $-categorical for $\kappa>\aleph_{0}$ , but not $\aleph_{0}$-categorical.
¿It can be an arbitrary equivalence relation $R$ , not necessarily $=$?

A: Your theory is $\kappa$-categorical for all uncountable $\kappa$, since every model of uncountable size $\kappa$ of the theory has the $\omega$ many distinct constants, plus $\kappa$ many other individuals, and all such models are isomorphic. But your theory is not $\aleph_0$-categorical, since your theory has a model with only the constants, and another with the constants plus another individual that is not a constant, or two others or $n$ others or $\omega$ many others, and these models are not isomorphic. So there are countably many distinct countable models up to isomorphism.
The result isn't true if you interpret $=$ only as an equivalence relation, since in this case, there can be non-isomorphic models of uncountable size $\kappa$, depending on the size of the equivalence class of each $c_i$.


text:
Q: Send message content to a channel when it matches word I am looking to send a message to my logging channel when a user types something important (for a game server) what I have now doesn't work and just spams messages for some reason. if you know how to fix this and make it work and not spam messages, that would be good. (no errors in console)
client.on('message', (message) => {
if (message.content.startsWith("####")) return; {}
const logChannel = client.channels.cache.get('783009285709496371');
logChannel.send(`User: <@${message.author.id}> | Message: ${message.content}`);
})

A: Invert the return condition. Right now you are sensing all messages that dont start with #####.
Put a ! in front of the content check.


text:
Q: Foreach does not return all values I have a foreach but it only returns the last value and not all the values, what is the problem?
my array
array:1 [▼
  "ciudad" => array:15 [▼
    0 => "Piura"
    1 => "10"
    2 => "0"
    3 => "Lima"
    4 => "20"
    5 => "0"
    6 => "Pisco"
    7 => "30"
    8 => "0"
    9 => "Arequipa"
    10 => "40"
    11 => "0"
    12 => "Loreto"
    13 => "50"
    14 => "0"
  ]
]

My code:
public function updateciudadpreciosdelivery(Request $request)
{
    $data = $request->except(['_token', 'restaurant_id']);
    $i = 0;
    $result = [];
    foreach ($data as $day => $times) {
        $day_result = [];
        foreach ($times as $key => $time) {
            if ($key % 3 == 0) {
                $day_result["open"] = $time;
            }
            elseif ($key % 2 == 0) {
                $day_result["cod"] = $time;
            }
            else {
                $day_result["close"] = $time;
            }
        }
        $result[$day][] = $day_result;
    }
    // Fetches The Restaurant
    $restaurant = Restaurant::where('id', $request->restaurant_id)->first();
    // Enters The Data
    if (empty($result)) {
        $restaurant->deliveryciudadprecios = null;
    }
    else {
        $restaurant->deliveryciudadprecios = json_encode($result);
    }
    $restaurant->delivery_charge_type = 'XCIUDAD';
    // Saves the Data to Database
    $restaurant->save();
    return redirect()->back()->with(['success' => 'Las ciudades se guardaron correctamente']);
}

Currently it only returns the last value
"{"ciudad":[{"open":"Loreto","close":"50","cod":"0"}]}"

I need you to return the following (example)
{"ciudad":[{"open" :"Piura","close" :"10","cod" :"0"},{"open" :"Lima","close" :"20","cod" :"0"},{"open" :"Pisco","close" :"30","cod" :"0"},{"open" :"Arequipa","close" :"40","cod" :"0"},{"open" :"Loreto","close" :"50","cod" :"0"}]}

If it is not clear I will try to improve it

A: If we consider your data won't change, and you have 3 entries to get, you can use array_chunk:
$result = [];
foreach ($data as $day => $times) {
    $timesChunked = array_chunk($times, 3);

    foreach ($timesChunked as $time) {
        $result[$day] []= [
            'open' => $time[0],
            'close' => $time[1],
            'code' => $time[2],
        ];
    }
}

But your problem was logical, you don't change the key in your loop, of course your array will have only the last elements. Reread your code, and try to understand why.


text:
Q: problemas con registro de base de datos termina nulo o salta de registro bueno tengo el siguiente problema quisiera que cada vez que pase el ciclo guardar cada  variable dentro de la base de datos pero no logro hacerlo me guarda o un registro vacio o un registro con el codigo el tipo de orden y la fecha en otro registro. ya tengo creado un CRUD
esto es mas o menos lo que quiero

           if line.start_with?('UNH')
               clave     = line[0..4]
              guadar variable clave  em mi base de datos y seguir en el mismo regitro hasta leer la ultima variable
           end

      if line.start_with?('DTM137')
         clave  = line[0..5]
         fechag = line[6...14]
         guardar fecha dentro del mismo registro
      end

 este es mi codigo

           File.foreach('ojo.txt').with_object([]) do |line, result|

            if line.start_with?('UNH')
               clave     = line[0..4]
               result << "#{clave} ORDEN DE COMPRA"
            end

          if line.start_with?('BGM')
              clave     = line[0..2]
              codigooc = line[6...26]

               if line.include?('BGM2')
                  region = 'ORDEN DE COMPRA '
               else
                  region = 'ORDEN DE COMPRA SUGERIDA'
               end

               if cajas = '1'
                  region = 'CANCELACION'
               end

              if cajas = '9'
                 region = 'ORIGINAL'
              end

              if cajas = '6'
                 region = 'PROPUESTA'
              end

              result << "#{clave} codigo #{region}, #{@codigooc}"

              Encabezado.create!(numero_oc: codigooc, tipo_oc: region)

          end

      if line.start_with?('DTM137')
          #line.delete(' ')
          clave     = line[0..5]
          fechag = line[6...14]
          result << "#{clave} ,FECHA DE GENERACION MENSAJE #{fechag}"

      end

    if line.start_with?('DTM ')
        clave    = line[0..2]
        fechaen = line[5...13]
        result << "#{clave} , FECHA DE ENTREGA: #{fechaen}"
                       #Encabezado.create!(fechaen: fechaen)
    end

    if line.start_with?('DTM157')#
       fechalist = line[6...14]
       clave = 'DTM157'
       result << "#{clave} , FECHA DE LISTA DE PRECIOS: #{fechalist}"

    end

      if line.start_with?('NADBY')
        clave     = line[0..4]
        comprador = line[6...-1]
        result << "#{clave} , codigo comprador #{comprador}"
      end

     if line.start_with?('NADSU')
        clave     = line[0..4]
        comprador = line[6...-1]
        result << "#{clave} , codigo proveedor #{comprador}"
     end

    if line.start_with?('CTAOC')
       clave     = line[0..4]
       comprador = line[5...-1]
       result << "#{clave} , INFORMACION PROVEEDOR #{comprador}"
    end

    if line.start_with?('PAT')
       clave     = line[0..2]
       tpago = line[5]
       dentrega = line[7..8]
       dpagar = line [-3..-1]
        result << "#{clave} , codigo #{tpago} , condiciones normales #{tpago} , dias para entrega #{dentrega}  , Dias para pagar #{dpagar} "
    end

       if line.start_with?('TODNC')
          clave     = line[0..4]
          flete1 = 'flete por cuenta del vendedor sin costo'
               else
          flete2 = 'flete por cuenta del comprador'
        result << "#{clave} #{flete2}"
       end

        if line.start_with?('LOC')
          clave     = line[0..2]
          lugar = line[5]
          codigolugar = line[6...-1]
          result << "#{clave} direccion de entrega #{codigolugar}"
        end

imagen de la base de datos y como guarda los registros vacios o guarda lo que deberia ser un registro en dos... intente poner los demas campos y no me los toma


text:
Q: How to use unzOpenCurrentFilePassword? Can someone help me port my code from
void * uzFile = unzOpen("zip filename");
to use the unzOpenCurrentFilePassword from minizip ?
I want to protect my zip file with a password.
I tried many times but I failed using it. Thanks
extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file,
                                                  const char* password));
/*
  Open for reading data the current file in the zipfile.
  password is a crypting password
  If there is no error, the return value is UNZ_OK.
*/

A: Before you compile zlib, remove the definition of NOUNCRYPT in unzip.c. Then "unzOpenCurrentFilePassword will be enabled".
unzip.c Line 72:
#ifndef NOUNCRYPT
    //#define NOUNCRYPT Comment this line, so unzip protected files will be enabled
#endif

Why? Among other things, the definition of NOUNCRYPT causes an absurd return in unzOpenCurrentFilePassword function.
extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method,
                                        int* level, int raw, const char* password)
[...]

#   ifndef NOUNCRYPT
    char source[12];
#   else
    if (password != NULL)
        return UNZ_PARAMERROR;
#   endif


text:
Q: split bigquery dataframe into chunks using dask I searched and tested different ways to find if I can be able to split bigquery dataframe into chunks of 75 rows, but couldn't find a way to do so. here is the senario:
I got a very large bigquery dataframe (millions of rows) using python and gcp SDK:
    from google.cloud import bigquery

    def returnBQResult(sqlQuery):
       bqClient = bigquery.Client()
       query_job = bqClient.query(sqlQuery)
       return query_job.to_dataframe()

I am looking for something similar to below numpy code but using dask and doing it parallel:
       dfBQResults=returnBQResult(sql)
       result=numpy.array_split(dfBQResults,75)


text:
Q: What is the Clojure equivalent of Scala's zipWithIndex? Scala Seq has the zipWithIndex method:

def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Seq[A], (A1, Int), That]): That
Zips this sequence with its indices.
returns: A new sequence containing pairs consisting of all elements of this sequence paired with their index. Indices start at 0.
Example: List("a", "b", "c").zipWithIndex = List(("a", 0), ("b", 1), ("c", 2))

What is the equivalent function in Clojure?

A: Clojure's map-indexed will give you an indexed list of elements in a collection.
user=> (map-indexed vector "foo")
([0 \f] [1 \o] [2 \o])

A: As @jmargolisvt answered map-indexed is a good solution.
As your example got index inverted with collection items, you can always compose with reverse:
(map-indexed (comp reverse list) ["a", "b", "c"])
Or map over two sequences:
(map list ["a", "b", "c"] (range))


text:
Q: Searching Sharepoint/Access - Update table I have been working on a sharepoint search tool.  I know very little about sharepoint so if anyone can point me in the right direction it would be greatly appreciated.
I have a number of tables on a sharepoint site. One of the tables contains the "People" in the database. I have the ability to view this table as a linked table using access, but my coworkers do not have the permissions to do so. My way around it was to use a make table query insert a table into a shared folder and give them read only front end in access to search for the client and when they find them open up a hyperlink to the person on sharepoint. The search feature works great, but I have to manually update the local table (using make table) (which I am not able to do if someone is using the search).
As I see it there are two ways I might be able to solve this, but I am open to any ideas I am by no means an expert:
Is there a better way to search in sharepoint? - I am hoping to have something where they are able to enter in a first name last name dob etc and find the results that match the fields and allow a partial match (so if some fields aren't entered they are ignored). I have not found anything that was able to help me do this, but I do not know what it would be called so if you know what I should look into I would greatly appreciate it!
Is there a way to update the table in Access while someone is using it? Is there another way to accomplish this in access?
What direction do you think I should take? I am usually able to find the information I need online, but I have not had too much success with this.
Thank you!

A: http://root site URL/_catalogs/users/simple.aspx
This syntax will get you to your hidden user content type list on a SP 2010 site - and you can change the view on this to give you different fields.  I haven't yet found a way for this to link to anything that gives me site/list/library access rights, but have found it EXTREMELY useful in place of anything approaching a third party central user administration tool. - You might be able to do something with this for what you're trying to do.


text:
Q: Authorizing requests with OAuth 2.0 without the user signing in A client has requested implementation of the new Google Photos API as a feed of their photos on the website.
The issue arises whereas the library only supports OAuth 2.0 to authorise the library requests. Meaning that each visitor needs to authenticate themselves prior to seeing the photos.

Authorization
  Like other Google REST APIs, the Library API uses OAuth 2.0 to handle authentication and authorization. Your app can request access to the user's Google Photos library via the various authorization scopes provided by the API.
Note that the Library API does not support service accounts; to use
  this API, users must be signed in to a valid Google Account.

Does anyone know a way that I can authenticate the library for all web traffic? I want to use Google Photos as a CMS for images and have a constant feed on the site.

A: Since the Google Photo APIs requires OAuth 2.0 User Credentials, you will not be able to use this API as a CMS for you website.
Each API request requires an OAuth Token and this token can only be obtained by a person authenticating with Google Accounts. The OAuth Flow requires the user to authenticate and grant permission to their personal Google Account.
In addition this API requires that you create OAuth Client Secrets which is used to track your app.


text:
Q: Find and replace in Papeeria I'm using the online LaTex editor Papeeria for working on shared online LaTeX-files with collaborators. I just realized that I don not know how to "find & replace" terms. I found out that "⌘ + F" allows me to find items, but nowhere do I find a way to replace them too.
Does someone know how to do this ?


text:
Q: Serving Large Files Through Nginx via Rails 2.3 Using x-sendfile Let's say I have a Rails 2.3.2 application fronted by nginx and served by mongrel in which I need to serve a large static file through Rails (to control access to it). I want the Rails app to delegate the transfer of the file to nginx, to avoid blocking the mongrel instance.
The available information seems contradictory and incomplete. This post shows how to do it with Apache, and hints that it can also be done with ngninx - but no examples. This post and this post show how to do it using the a plugin that apparently Rails 2.3 makes uncessary. This post suggests that maybe there isn't support for x-sendfile with nginx after all.
I'd rather not muck around with plugins for things Rails can now do by itself.
Has anybody gotten x-sendfile-like behavior to work using no plugins and Rails 2.3/nginx/mongrel? If not, what's the best documentation for getting it to work with a plugin (and/or monkeypatch) and Rails 2.3/nginx/mongrel?

A: The main idea: all your controller does is to set the nginx x-accel-redirect header. Once your controller method returns (which will be very fast), nginx will look at the header your Rails app set. If x-accel-redirect is set, then nginx serves the static file.
Your controller will look something like:
def show
  @attachment = Attachment.find(params[:id])
  # Do anything else you need for authentication, etc.

  head(:x_accel_redirect => '/files/' + @attachment.filename,
   :content_type => @attachment.content_type,
   :content_disposition => "attachment; filename=\"#{@attachment.filename}\"")
end

This alone won't do the trick. You need to also tell nginx about the files located at $RAILS_ROOT/files. Add this to the end of your nginx config inside the server block:
location /files {
  root /path/to/rails_app;
  internal;
}

Put the static file into $RAILS_ROOT/files and it should work. No need for plugins or monkeypatching Tested with Rails 2.3.2 and 2.3.14.


text:
Q: How to map SubDomain to the subfolder? Hi I'm using a BlogEngine.net for my blog and I would like to create 5 different subdomains and point to different subfolders(not redirecting). For example:
firstsubdomain.domain.com - domain.com/posts/helloworld.aspx
firstsubdomain2.domain.com - domain.com/posts/helloworld2.aspx
firstsubdomain3.domain.com - domain.com/posts/helloworld3.aspx

Thank you in advance for working example.
I'm using asp.net 3.5, C#, Windows Server 2008, IIS 7

A: I think you have to create a new web site in IIS manager, point it to the folder where the files are, and set the hostname to subdomain.domain.com

A: You have to use URL rewriting if you limitation on IIS and if you have full control on IIS then can do using .htaccess:
Check these links for more details:
Web.config and mapping subdomains to folders
http://learn.iis.net/page.aspx/465/url-rewrite-module-configuration-reference/
https://help.brinkster.com/KB/a125/how-do-i-redirect-a-domain-or-subdomain.aspx#b3
check this Ionic's ISAPI Rewrite Filter
IIRF is an ISAPI filter that does URL Rewriting for IIS. It's small, FREE, and easy to use. It is easy to install, fast, and powerful. You can get Search-Engine Friendly (SEF) or Search-Engine Optimized (SEO) URLs easily on IIS 6, 7, or 7+. It works with what you have, and there's help available to get you going. You can get the source code to inspect it or even modify it yourself.


text:
Q: FOREIGN KEY -ORA-00904: invalid identifier I'm new using ORACLE SQL and I'm having a hard time trying to create a FOREIGN KEY.
What I made so far:
    CREATE TABLE PESSOA(
PES_CODE INT,
PES_NOME VARCHAR2(40),
CPF INT,
RG VARCHAR2(20),
EMAIL VARCHAR2(30) UNIQUE,
PRIMARY KEY (PES_CODE)
);

CREATE TABLE PROFESSOR(
TITULACAO VARCHAR2(20),
FOREIGN KEY (PES_CODE) REFERENCES PESSOA(PES_CODE);
);

Adding "FOREIGN KEY (PES_CODE) REFERENCES PESSOA(PES_CODE)" leds me to "ORA-00904: "PES_CODE": invalid identifier" error (Using LiveSQL).
I also tried something like
CONSTRAINT FK_PES_COD
FOREIGN KEY (PES_CODE) REFERENCES PESSOA(PES_CODE)

But, again, it remains the same error and I don't understand why.
Could someone please enlighten me?

A: You need to create the column and then create the foreign key constraint as follows:
CREATE TABLE PROFESSOR(
TITULACAO VARCHAR2(20),
PES_CODE INT, -- this
CONSTRAINT PROFESSOR_PESCODE_FK FOREIGN KEY (PES_CODE) REFERENCES PESSOA(PES_CODE)
);


text:
Q: Default 401 instead of redirecting for OAuth2 login Spring Security I support two types of authentication and need to return 401 for most paths instead of redirects. For Keycloak I used the HttpUnauthorizedEntryPoint below and its fine, but for the OAuth2 login, it prevents the automatic redirect (on "/auth/challenge" in my case) to "/oauth2/authorization/azure" on NegatedRequestMatcher(/login, and some other things) to be put in place. The valid process is reflected in logs below:
org.springframework.security.web.util.matcher.NegatedRequestMatcher: matches = true
org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint: Match found! Executing org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint@112c824c
org.springframework.security.web.context.SecurityContextPersistenceFilter: SecurityContextHolder now cleared, as request processing completed org.springframework.security.web.DefaultRedirectStrategy: Redirecting to 'http://localhost:2222/oauth2/authorization/azure'
This is the code that adds the Ouath2 bit to the common configuration:
    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http.commonConfiguration()
                .exceptionHandling()
                    .authenticationEntryPoint(HttpUnauthorizedEntryPoint())
                .and()
                .oauth2Login()
                    .userInfoEndpoint()
                    .oidcUserService(userService)
    }

public class HttpUnauthorizedEntryPoint implements AuthenticationEntryPoint {
    private static final Logger LOG = LoggerFactory.getLogger(HttpUnauthorizedEntryPoint.class);

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg) throws IOException {

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "This endpoint requires authorization.");
    }
}

The question is, how can I by default return 401 and let all the OAuth2 redirects to be placed under the hood?
Thanks in advance.
I know that because of the HttpUnauthorizedEntryPoint the DelegatingAuthenticationEntryPoint is not filled in by Spring Security. I tried to add this manually, but I would rather have this process done by Spring.
val entryPoints = LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>()
entryPoints[loginPageMatcher] = LoginUrlAuthenticationEntryPoint("/oauth2/authorization/azure")
val loginEntryPoint = DelegatingAuthenticationEntryPoint(entryPoints)
loginEntryPoint.setDefaultEntryPoint(HttpUnauthorizedEntryPoint())

A: My guess is you serve both a REST API and server-side rendered UI (Thymeleaf, JSF or whatever) and you want to return

*

*401 for unauthorized requests to @RestController

*302 (redirect to login) for unauthorized requests to UI pages.

Define two SecurityFilterChain beans:

*

*first with client configuration restricted to UI paths

*

*@Order(Ordered.HIGHEST_PRECEDENCE)

*http.securityMatcher(new OrRequestMatcher(new AntPathRequestMatcher("/login/**"), new AntPathRequestMatcher("/oauth2/**"), ...); // add here all paths to UI resources

*http.oauth2Login(); // and all client configuration you need for UI

*http.authorizeHttpRequests().requestMatchers("/login/**").permitAll().requestMatchers("/oauth2/**").permitAll().anyRequest().authenticated();

*second being default with resource-server configuration (no securityMatcher and an order greater than HIGHEST_PRECEDENCE)

Details in this answer and that tutorial


text:
Q: Move an element at the beginning of an array of objects I have array format like this

response = {
  "data": [{
      "districts": [{
        "id": 1,
        "name": "sikkim district",
        "statistics": [{
          "food saftey": 2,
          "food ": 2,
          "air pollution": 0
        }]
      }]
    },
    {
      "districts": [{
        "id": 2,
        "name": "Bhojpur",
        "statistics": [{
          "food saftey": 1,
          "food ": 1,
          "air pollution": 1
        }]
      }]
    }
  ],

}

and the required format is

{
    "data": [
        {
            "district": "sikkim district",
            "food saftey": 2,
            "food ": 2,
            "air pollution": 0
        },
        {
             "district": "Bhojpur",
             "food saftey": 1,
             "food ": 1,
             "air pollution": 1
        },

    ],

}

The array format is in dynamic which keeps changing except the district
and the district has to be at the beginning of the array.

A: What you can do is put the property you know first in a column array and then get the other properties and loop over using the order in the column array.
Something like this:
Stackblitz

import {
  Component
} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data = [{
      "Bal Vivah": 1,
      "Type": 0,
      "districts": "East District"
    },
    {
      "Bal Vivah": 1,
      "Type": 0,
      "districts": "West District"
    },
    {
      "Bal Vivah": 1,
      "Type": 0,
      "districts": "North District"
    }
  ]

  columns: string[] = ["districts"];

  constructor() {
    // get the columns from the data
    if (this.data) {
      var dataObject = this.data[0];
      for (var property in dataObject) {
        if (property != "districts" && dataObject.hasOwnProperty(property)) {
          this.columns.push(property);
        }
      }
    }
  }
}

      {{column}}

    <ng-container *ngFor="let columnData of data">

          {{columnData[column]| json}}

    </ng-container>

Note: I changed your data to be valid json.


text:
Q: Get all bytes from stream I'm writing a proxy in c# and I wrote this method to get bytes from the stream but after looking at answer in this thread : Proxy won't work in chrome and only partly in firefox I realize that I do not get all the bytes. How can I solve this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace LexProxy
{
    class ProxyServer
    {
        private TcpListener tcpListener;

        public ProxyServer()
        {
            this.tcpListener = new TcpListener(IPAddress.Any, 3000);
            this.tcpListener.Start();
            while (true)
            {
                Console.Write("Waiting for a connection... ");
                TcpClient client = tcpListener.AcceptTcpClient();
                Thread thread = new Thread(delegate()
                {
                    Serve(client);
                });
                thread.Start();
            }
        }

        private void Serve(TcpClient client)
        {
            Console.WriteLine("Connected!");
            NetworkStream stream = client.GetStream();
            byte[] request = GetBytesFromStream(stream, client.ReceiveBufferSize);
            if (request != null)
            {
                string requestString = System.Text.Encoding.UTF8.GetString(request);
                string[] requestParts = requestString.Split(' ');
                if (requestParts.Length >= 2)
                {
                    string method = requestParts[0];
                    if (!requestParts[1].Contains("http://") && !requestParts[1].Contains("https://"))
                        requestParts[1] = "http://" + requestParts[1];

                    Uri uri = new Uri(requestParts[1], UriKind.RelativeOrAbsolute);
                    string host = StringUtils.ReplaceFirst(uri.Host, "www.", "");
                    int port = uri.Port;
                    byte[] response = getResponse(host, port, request);
                    if (response != null)
                        stream.Write(response, 0, response.Length);
                    client.Close();
                }
            }
        }

        private byte[] getResponse(string host, int port, byte[] request)
        {
            TcpClient client = new TcpClient(host, port);
            NetworkStream stream = client.GetStream();
            stream.Write(request, 0, request.Length);
            byte[] response = GetBytesFromStream(stream, client.ReceiveBufferSize);
            return response;
        }

        private byte[] GetBytesFromStream(NetworkStream stream, int bufferSize)
        {
            Byte[] bytes = new Byte[bufferSize];
            int i;
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                return bytes;
            }

            return null;
        }
    }
}

A: Try out this sample Proxy Server instead:
http://times.imkrisna.com/2011/08/simple-http-proxy-server-c-source-code/

A: You're doing this wrong. Instead of trying to gather the entire response before sending it downstream, you should just be copying bytes as they arrive. No need to add latency.
But note that the code you have written in getAllBytesFromStream() is nonsense. You have a while loop with an unconditional return statement in it. How is that ever going to execute more than once?


text:
Q: Is it compulsory to download Visual Studio for spacy? I have tried installing spacy, but it is throwing the below error:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft
  Visual C++ Build Tools":
  http://landinghub.visualstudio.com/visual-cpp-build-tools

I don't want to install Visual Studio. Is there other way to resolve this?

A: At the moment, installing spaCy requires a compiler. On Windows, this is included in the Visual C++ Build Tools. (Not to be confused with Visual Studio – you definitely don't need the whole thing.)
If you install spaCy from conda, you should be able to install binary wheels, which don't require a compiler:
conda install -c conda-forge spacy

Providing binary wheels for pip is definitely on the spaCy roadmap – you can follow the discussion and work in progress in this thread.

A: I stumbled upon the same thing but however managed to do it without MS Build Tools. However the process requires a bit of manual effort, but that's worthy if you don't want to waste space for MS Build Tools.

*

*Visit Unofficial Windows Binaries for Python Extension Packages. Here you can get many binary wheels of a number of python packages for various python versions and both for 32/64 architectures.

*Next search and download ujson, cymem, murmurhash, preshed, cytoolz, thinc and finally spaCy.

*Install each wheel in the downloaded order using pip install some-package.whl
Hopefully spaCy will be installed successfully. If not, please leave a comment and I'll try my best to help you out.


text:
Q: why is this heap algorithm for permutation not working; i'm preparing for an interview and was trying heap's algorithm for permutation with javascript. so the code works fine when i try to print to console.

function per(a, size){
    if(size === 1){
        console.log(a);
    }

    for(let i = 0; i < size; i++){
        per(a, size-1;
        if(size % 2 === 1){
            let temp = a[0];
            a[0] = a[size - 1];
            a[size - 1] = temp;
        }else{
            let temp = a[i];
            a[0] = a[size -1];
            a[size - 1] = temp;
        }
    }
}
let a = [1,2,3];
per(a, a.length,count);
console.log(count);

but when i try to put the result into an array it doesn't work.

function per(a, size){
    if(size === 1){
        count.push(a);
    }

    for(let i = 0; i < size; i++){
        per(a, size-1);
        if(size % 2 === 1){
            let temp = a[0];
            a[0] = a[size - 1];
            a[size - 1] = temp;
        }else{
            let temp = a[i];
            a[0] = a[size -1];
            a[size - 1] = temp;
        }
    }
}
let count = [];
let a = [1,2,3];
per(a, a.length,count);
console.log(count);

it prints this:

[
  [ 3, 1, 1 ],
  [ 3, 1, 1 ],
  [ 3, 1, 1 ],
  [ 3, 1, 1 ],
  [ 3, 1, 1 ],
  [ 3, 1, 1 ]
]

A: count.push(a.slice()); // push a shallow-copy of the array

As an aside, you don't need a temporary variable to swap two items.
[a[0], a[size-1]] = [a[size-1], a[0]];


text:
Q: Use bluetooth in Android app coded using python I know there are various tools for creating android apps using python eg python-for-android, android-scripting-evrironment, SL4A etc.
What I need to know is which of these would be helpful if I need my application to use the Bluetooth module of the device.

A: There is a BluetoothFacade that has been implemented for the upcoming release 5 of SL4A.
The API reference is located at http://code.google.com/p/android-scripting/wiki/unofficial_apiref
I don't believe that access to Bluetooth services is (at present) available via Kivy or any Kivy-derived project.

A: It looks kivy start to provide Bluetooth related function now: https://github.com/kivy/python-for-android/tree/bluetooth

A: You can also use the PyBluez library. You need it compiled for ARM cores to use it on Android, but this has already been done and is available from the PY4A website's Modules page. You just download it to your device, then install it using your PY4A app's Install Module feature.


text:
Q: Junction conditions in GR including electromagnetism I have recently learned about the Israel junction conditions in GR (as explained in for example Gravitation by MTW). I then tried to generalize it when including Electromagnetism, i.e. matching two spacetimes over a junction but when there is some non-zero electromagnetic content in, but I ran into difficulties. Does anyone know where this has been studied in the literature?
Basically the problem I ran into was that the Einstein equations are schematically on the form
$$G=F^2+T$$
Here $T$ is a matter stress energy tensor for some delta function matter at the junction, $F$ is the electromagnetic field tensor and $G$ is the Einstein tensor. When deriving the Israel junction conditions we would integrate over a small slice over the junction and it turns out that the Einstein tensor has a delta function which comes from a discontinuity in the extrinsic curvature so we obtain relations between the jump of the extrinsic curvature and the stress energy tensor of the shell. However, no such delta function can appear in F^2 if we assume a discontinuity in e.g. the four potential. Differentiating A then gives a delta function in $E$ and/or $B$ but $F^2$ is then a delta function squared and contributes nothing.
If we argue that it is really $B$ and $E$ that are the physical quantities of interest and they can not possess a delta function, then $F^2$ would contribute zero to the junction integral since there are not derivatives wrt E or B. Thus the Israel junction conditions should be unchanged by adding electromagnetism, but I dont think this is the right answer?

A: I believed I found the answer to my own question. My reasoning seems to be right, the junction conditions obtained by a small integration over the shell are not altered by adding electromagnetism. However, to find the dynamics, these equations must be appended by at least one more equation, for example the Hamiltonian constraint, and these are indeed changed when there is a background stress energy tensor for the matter content.


text:
Q: how to update javascript function every minute and update chart? I am trying to update my chart every minute and call the chart function. Not sure what I'm doing wrong. Can anyone help.
The page is here:-
http://www.api.jonathanlyon.com/m.html
Here is the code:-
        <!DOCTYPE html>

<meta charset=utf-8 />
<title>Morris.js Line Chart Example</title>

Any help would be much appreciated.
Thanks
Jonathan

A: The purpose of the outer $() is a shorthand for $(document).ready(). Go ahead and throw all your code into the jQuery wrapper to delay execution until the DOM is ready.

Also, you need to include your scripts in either the head or (better) the end of the body tag. Including elements outside of those elements is not valid markup.

A: additionally you may split it like this
function chart(){
    $.ajax({
        url: "http://www.api.jonathanlyon.com/api_fanpage2.php?pagename=volvo&format=json&hourly=true",
            success: function (data){
            toPlot = []
            $.each(data[0]['pagename']['volvo']['data'], function(i, item){
                toPlot.push({x: item['date'] , volvo: item['newfans']   });
            });
            console.log("length:" + toPlot.length)
            toPlot.reverse()
            morrisTemplate.data = toPlot.slice(toPlot.length - 24, toPlot.length)
            Morris.Line(morrisTemplate);
        }
    });
}

$(function () {
    chart();
});

This is not most beautiful solution as it makes dirt in global scope, but quick


text:
Q: What should I use to get the title and post to show? I'm working on an assignment using python, flask-env, and my sql and I am stuck on trying to get the blog title and blog post to show. I can only get the name of the person to show(which I need but the other stuff is important as well).
If I leave the template with just "indiv_post" for both fields, it shows "None", but if I put anything other that or anything with it, nothing but the author name shows.
in my main.py:
@app.route('/blog', methods=['POST', 'GET'])
def blog():
    owner = User.query.filter_by(username=session['username']).first()

    if request.method == 'POST':
        blog_name = request.form('blog')
        new_blog = Blog(blog_name, owner)
        #post_title = request.form('blog_title')
        #post_entry = request.form('your_thoughts')
        db.session.add(new_blog)
        db.session.commit()
    post_id = request.args.get('id')
    indiv_post = Blog.query.get('post_id')
    user_id = request.args.get('owner_id')
    posts = Blog.query.filter_by(owner_id=user_id)
    blog = Blog.query.filter_by(owner_id=user_id)
    return render_template('indiv_post.html', owner_id=owner, blog=blog, post=post_id, indiv_post=indiv_post)

in my template(indiv_post.html):

My Posts

{{posts}}

{{indiv_post}}

Written by {{session['username']}}

I expect the output to be show:
Blog Title
Blog post
written by: user
But I'm getting:
None
None
written by: user


text:
Q: wix: unable to detect servicepacks I am trying to detect .net framework 2.0 service pack 2. But it seems that wix is unable to detect that.
below is the script that i am using.
NAnt:
<exec program="${wix.dir}\light.exe" workingdir=".\wix" commandline="-ext WixUIExtension -ext WixNetFxExtension -cultures:en-us SampleFirst.wixobj -out ${release.dir}\NantTest.msi"/>

wix:
<PropertyRef Id="NETFRAMEWORK20"/>
<Condition Message="This application requires .NET Framework 3.5 SP1. Please install the .NET Framework then run this installer again.">
    <![CDATA[Installed OR (NETFRAMEWORK20_SP_LEVEL and NOT NETFRAMEWORK20_SP_LEVEL = "#2")]]>
</Condition>

It is able to detect  the ,net framework. But it is not detecting service packs. Any suggestion?

A: Just use
<PropertyRef Id="NETFRAMEWORK20_SP_LEVEL"/>

instead of
<PropertyRef Id="NETFRAMEWORK20"/>


text:
Q: Subscript out of range error 9 I keep getting that error when trying to do this:
Dim MaxFileSize As Long
...
MaxFileSize = Application.WorksheetFunction.Max(Worksheets("'system32-he'").Range("B2:B24"))

I've tried googling it but nothing useful came up.

A: For reference see MSDN Subscript out of range error 9
In your case the Worksheets Collection can't return the correct sheet due to the extra single quotes around the sheet name. I believe that's what's caused the error.


text:
Q: how to find users who have a specific points and not subscribed a record in two tables I am trying to display the users only who have more of a particular number of points and also who does not have subscribed for that particular lesson in one of my promo competition code. I am just wondering if I should include the reward points in the membership table just to make it easier? I have read somewhere that I can do this with inner join but I don't have a matching column....
<?php
ob_start();
include_once __DIR__ . '/header2.php';
if (!isset($_SESSION['u_uid'])) {
    echo "<meta http-equiv='refresh' content='0;url=index.php?level3promo=notlogin'>";
    exit();
} else {
    if ($_SESSION['u_permission'] == 0) {
        echo "<meta http-equiv='refresh' content='0;url=header2.php?level3promo=nopermission'>";
        exit();
    } else {
        include_once __DIR__ . '/includes/dbh.php';

        $category = strip_tags($_POST['category']);
        $csrf = strip_tags($_POST['csrf']);

        if (!isset($_SESSION['key'])) {
            echo "<meta http-equiv='refresh' content='0;url=header2.php?level3promo=notset'>";
            exit();
        } else {

            if ($csrf !== $_SESSION['key']) {

                echo "<meta http-equiv='refresh' content='0;url=header2.php?level3promo=errorwithform'>";
                exit();
            } else {
                $sql = "SELECT * FROM level3promo WHERE id = ?;";

                $stmt = mysqli_stmt_init($conn);
                //Prepare the prepared statement
                if (!mysqli_stmt_prepare($stmt, $sql)) {
                    echo 'SQL statement failed';
                } else {
                    //Bind parameters to the placeholder
                    mysqli_stmt_bind_param($stmt, "i", $category);
                    //Run parameters inside database
                    mysqli_stmt_execute($stmt);
                    $result = mysqli_stmt_get_result($stmt);
                    $resultCheck = mysqli_num_rows($result);

                    if ($resultCheck < 1) {

                        echo "<meta http-equiv='refresh' content='0;url=header2.php?level3promo=nocategories
         exit();'>";
                    } else {
                        $row = mysqli_fetch_assoc($result);

                        echo $row['points'];
                        $sql2 = "SELECT * FROM rewards WHERE reward_points >= ?;";

                        $stmt = mysqli_stmt_init($conn);
                        //Prepare the prepared statement
                        if (!mysqli_stmt_prepare($stmt, $sql2)) {
                            echo 'SQL statement failed';
                        } else {
                            //Bind parameters to the placeholder
                            mysqli_stmt_bind_param($stmt, "i", $row['points']);
                            //Run parameters inside database
                            mysqli_stmt_execute($stmt);
                            $result2 = mysqli_stmt_get_result($stmt);
                            $resultCheck2 = mysqli_num_rows($result2);

                            if ($resultCheck2 < 1) {

                                echo "<meta http-equiv='refresh' content='0;url=header2.php?level3promo=lackofpoints'>";
                                exit();
                            } else {
                                $sql3 = "SELECT * FROM memberships WHERE subscriptionplan3 IS NULL;";

                                $stmt = mysqli_stmt_init($conn);
                                //Prepare the prepared statement
                                if (!mysqli_stmt_prepare($stmt, $sql3)) {
                                    echo 'SQL statement failed';
                                } else {
                                    //Bind parameters to the placeholder

                                    //Run parameters inside database
                                    mysqli_stmt_execute($stmt);
                                    $result3 = mysqli_stmt_get_result($stmt);
                                    $resultCheck3 = mysqli_num_rows($result3);

                                    echo $resultCheck3;

                                    if ($resultCheck3 < 1) {
                                        echo "<meta http-equiv='refresh' content='0;url=header2.php?level3promo=noqualifiedlevel3users'>";
                                        exit();
                                    } else {
                                        echo '

           Welcome to the Administrator\'s Level 3 Promo Qualified Users\' Section

';

                                        while ($row2 = mysqli_fetch_assoc($result2)) {
                                            while ($row3 = mysqli_fetch_assoc($result3)) {

                                                echo '

                      Result No:	', htmlspecialchars($rowCounter), '

                      ID:	', htmlspecialchars($row2['id']), '

                      Username:	', htmlspecialchars($row2['user_uid']), '

                      E-Mail:	', htmlspecialchars($row2['user_email']), '

';

                                            }

                                            echo '
';

                                            $rowCounter = 0;

                                            $rowCounter++;

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
ob_end_flush();
?>
```[enter image description here][1]

[enter image description here][2]

  [1]: https://i.stack.imgur.com/Kkh8S.png
  [2]: https://i.stack.imgur.com/Z8Knz.png

As can be seen, only musician888 should qualify because she has more than 5000 points but I am getting number 10 returned when echoing $resultCheck3


text:
Q: NodeJS and Javascript and HTML If I have some HTML code:

        <input type="text" name="user" placeholder="User Name" />
        <input type="password" name="password" placeholder="Password" />
        <button type="button">Login</button>

and when I click on the login button, it goes to the /api/users/ function in my nodejs file. How do I pass the strings stored in the username and password in the HTML code? Using sqlite3.
app.get('/api/users/', function (req, res) {
    let sql = 'SELECT * FROM users;';
    db.all(sql, [], (err, rows) => {
       var result = {};
       result["users"] = [];
       if (err) {
            result["error"] = err.message;
       }else {
            rows.forEach((row) => {
               result["users"].push(row);
           });
       }
       res.json(result);
    });
});

I want to execute some type of function, where if the username and password does not exist, than add it to the table "users" and redirect to another HTML file.

A: You should use a html form. See here. You're HTML is just sending an empty get request to your API, a form will send the data as well.


text:
Q: Won't exit Do loop Could someone tell me why this code never exits the Do loop?  I have managed to come up with a work around, but I'm puzzled as to why it doesn't work as is.  Same results running under Excel 2003 or 2010.
Public Declare Function EnableWindow Lib "user32.dll" (ByVal hWnd As Long, ByVal fEnable As Long) As Long
Public Declare Function IsWindowEnabled Lib "user32" (ByVal hWnd As Long) As Boolean

Sub test()
    Dim b As Boolean, h As Long

    h = FindWindow("xlmain", Application.Caption)

    Do
        EnableWindow h, True
        b = IsWindowEnabled(h)
    Loop Until b = True

End Sub

A: This is a very interesting article that I believe holds the key to your problem:
http://blogs.msdn.com/b/oldnewthing/archive/2004/12/22/329884.aspx
It basically says, that different coding languages represent bool in  different manners.
Behind the scenes, bool is actualy a numerical variable.
In vba the value of False is represented as (-1).
You can test this if you do:
Public sub TestBool
   dim b as boolean
   b = 1
   msgbox cint(b)  '->> the result will be -1, not 1
End sub

As you can see above, in the "b = 1" line vba does a secret conversion from 1 to -1.
However, my bet is that, when you declare IsWindowEnabled as boolean, because
this is external code, vba does not do the "heavy lifting" for you, and does
not do the above conversion (I guess IsWindowEnabled  is written in C, where their bool is represented as 1).
So, in the line :
Loop Until b = True

what actually happens is this :
Loop until 1 = -1

You can test this by adding before the "loop until" the following line:
msgbox clng(b) & " " & clng(True)

There are a few solutions:

*

*Declare IsWindowEnabled as Long  (I think this is the best solution):
Public Declare Function IsWindowEnabled Lib "user32" (ByVal hWnd As Long) As Long

*Declare b as variant (it works, as of now, not sure why) :
Dim b
-EDIT (30.3.15)-
This is a small sub to demonstrate the matter :
Private Declare Function IsWindowEnabled Lib "user32" (ByVal hWnd As Long) As Boolean
Private Sub Demo_API_true_in_VBA()
    Dim b As Boolean
    Dim b2 As Boolean

    b = 1
    Debug.Print "b = 1 :  " & "Clng(b)=" & CLng(b) & "  b=" & b
    'result- b = 1 :  Clng(b)=-1  b=True

    b = -1
    Debug.Print "b = -1:  " & "Clng(b)=" & CLng(b) & "  b=" & b
    'result- b = -1:  Clng(b)=-1  b=True

    Debug.Print

    b2 = IsWindowEnabled(Application.hWnd)
    Debug.Print "b2 = IsWindowEnabled() :  " & "Clng(b2)=" & CLng(b2) & "  b2=" & b2
    'result- b2 = IsWindowEnabled() :  Clng(b2)=1  b2=True
    ' NOTE HERE THAT b2 equels to 1, not to  -1 !!!

    Debug.Print

    Debug.Print "b = " & b & " ; " & "b2 = " & b2  ' both will **appear** as True
    'result- b = True ; b2 = True

    Debug.Print

    ' However, the result of the comparison here will be False !!!
    ' because vba actually does a numerical comparison, and 1 <> -1 .
    Debug.Print "Is b = b2 ?  " & CStr(b = b2)
    'result- Is b = b2 ?  False
End Sub


text:
Q: Facebook deep linking/App link not working on iOS I am trying to open my app from facebook when I tap on the post I made from my app.
I registered my app in developers.facebook.
I enabled the deep linking in my facebook app settings.
I have created the URL scheme for the app.
Note:My app is not published into app store. (Appple Appstore & Facebook app center)
I tried the following ways: However the post is made successful but facebook is not opening my app when I tap on that post.
One Way:
    // Create an object
    NSDictionary *properties = @{
                                 @"og:type": @"books.book",
                                 @"og:title": @"A Game of Thrones",
                                 @"og:description": @"In the frozen wastes to the north of Winterfell, sinister and supernatural forces are mustering.",
                                 @"books:isbn": @"0-553-57340-3",
                                 };
    FBSDKShareOpenGraphObject *object = [FBSDKShareOpenGraphObject objectWithProperties:properties];

    // Create an action
    FBSDKShareOpenGraphAction *action = [[FBSDKShareOpenGraphAction alloc] init];
    action.actionType = @"books.reads";
    [action setObject:object forKey:@"books:book"];

    // Create the content
    FBSDKShareOpenGraphContent *content = [[FBSDKShareOpenGraphContent alloc] init];
    content.action = action;
    content.previewPropertyName = @"books:book";

    FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];

    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fbauth2://"]]){
        dialog.mode = FBSDKShareDialogModeNative;
    }
    else {
        dialog.mode = FBSDKShareDialogModeBrowser; //or FBSDKShareDialogModeAutomatic
    }
    dialog.shareContent = content;
    dialog.delegate = self;
    dialog.fromViewController = self;
    [dialog show];

Another Way:
   FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];

    content.contentURL = [NSURL URLWithString:@"https://developers.facebook.com"];
    content.contentTitle=@"TestSHare";

    FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];

    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fbauth2://"]]){
        dialog.mode = FBSDKShareDialogModeNative;
    }
    else {
        dialog.mode = FBSDKShareDialogModeBrowser; //or FBSDKShareDialogModeAutomatic
    }
    dialog.shareContent = content;
    dialog.delegate = self;
    dialog.fromViewController = self;
    [dialog show];

Facebook is opening the app center page. But not my app.
Does the deeplink works only when app is pubished ?
Any reasons ?


text:
Q: Conditional formatting - coloring a row based on whether a cell within the row matches a cell outside the range
Wanting to apply conditional formatting to a range within a Google sheet, but the dependency is based on whether a cell within the range matches a cell outside the range.
    A     B     C
1 John
2 Bob
3 Phil
4
5
6  NZ    John  Rugby
7  Aust  John  Soccer
8  NZ    Bob   Tennis
9  NZ    John  Baseball
10 Aust  Phil  Tennis

Above is a simplified sheet. I have 3 unique names in A1, A2 & A3. Below that info is a chart of people from a work group.
I want to apply conditional formatting to the chart so that all the rows containing John are shaded red, rows containing Bob are shaded blue and rows containing Phil are shaded green.
Most tutorial videos are based on the assumption that the conditional formatting required would need a formula like =$B6="John" with a range of A6:C10 and shading it red.
I'm looking for something a bit more generic so the formula isn't listing specific names, rather a cell such as A1. So the formula might look like =$B6=A1 with a range of A6:C10 and a shade of red.
Help?

A: red color: =$B6=$A$1
blue color: =$B6=$A$2
green color: =$B6=$A$3


text:
Q: How significant is the material in drag force calculations? I went to Wolfram's "Drag Force Calculator" and received 4900 newtons for a cone that has a radius of 3 meters and a height of 3 meters, moving through air at a standard pressure, 15 celsius, at a speed of 20 m/s.
I looked up the cone drag coefficient and it was 0.50, and it does not appear that any further information is required. The material does make a difference, of course, but is the difference so miniscule that it's not worth adding?

A: As the material of which something is made of affects an object's mass, given two objects with different densities but with exactly the same surfaces (size, shape, texture), the more dense object will be subject to less drag deceleration. Surface shape and texture are important factors as well. This is, for example, why dimples on golf balls are highly regulated, why baseballs scuff with dirt are highly prized by pitchers (and tossed by umpires), and why airplane engineers are constantly toying with slight changes to the shape of a wing.
An exception to the above occurs above the Karman line. Shape and texture don't matter nearly as much in the very thin air of the upper atmosphere. Just about everything has a coefficient of drag of 2.2 (or higher) in the thermosphere.


text:
Q: Google Search Console API : HttpError 403 "Search Analytics load quota exceeded. Learn about usage limits:" I have a python script that extracts data from Google search console API.  The code worked for over 2 months and suddenly started getting this error "HttpError 403" Search Analytics load quota exceeded.
Learn about usage limits:".
I also checked our quotas and we're nowhere near being close to the max. For today, I show 20 requests against a 100,000,000 query max.
Has anyone else had this happen? Any ideas on where I can look for solutions?


text:
Q: how to exchange value between 2 inputs I have 2 input text and button.. I want to make exchange value between 2 inputs at the same time. here is my code.

$("button").on('click', function() {
    if (!($(this).hasClass("clicked"))) {
        $(this).addClass("clicked");
        $(".first").val($(".second").val());
        $(".second").val($(".first").val());
    } else {
        $(this).removeClass("clicked");
        $(".first").val($(".second").val());
        $(".second").val($(".first").val());
    }
})

  <input class="first" type="text" value>
  <input class="second" type="text" value>
  <button type="button">Exchange</button>

the first input works fine but the second not working.. I want the exchange happen at the same time.

A: You are overwriting one of the two before reading that other value. So you end up with twice the same value.
The traditional way is to use a temporary variable:

$("button").on('click', function() {
    $(this).toggleClass("clicked");
    var temp = $(".first").val();
    $(".first").val($(".second").val());
    $(".second").val(temp);
});

  <input class="first" type="text" value>
  <input class="second" type="text" value>
  <button type="button">Exchange</button>

At the same time note how you can shorten your code with the toggleClass method.
Alternative
Just to provide an alternative, you can do this without an explicit extra variable, using the ES6 destructuring assignment. For that to work, you need to have an assignable property for the input value. Of course, the DOM value property would just be that:

$("button").on('click', function() {
    $(this).toggleClass("clicked");
    [$(".first").get(0).value, $(".second").get(0).value] =
            [$(".second").val(), $(".first").val()];
});

  <input class="first" type="text" value>
  <input class="second" type="text" value>
  <button type="button">Exchange</button>

A: that because the value was changed . try to save old value on var

$("button").on('click', function() {
    var first = $(".first").val(),
        second = $(".second").val();

    if (!($(this).hasClass("clicked"))) {
        $(this).addClass("clicked");
        $(".first").val(second);
        $(".second").val(first);
    } else {
        $(this).removeClass("clicked");
        $(".first").val(second);
        $(".second").val(first);
    }
})

  <input class="first" type="text" value>
  <input class="second" type="text" value>
  <button type="button">Exchange</button>

A:

$("button").on('click', function() {
    var firstVal = $(".first").val()
    var secondVal = $(".second").val()
    if (!($(this).hasClass("clicked"))) {
        $(this).addClass("clicked");
        $(".first").val(secondVal);
        $(".second").val(firstVal);
    } else {
        $(this).removeClass("clicked");
        $(".first").val(secondVal);
        $(".second").val(firstVal);
    }
})

  <input class="first" type="text" value>
  <input class="second" type="text" value>
  <button type="button">Exchange</button>

You need to store the original values first, when you try to swap them without storing you forget that one of the values is overridden.

A: Use an intermediate temp variable to swap them.
$("button").on('click', function() {
    if (!($(this).hasClass("clicked"))) {
        $(this).addClass("clicked");
        var temp = $(".first").val();
        $(".first").val($(".second").val());
        $(".second").val(temp);
    } else {
        $(this).removeClass("clicked");
        var temp = $(".first").val();
        $(".first").val($(".second").val());
        $(".second").val(temp);
    }
});

Working DEMO


text:
Q: Modify values of a CSV based on previous values using awk I'd like to replace extraneous data values (any value >100,000) of a csv with the previous non-extraneous value.
    Input
    1/1/2017 01:00 56242
    1/1/2017 02:00 51214
    1/1/2017 03:00 101442
    1/1/2017 04:00 44242
    1/1/2017 05:00 990919
    1/1/2017 06:00 221512
    1/1/2017 07:00 52100

    Expected Output
    1/1/2017 01:00 56242
    1/1/2017 02:00 51214
    1/1/2017 03:00 51214
    1/1/2017 04:00 44242
    1/1/2017 05:00 44242
    1/1/2017 06:00 44242
    1/1/2017 07:00 52100

Can this be done using awk in a bash script?
Something like:
awk 'BEGIN{FS=OFS=" "} NF{print $1, $2, ($3 >=100000 "not sure") output.csv

Any help would be appreciated - I'm not very familiar with awk.

A: awk to the rescue!
awk '{if($NF>100000) $NF=p; else p=$NF}1' file


text:
Q: Lua 5.4.0/LuaRocks installation Hello,
I have been using Lua 5.1.2 since I begun learning Lua, and I wanted to upgrade to a more recent version, but there aren't any tutorial on how to do it, and I never did something similar. I downloaded the Lua 5.4.0 binaries, but I don't know how to install LuaRocks, which is really useful. (I don't know if this information is useful, but I'm using Windows 7)
Thank you.

A: so you got 5.4.0 installed?
https://github.com/luarocks/luarocks/wiki/Download
you probably want the 64-bit version of LuaRocks
if it complains, try the 32-bit instead.
just guessing, because most processors are 64-bit these days - unless it's something like a Raspberry Pi, but then you wouldn't be on Win7...


text:
Q: CSS hack not working anymore I used some CSS hacks in my code and I changed it but now it does not work anymore.
Here is the example
@-moz-document url-prefix() {
    h1:before {
    top: 102px;
}}

before I used this code (that worked):
@-moz-document url-prefix() {
div#hr-title {
    top: 102px;
}}

I dont understand. why does it not work anymore? Thanks in advance

A: It appears you're trying to use a Gecko-specific (as in Mozilla Firefox) CSS property.  There's no reason it shouldn't work in Firefox, and without any further context or example we can only take wild guesses as to why it doesn't work in your setup.  Are you trying to use it in a non-Firefox browser?
You may also want to re-evaluate this hack and try to write your CSS such that you don't need to target specific browsers with disparate styles.


text:
Q: What is the limit for the following sequence of products? $\lim\limits_{n \to \infty}$ $\displaystyle\frac{q \cdot n +1}{q \cdot n} \cdot \frac{q \cdot n +p+1}{q \cdot n +p} \cdot \ldots \cdot \frac{q \cdot n +n \cdot p +1}{q \cdot n + n \cdot p}$ , for $q > 0, p \geq 2$ .
Thank a lot !

A: Introducing the parameters $a=q/p$ and $b=1/p$, the $n$th ratio is
$$
R_n=\prod_{k=0}^n\frac{an+b+k}{an+k}=\frac{\Gamma(an+b+n+1)\cdot\Gamma(an)}{\Gamma(an+b)\cdot\Gamma(an+n+1)}.
$$
One knows that $\Gamma(x+b)\sim x^b\cdot\Gamma(x)$ when $x\to+\infty$. Applying this twice, one gets
$$
\frac{\Gamma(an+b+n+1)}{\Gamma(an+n+1)}\sim (an+n+1)^b\sim (a+1)^bn^b,
\qquad
\frac{\Gamma(an+b)}{\Gamma(an)}\sim a^bn^b,
$$
hence
$$
\lim\limits_{n\to\infty}R_n=\left(\frac{a+1}a\right)^b=\left(\frac{q+p}q\right)^{1/p}.
$$


text:
Q: Resistors in parallel - Written description of a circuit - drawing needed I can't visualise what this circuit looks like from the description

Three identical resistors are connected across a potential difference V so that one of them is in parallel with the other two which are connected in series.

I am guessing it looks like this . . . . (there is no diagram given in the question)

Would I be right in assuming this?
The rest of the question depends getting this part right.
The rest of the question is as follows . ...

The power dissipated through the first one , compared to the power dissipated by each of the other two , is approximately..
A the same,
B half as much,
C twice as much,
D four times as much,

The answer is apparently D, which makes me think my drawing can't be correct.
Any help?

A: Yes, your drawing correctly illustrates what the question describes.
Since the question later refers to the first one and the other two, it is reasonable to assume the author is referring to the resistor with $V$ across it and the two in series, respectively.
In case it still isn't clear, the power dissipated in any one of those resistors is given by
$$P=I^2R,$$
where $R$ is the same for the all resistors but $I$ is different for the two "branches".  Once you find the lone resistor has twice the current going through it, you can see why it has four times the power dissipation.


text:
Q: calculate the modulus of a fraction with big numbers I have two big numbers (<10^9) n and m. I have to calculate [(n-1+m)!]/[(n-1)!*m!]
if the answer is too big I have to get the modulus from (10^9+7). (ex : n%mod if n is too large that mod).
 int mod = 1000000000+7;

I calculated it like below. (I  calculated the upper half and bottom half separately)
    long up=1;
    for (long i = a+b-1; i>=Math.max(a, b); i--) {
        up*=i%mod;
    }
    up=up%mod;
    long down=1;
    for (long i = Math.min(a, b); i>0; i--) {
        down*=i%mod;
    }

then print the answer as
System.out.println((up%mod/down%mod)%mod);

Is this approach correct. Will  it gives the correct out put.
I know (a*b*c)%d == [(a%d)*(b%d)*(c%d)]%d (correct me if i'm wrong)
So is there any way like that to calculate [a/b]%d ?

A: (a/b) % c != ((a%c) / (b%c) % c)

Instead use recursive formula of binomial coefficient to calculate the modulus
(n, k) = (n - 1, k - 1) + (n - 1, k)

In your case it will be
(n - 1 + m, m) % MOD = ((n - 2 + m, m - 1) % MOD + (n - 2 + m, m) % MOD) % MOD

use above recursion to get the result.


text:
Q: How to trigger window.onbeforeunload in jasmine test Currently, I have created a directive attached to a form. Anytime the form is dirty, I have a confirmation modal by window.onbeforeunload pop up when trying to leave. Right now I'm trying to write a jasmine test to make sure window.onbeforeunload gets called upon refresh/url change.
var app = angular.directive('app');

app.directive('dialog',[$window, function() {
    return {
        restrict: 'A',
        require: 'form',
        link: function(scope, element, attrs, formCtrl) {
            $window.onbeforeunload = function () {
                if(formCtrl.$dirty) {
                    return 'Are you sure you want to leave this form';
                }
            };
        }
    };
}]);

Part of the Jasmine Spec
beforeEach(inject(function(_$rootScope_,_$state_,_$window_) {
    $rootScope = _$rootScope_;
    $state = _$state_;
    $window = _$window_;

    spyOn($window, 'onbeforeunload')
}));

describe('Listen for window prompt', function () {
    it('should be called on url/refresh change', function () {
        window.location.reload();
        expect($window.onbeforeunload).toHaveBeenCalled();
    });
});

A: It sounds like you are trying to test if the method does what it is supposed to do which is fire when the url has changed/refreshed. You should probably be testing the code that happens inside this event. You can trigger this event in your jasmine script by using the jquery trigger command on the window object:
$(window).trigger('onbeforeunload');

A: In a unit test it's enough just to test your implementation of the 'onbeforeunload' event. Otherwise you can write e2e test with Protractor.
You can do your test like this:
describe('page leave handler', function () {
  it('should handle page leave', function () {
    // given
    var element = compileDirective();
    var formCtrl = element.controller('ngForm');
    formCtrl.$dirty = true;

    // when
    var result = $window.onbeforeunload();

    // then
    expect(result).toBe('Are you sure..');
  });
});


text:
Q: How to do y-split for tree nodes in pstree? As I need to draw lines between edges, I'd like to have y-splits when there are multiple child nodes. At the moment I realized it through a hidden node and nodesep=0. Unfortunately, I don't know of any way to reset nodesep for the direct parent and children of the split node and therefore the spacings are wrong (see screenshot).

\documentclass{minimal}

\usepackage{pstricks,auto-pst-pdf}
\usepackage{pst-tree}

\newcommand{\terminal}[2][]{\TR[#1]{\boldsymbol{#2}}}
\newcommand{\nonterminal}[2][]{\TR[#1]{#2}}
\newcommand{\emptyword}{\TR{\epsilon}}
\newcommand{\derivationtree}[1]
{
    \begin{postscript}
        $   \pstree[treemode=R,nodesep=2pt,treesep=0.4cm,levelsep=1.5cm]{\TR{S}}{#1} $
    \end{postscript}
}

\begin{document}

\derivationtree{
  \pstree[nodesep=0]{\nonterminal{N_1}}
  {
    \pstree{\Tr{}}
    {
        \pstree[nodesep=2pt]{\nonterminal{N_1}}
        {
            \terminal{[}
        }
        \terminal{[}
    }
  }
}

\end{document}

In the pst-tree manual, there is an example where \psedge is redefined as \ncdiag. But I couldn't really figure out how to do it and how to restrict the effects just for one case.

A: Usually one redefines \psedge but it works with any other definition.
\documentclass{minimal}
\usepackage{pstricks,auto-pst-pdf}
\usepackage{pst-tree}
\newcommand\terminal[2][]{\TR[#1]{\boldsymbol{#2}}}
\newcommand\nonterminal[2][]{\TR[#1]{#2}}
\newcommand\emptyword{\TR{\epsilon}}

\def\psEdge#1#2{\ncdiagg[armA=1cm,angleA=0,angleB=180]{#1}{#2}}

\newcommand\derivationtree[1]{
    \begin{postscript}
        $   \pstree[treemode=R,nodesep=2pt,treesep=0.4cm,levelsep=1.5cm]{\TR{S}}{#1} $
    \end{postscript}}

\begin{document}

\derivationtree{%
  \pstree[thislevelsep=2.75cm]{\nonterminal{N_1}}{
        \pstree{\nonterminal[edge=\psEdge]{N_1}}{ \terminal{[} }
        \terminal[edge=\psEdge]{[}
  }
}
\end{document}


text:
Q: Target Display Mode: how to automate and persist on closing laptop I have connected my MacBook (Early 2013, OS X 10.9.4) with my iMac (Late 2012, 27 inch, OS X 10.9.4) via a ThunderBolt cable in order to use the iMac screen with my MacBook.
I have two related questions:
(i) Is there a way to automatically mirror the screen without needing to press Command-F2?
(ii) How can I allow screen mirroring to persist when I close my MacBook?


text:
Q: changing the footer font size to 12 pt and footer margin to .8 in I need to change the footer font size to 12pt and the footer margin to 0.8 inches.
\documentclass[]{report}

\usepackage[md]{titlesec} %required for section titles
\usepackage{subfiles}
\usepackage{algorithm}
\usepackage{algpseudocode}

\usepackage[titles]{tocloft}
\usepackage[tocindentauto]{tocstyle}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{gensymb}
\usepackage{float}
\usepackage{floatpag}
\floatpagestyle{plain}
\usepackage[verbose]{cite}
\usepackage{cleveref}
\usepackage{url}
\usepackage{breakurl}

\usepackage{setspace}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}%margins
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@chapter}{\addtocontents{lof}{\protect\addvspace{10\p@}}}{}{}{}
\makeatother
\usepackage{pgfplots}
\titleformat{\chapter}[display]{\centering\normalfont\large}{CHAPTER \arabic{chapter}}{0pt}{}{}
\titleformat*{\section}{\centering\bfseries\large}
\titleformat*{\subsection}{\bfseries\large}
\titleformat*{\subsubsection}{\normalfont\large}%
\titlespacing*{\section}{0pt}{1\baselineskip}{0pt}
\titlespacing*{\subsection}{0pt}{0pt}{0pt}
\titlespacing*{\subsubsection}{0pt}{2\baselineskip}{0pt}
\titlespacing{\paragraph}{0pt}{0pt}{1em}
\renewcommand{\cftpartleader}{\cftdotfill{\cftdotsep}}
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}}

\setcounter{tocdepth}{3}
\setcounter{secnumdepth}{3}
\renewcommand{\cftpartfont}{\normalsize\normalfont}
\renewcommand{\cftchapfont}{\normalsize\normalfont}
\renewcommand{\cftpartpagefont}{\normalsize\normalfont}
\renewcommand{\cftchappagefont}{\normalsize\normalfont}

\cftsetindents{chapter}{.25in}{.25in}%
\cftsetindents{section}{.5in}{.25in}
\cftsetindents{subsection}{.75in}{.5in}
\cftsetindents{subsubsection}{1in}{.5in}

\renewcommand\cftsecafterpnum{\vskip-.5\baselineskip}
\renewcommand\cftsubsecafterpnum{\vskip-.5\baselineskip}
\renewcommand\cftsubsubsecafterpnum{\vskip-.5\baselineskip}
\doublespacing %double space
\raggedbottom

\begin{document}

\thispagestyle{empty}
\begin{center}
\large

\vspace*{2in}
Ic\\
\vspace{2in}
By\\
J
\vspace{1in}
\end{center}

\renewcommand{\thepage}{\roman{page}}% lowercase roman numerals for pre-document stuff
\begin{center}
\vspace*{2in}
ID\\
\vspace{1in}
By\\~\\
J\\
\vspace*{1in}
A Thesis Submitted to the Faculty of the University of  in Partial Fulfillment of the Requirements for the Degree of Master of Science: Computer Science\\~\\~\\~\\
U\\
CUU\\~\\
December 2017\
\end{center}
\chapter*{}
\begin{center}
\vfill
Copyright \copyright\ 2017

\bigskip

By J

\bigskip

All Rights Reserved
\vfill
\end{center}
\chapter*{ABSTRACT}
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}ABSTRACT}
\large
\paragraph{ }

\chapter*{ACKNOWLEDGMENTS}
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}ACKNOWLEDGMENTS}
%\subfile{sections/Acknowledge}

\chapter*{DEDICATION}
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}DEDICATION}
%\subfile{sections/Dedication}

\vspace{-6\baselineskip}
\renewcommand{\contentsname}{TABLE OF CONTENTS}
\tableofcontents

\vspace{-4\baselineskip}
\renewcommand{\listfigurename}{LIST OF FIGURES}
\listoffigures
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}LIST OF FIGURES}

\chapter*{LIST OF SYMBOLS}
%\vspace{-6\baselineskip}
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}LIST OF SYMBOLS}
%\subfile{sections/Los}

\chapter*{LIST OF ABBREVIATIONS}
%\vspace{-6\baselineskip}
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}LIST OF ABBREVIATIONS}
%\subfile{sections/Loa}

\cleardoublepage
\cleardoublepage
\large
\clearpage
\setcounter{page}{1}
\renewcommand{\thepage}{\arabic{page}}

\chapter{INTRODUCTION}
\label{Intro}
\section{Background}
\label{Backgrnd}
%\subfile{Sections/Background}

\section{Questions and Limitations}
\label{Quest}
%\subfile{Sections/quest}

\chapter{RELATED WORKS}
\label{RelWorks}
%\subfile{Sections/Relworks}

\chapter{METHODOLOGY}
\label{Method}
%\subfile{Sections/Methodology}

\chapter{RESULTS}
\label{Result}
%\subfile{Sections/Result}

\chapter{CONCLUSION}
\label{Conclusion}
%\subfile{Sections/conclusion}

\cleardoublepage
\addcontentsline{toc}{part}{\vspace{-.5\baselineskip}REFERENCES}
\cleardoublepage
\renewcommand\bibname{REFERENCES}
\setstretch{1}

\makeatletter
\addtocontents{toc}{\def\string\@dotsep{10000}}
\makeatother
\addtocontents{toc}{%
    \protect\contentsline{part}{APPENDIX }{}}

\appendix
\titleformat{\chapter}[display]{\centering\normalfont\large}{APPENDIX  \Alph{chapter}}{0pt}{}{}
\makeatletter
\addtocontents{toc}{\def\string\@dotsep{100}}
\makeatother
\chapter{Equations }
\label{eqn}

\clearpage
\chapter*{VITA}
\addcontentsline{toc}{part}{VITA}
\large
\end{document}

I can't figure out where I need to change the code to make it to be 0.8 inches and size 12 pt font.
Thank You