text:
Q: Vue, change native event not working, input native does I have a question and maybe a Vue bugg.
I have a custom component that needs a @change.native event. But it does not trigger anything and I could not find anything about this issue myself.
So i tried some different stuff and like @click.native and @input.native does work. Even tho @input.native works and do the trick i want to, i still want to know why the change event does not work.
Anybody? Else I should report this.
Vue version: 2.5.2
<custom-input type="search"
              placeholder="search"
              v-model="search"
              @input.native="change" />

A: If the <input /> inside the custom component is a child element of another element, then the event listener bound by the .native modifier will not be reached, since it is listening to the event of a different element.
custom-input.vue:
<template>
    <div>
        <input :value="someValue" />
    </div>
</template>

<script>
export default {
  props: ['value']
}
</script>

so if you have this scenario, then the @change.native will be bound on the <div> (the wrapper).
(sadly) You need to manually propagate the event manually.


text:
Q: Match multiple pattern from a file and copy matching files in a dir to new dir How to copy files from dir1 to dir2, matching pattern in a file1?
for example:
file1:
T0_1
T0_2
T0_3

Dir1:
T0_1_xxx_xx
E1_1_xxx_xx
T0_2_xxx_xx
E1_2_xxx_xx
E1_3_xxx_xx
T0_2_xxx_xx

I want to copy T0_1_xxx_xx, T0_2_xxx_xx, T0_3_xxx_xx to new dir2. There are 124 names in file1, and 372 files in dir1.

A: Just iterate over the file:
while read prefix; do
    cp -- "$prefix"* new_dir_2/
done < file1

This will read each line of your file, saving it as $prefix and then will copy all files whose name starts with $prefix to new_dir_2. The -- after the cp is to tell cp that there are no more options and this ensures it will also work in the unlikely case where you have a file name starting with a -.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove key from array if the element starts with certain value How can I remove element that starts with TOR example key [27].
Array
(
    [1] => memory_target
    [2] => vif_2_rx
    [3] => vif_2_tx
    [4] => memory
    [5] => vbd_xvda_read
    [6] => vbd_xvda_write
    [7] => vbd_xvdd_read
    [8] => vbd_xvdd_write
    [9] => vif_1_rx
    [10] => vif_1_tx
    [11] => vif_0_rx
    [12] => vif_0_tx
    [13] => cpu0
    [27] =>  TOR-SRV65
)

This is what I have tried so far.
if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

But haven't been able to get it to work!

A: You can simply array_filter() the elements out which have TOR at the start like this:
$messages = array_filter($messages, function($v){
    return !(substr(trim($v), 0, 3) === "TOR");
});

Case insensitive version:
$messages = array_filter($messages, function($v){
    return !(strtoupper(substr(trim($v), 0, 3)) === "TOR");
});

EDIT:
Even simpler with preg_grep() (Remove the modifier i if you want it case sensitive):
$messages = preg_grep ("/[^\bTOR]/i", array_map("trim", $messages));

A: Try:
$array = array(
    'memory_target',
    'vif_2_rx',
    'TOR-SRV65'
);

foreach ($array as $key => $value) {
    if (strtolower(substr($value, 0, 3)) == 'tor') {
        unset($array[$key]);
    }
}

print_r($array); // Output => Array ( [0] => memory_target [1] => vif_2_rx )

A: I am using this function to delete a key from array
function removeValueFromArray($array, $key, $value){
   foreach($array as $subKey => $subArray){
      if($subArray[$key] == $value){
      unset($array[$subKey]);
      }
   }
   return $array;
}

This function remove the key from array based on certain value and return final array


text:
Q: Create React App Server Side Rendering SCSS Webpack Error I needed to add the blogs in our web app and to make our app configure for SEO therefore I'm trying to add SSR support in my current create react app. I'm trying react hydrate and react render method. I'm getting following error while building the app.
ERROR in ./src/assets/scss/theme.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/assets/scss/theme.scss)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve '../../../../fonts/materialdesignicons-webfont.eot?v=5.0.45' in '/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/src/assets/scss'
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:209:21
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:27:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:67:43
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:16:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:16:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:16:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js:27:15
    at /home/muhammadwaqastekrowe/dev/tekrowe/speetar-react-frontend/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:85:15
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
 @ ./src/assets/scss/theme.scss 2:12-140 9:17-24 13:15-22
 @ ./src/App.js
 @ ./server/index.js

Webpack configuration
 {
   test: /\.s[ac]ss$/i,
   use: [
      // Creates `style` nodes from JS strings
      "style-loader",
      // Translates CSS into CommonJS
      "css-loader",
      // Compiles Sass to CSS
      "sass-loader",
   ],
 }

Dev dependencies
"devDependencies": {
    "@babel/core": "^7.10.4",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/preset-env": "^7.10.4",
    "@babel/preset-react": "^7.10.4",
    "babel-loader": "^8.1.0",
    "css-loader": "^5.2.2",
    "cssnano": "^5.0.1",
    "node-sass": "^4.14.1",
    "nodemon": "^2.0.4",
    "npm-run-all": "^4.1.5",
    "postcss-loader": "^5.2.0",
    "prettier": "2.2.1",
    "sass": "^1.32.8",
    "sass-loader": "^7.3.1",
    "style-loader": "^2.0.0",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.12",
    "webpack-node-externals": "^1.7.2"
  }

A: use file-loader and resolve-url-loader for load font file in scss
{
    test: /\.(woff2?|ttf|otf|eot|svg)$/,
    exclude: /node_modules/,
    loader: 'file-loader',
    options: {
        name: '[path][name].[ext]'
    }
},
{
    test: /\.scss$/,
    use: ExtractTextPlugin.extract({
         fallback: 'style-loader',
         use: ['css-loader', 'resolve-url-loader', 'sass-loader?sourceMap']
    })
}

A: See production build approach for SSR that supports sass in this thread. Note that style-loader is not the preferred method for SSR builds.


text:
Q: SSMS v18.10 - Open a script file with existing connection and database In previous versions of SSMS, if I had a database selected in Object Explorer and then opened a script file through File → Recent Files, SSMS automatically used my existing connection and database. In v18.10 (build 15.0.18390.0), SSMS instead prompts me for a connection and then defaults to the master database.
Is there a setting somewhere that will make v18.10 (build 15.0.18390.0) behave like previous versions?

A: I uninstalled a previous version (SSMS 2016) and repaired the 18.10 install and it's behaving as normal now.


text:
Q: Question related to electronic thermal conductivity I've been presented with the following question:

The atomic weight is of a monovalent metal is 197u and it's density is $19.32 g cm^-3$.
Calculate the density of conduction electrons. Given that the Fermi energy of the
metal is 5.53eV calculate the electronic thermal conductivity at 300 K.

Now, I know I can calculate density of conduction electrons, n, by -
$n = NZ\rho/m $
Where N is Avogadro's Constant, m is the atomic mass, $\rho$ is the density and Z is valency of atom.
The problem I face is in tackling the next part; I know I can use this method to calculate the electronic thermal conductivity-
$K_e= 4 n k^2_BT\tau_F/3m$
Where $K_e$ is electronic thermal conductivity and $\tau_F$ if Fermi Relaxation time.
I can't find any relation from which I can calculate $\tau_F$ from Fermi Energy or any other method to solve this problem.
Thanks.


text:
Q: Unable to load dynamic library in Codeigniter I have uploaded a CodeIgniter application on server and getting this error, application is working perfectly in local server

After searching around stackoverflow I found that It may be an extension issue.
But don't know how to solve this extension issue on live server ?

A: In index.php file of CI I have changed environment from development to production
$_SERVER['CI_ENV'] = 'production'; // By Adding this line
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');


text:
Q: How to bind a property to a static enum value? I have an enum with various values:
public enum UserStatus
{
    Active = 1,
    Inactive = 2,
    Invalid = 3,
    Blocked = 4,
    Pending = 5
}

And on my UI I'm assigning a color for each value of the enum, and since it's used in various windows, I've created a Converter for it.
Now I want to display a legend of some of the enum values, is there anyway I can bind a static enum value to a property in a WPF control?
<!-- I want ? to be a fixed enum value -->
<TextBlock Text="{Binding ?, Converter={StaticResource=UserStatusToString}}" Foreground={Binding ?, Converter={StaticResource=UserStatusToBrush}} />

I don't have a data object at this point and I only want to somehow pick the color value from the converter instead of hard-typing it in the legend. Is there anyway I can do this?

A: I think this Stack Overflow post might be your answer. You'll have to have your enum value listed in your xaml's resources section and use its key as StaticResource key.

A: Use ObjectDataProvider to get all enum values and then show them in ListBox with ItemTemplate
<Window xmlns:local="clr-namespace:FooApp" ... >
    <Window.Resources>
        <ObjectDataProvider x:Key="FooEnumValues"
            MethodName="GetValues"
            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:Foo" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource FooEnumValues}}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock
    Text="{Binding Converter={StaticResource=UserStatusToString}}"
    Foreground="{Binding Converter={StaticResource=UserStatusToBrush}}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


text:
Q: When generalizing from discrete (but infinite) eigenstates to continuous eigenstates, Why do we change the definition? The propagator function for discrete eigenstates is
$$u(t)=\sum_{n=1}^{\infty}|E_n\rangle\langle E_n|e^{-iE_nt/ \hbar } \tag{1}\ .$$
But when we have continuous eigenstates, (like for the case of free particle) then:
$$u(t)=\int_{- \infty}^{\infty} |E\rangle\langle E|e^{-iEt/\hbar}\,dE \tag{2}$$
My question is, how do we translate from the discrete eigenstates to continuous eigenstates? And what is the proof that (2) is the generalization of (1)?
This doubt also arose while defining the inner product for 2 continuous vectors. We said that for continuous states, the inner product will tend towards infinity and thus we introduce a normalizing factor. But, shouldn't this be the case when the sum is of discrete eigenstates but infinite?
For discrete inner products:
$$\langle f,g\rangle=\sum_i f_i(x) g_i(x)$$
and for continuous inner product, magically:
$$\langle f,g\rangle=\int f(x)^*g(x)\,dx.$$

A: The correct formulation of the result is called spectral theorem. It encompasses all type of spectra for self-adjoint operators, and thus both (1) and (2).
Given a self adjoint operator $A$ with only discrete spectrum (you have such situations for compact operators, and operators with compact resolvent) the spectral theorem has a nice and simple form:
$$A=\sum_{i}\lambda_i P_i\; ,$$
where the sum ranges over all possible eigenvalues $\lambda_i$ and $P_i$ is the projection on the eigensubspace corresponding to $\lambda_i$ (that if the eigenvalue has multiplicity one has the form $\lvert \psi_i\rangle\langle \psi_i\rvert$ where $\psi_i$ is the normalized eigenvector). The spectral theorem gives also the so-called functional calculus (I will not be completely precise mathematically but to give the idea will be enough): given a suitable function $f:\mathbb{R}\to \mathbb{C}$, the operator $f(A)$ is defined by
$$f(A)=\sum_i f(\lambda_i)P_i\; .$$
The particular case of $e^{-itA}$ is the one that gives you quantum evolution.
Now if $B$ is an operator with general spectrum (i.e. a discrete part and a continuum one) the theorem still holds, but instead of having a simple discrete family of projections $P_i$ we have what is called a spectral family $\{P_\Omega\}_{\Omega\in \{X, X\subseteq \mathbb{R}\}}$ of projections. This family is uncountable, so you cannot take the sum, but it defines a projection valued measure $dP_\lambda$ (a function from sets to self-adjoint projections that satisfies the axioms of a measure) and it is possible to integrate functions with respect to it. So the spectral theorem for (measurable) functions $f$ of $B$ becomes:
$$B=\int_{\mathbb{R}}\lambda dP_\lambda\; ,$$
$$f(B)=\int_{\mathbb{R}}f(\lambda) dP_\lambda\; .$$
Or, in the case of the evolution operator $e^{-itB}$ applied to $u\in \mathscr{H}$ (the Hilbert space):
$$u(t)=e^{-itB}u=\int_{\mathbb{R}}e^{-it\lambda} dP_\lambda u \; .$$
Observe that if $B$ has only discrete spectrum, the corresponding measure is just the sum of delta measures pointed at each discrete eigenvalue $\lambda_i$, so it can be written $dP_\lambda = \sum_i \delta(\lambda-\lambda_i)P_\lambda d\lambda$. Therefore the discrete spectrum is just a special case of the spectral theorem.
Anyways, what you are writing is an operator on the right hand side, and a function on the left hand side, so it is not correct as written ;-)

A: You do not obtain the rules for the infinite-dimensional case by "proving" them from the finite-dimensional rules. Rather, you know that you need to have a Hilbert space, which is a complex vector space with an inner product, essentially.
If you now search for infinite-dimensional Hilbert spaces that could possibly be used in quantum mechanics, you find that all separable Hilbert spaces are isomorphic to the complex valued square-integrable functions $L^2(\mathbb{R})$ with inner product
$$ (f,g) = \int_\mathbb{R} f^*g$$
Now, you implement quantum mechanics by choosing a self-adjoint Hamiltonian operator $H$ on the space, and just impose the Schrödinger equation
$$ Hf = \mathrm{i}\hbar \partial_t f$$
Now, as yuggib write, the spectral theorem gives you that the self-adjoint Hamiltonian has an orthonormal eigenbasis, and the form of the propagator follows naturally.


text:
Q: drawInRect not preserving transform     UIGraphicsBeginImageContext(backgroundImageView.frame.size);

    UIImageView *image1 = backgroundImageView;
    UIImageView *image2 = boat;

    // Draw image1
    [image1.image drawInRect:CGRectMake(0, 0, image1.image.size.width, image1.image.size.height)];

    // Draw image2
    [image2.image drawInRect:CGRectMake(boat.center.x, boat.center.y, boat.image.size.width, boat.image.size.height)];

    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();

When resultingImage is displayed the transform angle value for image2 is not preserved after I set it equal to the boat UIImageView.  I thought that when I set image2 = boat that the transform value of boat would carry over to image2.
I suspect it relates to the fact that I am I am working with UIImageView instead of UIVIew.    I have tried many different things but have been unable to resolve this issue.
Any help would be appreciated.
Thanks.

A: When you draw an image into a graphics context, it uses the context's transformation matrix, which is distinct from any transformation applied to a view. So the transformation on image2 (a UIImageView presumably) is completely irrelevant to direct image drawing.
You can either specify a new transformation with the various CGContext and CGAffineTransform functions in Quartz, or you can directly apply a copy of the UIImageView 's transformation like so:
CGContextConcatCTM(UIGraphicsGetCurrentContext(), someView.transform);
[someView.image drawInRect: CGRectMake(...)];


text:
Q: Javascript: Submit form with arrow keys I have four forms on a page, and I want any one of them submitted depending on which arrow key is pressed.
<form  name='go_north' action='' method='post'>
<input type='hidden' name='direction' value='north' />
</form>

<form  name='go_east' action='' method='post'>
<input type='hidden' name='direction' value='east' />
</form>

etc...

I can see how to do it with text inputs if they have focus, but I can't figure out how to do it with hidden inputs. Also, it only needs to work in Chrome. Any advice would be greatly appreciated.

A: Add a document.addEventListener("keydown", function(){}) which will listen for the keypresses, then determine the keycode and map them to submit the form based on the keycode.
Submitting the forms is as easy as finding the form and calling .submit() on it!

document.addEventListener("keydown", function(event) {
  var code;
  if (event.key !== undefined) {
    code = event.key;
  } else if (event.keyIdentifier !== undefined) {
    code = event.keyIdentifier;
  } else if (event.keyCode !== undefined) {
    code = event.keyCode;
  }
  console.log(code);
  handleArrow(code);
});

function handleArrow(code) {
  switch (code) {
    case 'ArrowLeft':
      submitForm('go_west');
      break;
    case 'ArrowRight':
      submitForm('go_east');
      break;
    case 'ArrowDown':
      submitForm('go_south');
      break;
    case 'ArrowUp':
      submitForm('go_north');
      break;
  }
}

function submitForm(id) {
  $("#" + id).submit();
}

<form id="go_north">
  north
  <input id="north" type="text" name="north" value="north">
</form>
<form id="go_east">
  east
  <input id="east" type="text" name="east" value="east">
</form>
<form id="go_south">
  south
  <input id="south" type="text" name="south" value="south">
</form>
<form id="go_west">
  west
  <input id="west" type="text" name="west" value="west">
</form>


text:
Q: How to give an unique ID for each file selected when uploading multiple files Im making a file uploader and I need to get the ID for each image selected in order to delete them later, any idea?
Im trying to use "imgn" but it's not working.
var imgn=0;

function readURL(file) {
        var reader = new FileReader();
        var image  = new Image();
        reader.readAsDataURL(file);

        imgn++;

        reader.onload = function (e) {

            image.src    = e.target.result;
            image.onload = function() {

            $('#imgpre').append('
<input type="button" value="Remove" onclick="removeimg('+imgn+');">
');

            }
            image.onerror= function() {
                alert('Invalid file type: '+ file.type);
            }
        }
}

$("#imgsel").change(function(e){
    if(this.disabled) return alert('File upload not supported!');
    var F = this.files;
    if(F && F[0]) for(var i=0; i<F.length; i++) readURL( F[i] );
});

function removeimg(rnum) {
    jQuery('#imgnum'+rnum).remove();
}

http://jsfiddle.net/8j7gnqve/

A: You can generate a random number for each file using mt_rand() and then make a hash of it using md5() or sha1(). See this to know how to convert number to string.
Another solution (may be slower and more complicated)
Count every file you receive and create a hash of the number. Example: first file ever uploaded will be number 1 and will have the corresponding hash, the second'll be number 2, etc. This will help if you want to be sure the numbers are unique, but you'll have to store them somehow.

A: Increment imgn in the FileReader load handler. FileReader.readAsDataURL is asynchronous and the onload function will fire long after the loop finishes, to be safe put it in the image load callback.
    reader.onload = function (e) {
        image.src    = e.target.result;
        image.onload = function() {
            imgn++;
            $('#imgpre').append('
<input type="button" value="Remove" onclick="removeimg('+imgn+');">
');
        }
        image.onerror= function() {
            alert('Invalid file type: '+ file.type);
        }
    }

A:

const [uploadedFiles,setUploadedFiles]=useState([])
<input
  className="upload-image-input-body"
  type="file"
  multiple="true"
  title=""
  onChange={(e) => {
    const file = e.target.files;
    let files = [];
    for (const k of file) {
      files = [
        ...files,
        {
          data: k,
          id: new Date().getTime().toString() + Math.floor(Math.random() * 1000000),
        },
      ];
    }
    setUploadedFiles((uploadedFiles) =>[...uploadedFiles,...files]);
  }}
/>

A: That's the answer: put the imgn++ inside each function
    reader.onload = function (e) {

        image.src    = e.target.result;
        image.onload = function() {

        $( "#imgpre" ).each(function( index ) {
            imgn++;
        });

        $('#imgpre').append('
<input type="button" value="Remove" onclick="removeimg('+imgn+');">
');

        }
        image.onerror= function() {
            alert('Invalid file type: '+ file.type);
        }
    }

}


text:
Q: Alt Tab Win32 Message Queue and SetWinEventHook I am trying to detect Alt+Tab in a Win Event Hook using SetWinEventHook. However the callback for the hook is never triggering for Alt+Tab, even though I have a message pump (I am on windows 10)
I came across this idea to process Alt+Tab like this when I stumbled across this series of posts:
Alt Tab overlay Win32 identificator
SetWinEventHook does not catch any event
Which describe using a WinEventHook to get the Alt+Tab message (which I don't know if it is even efficient or not to use in the modern day). I found an article by Raymond Chen detailing it (however it doesn't work anymore and I don't know why, but it should.)
How do I get the Alt+Tab message in my event callback?
EDIT: Here is my example to mimic what I was doing on a large scale (the small program doesn't work) and to remove doubt from the comments. Here is the entire program plus compile script that shows what I am trying to do but doesn't work at all (what am I doing wrong? the above Raymond Chen Program seems to be effected by it). I am on Windows 10
(Edit, I found EVENT_MIN and EVENT_MAX give me events in the hook, but never the EVENT_SYSTEM_SWITCHSTART and EVENT_SYSTEM_SWITCHEND events)
Compile.bat:
@echo off
if not defined DevEnvDir (
    call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
)

if "%Platform%" neq "x64" (
    echo ERROR: Platform is not "x64" - previous bat call failed.
    exit /b 1
)

set FILES=main.cpp

set RELEASEFLAGS=/O2 /DMAINDEBUG=0
set DEBUGFLAGS=/Zi /DMAINDEBUG=1

set LIBS=kernel32.lib user32.lib gdi32.lib Winmm.lib

::Release
cl /nologo /W3 /GS- /Gs999999 %RELEASEFLAGS% %FILES% /Fe: AnnoyingSound.exe %LIBS% /link /incremental:no /opt:icf /opt:ref /subsystem:windows

::Debug
cl /nologo /W3 /GS- /Gs999999 %DEBUGFLAGS% %FILES% /FC /Fe: AnnoyingSoundDebug.exe %LIBS% /link /incremental:no /opt:icf /opt:ref /subsystem:console

main.cpp:
#define STRICT
#include <windows.h>
#include <mmsystem.h>
#include <stdio.h>

HINSTANCE hinst;
HWND hwndMain;

LRESULT CALLBACK
WndProc(
    HWND Window,
    UINT Message,
    WPARAM WParam,
    LPARAM LParam)
{
  if( Message == WM_CLOSE )
  {
    PostQuitMessage(0);
  }
  else
  {
    LRESULT Result  = DefWindowProc( Window, Message, WParam, LParam );
    return Result;
  }
  return 0;
}

HWND g_hwndAltTab = nullptr;
void CALLBACK WinEventProc(
    HWINEVENTHOOK hWinEventHook,
    DWORD event,
    HWND hwnd,
    LONG idObject,
    LONG idChild,
    DWORD dwEventThread,
    DWORD dwmsEventTime
)
{
  printf("Here!\n"); //This never gets called when Alt+Tab pressed
  PCTSTR pszSound = nullptr;
  switch (event)
  {
    case EVENT_SYSTEM_SWITCHSTART:
      if (!g_hwndAltTab)
      {
        g_hwndAltTab = hwnd;
        pszSound = "C:\\Windows\\Media\\Speech On.wav";
      }
      break;
    case EVENT_SYSTEM_SWITCHEND:
      if (g_hwndAltTab)
      {
        g_hwndAltTab = nullptr;
        pszSound = "C:\\Windows\\Media\\Speech Sleep.wav";
      }
      break;
  }
  if (pszSound) {
    PlaySound(pszSound, nullptr, SND_FILENAME | SND_ASYNC);
  }

}

#if MAINDEBUG
int main()
#else
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hinstPrev,
                   LPSTR lpCmdLine, int nShowCmd)
#endif
{
#if !MAINDEBUG
  UNREFERENCED_PARAMETER(lpCmdLine);
#endif
  {
    WNDCLASS wc;
    wc.style = 0;
    wc.lpfnWndProc = (WNDPROC) WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = GetModuleHandle( NULL );
    wc.hIcon = LoadIcon((HINSTANCE) NULL,
        IDI_APPLICATION);
    wc.hCursor = LoadCursor((HINSTANCE) NULL,
        IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);
    wc.lpszMenuName =  "MainMenu";
    wc.lpszClassName = "MainWndClass";

    if (!RegisterClass(&wc))
        return FALSE;
  }
  hinst = GetModuleHandle( NULL );  // save instance handle

  HWINEVENTHOOK hWinEventHook = SetWinEventHook(
     EVENT_SYSTEM_SWITCHSTART, EVENT_SYSTEM_SWITCHEND,
     nullptr, WinEventProc, 0, 0,
     WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);

    hwndMain = CreateWindow("MainWndClass", "Sample",
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT, (HWND) NULL,
        (HMENU) NULL, hinst, (LPVOID) NULL);

    // If the main window cannot be created, terminate
    // the application.

  if (!hwndMain)
      return FALSE;

  if (hWinEventHook)
  {
    ShowWindow(hwndMain, SW_SHOW);
    UpdateWindow(hwndMain);
    MSG msg;
    while(GetMessage( &msg, NULL, 0, 0 ))
    {
      if( msg.message == WM_QUIT )
      {
        PostQuitMessage(0);
      }
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }

    UnhookWinEvent(hWinEventHook);
  }
  return 0;
}

For context of what I am doing:
I am making my own rendering engine in DirectX12, and I am doing all the Win32 stuff manually. One thing I want to do is minimize the window on Alt+Tab when in fullscreen. (I heard DirectX renders on top of the window, so that the window is minimized, but DirectX keeps rendering on top of where the window was, so I need to process Alt+Tab and then stop the rendering (I don't know if that I true, just saw it in a forum post)). So I need a way of detecting Alt+Tab and processing it. (if this doesn't work, I may look into accelerators, but I don't know if that will work with Alt + Tab)
Going through old StackOverflow stuff, I found these two links, but all the examples are either dead or irrelevant:
Handle Alt Tab in fullscreen OpenGL application properly
Handling minimisation in Fullscreen Win32 OpenGL


text:
Q: Index of nested array I had an array like this
var data = [
    {
      name:"Movies",
      info: "category_name",
      data: [
         {
            name:"Interstellar",
            info: "category_data"
         },
         {
            name:"Dark Knight",
            info: "category_data"
         },
      ]
    },
    {
       name:"Music",
       info: "category_name",
       data: [
          {
             name:" Adams",
             info: "category_data"
          },
          {
             name:"Nirvana",
             info: "category_data"
          },
       ]
    }
]
console.log(data[0]);

If I console.log ([1][0]) the answer is undefined. I want to show "Interstellar" or "category data". Which is the index of this array?

A: data[1][0] is undefined because data[1] is will give you the second object in the array, data[1][0] wont give you the first value in data[1], instead, data[1].name will be the first value in your object. The square brackets with index are only applicable to arrays


text:
Q: Where will I put packages? Recently,I got WebMathematica. Initially I searched WebMathematica documentation in Mathematica documentation, but it doesn't return any results. For this I read tutorials; finally I placed the webMathematicaDocumentation folder in the following link.
FileNameJoin[{$InstallationDirectory, "AddOns", "Applications"}]

After that, I reopen Mathematica and search for webMathematica functions in the Mathematica documentation center. It shows all the results.
Out of all functions, I read HTMLTableForm description, if you want to call this function, first you should evaluate the MSP HTML package. This package corresponds to webMathematica layout.
So I copied all the packages, which are under webMathematica\WEB-INF\Applications and placed them in FileNameJoin[{$UserBaseDirectory, "Applications"}].
Again, I reopen Mathematica, directly searched for HTMLTableForm and evaluated MSP HTML package. It's working fine. But my doubt was, is this a good way for placing all the packages in Application folder. Or is there an efficient way?

A: You probably shouldn't put that package into the $InstallationDirectory, there are $BaseDirectory for system wide installations of packages and $UserBaseDirectory for user specific installations (As Alexey Popkov has indicated these did supersed $AddOnsDirectory and $UserAddOnsDirectory of earlier versions. These still exist for compatibility, but probably should not be used anymore).
But for that very case and if the webmathematica installation is on the same machine you could also consider to add the path to the webmathematica installation to the lists of directories where Mathematica searches for documentation and packages:
For the documentation to be found by the frontend I think that would be in the option inspector, then choose  Global Options -> File Locations -> AddOnHelpPath. To let the kernel now where it can find the package you'd need to append the corresponding path to $Path, which you could do in the startup file Kernel/init.m, which again is looked for in $BaseDirectory and $UserBaseDirectory (which usually are the same as the addons directory).
Depending on use case and OS you could also create corresponding symbolic links or tweak the environment variables MATHEMATICA_BASE and/or MATHEMATICA_USERBASE before starting Mathematica to make it find the "MSP`" package wherever it lives.
You can find some general information about the file organization of Mathematica here. That information can of course also be found in the documentation center with this adress "tutorial/MathematicaFileOrganization":


text:
Q: EF Code First rollback database table design I accidentally deleted my database tables and I need to get them back. I have tried running update-database, but I only get:

Cannot find the object "dbo.ArticleComments" because it does not exist or you do not have permissions.

I also tried running Update-Database -TargetMigration:"name_of_migration" with the migration name but resulted in:

Cannot find the object "dbo.ArticleComments" because it does not exist or you do not have permissions.

I need to know how to get my database tables back with their columns (empty or not I don't care)

A: This may be the issue on your situation.
check about this problematic table dbo.ArticleComments.If you renamed or deleted it,then it'll give above kind of error.B'cos when you created the old migration script that was there.Now it's not there.When you try to run the same old migration script, now that table is not on your DbSet or having with different name.
Solution :
If that is the case,then you have to manually edit your migration file to reflect the current table changes.


text:
Q: How can I automatically add line breaks in a textarea? I have a textarea that isn't very wide. I want as the user enters text for there to be line break once a line has 50 characters. I don't want any wrapped text. Just line breaks. Is there a way to make this happen?
I tried to test something basic out on one line and failed.
$('#textarea').keypress(function (e) {
if ($(this).val().length == 50) {
    $(this).val()[51] == '\n'
}
})

I clearly am not very experienced. I don't know if I should start looking into the regExp object.
I can't allow wrapped text because I need to measure what each line of the textarea has. After the user has submitted the form, I need to be able to use something like this:
var line = $('#textarea').val().split('\n');
for(i = 0; i < line.length; i++){
    // do something
}

A: You have use % to see if the length and multiple of 50 and add \n at the end. Demo
if ($(this).val().length % 50 == 0) {
    $(this).val($(this).val() + '\n);
}

A: Try this out. Demo: http://jsfiddle.net/ZtPPk/2
$("textarea").keyup(function(e) {
    var $this = $(this);
    var length = $this.val().length;
    if(length % 50 == 0) {
        $this.val($this.val() + "\n");
    }
});

A: Try
$('textarea').keypress(function () {
  var length = $(this).val().length;
  if (length % 51 == 0 &&
      length > 0) {
    var val = $(this).val();
    $(this).val(val + '\n');
  }
});

http://jsfiddle.net/2QZbG/


text:
Q: How can you sort infortmation from csv file you opened I wrote a code that opens file containing tracks, artist, albums, which reads in the following style 'Computer Love, Kraftwerk, Computer World\n', 'Paranoid Android. I need to organize them and make a list with the tracks information in the following way
 TRACK ARTIST ALBUM
Paranoid Android Radiohead OK Computer

(for example)
Here is the code I came up with so far:
def display_playlist( filename ):
    lines = []
    for line in f:
       lines.append(line)
    return lines

with open('geek-music.csv', 'r') as f:
    contents = display_playlist(f)
print(contents)

How can I organize them

A: One way that you could approach this is to use a Pandas dataframe. Some sample code would be:
Read the data into pandas, assuming it has no header.
import pandas as pd

df = pd.read_csv('geek-music.csv', header=None, names=['track','artist','album'])

Now you have a dataframe representation you can manipulate to sort as needed (by using sort_values, e.g. to sort by track:
sorted_df = df.sort_values('track', ascending=True)

I'm not exactly sure what your end goal is here - to print this on screen or to write to a file? If you wanted to write to a file using space separated variables, you can do:
sorted_df.to_csv('output', sep=" ")

If you wanted to print it on screen with the space separator, perhaps you could use iterrows.
for row in sorted_df.iterrows():
    print "{} {} {}".format(row['track'], row['artist'], row['album'])

Note, code untested so may contain some syntax errors!


text:
Q: Cake PHP Auth Error missing database table . I was trying to work with Cake PHP Auth Section in cake tutorials with my project. But it doesn't work.
I have created three tables 'admin_users' with fields(id,username,password,group_id,created,modified) , 'admin_groups'(id,name,created, modified) and 'users'(id,username,password,created,modified);
I tried normal users will be put in users table and admin users are in 'admin_users' table and grouped the admin users by 'admin_groups' for permission acess in admin side.
When I try to path '[rootpath]/users/login' gives an error Database table 'admins' for model Admin was not found. But I dont created a model for admin.
After I maually created the admins table  again error "Database table 'users_admin' for model UsersAdmin was not found". Here also dont created a model for UsersAdmin.
In Users Controller
class UsersController extends AppController {

    var $name = 'Users';
    var $uses = array();
    var $components = array('Auth','Session');

    function login() {
         $this->set('title_for_layout', 'Login');
         /*if ($this->Auth->user()) {
             $this->redirect($this->Auth->redirect());
         }*/
     }

     function logout() {
         $this->redirect($this->Auth->logout());
     }
}

A: The problem is probably related to your database structure.
A bit of topic first, but if you start your project from scratch, you should probably use only one table (users) to store all users, and link them to another table (groups) to give them different rights. It could be a direct link with a field group_id in the users table (which will allow you later to use the core ACL component), or a many to many relation with a table users_groups between users and groups.
That said, there is something that Cake can't understand out of the box: you called the foreign key between admin_users and admin_groups "group_id". With this name, Cake will try to find a table called groups, not admin_groups. If you want to keep with admin_groups, the foreign key name should be admin_group_id.
Correct this first, and maybe this will resolve some of the problems you get. You may also will have to correct the AdminUser model to reflect this update and clean the cache if you are not in debug mode.

A: Try like this
var $name = 'Users';
var $layout = 'main';

function beforeFilter(){

   $this->Auth->authenticate = ClassRegistry::init('User');
    parent::beforeFilter();
}

function index(){

    $this->set('title_for_layout', 'test site');
}

function login(){

    Security::setHash('md5');
    $this->set('title_for_layout', 'test site');

}

function welcome(){

}

function logout(){

    $this->set('title_for_layout', 'test site');

    $this->redirect($this->Auth->logout());
}

 }
 ?>


text:
Q: Can I create a category section at the bottom of my Wiki pages like in Wikipedia? At the bottom of every Wikipedia page is a 'Bring Together' block that links to everything the current page is connected to. For instance, when viewing the page for Thor you will find this at the bottom:

It breaks down all of the connections and such that this page has and it's hierarchy.
I don't need something even HALF as complex and powerful as this. I would simply like to list out links to all related Wiki Pages where the Wiki Categories were the same.
Is this an option and, if so, how would I go about creating this?

A: I can propose an alternative that can do something similar. Create an enterprise wiki site. All pages on the enterprise wiki site comes with a "Categories" column for you to tag the post. Your audience can then click on these "Categories" and it will bring them to a page with a list of pages with the same "Category" tagged.


text:
Q: Parsing multiple fields to the same parameter using Cypher I would like to parse an array of values to the same parameter in a cypher query via the REST API.
In the example taken from the neo4j documentation: http://docs.neo4j.org/chunked/milestone/rest-api-cypher.html
A cypher query such as the following:
MATCH (x { name: { startName }})-[r]-(friend)
WHERE friend.name = { name }
RETURN TYPE(r)

Cypher query via the REST API using the JSON format will look something like this.
{
  "query" : "MATCH (x {name: {startName}})-[r]-(friend) WHERE friend.name = {name} RETURN TYPE(r)",
  "params" : {
     "startName" : "I",
     "name" : "you"
  }
}

But what if I want to place multiple values for say example startName in addition to "I", perhaps "HIM" "HER" etc? Tried with the following but it didnt work. I would think making multiple such queries to complete all startName values will take a long time if lets say I've got thousands of values to go through
{
  "query" : "MATCH (x {name: {startName}})-[r]-(friend) WHERE friend.name = {name} RETURN TYPE(r)",
  "params" : {
     "startName" : "I","HER","HIM"
     "name" : "you"
  }
}


text:
Q: how use lottie in custom progress dialog in android studio how can i use lottie animation in custom progress dialog.
i know how implement custom progress bar with lottie but i want progress dialog.
i have my animation in json format.  but i dont know how make custom progress dialog.
in gradle i write this line
 implementation 'com.airbnb.android:lottie:3.4.4'

and new class
    import android.app.ProgressDialog;
import android.content.Context;
import android.view.animation.Animation;

public class MyProgressDialog extends ProgressDialog {

    public MyProgressDialog(Context context) {
        super(context,R.style.NewDialog);

        // TODO Auto-generated constructor stub
    }

}

i found this video but it is coded by kotlin. i want use java
https://www.youtube.com/watch?v=ZcR6AMNIagU

A: i found solution
1- make one xml layout for new design. "loading.json" is json format of animation in asset folder.
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="100dp"
    android:layout_height="100dp"
    >

    <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/progressAnimationView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:lottie_autoPlay="true"
        app:lottie_fileName="loading.json"
        app:lottie_loop="true" />

</androidx.constraintlayout.widget.ConstraintLayout>

2-create new java class
public class lottiedialogfragment extends Dialog {
public lottiedialogfragment(Context context) {
    super(context);

    WindowManager.LayoutParams wlmp = getWindow().getAttributes();

    wlmp.gravity = Gravity.CENTER_HORIZONTAL;
    getWindow().setAttributes(wlmp);
    getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    setTitle(null);
    setCancelable(false);
    setOnCancelListener(null);
    View view = LayoutInflater.from(context).inflate(
            R.layout.dialog_lottie, null);
    setContentView(view);
}

}
3-call dialog in main activity
 final lottiedialogfragment lottie=new lottiedialogfragment(this);
    lottie.show();

A: You can create it easily using the LottieDialog library
Code will be like this
LottieDialog dialog = new LottieDialog(this)
        .setAnimation(R.raw.ripple)
        .setAutoPlayAnimation(true)
        .setDialogHeightPercentage(.2f)
        .setAnimationRepeatCount(LottieDialog.INFINITE)
        .setMessage("Loading...")
        .setMessageColor(orangeColor);

dialog.show();

Github Repo for examples and documentation : LottieDialog
End result will be like this


text:
Q: How can I compile the JDK 9 Early Access on my Mac? After downloading the Java 9 early access for Mac, I tried the module quick start guide (http://openjdk.java.net/projects/jigsaw/quick-start). However, the code doesn't seem to compile. It fails with the following output:
src/com.greetings/module-info.java:1: error: class, interface, or enum expected
module com.greetings { }
^
1 error

Anyone get this example to work on a Mac?

A: It appears there are two JDK 9 early access packages. There is JDK 9 Early Access and JDK 9 Early Access with Project Jigsaw. I installed the package without Jigsaw because I thought Jigsaw would come automatically with the JDK. Apparently, that isn't the case, at least not for the early access JDK 9. After I installed the right package I was able to compile the QuickStart module code.
The standard JDK 9 comes with an installer, but the JDK w/Jigsaw is just a tar.gz. If you want the Jigsaw JDK version then you'll need to extract the file into the directory /Library/Java/JavaVirtualMachines. The result should be a jdk1.9.0.jdk folder in this directory, probably along with other JDKs. Hope this helps someone.


text:
Q: CSS changing color in a subclass on hover? I'm currently working on a portfolio website, and for some of my links I have certain text that's bolded, whereas the rest of the sentence is a normal weight. I was wondering if there was a way to only change the color on the bolded portion when you hover over the sentence. I know I can use JavaScript to accomplish this, but I was wondering if there was a pure CSS solution.
Here's my HTML markup for a list item:

      learn more about
     me

I'd like to only change the color of the text in the bold span when you hover over any part of the link. I put the link on everything within the li tag because I thought it was a bit misleading to put icons that weren't links. Thank you!

A: use hover selector for parent only in css as below
parent-class:hover child-class{
    /* your css here */
}

so for your code try like this

a:hover span.bold {
  color: red
}

      learn more about
     me


text:
Q: Ежедневная отправка сообщений в разные дни недели Как бот в телеграме может ежедневно отправлять сообщения в зависимости от дней недели в группы и личные сообщения пользователей, пример: если сегодня понедельник - бот должен отправить сообщение в группу и каждому пользователю.
Пример кода:
if today == 'monday':
   bot.send.message('Расписание на понедельник')


text:
Q: PyTorch Tensor Operation for adding the maximum of the previous row to the next Follow-Up question to PyTorch: Dynamic Programming as Tensor Operation.
Could the following be written as a tensor operation instead of a loop?
a = torch.Tensor([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 11, 12]])

print(a.shape)
# (3, 4)

for i in range(1, a.shape[0]):
    a[i] = a[i-1].max(dim=0)[0] + a[i]

print(a)
# tensor([[ 1,  2,  3,  4],
#         [ 9, 10, 11, 12],
#         [21, 22, 23, 24]])

Basically adding the maximum of the previous row to all elements of the next.
The interesting part is that you can't compute the maximum for each row beforehand and then add that to the respective row, because adding the first maximum influences what the maximum of the next row is.

A: Not entirely sure why you're trying to do this, but yes, this is possible. It's basically the same as your last question:
max_vals, _ = a.max(axis=1, keepdim=True)
additions = max_vals.cumsum(0)[:-1]
a[1:, :] += additions

This is because the marginal addition from one row to the next is equivalent to the maximum, so you can take the maximums first, then cumulatively sum them and add them to the original tensor.


text:
Q: Apache Tomcat examples directory vulnerabilities I am facing Apache Tomcat examples directory vulnerabilities in one of the scenario,
what I use the pattern '..;' in url relaive path as below:
https://website.com/..;/manager/html as it's a servlet based application,
The issue occurs when I use '..;' or any pattern preceded by '..;'
https://website.com/..;..=../manager/html
I can resolve it by settings of listings parameter in <CATALINA_HOME>\conf\web.xml'.
Other than this resolution, how can we eliminate semicolon OR the patter '..;' in the URL.

A: You're running a version that was released in 2013 of a branch (6.0.x) that has reached its end of life in 2016. Since then, lots of security issues have been fixed.
The only sensible recommendation is to upgrade to a version that is still being maintained (eg Tomcat 9), and never again let yourself get so horribly behind the times again, especially on server side software.
You might want to try if 6.0.53 fixes this particular issue, but it is not a long term solution, just a quick way to try fixing this particular issue that you're aware of before you finally do a major version upgrade, to fix all of the issues that you're not aware of yet:


text:
Q: What is the purpose of the windows firewall prompt? Example:

What is the purpose of this prompt? Pressing 'Cancel' doesn't block the program from accessing the internet, so... what does accepting this prompt allow the program to do?
I haven't been able to find a straightforward explanation for this online. Some sources say pressing 'Allow access' allows the program to open a port to allow incoming connections (I'm not sure what this would do, as, wouldn't ports for incoming connections have to be handled by port forwarding on the router?). I've also found mentions that this allows the program to access devices on the LAN.

A: The default configuration of Windows Firewall is to confirm inbound connections only. You get the alert whenever a program tries to create a "listening" socket – most commonly done to accept connections from other machines, but in case of Chrome it's usually for receiving LAN broadcasts for device discovery. (It's either Chrome's built-in UPnP/SSDP support, or mDNS, or both.)
Windows Firewall could be configured to prompt for outbound connections, and/or to outright block network access from specific programs (see wf.msc), but that's rarely done.

wouldn't ports for incoming connections have to be handled by port forwarding on the router?

If they actually come from the other side of the router, yes. But that's not always the case – for example, the whole point of Windows having a category for "public" networks is to guard against connections from devices that are already inside the network, such as all the various free Wi-Fi networks in stores (many block client-to-client packets, but many do not). In other words, an OS-level firewall is an additional layer on top of the firewall (and the NAT) that the router provides.
Also, not all computers are behind a router; when the Windows Firewall interactive prompts were first introduced (in WinXP SP2), it was still extremely common for home Internet connections to be terminated at the computer itself (often because it was still the only LAN-capable device in the household). Your DSL modem would come in 'bridge' mode by default, you would enter PPPoE parameters in Windows, and the computer would directly get a public IP address – the OS firewall would be the only defense.


text:
Q: Solving Minimum time target problem by solving HJB equation numerically
Here is the problem where I am trying to solve by solving HJB equation, where the following term is coming:

To solve this, what I am doing is from one point I am iterating for all u than deciding h that stencil remains in the 9 point neighborhood, and then taking the 5 top most weight (based on distance) and lastly deciding the max value to update the value function but it is actually diverging.
https://colab.research.google.com/drive/1J805FxYLRBnRQAbvRRDVKwyqGO9wkR_M#scrollTo=ykFMv5YNKGBQ
I have written everything in function form please give a look, it is easy to understand, if anybody have any suggestion please weigh in


text:
Q: Magento 2 - Get country name from country code I want to get country name from country code, in Magento 1.9 I use the code like this to get country name:
$countryCollection = Mage::getModel('directory/country_api')->items();
foreach($countryCollection as $key=>$val) {
    $countryCodes[$val['country_id']] = $val['name'];
}

How I can made this code to work for Magento 2?
I get the values from the multiselect attribute with the name country_iso_list, the values of this attribute are AD, AE, AF, AG ...ZW, so they are countries code. I just want to replace the country code with the country name in the frontend. So all I just need is to replace the this part of code:
echo $countryCodes[$val];

in this code
         $data = explode(',',$block->getProduct()->getData('hed_country_iso_list'));
                    foreach($data as $value):
                        $attr = $block->getProduct()->getResource()->getAttribute('country_iso_list');
                        if ($attr->usesSource()):
                                $countries = $attr->getSource()->getOptionText($value);
                                $ccode = explode(', ', $countries);
                        endif;
                    endforeach;
                    if (!empty($countries)):
                             echo "
"./* @escapeNotVerified */ __('This product can be sent to the following countries:')."
";
                             $k=0;
                             echo "
";
                             foreach($ccode as $key=>$val) {
                                    echo $countryCodes[$val];
                                    echo (++$k < sizeof($ccode)) ? ', ' : '';
                             }
                             echo "
";
                    endif;

Thank you

A: Try below code.
public function __construct(
    \Magento\Directory\Model\CountryFactory $countryFactory
)
{
    $this->countryFactory = $countryFactory;
}

public function getCountryName($code)
{
    $_country = $this->countryFactory->create()->loadByCode($code);
    if($_country)
    {
        return $_country->getName();
    }

    return false;
}

A:   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

  $country = $objectManager->create('\Magento\Directory\Model\Country')->load('AE')->getName();

It is an example replace your country code with 'AE'

or To get country collection according to store, you need to add
  following code in your file:

<?php
namespace Vendor\YourModule\Block;

class country extends \Magento\Framework\View\Element\Template {

    protected $_countryCollectionFactory;
    public function __construct(
        \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        $this->Customer = $customer;
        parent::__construct($context, $data);
        $this->_countryCollectionFactory = $countryCollectionFactory;
    }

    public function getCountryCollection()
    {
        $collection = $this->_countryCollectionFactory->create()->loadByStore();
        return $collection;
    }

    /**
     * Retrieve list of top destinations countries
     *
     * @return array
     */
    protected function getTopDestinations()
    {
        $destinations = (string)$this->_scopeConfig->getValue(
            'general/country/destinations',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        return !empty($destinations) ? explode(',', $destinations) : [];
    }

    /**
     * Retrieve list of countries in array option
     *
     * @return array
     */
    public function getCountries()
    {
        return $options = $this->getCountryCollection()
                ->setForegroundCountries($this->getTopDestinations())
                    ->toOptionArray();
    }
}

Another simple way of doing it

Add code in your controller :
protected $_country;

public function __construct(
\Magento\Directory\Model\Country $country
 ) {
$this->_country = $country;
}

public function getCountryname() {
$countryCollection = $this->_country->getCollection();
foreach ($countryCollection as $country) {
   echo "Country name:".$country->getName();
   echo "Country code:".$country->getCountryId();
}
}

I hope this will help


text:
Q: Pods fetchRecord skips items So I have am grabbing some records using Pods.
I have 31 records, but my while($thePod->fetchRecord()) loop only goes 15 times
$thePod = new Pod('projects');
$thePod->findRecords('slider_order ASC');
$totalItems = $thePod->getTotalRows(); // = 31

while($thePod->fetchRecord()) :
  $i++;

endwhile;

echo $i.'/'.$totalItems.' looped through'; // displays 15/31

Any ideas why this is occuring?

A: Change line 2 to:
$thePod->findRecords('slider_order ASC',-1);

15 is the default records per page, -1 returns all records.


text:
Q: Python BeautifulSoup get text first tag I need to get the text of the tag to the first level of li tag with BeautifulSoup in python.
The problem is that the tags contain other li tags which in turn contain other tags to.
Example html:

   Text1<-- GET THIS

      Text1<-- DON'T GET THIS

   Text2<-- GET THIS

      Text2-2<-- DON'T GET THIS

EDIT:
I've been testing and I do not get out only the first a tags.
This is the original piece of that I try to extract:

RELOJES

OUTLET

Adidas

Miss Sixty

Converse

Armand Basi

Marea

Marc Ecko

Festina

Seiko

Relojes Swatch liquidar

Lotus

Lotus Hombre

Lotus Mujer

Lotus Infantil

Daniel Wellington

Viceroy

Viceroy Hombre

Viceroy Mujer

Viceroy Infantil

Ice watch

Relojes Swatch

Mark Maddox

Ferrari

Relojes Cadete

Tous

Tous Kids

Tous Mujer

Tous Hombre

Certina

And this is the code as I try extract:
req2 = requests.get(url2)
        html2 = BeautifulSoup(req2.text)
        catmenu = html2.find('div', {'id':'categories_block_left'})
        categorys = catmenu.find_all('li', recursive=False)
        for cat in categorys:
            categor = cat.find('a').getText()
            print ("   SubCategor:%s" % categor)

But return no value, I just need to get the first a tags.
Example:

OUTLET,
  Lotus,
  Daniel Wellington,
  Viceroy,
  Ice watch,
  Relojes Swatch,
  Mark Maddox,
  Ferrari,
  Relojes Cadete,
  Tous,
  Certina

A: You may specify recursive=False in find_all method, this will only return top-level li tags:
In [62]: soup.find_all('li', recursive=False)
Out[62]:
[

 Text1

 Text1

,

 Text2

 Text2-2

]

Then you may retrieve text from first a tag of each li:
In [63]: [li.find('a').text for li in soup.find_all('li', recursive=False)]
Out[63]: ['Text1', 'Text2']


text:
Q: Dynamic Alert View Text Body Can you edit the contents of an UIAlertView once it has been shown? I would like to be able to update the text in it without having to dismiss and show a new one every time.
Thanks in advance,
Jonathan

A: There is a UIAlertView delegate called didPresentAlertView:. It is fired once the UIAlertView is presented on the view. Inside there you can set any of its properties. Here is an example:
- (void)viewDidLoad {
  [super viewDidLoad];

  UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"my message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [alert setDelegate:self];
  [alert show];
  [alert release];
}

- (void)didPresentAlertView:(UIAlertView *)alertView
{
  [alertView setTitle:@"My new title"];
  [alertView setMessage:@"My new message"];
}

A: Declare your UIAlertView in the .h , initiate it once (maybe in the viewDidLoad) . Show it only when it is first needed and than try changing its contents when you need to with:
  [alertView setTitle:@"new title"];
  [alertView setMessage:@"new message"];

A: Go through this . I guess the MBProgressHUD library's mode switching display will suit your requirements better than messing up with alert views. That particular mode/component in the library shows multiple messages sequentially and you also have the provision to set timers for each message in the sequence.


text:
Q: jQuery -webkit-transform yAngle Just as a learning experience, I am trying to make en element rotate on its yAxis upon clicking a link, but I am having no luck. Here is the code I am using. Any ideas?
$('rotate').click(function(){

$('object').style.webkitTransform = "rotateY(90deg)";});

A: That's not how you apply CSS styles with jQuery. This is.
$('rotate').click(function ()
{
    $('object').css('-webkit-transform', 'rotateY(90deg)');
    // or this:
    // $('object').attr('style', '-webkit-transform: rotateY(90deg)');
});

A: .style isn't a jQuery object property, if you wanted to affect one, use [0] like this:
$('.rotate').click(function(){
  $('.object')[0].style.webkitTransform = "rotateY(90deg)";
});

Or, to affect all of them use a .each():
$('.rotate').click(function(){
  $('.object').each(function() {
    this.style.webkitTransform = "rotateY(90deg)";
  });
});

Note that your selectors 'rotate' and 'object' are looking for <rotate> and <object> elements...so you'll want to adjust those selectors accordingly, above I'm looking for class="rotate" for the click, etc.
An alternative more jQuery-ish way (debatable for custom properties) is .css(), like this:
$('.rotate').click(function(){
  $('.object').css("webkitTransform", "rotateY(180deg)");
});

You can test it here.

A: The QTransform jQuery plugin extends jQuery's css to include setting css Transforms. You can write:
    $('object').rotate('30deg');
    or animate with
    $('object').animate({rotate:'+=30deg', 1000});
http://plugins.jquery.com/project/QTransform


text:
Q: ColorBlob detection in an imageview in android Assume that I have an image like this,
I want to draw contours around the roof and the wall. It may be achieved by color blob detection. There is a sample provided in Opencv 3.10, but its for camera view. I want it in an android imageView. Is there any way to achieve this?
Tried this code:
         File imgFile = new File(Environment.getExternalStorageDirectory()+"/instahome/" + imgName);

        if (imgFile.exists()) {
            myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            Log.d("heree",imgFile.getAbsolutePath().toString());
            mRgba = new Mat(myBitmap.getHeight(), myBitmap.getWidth(), CvType.CV_8UC4);
            ivw.setImageBitmap(myBitmap);
            try {
                detectEdges(myBitmap);
               // contours(myBitmap);
            }catch (Exception e)
            {
                Log.d("Error!!!", e.toString());
            }
        }
        ivw.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int cols = mRgba.cols();
                int rows = mRgba.rows();

                int xOffset = (ivw.getWidth() - cols) / 2;
                int yOffset = (ivw.getHeight() - rows) / 2;

                int x = (int)event.getX() - xOffset;
                int y = (int)event.getY() - yOffset;

                Log.d(TAG, "Touch image coordinates: (" + x + ", " + y + ")");

                if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;

                Rect touchedRect = new Rect();

                touchedRect.x = (x>4) ? x-4 : 0;
                touchedRect.y = (y>4) ? y-4 : 0;

                touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
                touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;

                Mat touchedRegionRgba = mRgba.submat(touchedRect);

                Mat touchedRegionHsv = new Mat();
                Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);

                // Calculate average color of touched region
                mBlobColorHsv = Core.sumElems(touchedRegionHsv);
               int pointCount = touchedRect.width*touchedRect.height;
                for (int i = 0; i < mBlobColorHsv.val.length; i++)
                    mBlobColorHsv.val[i] /= pointCount;

                mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);

                Log.d(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
                        ", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");

                mDetector.setHsvColor(mBlobColorHsv);

                Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);

                mIsColorSelected = true;
                if (mIsColorSelected) {
                    mRgba= new Mat(myBitmap.getHeight(), myBitmap.getWidth(), CvType.CV_8UC4);
                    mDetector.process(mRgba);
                    List<MatOfPoint> contours = mDetector.getContours();
                    Log.e(TAG, "Contours count: " + contours.size());
                    Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);

                    Mat colorLabel = mRgba.submat(4, 68, 4, 68);
                    colorLabel.setTo(mBlobColorRgba);

                    Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
                    mSpectrum.copyTo(spectrumLabel);
                    Bitmap newBitmap=Bitmap.createBitmap(myBitmap.getWidth(),myBitmap.getHeight(),myBitmap.getConfig());
                    try {
                    Utils.matToBitmap(mRgba,newBitmap);

                }catch (Exception ex)
                    {
                        Log.d("error!", ex.toString());
                    }
                    ivw.setImageBitmap(newBitmap);
                }
                touchedRegionRgba.release();
                touchedRegionHsv.release();

                return false; // don't need subsequent touch events
            }

        });

        addListeners();
        addViews();

    }

Searching around 5-6 hours, but no luck, any help will be appreciated!


text:
Q: Helm fetches different "latest" image different than Docker pull's latest image A different image is fetched with the same image name Helm does a chart install than if I do an ordinary docker pull. My values.yaml has
image:
  repository: gcr.io/rsi-api-test/rsi-api
  tag: latest
  pullPolicy: IfNotPresent

The only image in the container registry is
gcr.io/rsi-api-test/rsi-
api@sha256:473bd9e31df8fd5d5424e11a57cabfd308179c8507683d6b9219c804bb315116

But helm somehow finds this image with this code:
gcr.io/rsi-api-test/rsi-api@sha256:c5cc78caa54ac4cf855c5fdb6a3448ff74ab641581fcda35d3e4e245c3154766

I believe it found some old version and for some reason refuses to get the latest version. Where is the "cached" or local collection of repositories used by helm and how can I force it cleaned?
The registry is a GCP Artifact Registry
>helm version
Client: &version.Version{SemVer:"v2.17.0", GitCommit:"a690bad98af45b015bd3da1a41f6218b1a451dbe", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.17.0", GitCommit:"a690bad98af45b015bd3da1a41f6218b1a451dbe", GitTreeState:"clean"}
(base)

UPDATE, CHANGED TAGGING
I edited the tags in the image in GCP, removing both the "latest" and "v0.1.0" tag and adding tag "v1.0.0".  I changed the respective values in the Values.yaml file (above) to
image:
  repository: gcr.io/rsi-api-test/rsi-api
  tag: 1.0.0
  pullPolicy: IfNotPresent

Then, I did
docker image pull gcr.io/rsi-api-test/rsi-api:latest

and confirmed there was no more latest (I'm not sure where it's getting these images from).
then
docker run --detached gcr.io/rsi-api-test/rsi-api:1.0.0

Docker fetched the 1.0.0 version, and it ran as I expected/wanted.
As for helm, I re-ran helm install, and it didn't work due to an image error (kubectl logs shown below).
helm install rsapi
>kubectl logs pod/sullen-lemur-rsiapi-7b8d6d656c-7xmxh
Error from server (BadRequest): container "rsiapi" in pod "sullen-lemur-rsiapi-7b8d6d656c-7xmxh" is waiting to start: trying and failing to pull image
(base)
id=woodsman pwd= ~/rsi/backend/rsiapi git=(master) history-id=1494$
>^Cep -R "\/v2" * |less
(base)
id=woodsman pwd= ~/rsi/backend/rsiapi git=(master) history-id=1494$
>kubectl describe pod/sullen-lemur-rsiapi-7b8d6d656c-7xmxh
Name:         sullen-lemur-rsiapi-7b8d6d656c-7xmxh
Namespace:    default
Priority:     0
Node:         gke-helm-cluster-default-pool-7c542461-sdpv/10.128.0.6
Start Time:   Thu, 26 May 2022 23:19:00 -0400
Labels:       app.kubernetes.io/instance=sullen-lemur
              app.kubernetes.io/name=rsiapi
              pod-template-hash=7b8d6d656c
Annotations:  <none>
Status:       Pending
IP:           10.72.1.13
IPs:
  IP:           10.72.1.13
Controlled By:  ReplicaSet/sullen-lemur-rsiapi-7b8d6d656c
Containers:
  rsiapi:
    Container ID:
    Image:          gcr.io/rsi-api-test/rsi-api:1.0.0
    Image ID:
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       ImagePullBackOff
    Ready:          False
    Restart Count:  0
    Liveness:       http-get http://:http/ delay=60s timeout=1s period=10s #success=1 #failure=3
    Readiness:      http-get http://:http/ delay=20s timeout=1s period=10s #success=1 #failure=3
    Environment:
      SPRING_CLOUD_KUBERNETES_CONFIG_NAME:      sullen-lemur-rsiapi
      MANAGEMENT_ENDPOINT_RESTART_ENABLED:      true
      SPRING_CLOUD_KUBERNETES_RELOAD_ENABLED:   true
      SPRING_CLOUD_KUBERNETES_RELOAD_STRATEGY:  refresh
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-fvgg8 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kube-api-access-fvgg8:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason     Age                   From               Message
  ----     ------     ----                  ----               -------
  Normal   Scheduled  13m                   default-scheduler  Successfully assigned default/sullen-lemur-rsiapi-7b8d6d656c-7xmxh to gke-helm-cluster-default-pool-7c542461-sdpv
  Normal   Pulling    12m (x4 over 13m)     kubelet            Pulling image "gcr.io/rsi-api-test/rsi-api:1.0.0"
  Warning  Failed     12m (x4 over 13m)     kubelet            Failed to pull image "gcr.io/rsi-api-test/rsi-api:1.0.0": rpc error: code = NotFound desc = failed to pull and unpack image "gcr.io/rsi-api-test/rsi-api:1.0.0": failed to resolve reference "gcr.io/rsi-api-test/rsi-api:1.0.0": gcr.io/rsi-api-test/rsi-api:1.0.0: not found
  Warning  Failed     12m (x4 over 13m)     kubelet            Error: ErrImagePull
  Warning  Failed     11m (x6 over 13m)     kubelet            Error: ImagePullBackOff
  Normal   BackOff    3m32s (x42 over 13m)  kubelet            Back-off pulling image "gcr.io/rsi-api-test/rsi-api:1.0.0"
(base)
id=woodsman pwd= ~/rsi/backend/rsiapi git=(master) history-id=1495$
>helm ls
NAME            REVISION    UPDATED                     STATUS      CHART           APP VERSION NAMESPACE
sullen-lemur    1           Thu May 26 23:19:00 2022    DEPLOYED    rsiapi-0.1.0    1.0         default

The same image id was tied up in two SHA codes:
> docker image rm 8d0bfa85e8f9
Error response from daemon: conflict: unable to delete 8d0bfa85e8f9
(must be forced) - image is referenced in multiple repositories

>docker image ls
REPOSITORY                                                             TAG             IMAGE ID       CREATED         SIZE
gcr.io/rsi-api-test/rsi-api                                            latest          8d0bfa85e8f9   10 hours ago    379MB
gcr.io/rsi-api-test/rsi-api                                            v1.0.0          8d0bfa85e8f9   10 hours ago    379MB

>docker image rm -f 8d0bfa85e8f9
Untagged: gcr.io/rsi-api-test/rsi-api:latest
Untagged: gcr.io/rsi-api-test/rsi-api:v1.0.0
Untagged: gcr.io/rsi-api-test/rsi-api@sha256:473bd9e31df8fd5d5424e11a57cabfd308179c8507683d6b9219c804bb315116
Deleted: sha256:8d0bfa85e8f929221a7c6b66e5fd6008151e496407ed9e74072dd3e02314ad12

BONUS points to suggest a way/policy to increment the version tag in for helm. This is a Github Workflow Maven build of a spring boot application.
Also, I'm running Helm on my personal Linux machine, but want it to target a GCP cluster. However, I also tried installing helm and using it on a Minikube installation. What do I need to do to make sure I fully switch?


text:
Q: alternate to indexed views Whats the alternate approach to indexed views in sql server?
Thanks,
Salman Shehbaz.

A: Dumping the view contents to summary tables and putting indices on those instead.
What benefit is it that indexed views provide you with that you'd like to try and achieve with an alternative approach

A: create a select stored procedure and then execute the stored procedure whever you need it.

A: I will assume you want to index a view with an outer or self join (or one of the other limitations).
Use a normal view or in-line table function if you want to use it in a FROM clause.
However, remember this: In a query with indexed views, the optimiser may unnest (expand) the view and use the base tables if it sees fit. An alternative query using unindexed views or in-line table functions would also be nnested.
See my answer here: Does query plan optimizer works well with joined/filtered table-valued functions
And Tony Rogerson
Otherwise, can you add more info please.

A: Alternative approaches inlcude using an INSTEAD OF trigger on a regular VIEW and using a regular trigger on the base tables.


text:
Q: Umbraco Parse error with Google AMP style boilerplaye As the title says, I'm trying to convert the below MasterPage.cshtml into a AMP page. I'm following the AMP guide but when I add the boilerplate styles the page hits a parse error. I've added the error as a screen cap below the code. All the guides I've found online just state that the code from AMP has to be without white-space which I've done. I'm at a bit of a loss as to why it's throwing an error on a style rule inside a style attribute.
Umbraco v6.1.6

<title>@ViewBag.MetaPageTitle</title>

<meta name="viewport" content="width=device-width,minimum-scale=1">
<meta property="og:type" content="website" />
<meta property="og:image" content="@hostURL/Images/fb-share-icon.jpg" />

<meta name="description" content="@ViewBag.MetaDescription">
<meta name="keywords" content="@ViewBag.MetaKeywords">
<meta property="og:title" content="@ViewBag.OpenGraphTitle" />
<meta property="og:description" content="@ViewBag.OpenGraphDescription" />

<link rel="shortcut icon" href="@hostURL/favicon.ico">

@Html.Raw(@Html.RenderCssHere())

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

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

@Umbraco.RenderMacro("CanonicalUrl")

                        PRODUCTS

                                Product Selector

                                Ways to quit smoking

                                Patches

                                Gum

                                Minis

                                Combo therapy

                                Where to buy

                        WANTING TO QUIT

                                How come you're hooked?

                                Tips that can help you quit

                                Managing the five withdrawal symptoms

                                How nicotine replacement can help

                                Ways you will become more healthy

                                How you will become better off financially

                                Smoke free during pregnancy

                                What is so hard about quitting?

                        WANT TO STAY QUIT

                                Commit yourself to quitting

                                Get support for quitting

                                Tips for managing nicotine withdrawal

                                Discover what to expect when you're quitting

                                How to handle occasional slip ups

                        SUPPORT

                                Support Community

                        WHERE TO BUY

                        Join us on

                    Support Community

                @Html.Action("Index", "SearchSurface")

    @RenderBody()

                    Nicabate Products

                        Product Selector

                        Ways to quit smoking

                        Nicotine Patches

                        Gum

                        Minis

                        Combo therapy

                        Where to Buy

                    Wanting to Quit

                        How come you're hooked?

                        Tips that can help you quit

                        Managing the five withdrawal symptoms

                        How nicotine replacement can help

                        Ways you will become more healthy

                        How you will become better off financially

                        Smoke free during pregnancy

                        What is so hard about quitting?

                    Want to stay Quit

                        Commit yourself to quitting

                        Get support for quitting

                        Tips for managing nicotine withdrawal

                        Discover what to expect when you're quitting

                        How to handle occasional slip ups

                About this Website

                        Contact Us

                        Frequently Asked Questions

                        Site Map

                        Privacy Policy

                        Terms of Use

                        Join us on Facebook

Stop smoking aid. Contains nicotine. Use only as directed. Always read the label.

NICABATE, PLEDGE TO QUIT and the hand logo are registered trade marks of the GlaxoSmithKline group of companies.

© 2015 GlaxoSmithKline Australia Pty Ltd - All Rights Reserved

        @if(CurrentPage.DocumentTypeAlias == "Home") {

The smoking facts are clear – the longer you continue smoking, the more damage you're doing to your health and the health
                of the people around you. Quit smoking and you'll begin healing your body immediately. Make no mistake about it – quitting
                smoking isn't easy. It's a journey of ups and downs, little wins and tempting cravings that threaten to crush your willpower
                and all your positive progress. Quitting smoking for good requires persistence, motivation and willpower.

Along the journey to successfully quitting smoking, you'll need all the support you can get and that's where Nicabate
                can help with a range of nicotine quit smoking products. Take your mind off the cravings with Nicabate Mint Gum. Tackle
                the toughest cravings when they occur with Nicabate Lozenges. Relieve smoking impulses in minutes with Nicabate Mini
                Mints. Make mornings less stressful and control cravings around the clock with Nicabate Nicotine Patches. If you're
                building up to quitting smoking on a certain date, prepare yourself to quit cold turkey with Nicabate Pre-Quit Patches.

Start enjoying the extensive health, lifestyle and financial benefits of quitting smoking. The Nicabate product range
                combined with the assistance of a support network will help you quit smoking for good.

        }

@Html.Raw(@Html.RenderJsHere()) @if(CurrentPage.DocumentTypeAlias == "Home") {

}

Error I'm getting from Umbraco
https://imgur.com/IVwaQVX

A: @ starts a code block, so you need to escape the @'s in the AMP styles. I believe you can just put another @ in front of them (so @@-webkit-whatever).


text:
Q: Vendor Banking Information Database Location QuickBooks Enterprise: 2021
I am trying to pull a list of all vendors and their associated banking information to transfer to a new accounting system via an ODBC connection.
Does anyone know in which table the banking information lives inside the database or a different way to pull that information?


text:
Q: Difference between Promise.all, webdriver.promise.all, protractor.promise.all I have a protractor test in which I use protractor.promise.all to resolve several promises and it works fine. However, if I change to use Promise.all instead of protractor.promise.all I get some error. So I think there is a significant difference between them. My questions:
1) What is the difference between:
webdriver = require('selenium-webdriver');
webdriver.promise.all

and
protractor.promise.all

and
Promise.all

2) How can I find all the cases where I have to use protractors own implementation instead of the standard. Is there a documentation about these special cases?
Thank you!

A: protractor.promise provides you a quick access to the webdriver promise and is the same as webdriver.promise. But Promise is a built-in EcmaScript 2015 object for asynchronous computations.
In Protractor, there is this "Control Flow" mechanism that controls the queue of webdriver promises to resolve them in order and keep thing organized. If you want for your promises to be handled with Control Flow, use webdriver promises via protractor.promise.


text:
Q: Find the inverse of a matrix with a variable $$X=
\begin{pmatrix}
2-n & 1 & 1 & 1 & \ldots & 1 & 1 \\
1 & 2-n & 1 & 1 & \ldots & 1 & 1 \\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
1 & 1 & 1 & 1 & \ldots & 2-n & 1 \\
1 & 1 & 1 & 1 & \ldots & 1 & 2-n\end{pmatrix}_{n\times n}
$$
Which means that the matrix with the size of $n\times n$ have $n-2$ along the diagonal and $1$ everywhere else.
Help please, I am stuck with this problem.

A: Hint: Use the Sherman–Morrison formula on $$X=\text{diag}(1-n)_{n\times n}+\begin{pmatrix} 1\\ \vdots \\1\end{pmatrix}_{n\times 1}\begin{pmatrix}1 & \ldots &1 \end{pmatrix}_{1\times n}.$$

A: HINT: Let $B$ be the $n\times n$ matrix of ones. Then $XB=B$, so
$$X(B-I)=XB-X=B-X=(n-1)I\;,$$
where $I$ is the $n\times n$ identity matrix.
By the way, manually calculating the inverses for $n=2$ and $n=3$ was enough to suggest what the answer ought to be, and discovering the argument suggested above was then quite easy.

A: If you see in terms of systems rather than matrices, you must solve
$X(x_1,x_2,\ldots,x_n)=(y_1,y_2,\ldots,y_n)$ where the $y_i$ are given
and the $x_i$ are the unknowns.
Adding everything up, you obtain
$$
x_1+x_2+\ldots +x_n=y_1+y_2+\ldots y_n (1)
$$
Then, comparing (1) with the $i$-th equation gives you the value of
$x_i$.


text:
Q: _("str") in Python , meaning of both I am a starter in python. Now I am working on a Django project.
I saw many lines of code containing  _('password'), _('last_login') etc.
Check the code below:

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )

What is the use of _('username')?

A: In Django the gettext function is often imported as _ for convenience


text:
Q: What is the mass and density distribution of a Schwarzchild black hole in the viewpoint of distant observer? According to Schwarzschild metric:
$$ c^2~\mathrm d\tau^2 = \left(1-\frac{r_s}{r}\right)c^2 ~\mathrm dt^2 - \left(1-\frac{r_s}{r}\right)^{-1}~\mathrm dr^2 - r^2\left(\mathrm d\theta^2 + \sin^2\theta~\mathrm d\varphi^2 \right) $$
,where $r_s$ is Schwarzschild radius: $ r_s = \frac{2GM}{c^2} $
the density element $$ \rho(r) = \frac{\mathrm dm}{\mathrm dV} $$ becomes infinite on the event horizon if there is mass $$ \mathrm dm(r) > 0, r \rightarrow r_s, r>r_s $$very near at the outside of event horizon.
The density is then:
$$ \delta(r)_\infty = \frac{\mathrm dm_{r,\infty}}{\mathrm dV_{r,\infty}} = \frac{\mathrm dm_{r,\infty}}{(1-\frac{r_s}{r})^{1/2}(r~\mathrm dr~\mathrm  d\theta ~\sin\theta~\mathrm  d\varphi)} = \frac{\mathrm dm_{r,\infty}}{~\mathrm dV_{\infty,\infty} }\left(\sqrt{\frac{r}{r-r_s}}\right) $$
and at the limit $r \rightarrow r_s$:
$$ \delta(r)_{\infty}\to \infty , \text{when}~ (r \rightarrow r_s)~\text{and}~ (\mathrm dm_{r,\infty} > 0 ) $$
Note that this equation does not yet describe the density distribution. The mass element $$ \mathrm dm_{r,\infty} $$ is the mass inside volume element $$\mathrm  dV_{r,\infty} $$. In this equation, this can be anywhere between 0 and
$$ \text{max}(\mathrm dm_{r,\infty}) = \frac{M}{A_{BH}}= \frac{M}{4 \pi r_s^2} = \frac{c^4}{16\pi G^2M} $$
,where the maximum is in the situation when all of the mass of BH is concentrated into very thin layer above the event horizon. minimum 0 is the situation that all of the mass is inside the event horizon and none outside of it.
The Schwarzschild metric describes only the metric of spacetime outside of the Black Hole event horizon, not inside.
Birkhoff's theorem states that spacetime in the outerior of non-rotating thin spherical shell has Schwarzchild metric. And the interior of thin spherical shell has flat Minkowsky metric
$$ds^2 = c^2dt^2 - (dx^2 + dy^2 + dz^2)$$
And according to this theorem the interior metric of spherical mass distribution depends only on the spherical mass distribution that is inside the radius r. For example Spherical mass distribution with constant density has following metric:
$$ds^2 = -(1-\frac{2M(r)}{r})c^2dt^2 + (1 -\frac{2M(r)}{r})^{-1} dr^2 + r^2(d\theta^2 + sin^2\theta d\rho^2)$$
I don't know at the moment what is the general solution for interior metric of spherical mass distribution, but i have a guess that it depends largely on the equation of state of the matter, that determines what kind of density and pressure distribution the matter will eventually have when it is in dynamical and thermical equilibrium.
My question is, what do we know about the mass distribution of density distribution of the black hole if it is observed by distant observer? In other words, what are $$ \delta(r) , m(r) $$ of the ideal Schwarzschild Black Hole, if it is observed by observer that is infinitely far away from BH?
I see here two different kind of possiblities for BH mass distribution:

*

*All or some of the mass is concentrated into very thin layer above the event horizon, when the density distribution is (more or less): $$ \rho (r) \rightarrow \delta (r_s) = \left \{ +\infty ,when r = r_s,= 0, when r > r_s \right \} $$

*All of the mass is inside the event horizon,when the density distribution is:
$$ \rho (r) = 0 , when r \geqslant r_s $$
One possibility could be that all of the BH mass is concentrated into a very thin layer above the event horizon, and that there is no mass inside the event horizon. The reason why I think that it is possible is that the time dilation of BH becomes near infinity just above the horizon relative to the clock that is infinitely far away from the black hole and the matter stops falling down for this reason, if it is observed by observer that is far away from the black hole. Also the falling objects have nearly infinite radial length contraction relative to the metric infinitely far away from BH.

$$ \left(\frac{\tau_r }{\tau_\infty }\right) = \sqrt{1-\frac{r_s}{r}} \to 0, ~\text{when}~ (r \to r_s ) $$
$$ \left (  \frac{dr_{r}}{dr_{\infty}}\right ) = \sqrt{1 - \frac{r_s}{r}}\rightarrow 0, when (r\rightarrow r_s) $$
I am not sure what happens to the matter of BH in the birth of the black hole. Does the matter enter inside the event horizon or does it stay outside of the event horizon of the newborn black hole? IF the matter stays outside event horizon at the birth of BH, then it may be possible that all of the mass of BH is outside event horizon and the black hole is hollow inside in this sense.
On the other hand I am not sure about this, but the quantum tunneling effect and Heisenberg uncertainty principle may make possible that some of the particles can enter inside the event horizon.
So the question is, how the mass is distributed in ideal Schwarzchild Black hole in the viewpoint of distant observer?


text:
Q: Content is not matching with the routing after refreshing I have multiple tabs in one of my setting module which further have nested tabs.
I do not want to duplicate the code so I made a routing file inside which I have this route.
const routes: Routes = [
  {
    path: '',
    component: SettingsComponent,
    children: [
      {
        path: '',
        redirectTo: 'my-account',
        pathMatch: 'full',
        component: MyAccountComponent
      },
      { path: 'my-account', component: MyAccountComponent },
      { path: 'apps', component: AppsComponent }
    ]
  }
];

this is the code of setting.html

      My Account

      Apps

      <router-outlet></router-outlet>

So when the url will be setting then my settingComponent will load which have the layout of my tabs and it will redirect to setting/my-account which has then content. it will work unless if I go to setting/apps and then if I refresh it then instead of seeing setting/apps content, I will see the content of setting/my-account
how can I fix it?

A: Move the 'default' route last. They are processed in order.
const routes: Routes = [
{
  path: '',
  component: SettingsComponent,
  children: [
    { path: 'my-account', component: MyAccountComponent },
    { path: 'apps', component: AppsComponent },
    {
      path: '',
      redirectTo: 'my-account',
      pathMatch: 'full',
      component: MyAccountComponent
    },
  ]
 }
];


text:
Q: How to use QUERY in expdp to extract only the last 3 months data In my other thread, I have asked how to extract only the last 3 months. However, I managed to extract data from the  last 3 months only from one table and it extracted all data for other tables. I have several tables in my schema and the column names for the timestamp are different.
In my par file I have the following QUERY but it did not work. I got ORA-00911 error message. I would like to know if the syntax of the below query is correct/possible .
    QUERY=TABLE1,TABLE2:"where TABLE1_STARTTIME >= TO_DATE('01-AUG-2015','dd-mon-yyyy') and TABLE2_STARTIME >= TO_DATE('01-AUG-2015','dd-mon-yyyy');"

A:
QUERY=TABLE1,TABLE2:"where ... TO_DATE('01-AUG-2015','dd-mon-yyyy');"

Remove the semi-colon in the QUERY parameter.:
QUERY=TABLE1,TABLE2:"where TABLE1_STARTTIME >= TO_DATE('01-AUG-2015','dd-mon-yyyy')
                     and TABLE2_STARTIME >= TO_DATE('01-AUG-2015','dd-mon-yyyy')"

On a side note:
Not directly related to your issue. But remember TO_DATE is NLS dependent. You should specify the NLS_DATE_LANGUAGE, else your query might fail for a different nls_date_language.
For example,
SQL> alter session set nls_date_language='FRENCH';

Session altered.

SQL> SELECT TO_DATE('01-AUG-2015','dd-mon-yyyy') FROM DUAL;
SELECT TO_DATE('01-AUG-2015','dd-mon-yyyy') FROM DUAL
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> SELECT TO_DATE('01-AUG-2015','dd-mon-yyyy', 'nls_date_language=ENGLISH') FROM DUAL;

TO_DATE('01
-----------
01-AO█T -15

I would prefer using ANSI Date literal, when you do not have any time portion. It is NLS independent. It uses a fixed format YYYY-MM-DD.
For example,
SQL> alter session set nls_date_language='FRENCH';

Session altered.

SQL> SELECT DATE '2015-08-01' FROM DUAL;

DATE'2015-0
-----------
01-AO█T -15

SQL> alter session set nls_date_language='AMERICAN';

Session altered.

SQL> SELECT DATE '2015-08-01' FROM DUAL;

DATE'2015
---------
01-AUG-15


text:
Q: Own SSH key file to tie up for SSH access to a foreign Linux server We are to have SSH access to client's Linux server for code installation and launch. As the client has given us FTP connection
client has also said:
"SSH access: Can you send me your SSH key. I will connect it to our Linux server."
Is this procedure correct, valid ?
Seems to me client should generate SSH key and forward to us for SSH access...

A: I think that's correct, you can create your own ssh keys with ssh-gen:
ssh-keygen -t rsa

You must send him the public key, for him to add to authorized_keys and enable you to access.
You may need to additionally add the private key to the ssh-agent for it to use by default:
eval $(ssh-agent -s)
ssh-add /dir_to_private_key


text:
Q: How to remove area of UIImage where user move his finger?
*

*IMAGECROPPER

*UIGESTURE

*TOUCH
Needed to achieve this, User selects Image and then cut it with Touch drag like Photo Editing App.

A:          UIGraphicsBeginImageContext(drawImage.frame.size)
            var context = UIGraphicsGetCurrentContext()

            drawImage.image.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height - 50))

            context?.move(to: fromPoint)
            context?.addLine(to: toPoint)
            context?.setLineCap(.butt)
            context?.setLineWidth(2)
            context?.setBlendMode(.clear)
            context?.setShouldAntialias(true)

            UIColor.clear.set()

            context?.strokePath()

            let newImage = UIGraphicsGetImageFromCurrentImageContext()!


text:
Q: How to migrate my "Codenameone" Project from (java 5) to (Java 8) I read that CodenNameOne plugin will work only with Java 8 on 3.5 version.
My project is a big project with code writen in Java 5 with several components customized by myself.  It is a mix of Native-App with Web-App
(WebComponet + JavaScript Bridge + AngularJS, and so on).
Is there risk of breaking my code?
What I need to do to make a smooth transition to Java 8.
With the last version of plugin (3.4) can I write my code in Java8 at this moment?

A: When we say it will only work with Java 8 we mean as the underlying VM of the IDE and SDK. You don't need to activate the Java 8 functionality for your application if you don't want to.
You can use 3.4 and 3.3 targets with Java 8 support enabled.
If you do want to make use of Java 8 features do the steps outlined here:

*

*Add the java.version=8 build hint

*Make sure the IDE and the project use Java 8

*In the build.xml replace usage of 1.5 with 1.8


text:
Q: Is there a data model, or principle, for structuring data for scripting, rather than the human eye? I spend a lot of time writing scripts to automate Google Sheets using Google Apps Script.
Google Apps Script can get relatively slow when the size of your data gets very big, spanning multiple sheets within multiple workbooks. I've spent my fair share of time trying to refactor my code as much as possible to reach Apps Script's 6 minute execution quota (excluding cache service).
I believe the root of the problem is the way data is being organized on sheets. An example of this is splitting 1 column into 5 columns for readability despite the data being automated. I'm sure there are other factors such as validating data once its processed into information & making sure there are no bugs but, beyond that, code doesn't care about what data looks like.
Additionally, I don't think this is a matter of the XY Problem. The best way, overall, to make Google Apps Script more efficient is to use less of it.
I'm not well versed in data science in general so I could definitely be wrong but, nonetheless, is this an existing principle I can learn more about? I've tried searching for this already but its hard to look for what you don't know.


text:
Q: How does discord.py detect that a message is sent using just a coroutine which is being defined in the code itself? I am a intermediate python programmer and just started coding discord bots using the discord.py module. One question that always revolves around my head is, how does the module detect that a message is sent using on_message() coroutine which is declared in our code and no such detection construct is there?
async def on_message(mssg):
    #our conditions and responses

Consider the above code. Is there an equivalent predefined coroutine in the module that calls when we declare the on_message() in our code or is there something else that makes it to detect messages and pass it to the function argument, or detect any other event? On youtube or elsewhere, they just make you learn the syntax for some reason that you have to use async...await from the documentation.

A: so if memory serves me correct, the on_message() is what calls the bot to listen to each message that is sent, every time a message is sent. So with your code there:
async def on_message(mssg):
    #our conditions and responses

we can actually dress that up a bit with some inter-workings, like so:
@bot.listen('on_message')
it's a bot event, so every-time a message is sent, this function is called.
async def stuff(message):
pass message so that the bot knows what to scan.
if message.content.startswith("buttlerprefix"):
start it off with an if statement so that the bot has something to check the user's message against
If I typed buttlerprefix and hit enter, it would respond with this message:
msg = await message.channel.send("my prefix is `>`")
if you want to go an extra step, and keep the channels declutterd, you can set the response equal to a variable msg in the event that you want to manipulate it later, thus in this scenario, it's set to auto delete with
await asyncio.sleep(10)
await msg.delete()

So if we put all of that together:
@bot.listen('on_message')
async def stuff(message):

    if message.content.startswith("buttlerprefix"):
        msg = await message.channel.send("my prefix is `>`")
        await asyncio.sleep(10)
        await msg.delete()

we get a function that is now scanning every message that comes through the guild that this bot functions in, no matter the channel, due to the on_message() function being called every-time a message is sent which is triggered by the @bot.listen