text:
Q: Compiling React component with rollup is returning webpack error I'm trying to compile a React jsx components throught Rollup.js to fill my components library in commonjs.
This is my rollup configuration
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import postcss from 'rollup-plugin-postcss';
import image from '@rollup/plugin-image';
import json from '@rollup/plugin-json';

export default {
  input: ['./src/xxx.jsx'],
  output: [
    {
      dir: './public/build/lib/xxx/commonjs/',
      format: 'esm',
      sourcemap: true,
    },
  ],
  plugins: [
    peerDepsExternal(),
    resolve({
      browser: true,
      preferBuiltins: false,
      extensions: ['.mjs', '.js', '.json', '.node', '.jsx', '.ts', '.tsx'],
    }),
    babel({
      exclude: './node_modules/**',
      presets: ['@babel/preset-env', '@babel/preset-react'],
      plugins: ['@babel/plugin-transform-runtime'],
      babelHelpers: 'runtime',
    }),
    commonjs(),
    postcss({
      extensions: ['.css'],
    }),
    image(),
    json(),
  ],
};

On rollup compilation i get no error, but just this warning

(!) Circular dependencies node_modules/@rjsf/core/dist/es/utils.js ->
node_modules/@rjsf/core/dist/es/components/fields/index.js ->
node_modules/@rjsf/core/dist/es/components/fields/ArrayField.js ->
node_modules/@rjsf/core/dist/es/utils.js
node_modules/@rjsf/core/dist/es/utils.js ->
node_modules/@rjsf/core/dist/es/components/fields/index.js ->
node_modules/@rjsf/core/dist/es/components/fields/BooleanField.js ->
node_modules/@rjsf/core/dist/es/utils.js
node_modules/@rjsf/core/dist/es/utils.js ->
node_modules/@rjsf/core/dist/es/components/fields/index.js ->
node_modules/@rjsf/core/dist/es/components/fields/MultiSchemaField.js
-> node_modules/@rjsf/core/dist/es/utils.js ...and 19 more

But when i want to import my component into another app, i have thoses errors concerning webpack but from where it come from ?

Compiled with problems:X
ERROR in ./node_modules/@xxx/xxx/xxx.js 1:0-32
Module not found: Error: Can't resolve 'http' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'

*install 'stream-http' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "http": false
}

ERROR in ./node_modules/@xxx/xxx/xxx.js 2:0-33
Module not found: Error: Can't resolve 'https' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'

*install 'https-browserify' If you don't want to include a polyfill, you can use an empty module like this:    resolve.fallback: { "https":
false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 3:0-31
Module not found: Error: Can't resolve 'url' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'

*install 'url' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "url": false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 4:0-34
Module not found: Error: Can't resolve 'stream' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'

*install 'stream-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"stream": false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 5:0-32
Module not found: Error: Can't resolve 'assert' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "assert": require.resolve("assert/") }'

*install 'assert' If you don't want to include a polyfill, you can use an empty module like this:  resolve.fallback: { "assert": false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 6:0-30
Module not found: Error: Can't resolve 'zlib' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "zlib": require.resolve("browserify-zlib") }'

*install 'browserify-zlib' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "zlib":
false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 7:0-28
Module not found: Error: Can't resolve 'crypto' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'

*install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"crypto": false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 8:0-30
Module not found: Error: Can't resolve 'fs' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
ERROR in ./node_modules/@xxx/xxx/xxx.js 9:0-32
Module not found: Error: Can't resolve 'path' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'

*install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "path":
false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 10:0-34
Module not found: Error: Can't resolve 'module' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
ERROR in ./node_modules/@xxx/xxx/xxx.js 12:0-34
Module not found: Error: Can't resolve 'buffer' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'

*install 'buffer' If you don't want to include a polyfill, you can use an empty module like this:  resolve.fallback: { "buffer": false }

ERROR in ./node_modules/@xxx/xxx/xxx.js 13:0-32
Module not found: Error: Can't resolve 'util' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'

*install 'util' If you don't want to include a polyfill, you can use an empty module like this:    resolve.fallback: { "util": false }

ERROR in ./node_modules/@xxx/xxx/xxx.js
123470:44-83
Module not found: Error: Can't resolve '../include/module.js' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
ERROR in ./node_modules/@xxx/xxx/xxx.js
123471:44-83
Module not found: Error: Can't resolve '../include/action.js' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
ERROR in ./node_modules/@xxx/xxx/xxx.js
162102:17-48
Module not found: Error: Can't resolve 'ajv-i18n/localize/fr' in
'C:\dev\Test\my-app\node_modules@xxx\xxx'
ERROR in
./node_modules/string_decoder/node_modules/safe-buffer/index.js
4:13-30
Module not found: Error: Can't resolve 'buffer' in
'C:\dev\Test\my-app\node_modules\string_decoder\node_modules\safe-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:

*

*add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'

*install 'buffer' If you don't want to include a polyfill, you can use an empty module like this:  resolve.fallback: { "buffer": false }

A: Try to replace imported @rollup/node-plugin-resolve
from :
import resolve from '@rollup/plugin-node-resolve';

To:
import {nodeResolve} from '@rollup/plugin-node-resolve';

And replace it in plugins:
nodeResolve({
  extensions: [".js", ".jsx"],
}),

It's worked for me.

A: I was able to fix this by adding resolve: ({ browser : true }) to rollup.config.js which I see you already have added.
Another solution that worked for me was to use:
https://github.com/FredKSchott/rollup-plugin-polyfill-node
To use this plugin modify your rollup.config.js as follows
import nodePolyfills from 'rollup-plugin-polyfill-node';

...

export default {

  ...

  resolve: ({
    preferBuiltins: false
  }),

  ...

  plugins: [
    nodePolyfills()
  ],

  ...

};

This will include these "missing" libraries in your bundle.


text:
Q: Control mouse with keyboard in Ubuntu I'm looking for a program that I can use to control the mouse from the keyboard.
I think a video can explain it much better than I could, so please check out Mouser from lifehacker.com:
http://lifehacker.com/212816/hack-attack-operate-your-mouse-with-your-keyboard
Unfortunately, it's only for Windows, but something like this would be the perfect solution.
I found a lot of help on mapping keys to programs, but nothing about mapping keys to mouse control.

A: It can help out partially . System -> Settings -> Assistive Technologies; then Keyboard Accessibility, under "Mouse Buttons"
Also using Shortcuts may help you too.
another way is using ctrl-shift-numlock that is supposed to be the key combo that will let you move the cursor with the keyboard. But, I can't very sure that it works, since my laptop doesn't have a dedicated numlock key. you can control the mouse from keyboard. Keys / and * on the numpad select left mouse click and right mouse click respectively. Mouse click is done by 5 on the numpad.

A: In Ubuntu 11, Gnome I found this in System -> Preferences -> Keyboard and then Mouse Keys tab and check Pointer can be controlled using keypad.
To access System menu use ALT+F1 shortcut.

A: I also wanted to control the mouse from the keyboard, but with a different set of actions for keys.  I implemented this functionality with a little utility program that I've put up on GitHub:
https://github.com/SalmonChris/KeyboardMouse

A: If you look at that HackaDay article, it says he created Mouser.exe after viewing a presentation from a guy at Google. Google's known for its use of linux, right? One of the links from your HackaDay article took me here: http://www.semicomplete.com/projects/keynav/
And here is a demo of keynav in action
Just tested on Ubuntu 10.10 and it works fine. I had to install libxdo-dev before it would build (make), but then it ran fine. Note there's no 'make install' target, so just copy the keynav binary it builds to someplace in your path (~/bin, /opt/bin, etc).
Doesn't work awesome with dual monitors.Edit: NM. Split at least once, than use Shift+[hjkl] to move the divider around. That can jump you to the other screen.

A: For Ubuntu users you can try:

*

*System-settings

*Universal Access

*Pointing and Clicking tab

*Switch off the key that says Mouse keys.

redpajama_set_name: RedPajamaStackExchange


text:
Q: writing to a file on the -iphone-unwanted symbols I have an array and i am writing it to a file using :
memoryString=[memoryString stringByAppendingString:WhatsTheTimeNow];
[memoryFile addObject:memoryString];
[memoryFile writeToFile:fullFileName atomically:NO];

the log is ok , But what i get on the log file is also some more symbols :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>  Touch Event: leftEye    --- ר10 10:33:10---2011</string>
    <string>  Sensor Event: rightHand    --- א10 10:33:26---2011</string>
    <string>  Sensor Event: rightHand    --- ר10 10:33:29---2011</string>
    <string>  Sensor Event: rightLeg    --- א10 10:33:32---2011</string>
    <string>  Touch Event: leftEye    --- ר10 10:33:34---2011</string>
    <string>  Touch Event: leftEye    --- א10 10:33:36---2011</string>

</array>
</plist>

The problem, is that i dont want that <string> ,<array>  symbols at the start and end , and the 3 openning lines.
how do i get rid of this symbols ??
thanks alot .

A: Those "symbols" are what makes your file a .plist, which is what is created when you call writeToFile: on an NSArray. If you want a custom output (which you won't be able to read back in to an array using standard functionality), you'll have to write it yourself, probably using NSString's writeToFile: method instead.

A: The writeToFile method will automatically generate a .plist which is very convenient for reading it back in. If you would like to roll your own,
NSMutableString *file = [NSMutableString string];
for (NSString *s in memoryFile) {
    [file appendFormat:@"%@\n", s];
}
[memoryFile writeToFile:fullFileName atomically:NO
   encoding:NSUTF8StringEncoding error:nil];

Note that writeToFile:atomically: is deprecated.
Your strange characters must stem from some issue with the assignment to memoryString.


text:
Q: Vuejs testing library - how to write a test to handle axios request in "mounted" hook I have a vue component that fetches data from an api in the "created" function. I'm just getting up and running using the following testing stack:
  "devDependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/vue": "^5.8.2",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^27.4.6",
    "jest": "^27.4.7",
    "vue-jest": "^3.0.7",
    "webpack-dev-server": "^3.11.0"
  }

My current test:
import BatchCalendar from '../src/components/batch_calendar.vue';
import { render } from '@testing-library/vue';

test('It renders correctly and loads initial data', done => {
    const wrapper = await render(BatchCalendar);

    getByText('Calendar Notices');
});

I know that vue testing library abstracts some methods away from the core vue testing utilities, so I'm left with using the "render" method of vue testing library.
My question is how should I go about handling the API call in the vue created hook.

*

*Should all api calls (and also async methods?) be mocked?

*How/where do I place await/async functions?

*If I have a plugin (fullcalendar) that is making API requests on its own when rendering, how would I go about mocking/handling that?

Let me know if you need more info, thanks.


text:
Q: Nondeterministic pyaudio/ALSA failure I test some vanilla python code making a sound, specifically the code from this other question.
As I run that code from the command line a la python code.py, it issues this series of messages coming directly from ALSA. So far that's not unusual, as I understand it is ignoring some unavailable devices that are somehow present in the involved ALSA config files, and skipping on using jack after not finding it present:
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm_route.c:869:(find_matching_chmap) Found no matching channel map
connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory)
attempt to connect to server failed
connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory)
attempt to connect to server failed
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave

However, when I modify the duration of the sound to e.g. 50 or 100 milliseconds, then the duration actually heard via the speakers is noticeably different on different runs. And as I wish to program some special beeps and stuff, this is an issue. It remains non-deterministic, also after restarts.
How would you go about figuring the reason for the variability in the actual sound duration being heard?
An accompanying symptom: the message about "unable to open slave" does not get issued on every run, sometimes it does and sometimes it does not. Something is nondeterministic, and I wonder whether you'd put down a day for cleaning up the elaborate ALSA config or approach this very differently.
Anyway, duplicating the play_sound call to add another sound right after the first one:
play_sound("sine", 150, 0.8, 100)
play_sound("sine", 130, 0.8, 200)

I get a slightly different console output:
attempt to connect to server failed
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:869:(find_matching_chmap) Found no matching channel map
connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory)
attempt to connect to server failed
connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory)
attempt to connect to server failed
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave

I have not manually tinkered the ALSA configuration and it is an Ubuntu 20.04 system. Maybe I'm using the wrong linux distribution for having it all work very smoothly out of the box.
How would you approach figuring why the duration of the sound is non-deterministic?


text:
Q: Accessing an elements event handlers with jQuery How can I access an elements event handler's with jQuery.
The following link seems to indicate that you could previously access them via $(element).data('events')
Accessing functions bound to event handlers with jQuery
But this method doesn't seem to work anymore.

A: $(element).data('events') still works for me.
See here in jQ 1.5.2: http://jsfiddle.net/JAAulde/f82Ky/1/


text:
Q: Android Php login error , namevalued pairs sending blank data I wanted to create a login page in android which connects to a my sql database
Android Code --
public class Hetro01Activity extends Activity implements OnClickListener {

    EditText uname;
    EditText password;
    Button ok;
    ArrayList<NameValuePair> nameValuePairs;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ok=(Button)findViewById(R.id.submit);

        ok.setOnClickListener(this);

    }

    public void onClick(View vu)

    {
        switch(vu.getId())
        {
        case R.id.submit:

             uname=(EditText)findViewById(R.id.uname);
             password=(EditText)findViewById(R.id.password);

            nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("uname",uname.getText().toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString().trim()));

        String result=null;
        InputStream is=null;
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.hetroservers.orgfree.com/login1/checklogin.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response=httpclient.execute(httppost);

            HttpEntity entity=response.getEntity();

            is=entity.getContent();
            Log.e("response",is.toString());
            try
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(is),8);
                StringBuilder sb=new StringBuilder();
                String line=null;

                while((line=br.readLine())!=null)
                {
                    sb.append(line+"\n");

                }
                is.close();

                result=sb.toString();
                result= result.replaceAll("\\s+","");
                Toast.makeText(getApplicationContext(), sb, Toast.LENGTH_LONG).show();
                //validate(result);
                      }
            catch(Exception e)
            {
                  Log.e("log_tag2", "Error");
            }

        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error:  "+e.toString());
        }

        }
        }

    public void validate(String res)
    {
        if(res.equals("Session Created"))
        {

            Intent myInt=new Intent(this,Main1.class);
            startActivity(myInt);

        }
        else
        {

        }

    }
    }

and the php code is
mysql_connect("$host", "$user", "$pass")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_REQUEST['uname'];
$mypassword=$_REQUEST['password'];

$insert="INSERT INTO hetrologin(username,password) VALUES ('$myusername','$mypassword')";
$init=mysql_query($insert);

$sql="SELECT username FROM hetrologin WHERE username= '$myusername' AND password= '$mypassword'";
$result=mysql_query($sql);

$count=mysql_num_rows($result);

if($count == 1){
echo "1";
}
else{
echo "Wrong Username or Password";
}

?>

I wanted to check where the error was so used an insert statement to check in my db, i notice that no matter what input i give the db only stores blank values for both username and password, when i tried the same via a get request to server from my browser the data is being stored properly. Any idea why?

A: UrlEncodedFormEntity takes an arument of type List.

Try changing
ArrayList<NameValuePair> nameValuePairs;

to
List<NameValuePair> nameValuePairs;

Leave this line the same
nameValuePairs = new ArrayList<NameValuePair>(2);


text:
Q: Python 2.7: Using list.append in function arguments I am trying to write a code to print the path in a Binary Tree which add up to the sum passed to the function. To which the below code keeps on failing for a simple test case:
Last executed input: Binary Tree = [1], sum = 1
Runtime Error Message:
Line 26: TypeError: object of type 'NoneType' has no len()
Stdout:None None
I cannot understand how the leftPath and rightPath are becoming None. I am not returning None at all.
'''
Created on Aug 12, 2015

@author: debpriyas
'''

class BTNode(object):
    '''
    classdocs
    '''
    def __init__(self,value, leftBTNode=None, rightBTNode=None):
        '''
        Constructor
        '''
        self.value = value
        self.left = leftBTNode
        self.right = rightBTNode
        # To deal with duplicate values in BST.
        self.count = 1

def pathSum(root, sum):
    return pathSumHelper( root, sum, [])

def pathSumHelper(root, sum, path):

    if root == None:
        if sum == 0:
            return path
        else:
            return []

    leftPath = pathSumHelper(root.left, sum-root.value, path.append(root.value))
    rightPath = pathSumHelper(root.right, sum-root.value, path.append(root.value))
    print leftPath, rightPath
    if len(leftPath) == 0 and len(rightPath) == 0:
        return []

    if len(leftPath) == 0:
        return [rightPath]
    elif len(rightPath) == 0:
        return [leftPath]
    return [leftPath, rightPath]

if __name__ == '__main__':
    root = BTNode(1)

    print pathSum(root, 1)

A: The problem is here:
leftPath = pathSumHelper(root.left, sum-root.value, path.append(root.value))
rightPath = pathSumHelper(root.right, sum-root.value, path.append(root.value))

You are using path.append(root.value) and then using what is returned from the "append" function call as an argument in the pathSumHelper function, which is a NoneType (it modifies the object in-place, and returns None, which is why when you call it from the console, it returns nothing).
Rather, you need to use append prior to the function call and then use path in the function or do
path + [root.value]

in your function call so it will return an actual list.
I would recommend doing the following since you want to modify "path" in-place I am assuming.
path.append(root.value)
leftPath = pathSumHelper(root.left, sum-root.value, path)

Anything where the sum is 0, it will then return a Nonetype, which will cause a TypeError during the len call.
A simple, verifiable, reproducible example is:
>>>def a(x):
...    print(x)

>>>mylist = list(range(10))
>>> a(mylist.append(1))
None

>>> a(mylist + [5])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 5]


text:
Q: How to find confidence interval from the simulation of linear model I have used the arm package, sim() function,  to create a simulation of linear model. The simulation result contains the coefficients and residual error. I would like to find the 95% confidence interval for the coefficients. How do I find it?
The codes I have used to run the simulation are provided below.
mod <- lm(y ~ normal_dist + uniform_dist)
sims <- arm::sim(mod, n = 1000)

A: You can retrieve approximate CIs by computing quantiles of the coefficients simulated by arm::sim():
library(arm)
t(apply(sims@coef, 2, quantile, c(0.025, 0.975)))
                 2.5%     97.5%
(Intercept) 33.394308 42.024628
cyl         -3.485516 -2.169014

(@coef retrieves the coefficients; apply(., 2, quantile, c(0.025, 0.975)) computes the quantiles for each column; t() transposes the result)
However, this is very inefficient and a bit backwards as the simulations are derived by drawing multivariate normal simulations based on the sampling covariance matrix of the coefficients (as such, these limits also won't include the finite-size correction that uses the t distribution instead of the Normal).  You can get the confidence intervals much more easily:
> confint(mod)
                2.5 %    97.5 %
(Intercept) 33.649223 42.119930
cyl         -3.534237 -2.217343
>

A: Is this what you're looking for? 95% CI for coefficients with data iris, replace petal.length with your coefficients of choice
  fit <- lm(Petal.Width ~Petal.Length,iris)
    confint(fit,'Petal.Length',level=0.95)

Output
  2.5 %    97.5 %
Petal.Length 0.3968193 0.4346915


text:
Q: How to collect data from INMEMORY partition? I'm tuning Oracle 12c DB and trying to load some tables to INMEMORY partition. So, I'm altered 2 tables with CRITICAL PRIORITY. But, when I'm trying to SELECT some data from table in memory, it collects from general patition. I've got it from Autotrace.
What I'm doing wrong?

A: The IMCO(Inmemory Coordinator) process wakes up every two minutes and checks to see if any population tasks needs to be completed. So, querying a table immediately after enabling it for inmemory doesn't ensure that query to be served from inmemory.
Objects are populated into the IM column store either in a prioritized list immediately after the database is opened or after the tables are scanned (queried) for the first time.
For example, if we enable table tab1, tab2, tab3 for inmemory:
alter table tab1 inmemory priority medium;
alter table tab3 inmemory priority high;
alter table tab2 inmemory priority critical;

These tables get into inmemory when:

*

*IMCO process picks up these tables and loads them into inmemory area
(in the order of priority higest to lowest: tab2, tab3 and tab1)

*If we perform select query on any of the tables (example: select * from tab1) before the IMCO process kicks in (in every 2 mins)

To know if a table/partition is loaded completely into inmemory you can query v$im_segments view like following:
select owner, segment_name, partition_name, segment_type, bytes,
bytes_not_populated, populate_status from v$im_segments;

So, to answer your question:

*

*Ensure the table is loaded into inmemory by querying v$im_segments

*If the table is not loaded perform select query on it to make it
loaded into inmemory area

*Get query plan for the select query on the
table, it should show INMEMORY as part of the plan

Check this whitepaper for more details.


text:
Q: Marshmallow Permission Error I Am Working On Music Player Application So I have to get All Songs From Memory Card And I successfully got songs from Memory Card Application and Working Fine On Lollipop.
Problem
Marshmallow Run Time Permission I also Add Run time Permission For Marshmallow but App Still Crashing..
Here Is My Full Code Please Tell Me Where I have To write Run Time Permission For Marshmallow.
public class MainActivity extends AppCompatActivity {

    private int STORAGE_PERMISSION_CODE = 23;
    ListView musiclist;
    Cursor musiccursor;
    int music_column_index;
    int count;
    MediaPlayer mMediaPlayer;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init_phone_music_grid();
        if(isReadStorageAllowed()){
            //If permission is already having then showing the toast
            Toast.makeText(MainActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
            //Existing the method with return
            return;
        }

        //If the app has not the permission then asking for the permission
        requestStoragePermission();
    }

    private void requestStoragePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
        }

        //And finally ask for the permission
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
    }

    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //Checking the request code of our request
        if(requestCode == STORAGE_PERMISSION_CODE){

            //If permission is granted
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

                //Displaying a toast
                Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
            }else{
                //Displaying another toast if permission is not granted
                Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
            }
        }
    }

    private boolean isReadStorageAllowed() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

        if (result == PackageManager.PERMISSION_GRANTED)
            return true;

        return false;

    }

    private void init_phone_music_grid() {
        System.gc();
        String[] proj = { MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Video.Media.SIZE };

        musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                proj, null, null, null);
        count = musiccursor.getCount();
        musiclist = (ListView) findViewById(R.id.PhoneMusicList);
        musiclist.setAdapter(new MusicAdapter(getApplicationContext()));

        musiclist.setOnItemClickListener(musicgridlistener);
        mMediaPlayer = new MediaPlayer();
    }

    private AdapterView.OnItemClickListener musicgridlistener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position,
                                long id) {
            System.gc();
            music_column_index = musiccursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
            musiccursor.moveToPosition(position);
            String filename = musiccursor.getString(music_column_index);

            try {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.reset();
                }
                mMediaPlayer.setDataSource(filename);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            } catch (Exception e) {

            }
        }

    };

    public class MusicAdapter extends BaseAdapter {
        private Context mContext;

        public MusicAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            System.gc();
            TextView tv = new TextView(mContext.getApplicationContext());
            String id = null;
            if (convertView == null) {
                music_column_index = musiccursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
                musiccursor.moveToPosition(position);
                id = musiccursor.getString(music_column_index);
                music_column_index = musiccursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
                musiccursor.moveToPosition(position);
                id += " Size(KB):" + musiccursor.getString(music_column_index);
                tv.setText(id);
            } else
         tv.setTextColor(Integer.parseInt(String.valueOf(R.color.colorAccent)));
                tv = (TextView) convertView;
            return tv;
        }
    }}

Please Don't Mark Duplicate Just Correct my Permission
Thanks
Crash Report:
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.example.j.musicapp, PID: 28606
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.j.musicapp/com.example.j.musicapp.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=28606, uid=10161 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                                                                            at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                         Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=28606, uid=10161 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                            at android.os.Parcel.readException(Parcel.java:1621)
                                                                            at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                                                                            at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
                                                                            at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
                                                                            at android.content.ContentResolver.query(ContentResolver.java:502)
                                                                            at android.content.ContentResolver.query(ContentResolver.java:445)
                                                                            at android.app.Activity.managedQuery(Activity.java:2227)
                                                                            at com.example.j.musicapp.MainActivity.init_phone_music_grid(MainActivity.java:100)
                                                                            at com.example.j.musicapp.MainActivity.onCreate(MainActivity.java:35)
                                                                            at android.app.Activity.performCreate(Activity.java:6904)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                                                                            at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: this is the sample code for marshmallow and above versions:
  public static class Utility {
        public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public static boolean checkPermission(final Context context) {
            int currentAPIVersion = Build.VERSION.SDK_INT;
            if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.MyAlertDialogStyle);
                        alertBuilder.setCancelable(true);
                        alertBuilder.setTitle("Permission necessary");
                        alertBuilder.setMessage("External storage permission is necessary");
                        alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                            }
                        });
                        AlertDialog alert = alertBuilder.create();
                        alert.show();

                    } else {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        }
    }

this is a method that checks for permission for reading external storage. please refer the code and manipulate accordingly.
Hope this helps you out.
also add this code in onCreate method
 boolean result = Utility.checkPermission(MainActivity.this);

A: You can have a look on this generic code structure see if matches... I practically followed it, worked well
if(permissionNotGranted){
       requestPermission() ;
}else{
   //Permission granted, good to go!
    doWhateverWithPermission() ;
}

You are good with onRequestPermissionsResult .. just see the structure. Hope it helps!


text:
Q: Is *.exp files necessary for linking dll to our solution? I am developing an application for my client in VC++ using Visual studio 2010. I have dependency on third party for compiling my solution. So, I requested them to provide following files:
1).lib
2).h
3).dll
My question is do i also need to request for .exp file or above files will be sufficient.
Please help.


text:
Q: How to Change this to letters? I have a Job No. : "02268-0000"
and if I pressed a button to it will look like this ---> "02268-ALL"
the button will call all job numbers having the same first set of numbers "02268"
and i want it to appear in the textbox of the job no. that i already call all the number having the same first set of numbers.
Thanks for your help... :)

A:  select replace('02268-0000','0000','ALL')


text:
Q: How to add "-ext WixUIExtension " to ant script in Netbeans? This is output of my native build script in JavaFX, Netbeans IDE.
This is default build via Netbeans.
Running [light, -nologo, -spdb, -sice:60,
C:\Users\Firma\AppData\Local\Temp\build7911949220829827228.fxbundler\tmp\Client.wixobj, **-ext, WixUtilExtension**, -out,
C:\devjava\rms\client\src\trunk\Client\dist\bundles\Client-2.0.msi] in
C:\Users\Firma\AppData\Local\Temp\build7911949220829827228.fxbundler\images\win-msi\Client

I'm trying to customize Wix UI interface, that is way I need to use WixUIExtension.
How can I add  "-ext WixUIExtension " to my building process in NB.
I do not know if this is customizable in NB.

A: It is tricky. I think that they're still ironing out the kinks when it comes to native packaging in Netbeans 8. However, if you're using the standard JavaFX ANT tasks then just package the image when calling <fx:deploy>. After that you'll want to call WIX ANT tasks. These can be downloaded at http://ant.apache.org/antlibs/bindownload.cgi
Once you add ant-dotnet-1.1.jar to your ANT classpath then you'll be able to call WIX with the UI extension like so...
<wix mode="candle" source="package/windows/<YOUR_PROJECT>.WSX" wixobjdestdir="${dist.dir}/bundles"/>
<wix mode="light" source="${dist.dir}/bundles/YOUR_PROJECT.wixobj" target="${dist.dir}/YOUR_PROJECT_NAME.msi">
  <lightarg line="-ext WixUIExtension"/>
</wix>


text:
Q: Magento 2.3 get row subtotal transactional email I want to load row subtotal inside the invoice transactional email.
Therefore I changed the following file (/app/design/frontend/Theme/Theme/Magento_Sales/templates/email/items/invoice/default.phtml)
And added the following: <?php echo $_item->getRowTotal();?>
But this does not work and does not load the row subtotal.
How can I get the row subtotal inside the invoice e-mail?

A: Check below code
I just get row total below SKU using the below code and it works for me.

<?= __("Row Totel")?>: <?= $block->escapeHtml($_item->getRowTotal())?>

Add above code in your

/app/design/frontend/Theme/Theme/Magento_Sales/templates/email/items/invoice/default.phtml

Then try to flush Magento cache and check
Output:-


text:
Q: Multi-input/Multi-output : Wrong output dimension when using KerasClassifier and GridSearchCV I have built a multi-input (100 features) multi-ouput (100 predictions) ANN model using keras and tensorflow. I have been able to train my model and reach a quite satisfying accuracy on the test set using the following code :
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout

def my_loss_fn(y_true, y_pred) :
   d = K.sum(K.abs(y_true), axis = -1)
   n = K.sum((K.tanh(100000*y_true*y_pred)/2 + 0.5)*K.abs(y_true), axis = -1)
   return 1 - n/d

def my_metric_fn(y_true, y_pred) :
   d = K.sum(K.abs(y_true))
   n = K.sum((K.tanh(100000*y_true*y_pred)/2 + 0.5)*K.abs(y_true))
   return n/d

def accuracy(y_true, y_pred) :
   #print(y_true.shape, y_true)
   #print(y_pred.shape, y_true)
   acc = np.zeros([1, len(y_true)])
   for day in range(len(y_pred)) :
       d = 0
       n = 0
       for i in range(len(y_pred[0])) :
           d = d + abs(y_true[day, i])
           if np.sign(y_pred[day, i])*np.sign(y_true[day, i]) > 0 :
               n = n + abs(y_true[day, i])
           else :
               n = n + 0
       acc[0, day] = n/d
   return np.mean(acc, axis = -1)[0]

#Model
classifier = Sequential()
classifier.add(Dense(units = 50, input_shape = (100, ), activation = "tanh"))
classifier.add(Dropout(0.2))
classifier.add(Dense(units=100, activation = 'tanh'))
classifier.compile(optimizer = 'rmsprop', loss = my_loss_fn, metrics = ['accuracy', my_metric_fn])

#Training
callback = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', min_delta = 0.0001, patience = 20, verbose = 0, mode = 'min')
nb_epochs = 250
history = classifier.fit(X_train, y_train, epochs = nb_epochs, batch_size = 31, callbacks = [callback], verbose = True, validation_split = 0., validation_data = (X_test, y_test), use_multiprocessing = True)

#Prediction
y_pred_train = classifier.predict(X_train)
y_pred_test = classifier.predict(X_test)
acc_test = accuracy(y_test, y_pred_test)
acc_train = accuracy(y_train, y_pred_train)

I am trying to improve the performance of my model by tuning the hyperparameters so I used KerasClassifier() and GridSearchCV(). The following code illustrates my approach for the gridsearch.
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from tensorflow import autograph

#Building a function to create the classifier
def build_classifier(nb_layers, nb_nodes, optimizer, dropout, activation_fn):
    classifier=Sequential()
    classifier.add(Dense(units = nb_nodes, input_shape = (100, ), activation = activation_fn))
    for i in range(nb_layers-1) :
        classifier.add(Dense(units = nb_nodes, activation = activation_fn, kernel_initializer = "uniform"))
        classifier.add(Dropout(dropout))
    classifier.add(Dense(units = 100, activation = 'tanh'))
    classifier.compile(optimizer=optimizer, loss = tf.autograph.experimental.do_not_convert(my_loss_fn), metrics= ['accuracy', tf.autograph.experimental.do_not_convert(my_metric_fn)])
    return classifier

#Creating a scorer to feed to the GridSearchCV()
my_scorer = make_scorer(accuracy, greater_is_better = True)
classifier=KerasClassifier(build_fn=build_classifier)
parameters={'batch_size':[13, 31],'epochs':[100, 150], 'optimizer':['adam', 'rmsprop'], 'dropout' : [0.2, 0.1], 'nb_layers' : [2, 3], 'nb_nodes' : [45, 50, 110, 115], 'activation_fn' : ['relu', 'tanh']}
grid_search=GridSearchCV(estimator=classifier, scoring = my_scorer, param_grid=parameters, cv=5, verbose = 1)
grid_search=grid_search.fit(X_train_, y_train_raw)

When I fit my GridSearchCV() object I get the following error at the end of the first combination of hyperparameters (when the scoring is computed) :
TypeError: object of type 'numpy.int32' has no len()

I investigated by adding print commandes inside my accuracy() function
#print(y_true.shape, y_true)
#print(y_pred.shape, y_pred)

to print both the shape and the array y_true and y_pred given as inputs for my accuracy() function used as the scoring in the GridSearchCV() object.
I found out that y_true.shape == (555, 100) but y_pred.shape == (555,). The value 555 corresponds to the number of lines of the fifth validation set because cv = 5.
However, I do not understand why the prediction of the gridsearch is not a multi-output prediction even though the number of nodes of the last layer of the classifier is (100,).

A: This was a regression problem so I used KerasRegressor() instead and it solved the issue. I guess that for a multi-output classification problem, KerasClassifier() expect the output to be a 2D hot encoded array.


text:
Q: DD command speed So the situation is: I've got an old Ipod 3g that's been jailbroken, and it's connected to my server, a windows machine, via ssh. The reason for that is that I want to make a copy of /dev/rdisk0 Ipod partition to my server. I use DD command for that, but the problem is, that it runs incredibly slow. My Ipod is 32GB, and it takes almost 11 hours to get stuff done, considering that keeping connection alive and healthy for such a long time is problem itself(broken Pipe errors, connection timeouts etc).
So I was wondering, is there some kind of a way to make it at least a little bit faster, considering my overall setup? I was playing with bs for a little bit, but no success found there. The speed is somewhere around 1.9Mb/s, sometimes even slower.


text:
Q: "Simple" rational inequality - How does one deduce this? I am a little puzzled by a past exam question. Part (a) is very easy and part (b) is easy too. However, according to the question, and the mark scheme, I should be able to deduce the answer to part (b) from my answer to part (a) without any further calculation. I am able to find the answer to part (b), but I have to draw some graphs and it is far from straight forward.
Part (a) [6 marks]
Find the set of values of $x$ for which
$$x+4>\frac{2}{x+3}$$
As I said: this is easy. Multiply both sides by $(x+3)^2$, take everything over to one side and then factorise. This gives $(x+2)(x+3)(x+5)>0$ and so $-5<x<-3$ or $x>-2$.
Part (b) [1 mark]
This is where it gets a little odd. The question says: Deduce the values of $x$ for which
$$x+4>\frac{2}{|x+3|}$$
According to the solutions, part (b) should be blindingly obvious. The answer is $x>-2$. However, I don't see how one can deduce this trivially. I drew the graph and got the right answer, but a 1 mark question means it is obvious and there is no need for calculation.
Adding a modulus usually makes a problem more difficult and adds solutions, e.g. $x-1>2 \iff x>3$, while $|x-1|>2 \iff x<-1 \ \ \text{or} \ \ x>3$.

A: The right-hand-side of (b) is positive. This forces $x > -4$. On the other hand, if $-4 < x < -3$, the left-hand side is less than $1$ but the right-hand-side is greater than $1$. Thus $x > -3$.
This means $|x + 3| = x+3$ so the two inequalities (a) and (b) are the same. Since the solution to (a) is $-5 < x < -3$ or $x > -2$, you must have $x > -2$.
I don't know if it is blindingly obvious, but there you go.

A: I don't know what they expected you to do. But notice that
$$x+4>\frac{2}{|x+3|}\geq\frac{2}{x+3}$$
This means that any solution of part (b) is a solution of part (a) and that discarding solutions is enough. It is not difficult to get rid of the interval $(-5,-3)$, but I think some argument has to be written in the exam.

A: You can see the result from the calc out of a).
but not out of yours.
I multiply first $(x+3)$. Then you have 2 cases.
First case $x+3 < 0$ then you've got $(x+4)(x+3) < 2$ (you have to change the sign, because you multipy by a negative figure)
this case return the solution $−5<x<−3$
And the second case $x+3 \geq 0$ returns $x>−2.$
It IS quite obvious, that if you multiply by $|x+3|$ there is only the second case. So only the solution of the second case is correct.


text:
Q: Htaccess rewrite url to lookup files in subfolder I have a web structure like this :
root/
|-> lib/
|-> web/
   |-> css/
   |-> index.html
|-> .htaccess

I would like, when a user requests a file, apache actually lookup in the web subfolder but without redirecting.
exemple : http://www.website.com/root/index.html the requested file is root/web/index.html but the url remains unchanged
Is there any way to accomplish that with the mod-rewrite (or anything else) and the .htaccess under root BUT without indicating the root (or domain) so that any "root" will work without modifying the .htaccess (for exemple if I rename root to "mynewroot") ?
Thanks.

A: Yes it's possible. Move your .htaccess to the parent folder where your "root" folder is located and use a wildcard rewrite rule.
In your case:
RewriteRule ^(.*)/$ /$1/web/ [L]

A: You can use this rule in root/.htaccess:
RewriteEngine On

RewriteRule ^(?!web/).*$ web/$0 [L,NC]

(?!web/) is negative lookahead to stop rewriting if request already starts with /web/


text:
Q: What is the meaning of map token while uploading an app on Windows Phone store? I am using bing map service in my Windows Phone app.I have registered the app on bing site and get a
map key to use in app.But I want to know while uploading an app to windows phone store there is
a Map Token option on Number 4 position.
What is the purpose of that Map token and Is I have to get that map token to use map service in my app although i am using bing map key in my app and if yes then how

A: Map token is a key which you will get while uploading application on market place. Below is the link which will guide you in details about this.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn741528.aspx


text:
Q: tkinter listbox get(ACTIVE) method I was trying to make the currently selected Listbox item to be printed out. For example, when I select item "one", it should print out "one" and when I select item "two", it should print out "two" etc. The following is what I have tried.
from Tkinter import*
root=Tk()
sizex = 600
sizey = 400
posx  = 40
posy  = 20
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
itemsforlistbox=['one','two','three','four','five','six','seven']

def CurSelet(evt):
    value=str((mylistbox.get(ACTIVE)))
    print value

mylistbox=Listbox(root,width=60,height=10,font=('times',13))
mylistbox.bind('<<ListboxSelect>>',CurSelet)
mylistbox.place(x=32,y=90)

for items in itemsforlistbox:
    mylistbox.insert(END,items)
root.mainloop()

My problem is whenever I selected an item in the listbox, it is actually printing out the previously selected item.For example, the moment I select the item "two" in the list, it is printing out "one". To make things more clear,please see the following

*

*I selected the item "one", it printed out "one"

*I selected the item "two", it print out "one" again

*I selected the item "three", it print out "two" and so on...

Am I missing something? or did I misunderstand the way the get(ACTIVE) works?

A: An item becomes active after you click on it—which means after your ListboxSelect method returns. So, you're printing out whatever was active before this click (meaning, generally, what you clicked last time).
Also, given that you refer to "selected" numerous times, I think what you want is the selected value(s), not the active one, so you should be asking for that.
For a listbox with selectmode=SINGLE or BROWSE (the default, what you have) listbox, you can fix both of these trivially. Just change this:
mylistbox.get(ACTIVE)

to:
mylistbox.get(mylistbox.curselection())

If you need to handle MULTIPLE or EXTENDED, then of course there are anywhere from 0 to 7 selections instead of exactly 1, so you need to do something like:
values = [mylistbox.get(idx) for idx in mylistbox.curselection()]
print ', '.join(values)

While we're at it, I'm not sure why you were doing str((mylistbox.get(ACTIVE))), or even str(mylistbox.get(ACTIVE)). The result of mylistbox.get with a single index is going to be a string, the same one you inserted.

A: You could use this, it doesn't require the list box. So if you have multiple list boxes it will retrieve the value from any
from tkinter import*
root=Tk()
sizex = 600
sizey = 400
posx  = 40
posy  = 20
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
itemsforlistbox=['one','two','three','four','five','six','seven']

def CurSelet(event):
    widget = event.widget
    selection=widget.curselection()
    picked = widget.get(selection[1])
    print(picked)

mylistbox=Listbox(root,width=60,height=10,font=('times',13))
mylistbox.bind('<<ListboxSelect>>',CurSelet)
mylistbox.place(x=32,y=90)

for items in itemsforlistbox:
    mylistbox.insert(END,items)
root.mainloop()

A: as stated by user1576772 the correct answer should be :
mylistbox.get(ANCHOR)

The Problem with curselection() is it returns the whole list currently selected each time.
consider a situation where you scroll through a Listbox and want always to get the last selected item forward or backward (not the last item in highlighted list , the last item pressed on by user )! curselection() will give you all the currently selected items which is helpful but you will never know which item was selected last !

A: This seems to work for me:
mylistbox.get(ANCHOR)

Based on your code, it will print out the current item.

A: The line picked = widget.get(selection[1]) should be picked = widget.get(selection[0]).
Otherwise, there will be an "index out of range" error.


text:
Q: Camera doesn't works in phonegap i am integrating camera in my phonegap application to record a video and to capture an image. i am using Phonegap 1.5.0 for iPhone.
to capture an imge i am using this code:
  function capturePhoto() {

   navigator.camera.getPicture(onPhotoDataSuccess, fail, { quality: 30 });
   }

On button click i am calling above function but it did nothing.
can anybody help me in this?
Thanks.

A: I have tried it with Cordova latest and it's working fine. Please check the code -
<script type="text/javascript">

document.addEventListener("deviceready",onDeviceReady,false);

function onDeviceReady() {

console.log("CORDOVA IS WORKING:::");
}

        function capturePhoto()
{
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
}

function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}

function onFail(message) {
alert('Failed because: ' + message);
}
</script>


text:
Q: Can I use python-escpos-printer with zebra zp500 label printer? I am going to print labels to zebra zp500 label printer.
I found a python package and am not sure if I can use it with zebra zp500 label printer.
This is the source code I found on python-escpos-printer package documentation.
from escpos.connections import getUSBPrinter

printer = getUSBPrinter()(idVendor=0x1504,  # USB vendor and product Ids for Bixolon SRP-350plus
                          idProduct=0x0006  # printer
                          inputEndPoint=0x82,
                          outputEndPoint=0x01)

printer.text("Hello World")
printer.lf()

Can anyone help me figure out if I can use this package with zebra label printer


text:
Q: F# Dictionary of Lists Equivalent I've just started learning F# and I'm using it with Monogame to create a simple game to help myself learn the various features of the language. I've got my window up and running and have basic drawing working (I'm able to draw a single object to the screen).
My current goal is to draw a scene using different 2D textures on n layers. For example, layer 1 could have the players, layer 2 could have the scene items, such as trees and rocks and layer 3 could have the mountains in the background. Layer n could have n items. Order matters at the scene level but (at the moment) does not matter at the layer level.
In C#, I would do something like the below, using a Dictionary of Lists, with the dictionary key being the layer and the list being the items that get drawn on that layer. However, after a bit of searching, I have been unable to find the equivalent "functional" way of doing it. Of course, it's easy for me to pull in and use the .NET collections, but I'd like learn the functional way before I jump to that.
Note, the code sample below is pseudocode and won't compile (for example, Texture2D's don't have an X or Y component). It's just to illustrate general code flow.
public class Game
{
    var items = new Dictionary<int, List<Texture2D>>();

    public void Initialize()
    {
        items.Add(1, new List<Texture2D>());
        items.Add(2, new List<Texture2D>());
        items.Add(3, new List<Texture2D>());

        items[1].Add(playerOneTexture);
        items[3].Add(jaggedMountainsTexture);
        items[2].Add(rocksTexture);
        items[3].Add(rollingHillsTexture);
        items[1].Add(playerTwoTexture);
        items[2].Add(treeTexture);
    }

    public void Update
    {
        //Example of update (in this case, just move stuff to the right)
        foreach(var key in items.Keys)
        {
            foreach(var texture in items[key])
            {
                texture.X++;
            }
        }
    }

    public void Draw
    {
        var layers = items.Keys.ToList.Sort(); //Or other appropriate sort function
        foreach(var layer in layers)
        {
            foreach(var texture in items[layer])
            {
                DrawToScreen(texture);
            }
        }
    }
}

Q: What is the functional way of solving this problem in F#?

A: I think the best way would be to use F# dicts and lists.
Some simple examples:
let items = dict [1,[playerOneTexture;...]...]

let update = items.Values
|> Seq.iter (fun t -> t |> Seq.iter (fun q -> do something here

etc.
F# dict and list function similar to their C# equivalent, except they are immutable


text:
Q: LongClickListener on ListView I have a ListView and want to get the long-click events on the ListView itself, not on the individual items in the ListView. I believe it should be as straight forward as just called ListView.setOnLongClickListener(View.OnLongClickListener). However, for me, it seems to do nothing at all. I'm just wondering if anyone else has the same issue with all ListViews or it just me and my implementation of the ListView made this not work.
I referred to this answer and tried using ListView.setLongClickable(true) but it still didn't work.

A: It might be easier to define a separate TextView in the parent layout, with id attribute to be android:id="@+id/android:empty" which would be displayed if there are no elements in the ListView, saying something like "--List is empty--", and that being long-clickable. You can easily manipulate the Click for the respective TextView.
In cases where the ListView ought to be long clickable, you can leave a small gap on the parent view, and set the parent view as Long clickable, rather than the ListView.


text:
Q: Moss 2007 - Event Log EventId:7888 Windows NT user or group not found I am getting this event in my Application event log:
Event Type: Error
Event Source: Office SharePoint Server
Event Category: Office Server General
Event ID: 7888
Date:  11/8/2010
Time:  11:15:36 AM
User:  N/A
Computer: ENTERPRISE
Description:
A runtime exception was detected. Details follow.
Message: Windows NT user or group 'domain.com\admin' not found. Check the name again.

Techinal Details:
System.Data.SqlClient.SqlException: Windows NT user or group 'domain.com\admin' not found. Check the name again.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.Office.Server.Data.SqlSession.ExecuteNonQuery(SqlCommand command)
   at Microsoft.Office.Server.Data.SqlServerManager.GrantLogin(String user)
   at Microsoft.Office.Server.Administration.SharedResourceProvider.SynchronizeConfigurationDatabaseAccess(SharedComponentSecurity security)
   at Microsoft.Office.Server.Administration.SharedResourceProvider.SynchronizeAccessControl(SharedComponentSecurity sharedApplicationSecurity)
   at Microsoft.Office.Server.Administration.SharedResourceProvider.Microsoft.Office.Server.Administration.ISharedComponent.Synchronize()

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

I am convinced that it is because I installed and configured Sharepoint with a domain.com\admin account and not the netbios version, domain_com\admin.  I have encountered this with other parts of sharepoint.
My question is:  Does anyone know how to figure out what/where to change that account so that the error will go away.  I have tried to add the account domain.com\admin to the sql server but since the account domain_com\admin is already there it won't let me.  (It is the same account).
The site seems to work fine, other than filling up the event log.
I have searched the world over and found nothing.
I am having some issues with IIS where I need to do a reset.  This is caused by the Sharepoint Timer service and I think if I can fix this issue it might fix the timer issue.
Thanks.

A: Can you login to the server or sharepoint with the given username?
First off, if you only used domain.com/admin as the installation user and nothing else, I don't think that is the cause of the problem.
Then take a look for Failure Audit entries on your sharepoint server and your domain controller to see if there is an obvious reason for the "user not found" error.
If that doesn't lead anywhere, take a look at all your Sharepoint service accounts, as these are the accounts that will be logging in here and there for Sharepoint.  Given the "general" nature of the error, it seems likely to be the Central Admin app pool account, but it could be a Shared Service Provider pool account, or even a web application.  Oh man - Sharepoint can have a lot of different accounts - it's a nightmare to keep track, even if only one of you set this up!
You should check each application pool's identity tab in IIS for your Sharepoint server, and note down which pool uses which account.  Also check the account used by SQL server, and any other accounts you may have used for crawling etc.
Once you have this list, you can follow Microsoft's procedure for changing service accounts.  If all your services/functions use the same account, you could try changing them to see if that fixes it.
If worst comes to the worst and things aren't working, as long as you have your config and content databases intact, you can blow away the Sharepoint server, and start again with your accounts.  If you do this, I recommend using different accounts for each function as suggested by Microsoft.  It may seem like overkill, but if nothing else makes the errors a lot easier to deal with!


text:
Q: Inverse implies surjection and follow-your-nose proofs (I'm posting this question with my own answer, to show a nice calculational proof for one of the examples in Luke Palmer's blog post Follow Your Nose Proofs.)
In what follows, $A$ and $B$ are sets, with $f,g : A \rightarrow B$ and $h : B \rightarrow A$, and $x \in A$ and $y \in B$.
Given the following definitions:
$$
\begin{align}
(0) & f \textrm{ is surjection} \;\equiv\; \langle \forall y :: \langle \exists x :: f(x) = y \rangle \rangle \\
(1) & f = g \;\equiv\; \langle \forall x :: f(x) = g(x) \rangle \\
(2) & (h \circ g)(x) \;=\; h(g(x)) \\
(3) & \textrm{Id}_A(x) \;=\; x \\
\end{align}
$$
prove that
$$
\begin{align}
(4) & \langle \exists h :: f \circ h = \textrm{Id}_B \rangle \;\Rightarrow\; f \textrm{ is surjection}
\end{align}
$$

A: Looking at the given definitions, we see that the expression $f \circ h = \textrm{Id}_B$ uses the terms defined in definitions (1), (2), and (3).  So our straightforward strategy is first to expand these, and see where that leads us.
So we calculate:
$$
\begin{align}
& f \circ h = \textrm{Id}_B \\
\equiv & \;\;\;\;\;\text{"expand $=$ using definition (1)"} \\
& \langle \forall y :: (f \circ h)(y) = \textrm{Id}_B(y) \rangle \\
\equiv & \;\;\;\;\;\text{"expand $\circ$ using definition (2); expand $\textrm{Id}$ using definition (3)"} \\
& \langle \forall y :: f(h(y)) = y \rangle \\
(*) \equiv & \;\;\;\;\;\text{"logic: one-point rule -- working towards the RHS of definition (0)"} \\
& \langle \forall y :: \langle \exists x : x = h(y) : f(x) = y \rangle \rangle \\
\Rightarrow & \;\;\;\;\;\text{"logic: weaken range of $\exists$"} \\
& \langle \forall y :: \langle \exists x :: f(x) = y \rangle \rangle \\
\equiv & \;\;\;\;\;\text{"definition (0)"} \\
& f \textrm{ is surjection}
\end{align}
$$
Note how almost every step is of the 'there is really only one thing you can do' variety.  The only 'creative' step is $(*)$, but also that step is directly guided by the shape for the formulae, in this case the shape of the RHS of (0).
Calculational proofs which mostly consist of such formula-driven steps are essentially the same proofs which Luke Palmer calls 'follow your nose proofs'.
Now we have the essence of the proof, and there are several ways to formally wrap it up, for example as follows:
$$
\begin{align}
& \langle \exists h :: f \circ h = \textrm{Id}_B \rangle \;\Rightarrow\; f \textrm{ is surjection} \\
\equiv & \;\;\;\;\;\text{"logic, allowed because the RHS does not contain $h$} \\
       & \;\;\;\;\;\;\text{ -- to bring the beginning and the end of our previous calculation together"} \\
& \langle \forall h :: f \circ h = \textrm{Id}_B \;\Rightarrow\; f \textrm{ is surjection} \rangle \\
\equiv & \;\;\;\;\;\text{"the above calculation"} \\
& \textrm{true} \\
\end{align}
$$
(See the end of my answer https://math.stackexchange.com/a/332186/11994 for references about this calculational proof style.)


text:
Q: how do the integer value relate to colors in the setTextColor(int color) in android studio? I have a specific question about Android.  Using setTextColor,
the developers guide shows void setTextColor (int color).  Ok checking stackoverflow syntax is myObjectName.setTextColor(Color.GREEN)
Can someone explain the integer value in setTextColor(int color) and what integer values as they relate to colors?
I know the hex value color code, just don't understand how this relates to the integer value.

A: Android has a Color class... the
android.graphics.Color

and every Color you get when you call
Color.aColor is in the class defined as a constant. Example

so for example:
Color.BLACK is mapped to a integer value, in this case
int BLACK
Constant Value: -16777216 (0xff000000)

and as you can imagine that value in hex is related aswell to a RGB+Alpha value
so at the end:
Color.BLACK = -16777216 = 0xff000000
                             | | | |
                        alpha  | | |
                              Red| |
                              Green|
                                Blue

why an integer? well every color can take a value between 0 and 255 (8 bits exactly) and you can perfectly match
Red
Green
Blue and
Alpha, all those a 8 bits makes 32 bits which can be represented with an integer


text:
Q: Sharepoint file upload randomly results in access denied error Since yesterday, the file upload api keeps returning 403 randomly. But it depends on the sharepoint. Many of our clients dont seem to encounter the issue, but our own sharepoint, and a new client's sharepoint have this problem.
Basically every upload request either succeeds or returns 403 Access denied error. And more often than not, it returns 403:
Here is an example of a request (client's sharepoint):
error: "{
↵  "error": {
↵    "code": "accessDenied",
↵    "message": "Access denied",
↵    "innerError": {
↵      "date": "2020-10-14T08:51:20",
↵      "request-id": "cacf89c3-5dbc-4390-98a1-5d7cb9e2668d",
↵      "client-request-id": "cacf89c3-5dbc-4390-98a1-5d7cb9e2668d"
↵    }
↵  }
↵}"

Another example (our sharepoint):
error: "{
↵  "error": {
↵    "code": "accessDenied",
↵    "message": "Access denied",
↵    "innerError": {
↵      "date": "2020-10-14T09:01:38",
↵      "request-id": "3c23f74d-579b-41e8-aafc-a6e3b3a6d885",
↵      "client-request-id": "3c23f74d-579b-41e8-aafc-a6e3b3a6d885"
↵    }
↵  }
↵}"

Nothing has been changed on our sharepoint, it used to always work, no code change, no configuration change on sharepoint.
Edit, code being used for upload:
    private function uploadSmallFile(string $localFilePath, string $remoteFilePath, $conflictBehavior)
    {
        $route = "/sites/root/drive/items/root:$remoteFilePath:/content";

        $route = $route . '?@microsoft.graph.conflictBehavior=' . $conflictBehavior;

        $item = $this->client->createRequest('PUT', $route, true)
            ->setReturnType(Model\DriveItem::class)
            ->attachBody(file_get_contents($localFilePath))
            ->execute();

        return $item;
    }

A: Further details:
Accessing sharepoint on the browser works fine.
Using Insomnia (like Postman but for all uses), here is what happens with a path (Content-Type and Content-Length specified):

*

*Successful upload (201),  403 Access denied (although it happens twice in about 50 uploads in Insomnia)

{
  "error": {
    "code": "accessDenied",
    "message": "Access denied",
    "innerError": {
      "date": "2020-10-15T07:34:19",
      "request-id": "cf7f0f59-046c-4115-ab67-3f471f340dca",
      "client-request-id": "cf7f0f59-046c-4115-ab67-3f471f340dca"
    }
  }
}

With itemId:

*

*Only Successful upload

This is strange, because I'm pretty sure it's not code related, since this happens on a codebase thats as old as june 2020 and didn't change since then.
Edit: Problem seems to be solved, no code was changed on my side. API Related problem.
Edit 2: Problem is back as of today 20-10-2020 (at least since 8am CEST)


text:
Q: How to rotate a non-squared image in frequency domain I want to rotate an image in frequency domain. Inspired in the answers in Image rotation and scaling the frequency domain? I managed to rotate square images. (See the following python script using OpenCV)
M = cv2.imread("lenna.png")
M=np.float32(M)
hanning=cv2.createHanningWindow((M.shape[1],M.shape[0]),cv2.CV_32F)
M=hanning*M
sM = fftshift(M)
rotation_center=(M.shape[1]/2,M.shape[0]/2)
rot_matrix=cv2.getRotationMatrix2D(rotation_center,angle,1.0)

FsM = fftshift(cv2.dft(sM,flags = cv2.DFT_COMPLEX_OUTPUT))
rFsM=cv2.warpAffine(FsM,rot_matrix,(FsM.shape[1],FsM.shape[0]),flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
IrFsM = ifftshift(cv2.idft(ifftshift(rFsM),flags=cv2.DFT_REAL_OUTPUT))

This works fine with squared images. (Better results could be achieved by padding the image)
However, when only using a non-squared portion of the image, the rotation in frequency domain shows some kind of shearing effect.
Any idea on how to achieve this? Obivously I could pad the image to make it square, however the final purpose of all this is to rotate FFTs as fast as possible for an iterative image registration algorithm and this would slightly slow down the algorithm.

A: Following the suggestion of @CrisLuengo I found the affine transform needed to avoid padding the image. Obviously it will depend on the image size and the application but for my case avoidding the padding is very interesting.
The modified script looks now like:
#rot_matrix=cv2.getRotationMatrix2D(rotation_center,angle,1.0)
kx=1.0
ky=1.0
if(M.shape[0]>M.shape[1]):
    kx= float(M.shape[0]) / M.shape[1]
else:
    ky=float(M.shape[1])/M.shape[0]

affine_transform = np.zeros([2, 3])
affine_transform[0, 0] = np.cos(angle)
affine_transform[0, 1] = np.sin(angle)*ky/kx
affine_transform[0, 2] = (1-np.cos(angle))*rotation_center[0]-ky/kx*np.sin(angle)*rotation_center[1]
affine_transform[1, 0] = -np.sin(angle)*kx/ky
affine_transform[1, 1] = np.cos(angle)
affine_transform[1, 2] = kx/ky*np.sin(angle)*rotation_center[0]+(1-np.cos(angle))*rotation_center[1]

FsM = fftshift(cv2.dft(sM,flags = cv2.DFT_COMPLEX_OUTPUT))
rFsM=cv2.warpAffine(FsM,affine_transform, (FsM.shape[1],FsM.shape[0]),flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
IrFsM = ifftshift(cv2.idft(ifftshift(rFsM),flags=cv2.DFT_REAL_OUTPUT))


text:
Q: 'dependencies.dependency.version' for org.slf4j:slf4j-jcl:jar is missing I was trying to import most of maven based project from the Github repository and once I imported all the projects, this is what I am seeing on my console -
Project build error: 'dependencies.dependency.version' for org.slf4j:slf4j-jcl:jar is missing.  pom.xml /testdemo   line 23 Maven pom Loading Problem
Project build error: 'dependencies.dependency.version' for org.slf4j:slf4j-api:jar is missing.  pom.xml /testdemo   line 28 Maven pom Loading Problem
null (org.apache.maven.plugins:maven-resources-plugin:2.5:resources:default-resources:process-resources)    pom.xml /testdemo   line 3  Maven Build Problem
null (org.apache.maven.plugins:maven-resources-plugin:2.5:testResources:default-testResources:process-test-resources)   pom.xml /testdemo   line 3  Maven Build Problem

There is some error complaining about org.slf4j:slf4j-jcl:jar missing.
I am not sure how to fix this issue? Any thoughts?
This is what in my pom.xml file -
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jcl</artifactId>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
</dependency>

A: Version of the library is missing, try this:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jcl</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>

A: You're missing the <version> tag from your <dependency> block.
For example:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jcl</artifactId>
    <version>1.1.1</version>
</dependency>

A: As said here you are missing the required version number.
Maybe you copied your code from somewhere else (not a bad thing, I do it, just saying) and then edited it a bit?  You can also specify your version numbers at the top like so, to help with readability and/or maintainability:
<properties>
    <slf4j.version>1.7.5</slf4j.version>
    <logback.version>1.0.9</logback.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>${logback.version}</version>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>1.9.5</version>
    </dependency>

</dependencies>


text:
Q: Trying to make a weight converter that converts a weight in kg to stones, pounds and ounces- Java I would like to create my own Converter class which will take an input weight from terminal and convert it to stones, pounds and ounces. I wondered how I would go about this?
I will create a method within this class called converter, and I wondered whether all my calculations should be within this method or whether I need more methods? I am anxious I haven't gotten the right idea of implementing my own methods yet.
also, would I put the input weight (using EasyIn library)as a parameter for this method?
Any examples would be much appreciated!
Many thanks!

A: are you trying the console in eclipse or other IDE, than look at system.in
class MyProg {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Printing the file passed in:");
        while(sc.hasNextLine()) System.out.println(sc.nextLine());
    }
}

A: welcome to stack overflow. Luckily, all you need to do is write some basic methods that perform math.
public double convertStone();
{
     // conversion code here
}

And you can repeat that for each value you need. For the conversion code, you only need to convert the actual math for, say, KG to LBS into code like so:
kgToLbs = kg * 2.21;

Hope this helps!

A: javaI worked on a project similar to this one. What I did was I posed a question within the terminal asking which conversion they would like to do, which would then prompt some "if" statements that run the selected conversion. This may not be exactly what you're looking for, but it's useful if you're unsure about inputting your own methods.
        String selection;
        double weight, stones;
        Scanner sc = new Scanner(System.in);

        //Print statements asking the user what conversion they would like to do
        selection = sc.nextLine();
            if(selection.equalsIgnoreCase("stones"))
            {
                //conversion
            }
            //etc


text:
Q: Writing new embedded document in Mongoid fails mysteriously I'm trying to embed a new document in a previously existing document. When the object was created, the root document looked like this:
class MongoPoll
  include Mongoid::Document

  embeds_one :region_count, :as => :voteable, :class_name => 'VoteCount'

I've added a few new embedded documents of the same class:
embeds_one :browser_count, :as => :voteable, :class_name => 'VoteCount'
embeds_one :os_count, :as => :voteable, :class_name => 'VoteCount'

The VoteCount class looks like:
class VoteCount
  include Mongoid::Document

  embedded_in :voteable, :polymorphic => true

When I create new documents from scratch, I create the embedded documents in a before_create handler, and it works fine:
self.region_count = VoteCount.new
self.browser_count = VoteCount.new
self.os_count = VoteCount.new

However, for migrating my old documents, I try to do the same assignment (poll.os_count = VoteCount.new; poll.save) and it fails silently for os_count (but oddly not for browser_count). When I try saving using update_attribute or poll['os_count'] = VoteCount.new from rails console, I get stacktraces that look like the following:
BSON::InvalidDocument: Cannot serialize an object of class VoteCount into BSON.
from /Library/Ruby/Gems/1.8/gems/bson-1.4.0/lib/../lib/bson/bson_c.rb:24:in `serialize'
from /Library/Ruby/Gems/1.8/gems/bson-1.4.0/lib/../lib/bson/bson_c.rb:24:in `serialize'
from /Library/Ruby/Gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/collection.rb:426:in `update'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/collections/master.rb:19:in `update'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/collections/retry.rb:29:in `retry_on_connection_failure'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/collections/master.rb:18:in `update'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/collection.rb:149:in `update'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence/operations/update.rb:45:in `persist'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence/modification.rb:25:in `prepare'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:414:in `_run_update_callbacks'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:94:in `send'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:94:in `run_callbacks'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence/modification.rb:24:in `prepare'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:414:in `_run_save_callbacks'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:94:in `send'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.9/lib/active_support/callbacks.rb:94:in `run_callbacks'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence/modification.rb:23:in `prepare'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence/operations/update.rb:43:in `persist'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence.rb:86:in `update'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.2.2/lib/mongoid/persistence.rb:151:in `save'
from (irb):5

Any idea what might be wrong here?


text:
Q: Difference in I2C Reading Arduino and Raspberry I tried to read my sensor data from my Raspberry Nano W(2017) via I2C and UART, but without success. Afterwards I tried via my Arduino Uno R3 and here it worked.
I am not that familiar with the SW-Differences, but is there the possibility, that the EEPROM on my Sensor only works with Arduino and is not compatible with the Raspi I am using?
Or I am just too stupid to get it running via my Raspi?
BR


text:
Q: We need more voting on ALL tag synonym requests All tag synonym requests should be exposed more for voting.

A: The tag synonyms page shows all current and suggested synonyms. You can filter it to show only suggestions; the number in parentheses next to pending is how many votes it has

A: Keep in mind...
Moderators have a one click approve process. I will frequently go through the list and approve trivial things. This process is significantly more efficient that the old "retag-request" route on meta.
I am not totally against exposing this a bit better when we do the tag page refactor (in the next few weeks) but for now this will have to wait.

A: We could have all proposed tag-synonyms auto-generate a question on Meta, that could then be seen and voted on.


text:
Q: Accessing matches variables in Powershell This question is more about my understanding Powershell's objects rather than solving this practical example. I know there are other ways of separating out a page number from a string.
In my example I want to do this by accessing the object-match-value of the piped pattern match.
# data
$headerString = 'BARTLETT-BEDGGOOD__PAGE_5 BEECH-BEST__PAGE_6'
# require the number of page only
$regexPageNum = '([0-9]$)'

# split the header string into two separate strings to access page numbers
[string[]]$pages = $null
$pages = $headerString -split ' '

# access page numbers using regex pattern
$pages[0] | Select-String -AllMatches -Pattern $regexPageNum | Select-Object {$_.Matches.Value}

The output is:
$_.Matches.Value
----------------
5

Okay. So far so good. I see the page number of array member pages[0] But how do I take this value from the object? The following does not work.
$x = $pages[0] | Select-String -AllMatches -Pattern $regexPageNum | Select-Object {$_.Matches.Value}
Write-Host "Here it is:"$x

Output:
Here it is: @{$_.Matches.Value=5}

Instead of assigning the value 5 to the variable $x Powershell assigns, what looks to me: a hash table with an object description as its only member?
But if I try to access my variable using "Brackets for Access" Reference: hashtables Powershell indicates that variable $x is in fact an array.
x = $pages[0] | Select-String -AllMatches -Pattern $regexPageNum | Select-Object {$_.Matches.Value}
Write-Host "Here it is:"$x
$y = $x[$_.Matches.Value]
Write-Host "What about now:"$y

Output:
Here it is: @{$_.Matches.Value=5}
InvalidOperation:

Line |
  33 |  $y = $x[$_.Matches.Value]
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~
     | Index operation failed; the array index evaluated to null.

What about now:

Okay. At this stage I know I'm being silly. But the point I'm trying to make is: How can I retrieve the value I want when I'm done with the Powershell object?

A: You can use $x.{ $_.Matches.Value } to access the value.
$x = $pages[0] | Select-String -AllMatches -Pattern $regexPageNum | Select-Object { $_.Matches.Value }
$x.{ $_.Matches.Value } # This will print 5

ie, You would have to wrap the property name inside {} since the property name contains "."
Instead of this way, I would suggest you to create a calculated property using Select-Object which makes the code more readable.
$x = $pages[0] | Select-String -AllMatches -Pattern $regexPageNum | Select-Object @{Name = 'PageNumber'; Expression = {$_.Matches.Value}}
$x.PageNumber

A: #Access matches in case of single match
$x = "red blue yellow green" | select-string -Pattern 'blue'
$x.matches.value
#Output
blue

#Access matches in case of multi match
$x = "red blue yellow green blue" | select-string -Pattern 'blue' -AllMatches
$x.matches.value
#Output
blue
blue

A: When you use a scriptblock as a parameter to Select-Object the return value will contain a property whose name matches the source code of the script block...
PS> @{ "aaa" = "bbb" } | select-object { $_.aaa; <# xxx #> }

$_.aaa; <# xxx #>
-------------------
bbb

In this pathological case, if I want to access the property I can't use the name in the default "dotted" notation because it contains reserved characters, but you can access it if you quote the property name:
PS> $x = @{ "aaa" = "bbb" } | select-object { $_.aaa; <# xxx #> }

# note the leading and trailing spaces in the string because the
# the original scriptblock source contains spaces between the "{" and "}"
PS> $x.' $_.aaa; <# xxx #> '
bbb

In your case you'd do this:
PS> $x = $pages[0] | Select-String -AllMatches -Pattern $regexPageNum | Select-Object {$_.Matches.Value}

PS> $x.'$_.Matches.Value'

Other options work too:
$x = $pages[0] `
    | Select-String -AllMatches -Pattern $regexPageNum `
    | Select-Object {$_.Matches.Value}

# get the property whose name is contained in the $name variable
PS> $name = '$_.Matches.Value'
PS> $x.$name
5

# the scriptblock gets converted into a string, and then that string
# is used as a property name
PS> $x.{$_.Matches.Value}
5

# note the whitespace in both scriptblocks has to match *exactly* otherwise the property name won't be found
PS> $x.{ $_.Matches.Value }
ParentContainsErrorRecordException: The property ' $_.Matches.Value ' cannot be found on this object. Verify that the property exists.

but...
There's an easier way - if you pass a hashtable to Select-Object instead of a scriptblock you can specify the name of the property - e.g.
PS> $x = $pages[0] `
    | Select-String -AllMatches -Pattern $regexPageNum `
    | Select-Object @{ "l"="Count"; "e"={$_.Matches.Value} }

PS> $x

Count
-----
5

PS> $x.Count
5

References:

*

*about_Calculated_Properties - Hashtable key definitions


text:
Q: Uploading base64 to azure file share I'm trying to upload a base64 image to Azure Storage File Share, but an error happens.
how can I solve?
ShareFileClient dirClient = new ShareFileClientBuilder()
    .endpoint("https://xxx.file.core.windows.net")
    .shareName("xxx")
    .resourcePath("photos")
    .credential(new StorageSharedKeyCredential("xxx", "xxx"))
    .buildFileClient();

    byte[] bytes = Base64.decodeBase64("iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==");

    try (ByteArrayInputStream dataStream = new ByteArrayInputStream(bytes)) {
        dirClient.upload(dataStream, bytes.length);
    } catch (IOException e) {
        e.printStackTrace();
    }

pom.xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-file-share</artifactId>
    <version>12.2.0</version>
</dependency>

error
Status code 416, "<?xml version="1.0" encoding="utf-8"?>
<Error>
InvalidRange
<Message>The range specified is invalid for the current size of the resource.
RequestId:e9efce20-501a-006d-31a5-f67649000000 Time:2021-01-30T01:14:24.3586552Z
</Message>
</Error>

reference: https://github.com/Azure/azure-sdk-for-java/tree/azure-storage-blob_12.4.0/sdk/storage/azure-storage-file-share

A: Solution
// Create a source file client
ShareFileClient dirClient = new ShareFileClientBuilder()
    .endpoint("https://xxx.file.core.windows.net")
    .shareName("xxx")
    .credential(new StorageSharedKeyCredential("xxx", "xxx"))
    .resourcePath("photos" + "/" + "test.png")
    .buildFileClient();

var base64Image = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

// Create a source file
try {
    var sizeInBytes = 4 * Math.ceil(base64Image.length() / 3)*0.5624896334383812;
    dirClient.create((long) sizeInBytes);
} catch (ShareStorageException e) {
    System.out.println("Failed to create source client. Reasons: " + e.getMessage());
}

// decodeBase64
byte[] bytes = Base64.decodeBase64(base64Image);

// Upload
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(bytes)) {
    dirClient.upload(dataStream, bytes.length);
} catch (IOException e) {
    e.printStackTrace();
}


text:
Q: How to share one physical hard-disk to multiple KVM guest in a Proxmox VE? I evaluate PROXMOX VE 2.0 to migrate a live server.
I have installed a server with the PROXMOX VE which hosts 4 KVM guests on two 300 GB HD's (RAID-1) and two 500 GB HD'a (RAID-1) as a data storage, which is .
1 UBUNTU 11.04 LTS based webservice application server VM-Client
1 UBUNTU 11.04 LTS based dynamic webproject server VM-Client
2 UBUNTU 11.04 LTS based MYSQL database server VM-Client
all those VM-Client's must have r/w access to the data storage (two 500 GB HD's RAID-1).
But I have now idea how I can fulfill these requirements, I don't know how I can add one or more partions of the data storage disk to multiple VM-Client's.

A: You may carve a disk from the host storage space and share it across VMs using 'sharable' flag. Here is a link that may help you.

A: One solution that you could try would be to assign the storage to one of the VMs and make that VM be an NFS server (or add an additional VM that is just an NFS server).  The other VMs would be NFS clients.  This way you can still migrate the client VMs off of the host if you ever need to.

A: You should share data storage via traditional NAS technologies (Samba, NFS), and service can be setup directly on Proxmox host.
Other options is using SAN technologies (iSCSI/AoE+GFS/OCFS2).
Finally, you could give GlusterFS or Ceph a try.


text: Q: Understanding .npmrc I am new to the npm. I have the npm documentation (here and here) to help me understand how to add .npmrc file to my project, however I am unable to grasp the concept of logging in ( as described here) just to make .npmrc file. FWIW I can simply create a new file by right clicking on the project and add a new file. I dont understand what that login is for? What purpose does it serve? It would be great if someone can really explain this concept in detail. And also explain how can I create .npmrc and force my project to read its settings from .npmrc? Thank you.