Q: npm local prefix always set to current working directory I've been searching for a while to try to find the answer to this. I've tried everything I've found that makes sense and more. Nothing has worked. Here's the breakdown:

*

*I'm on linux (12.3-RELEASE FreeBSD 12.3-RELEASE r371270 NFSN64  amd64)

*I've installed a package called hexo-cli using npm.

*My home directory is /home/private

*My global npm install directory is /home/private/.npm-global

*My npm prefix -g location is: /home/private/.npm-global

*When my cwd is /home/public/ and I execute hexo, hexo runs

*hexo then fails to find itself because it's using the npm prefix (this is my guess)

*When I type npm prefix it always returns my cwd

*I have checked /home/private/.npmrc file. A grep "prefix" /home/private/.npmrc returns:

*prefix=/home/private/.npm-global

*There are no other lines or entries returned from the grep

*npm config set prefix=/home/private/.npm-global only modifies the global prefix, not my local prefix

How do I get my local prefix var to be /home/private/.npm-global?
Edit:
Here is the output of my terminal when running hexo:
[username /home/public]$ hexo
ERROR Cannot find module 'hexo' from '/home/public'
ERROR Local hexo loading failed in /home/public
ERROR Try running: 'rm -rf node_modules && npm install --force'

Edit #2:
Forgot to mention. I also tried adding the following two lines to my ~/.profile file:
export PATH=~/.npm-global/bin:$PATH
export PATH=~/.npm-global/lib/node_modules:$PATH

I would then source ~/.profile.
This made absolutely no difference.
Edit #3:
Fixed a path in the 6th bullet point.
Edit #4
This is the output of my npm config list:
[username /home/public]$ npm config list
; "user" config from /home/private/.npmrc

prefix = "/home/private/.npm-global"

; node bin location = /usr/local/bin/node
; node version = v16.16.0
; npm local prefix = /home/public
; npm version = 8.13.0
; cwd = /home/public
; HOME = /home/private/
; Run `npm config ls -l` to show all defaults.

Notice it says npm local prefix. Attempting to npm config set local prefix ... does not work. local prefix is not a variable you can assign a value to. I tried localprefix as well. This did not work.

A: I don't know what the problem was. However I've nuked everything from orbit and started over. I deleted everything except a single html file in my /home/public directory. I deleted /home/private/.npm-global. I recreated /home/private/.npm-global. I followed the steps listed in the answer to:
Global Node modules not installing correctly. Command not found
Specifically the steps provided by Vicente, posted Feb 9, 2019 at 16:30. Which were:
[username /home/public]$ mkdir /home/private/.npm-global
[username /home/public]$ npm config set prefix '~/.npm-global'
[username /home/public]$ export PATH=~/.npm-global/bin:$PATH
[username /home/public]$ source ~/.profile
[username /home/public]$ npm install -g hexo-cli

Then I tried to run from /home/public: hexo init blog
This command worked and it creates a blog directory in the cwd. However, then I tried to run hexo server from the same directory I was still in. This did not work. I changed directories to /home/public/blog/ and then typed hexo server. This still did not work and would only print out some help message about a few commands you could run.
Their website says this is generally due to a missing version line in the dependency of the blog/package.json file. I edited the file and added version 3.2.2, and then re-ran it as hexo --version. When I did this, it dumped out some Validating config output with a bunch of dependencies and their version numbers. The version number specified for hexo was hexo: 6.3.0. I went to open the blog/package.json file again to update the version from 3.2.2 to 6.3.0. However, hexo had already updated the file for me.
Then I typed hexo server while still in /home/public/blog and then the hexo server started up. It errored out with some NaN is not a valid date! error, but the server was still running.
In a separate terminal connected to the same machine and inside the /home/public/blog directory I typed hexo new "Hello Hexo". This worked. Then I typed hexo generate to generate the static files. This also worked.
Everything seems to be working now. Not sure what the problem was earlier. Would still like to know how to set the local prefix to a specific path though, if possible.


Q: Work with and change the layout of an csv file in pandas I read a csv data with pandas and now I would like to change the layout of my dataset. My dataset from excel looks like this:

I run the code with df = pd.read_csv(Location2)
This is what I get:

I would like to have a separated column for time and Watt and their values.
I looked at the documentation but I couldn't find something to make it work.

A: Use read_excel
df = pd.read_excel(Location2)

A: It seems as if you'd need to set up the correct delimiter that separates the two fields. Try adding delimiter=";" to the parameters

A: I think you need parameter sep in read_csv, because default separator is ,:
df = pd.read_csv(Location2, sep=';')

Sample:
import pandas as pd
from pandas.compat import StringIO

temp=u"""time;Watt
0;00:00:00;50
1;01:00:00;45
2;02:00:00;40
3;00:03:00;35"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep=";")
print (df)
       time  Watt
0  00:00:00    50
1  01:00:00    45
2  02:00:00    40
3  00:03:00    35

Then is possible convert time column to_timedelta:
df['time'] = pd.to_timedelta(df['time'])
print (df)
      time  Watt
0 00:00:00    50
1 01:00:00    45
2 02:00:00    40
3 00:03:00    35

print (df.dtypes)
time    timedelta64[ns]
Watt              int64
dtype: object


Q: Intelligent credit cards fields iOS i'm currently developing an app for iOS 8 in swift with a credit card payment functionality.
I searched on the web for a library with intelligent credit card fields, but all i could find is BKMoneyKit, which is not really customizable, and doesn't fit my needs.
What i want is something with fancy features, like telling you if your card is a visa/mastercard when you enter the number, adding the "/" between month and year of expiration date etc... I've already used card.io, but it doesn't offer the possibility to include it's intelligent fields in my view, like said here by the developer himself.
Does anybody knows a tool like this ?
Thanks in advance for help :)

A: The functionalities you are asking for are provided by the PaymentKit library.


Q: How to store and pass information between list views The functionality of my app can be modeled after something like wanelo.
The user will enter a search term for what they want to buy in one Activity. They will get presented with a list of items that match that search term. So, the ListView will contain Items. An Item has many attributes, the main ones being:

*

*id - corresponds to the Item's id in a database

*date_modified - timestamp to know whether the Item was updated

*remote_directory - a URL to the base directory of the Item's assets like icon and other images. The URL is formatted like this: http://my.domain.com/items/a1bc234d/ where a1bc234d is randomly generated, seeded by date_modified.

*remote_dir_name - a substring of remote_directory. From the example above, this value would be a1bc234d.

From the list of search results, the user can mark an item to be viewed later. This will trigger a couple of things:

*

*First, I want to ad the Item to a different ListView that represents the Items the user has "downloaded".

*Then, I want to actually download of all of the Item's data: description, all assets in remote_directory. These things get stored my app's internal storage in folders remote_dir_name: /data/data/my.app.package.name/files/a1bc234d/.

These "downloaded" items are meant to be viewable in offline mode.
This "downloaded" ListView corresponds to a different Activity and will have list items that show a progress bar of the download status for an Item. Also, this ListView should be editable: use should be able to delete and re-order the Items in the list.
Finally, the "downloaded" ListView needs to be persistent. It should preserve order. The ListView of search results need not persist.
I'm having a lot of trouble figuring out how to store the list of Items getting downloaded. The "download" ListView needs to know when to update a list item's progress bar if it's getting downloaded. I think it's a little overkill to store the Items in a database because I'll be constantly updating a row's column until the download finishes. How should I pass this download status information between these two ListViews?

A: I am not entirely sure I am grasping the whole picture here, but it seems to me that you need two ArrayList fields.
List<Item> downloadedItems = new ArrayList<Item>;
List<Item> searchItems = new ArrayList<Item>;

then what you need to do is create your own custom ListAdapter for the DownloadListView and create your own custom download_item.xml that you will inflate inside of the ListAdapter. In your case it sounds like this download_item.xml will consist of a textview, and a progressbar, and will need the containing (or top layer) layout set to wrap content.
Now in the on click listener for the SearchListView set it so that it will call a function that will take the item that was tapped and add it to the downloadedItems ArrayList and start the download, as well as refresh the listadapter dataset so it knows to update the items in the list.
The download should be in a AsyncTask, and you will want to use the @Override publishProgress() portion of this, so that you can update the status of the download bar.
forgive me for any mis sights or mistakes, I just woke up.


Q: calling instance method on model and passing its parameters I have model.rb
class Foo
  def baz(param1, param2, param3, param4)
    puts 'something'
  end
end

controller.rb
def signup
  param4 = params[:param4] || 'N'
  begin
    @foo.baz(Integer(params[:param1]),
                              params[:param2],
                              params[:param3],
                              param4)
    head :ok
  rescue ArgumentError => e
    render_error(:bad_request, e.message)
  end
end

Is this the right way to call instance method on model? also should this param4 = params[:param4] || 'N' be done in model?

A:
Is this the right way to call instance method on model?

Yes, if @foo is an instance of Foo

should this param4 = params[:param4] || 'N' be done in model?

You can set the last parameter variable on you model to be option like so
class Foo
  def baz(param1, param2, param3, param4 = 'N')
    puts 'something'
  end
end

And remove the need to set it within the controller
def signup
  @foo.baz(Integer(params[:param1]),
                            params[:param2],
                            params[:param3],
                            params[:param4])
  head :ok
rescue ArgumentError => e
  render_error(:bad_request, e.message)
end

Since if params[:param4] is nil it will be set to 'N' as specified within the baz method on the Foo model.
Whether or not if you should set param4 in the model is up to you:

*

*Yes, if setting the last parameter param4 to 'N' should or need to occur outside the controller, or

*No, if setting a default value for param4 is unique to the signup controller action and param4 should not have default set, since it might be used elsewhere

A: I think you should handle it in model:
class Foo
  def baz(param)
    param1 = Integer(params[:param1])
    param2 = params[:param2]
    param3 = params[:param2]
    param4 =  params[:param4] || 'N'
    puts 'something'
  end
end


Q: Wordpress Custom Fields not displaying the section I have added a new layout in the Wordpress Custom fields plugin, and after adding it I have added the fields in the corresponding php file too. But for some reason, its printing the code in the browser. I am not sure what I am doing wrong here. I am new to WordPress, so can someone please help me?
Screenshots attached for reference.
PHP file code - https://codeshare.io/GklExO

A: Figured it out, I had to add an image tag and then it worked fine.
However, there are other PHP files in the site, where
<?php the_sub_field('image'); ?> displays the image, but in this particular case I had to write it as
<img src="<?php echo esc_url($image['url']); ?>"/>

Still trying to understand how this works.


Q: Covert name part after "ACCOUNTS\\" to lower case? I have web method to get user from this.User.Identity.Name.string username  = "ACCOUNTS\Ninja.Developer" I want to convert username part after "ACCOUNTS\" to lower case  to be username  = "ACCOUNTS\ninja.developer"
public User GetUser()
{
    var user = new User
    {
        Username = this.User.Identity.Name,<-- convert it here
        IsAuthenticated = this.User.Identity.IsAuthenticated
    };

    return user;
}

note: double \ not single \

A: Use this code:
var Identity = this.User.Identity.Name;
var Username = Identity.Split('\\')[0] + @"\\" + Identity.Split('\\')[2].ToLower();

Of course you should check before in the name have the \ character, etc.

A: You can use Regex.Replace to achieve it :
Username = Regex.Replace(this.User.Identity.Name, @"(?<=ACCOUNTS\\).+", n => n.Value.ToLower()),

The regex pattern (?<=ACCOUNTS\\).+ will match for anything after ACCOUNTS\, and the match is then replaced by its lower case equivalent.

A: As mentioned in other answers, you can use Regex or Split, but here's a substring approach specific to your case.
var user = new User
{
    Username = this.User.Identity.Name.Substring(0,9) + this.User.Identity.Name.Substring(9, name.Length - 9).ToLower(),
    IsAuthenticated = this.User.Identity.IsAuthenticated
};


Q: Swift 2.0 NSJSONSerialization fails if response has only one item Here is a snippet of my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
            do {
                guard let json = try NSJSONSerialization.JSONObjectWithData
(data!, options: .MutableContainers) as? [NSDictionary] else {
                    throw HttpError.ParsingFailed
                }
                completionHandler(success: true, data:json, error: nil)
            }
            catch HttpError.ParsingFailed {
...

It works fine, if the response data has more than one element.
However the NSJSONSerialization.JSONObjectWithData fails (goes in the else block which throws the exception), if there is only one item in the response.
Why doesn't it still parse the response in this case, and returns an array with one element inside?
How should be this problem generally solved?
Of course it would help to do an other parsing in the catch block with as? NSDictionary instead of as? [NSDictionary], but I would avoid this when possible.
EDIT:
object to be parsed which works:
[
    {
    "id": 1,
    "idConsumer": 12
    },
    {
    "id": 2,
    "idConsumer": 12
  }
]

and which does not work:
   {
    "id": 65,
    "delivery": {
    "id": 29,
    "idConsumer": 19
    },
    "postman": {
       "id": 13,
       "email": "testpostman"
     },
     "price": 89
    }

A: It's failing because you are casting your JSON to [NSDictionary]. When you get multiple objects, you get an array of dictionaries, but when you get a single object, you get a single dictionary.
You should try to cast to NSDictionary if casting to [NSDictionary] fails.
If both fail then you should throw the error.


Q: Read a text file into a pandas dataframe or numpy array I have a file that looks like this - http://pastebin.com/u1A7v1CV
It's just a sample of two rows from a file.
The rows contain word_label_id followed by freq.
For example, word_label_id 1237 occurs 1 time in the first row, 1390 occurs 1 time and so on...
I need to use this sparse representation but I'm unable to convert it into a DataFrame or any other usable format.
Edit: I know that pandas has a read_csv method where I can use a space as the delimiter. This is not ideal as I need two separators - one between word_label_id and freq and a different separator between this pair and the next.

A: Ok, it's not ideal but you can use notepad++.
It had a "find and replace" feature and you can use \t to replace tabs as \n
Then you can record a macro to move any given line to the previous, skipping lines.
Then you can use pandas, pd.from_csv but you have to define delimiters as tabs instead of commas
Another option is to read each line,and process it separately.  Basically a while loop with the condition being not m_line == null
Then inside the loop, split the string up with str.split ()
And have another loop that makes a dictionary, for each row.  In the end, you'd have a list of dictionaries where each entry is ID:frequency

A: Have you tried work separately with each item?
For example:
Open document:
with open('delimiters.txt') as r:
    lines = r.readlines()
    linecontent = ' '.join(lines)

Create a list for each item:
result = linecontent.replace(' ', ',').split(',')

Create sublist for ids and freqs:
newResult = [result[x:x+2] for x in range(0, len(result), 2)]

Working with each data type:
ids = [x[0][:] for x in newResult]
freq = [x[1][:] for x in newResult]

Create a DataFrame
df = pandas.DataFrame({'A ids': ids, 'B freq': freq})

A: Here's what I did.
This creates a dictionary containing key-value pairs
from each row.
data = []

with open('../data/input.mat', 'r') as file:
    for i, line in enumerate(file):
        l = line.split()
        d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
        data.append(d)


Q: Getting cache info using C/C++ with inline assembly/intrinsics in osx I wrote the following program using both gcc __get_cpuid and inline assembly to get the cache info of my laptop but fail to identify them on the table about (Encoding of Cache and TLB Descriptors) I found online.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <math.h>
#include <cpuid.h>

static inline void cpuid(uint32_t *eax, uint32_t *ebx,
                         uint32_t *ecx, uint32_t *edx);

int main() {
    uint32_t a, b, c, d;
    uint32_t eax, ebx, ecx, edx;
    eax = 2; /* processor info and feature bits */
    uint32_t command = 2;
    cpuid(&eax, &ebx, &ecx, &edx);
    __get_cpuid(command, &a, &b, &c, &d);

    printf("eax: %08x\n", eax);
    printf("ebx: %08x\n", ebx);
    printf("ecx: %08x\n", ecx);
    printf("edx: %08x\n", edx);

    printf("a: %08x\n", a);
    printf("b: %08x\n", b);
    printf("c: %08x\n", c);
    printf("d: %08x\n", d);
}

static inline void cpuid(uint32_t *eax, uint32_t *ebx,
                         uint32_t *ecx, uint32_t *edx)
{
        /* ecx is often an input as well as an output. */
        asm ("cpuid"
            : "=a" (*eax),
              "=b" (*ebx),
              "=c" (*ecx),
              "=d" (*edx)
            : "0" (*eax));
}

my output:
eax: 76036301
ebx: 00f0b5ff
ecx: 00000000
edx: 00c10000
a: 76036301
b: 00f0b5ff
c: 00000000
d: 00c10000

I found this table from here

I use sysctl hw.cachesize and find that
L1 cache: 32KB
L2 cache: 256KB
L3 cache: 6MB

My Environment:
system: os x 10.10.1
compiler: clang-602.0.53
CPU: I7-4850 HQ 2.3HZ

What's wrong with my program? My program should work since both methods give the same result... I am confused about this. Thank you!
EDIT:
I try what Mats' suggested and get the following as my output:
gcc intrinsic
a: 76036301
b: 00f0b5ff
c: 00000000
d: 00c10000
eax: 2
eax: 76036301
ebx: 00f0b5ff
ecx: 00000000
edx: 00c10000
eax: 4, ecx: 0
eax: 1c004121
ebx: 01c0003f
ecx: 0000003f
edx: 00000000
eax: 4, ecx: 1
eax: 1c004122
ebx: 01c0003f
ecx: 0000003f
edx: 00000000
eax: 4, ecx: 2
eax: 1c004143
ebx: 01c0003f
ecx: 000001ff
edx: 00000000
eax: 4, ecx: 3
eax: 1c03c163
ebx: 02c0003f
ecx: 00001fff
edx: 00000006
eax: 4, ecx: 4
eax: 1c03c183
ebx: 03c0f03f
ecx: 00001fff
edx: 00000004
eax: 4, ecx: 5
eax: 00000000
ebx: 00000000
ecx: 00000000
edx: 00000000

I look up the table at here
static cpuid_cache_descriptor_t intel_cpuid_leaf2_descriptor_table[] = {
//  -------------------------------------------------------
//  value   type    level       ways    size    entries
//  -------------------------------------------------------
    { 0x00, _NULL_, NA,     NA, NA, NA  },
    { 0x01, TLB,    INST,       4,  SMALL,  32  },
    { 0x02, TLB,    INST,       FULLY,  LARGE,  2   },
    { 0x03, TLB,    DATA,       4,  SMALL,  64  },
    { 0x04, TLB,    DATA,       4,  LARGE,  8   },
    { 0x05, TLB,    DATA1,      4,  LARGE,  32  },
    { 0x06, CACHE,  L1_INST,    4,  8*K,    32  },
    { 0x08, CACHE,  L1_INST,    4,  16*K,   32  },
    { 0x09, CACHE,  L1_INST,    4,  32*K,   64  },
    { 0x0A, CACHE,  L1_DATA,    2,  8*K,    32  },
    { 0x0B, TLB,    INST,       4,  LARGE,  4   },
    { 0x0C, CACHE,  L1_DATA,    4,  16*K,   32  },
    { 0x0D, CACHE,  L1_DATA,    4,  16*K,   64  },
    { 0x0E, CACHE,  L1_DATA,    6,  24*K,   64  },
    { 0x21, CACHE,  L2,     8,  256*K,  64  },
    { 0x22, CACHE,  L3_2LINESECTOR, 4,  512*K,  64  },
    { 0x23, CACHE,  L3_2LINESECTOR, 8,  1*M,    64  },
    { 0x25, CACHE,  L3_2LINESECTOR, 8,  2*M,    64  },
    { 0x29, CACHE,  L3_2LINESECTOR, 8,  4*M,    64  },
    { 0x2C, CACHE,  L1_DATA,    8,  32*K,   64  },
    { 0x30, CACHE,  L1_INST,    8,  32*K,   64  },
    { 0x40, CACHE,  L2,     NA, 0,  NA  },
    { 0x41, CACHE,  L2,     4,  128*K,  32  },
    { 0x42, CACHE,  L2,     4,  256*K,  32  },
    { 0x43, CACHE,  L2,     4,  512*K,  32  },
    { 0x44, CACHE,  L2,     4,  1*M,    32  },
    { 0x45, CACHE,  L2,     4,  2*M,    32  },
    { 0x46, CACHE,  L3,     4,  4*M,    64  },
    { 0x47, CACHE,  L3,     8,  8*M,    64  },
    { 0x48, CACHE,  L2,     12,     3*M,    64  },
    { 0x49, CACHE,  L2,     16, 4*M,    64  },
    { 0x4A, CACHE,  L3,     12,     6*M,    64  },
    { 0x4B, CACHE,  L3,     16, 8*M,    64  },
    { 0x4C, CACHE,  L3,     12,     12*M,   64  },
    { 0x4D, CACHE,  L3,     16, 16*M,   64  },
    { 0x4E, CACHE,  L2,     24, 6*M,    64  },
    { 0x4F, TLB,    INST,       NA, SMALL,  32  },
    { 0x50, TLB,    INST,       NA, BOTH,   64  },
    { 0x51, TLB,    INST,       NA, BOTH,   128 },
    { 0x52, TLB,    INST,       NA, BOTH,   256 },
    { 0x55, TLB,    INST,       FULLY,  BOTH,   7   },
    { 0x56, TLB,    DATA0,      4,  LARGE,  16  },
    { 0x57, TLB,    DATA0,      4,  SMALL,  16  },
    { 0x59, TLB,    DATA0,      FULLY,  SMALL,  16  },
    { 0x5A, TLB,    DATA0,      4,  LARGE,  32  },
    { 0x5B, TLB,    DATA,       NA, BOTH,   64  },
    { 0x5C, TLB,    DATA,       NA, BOTH,   128 },
    { 0x5D, TLB,    DATA,       NA, BOTH,   256 },
    { 0x60, CACHE,  L1,     16*K,   8,  64  },
    { 0x61, CACHE,  L1,     4,  8*K,    64  },
    { 0x62, CACHE,  L1,     4,  16*K,   64  },
    { 0x63, CACHE,  L1,     4,  32*K,   64  },
    { 0x70, CACHE,  TRACE,      8,  12*K,   NA  },
    { 0x71, CACHE,  TRACE,      8,  16*K,   NA  },
    { 0x72, CACHE,  TRACE,      8,  32*K,   NA  },
    { 0x78, CACHE,  L2,     4,  1*M,    64  },
    { 0x79, CACHE,  L2_2LINESECTOR, 8,  128*K,  64  },
    { 0x7A, CACHE,  L2_2LINESECTOR, 8,  256*K,  64  },
    { 0x7B, CACHE,  L2_2LINESECTOR, 8,  512*K,  64  },
    { 0x7C, CACHE,  L2_2LINESECTOR, 8,  1*M,    64  },
    { 0x7D, CACHE,  L2,     8,  2*M,    64  },
    { 0x7F, CACHE,  L2,     2,  512*K,  64  },
    { 0x80, CACHE,  L2,     8,  512*K,  64  },
    { 0x82, CACHE,  L2,     8,  256*K,  32  },
    { 0x83, CACHE,  L2,     8,  512*K,  32  },
    { 0x84, CACHE,  L2,     8,  1*M,    32  },
    { 0x85, CACHE,  L2,     8,  2*M,    32  },
    { 0x86, CACHE,  L2,     4,  512*K,  64  },
    { 0x87, CACHE,  L2,     8,  1*M,    64  },
    { 0xB0, TLB,    INST,       4,  SMALL,  128 },
    { 0xB1, TLB,    INST,       4,  LARGE,  8   },
    { 0xB2, TLB,    INST,       4,  SMALL,  64  },
    { 0xB3, TLB,    DATA,       4,  SMALL,  128 },
    { 0xB4, TLB,    DATA1,      4,  SMALL,  256 },
    { 0xBA, TLB,    DATA1,      4,  BOTH,   64  },
    { 0xCA, STLB,   DATA1,      4,  BOTH,   512 },
    { 0xD0, CACHE,  L3,     4,  512*K,  64  },
    { 0xD1, CACHE,  L3,     4,  1*M,    64  },
    { 0xD2, CACHE,  L3,     4,  2*M,    64  },
    { 0xD3, CACHE,  L3,     4,  4*M,    64  },
    { 0xD4, CACHE,  L3,     4,  8*M,    64  },
    { 0xD6, CACHE,  L3,     8,  1*M,    64  },
    { 0xD7, CACHE,  L3,     8,  2*M,    64  },
    { 0xD8, CACHE,  L3,     8,  4*M,    64  },
    { 0xD9, CACHE,  L3,     8,  8*M,    64  },
    { 0xDA, CACHE,  L3,     8,  12*M,   64  },
    { 0xDC, CACHE,  L3,     12,     1536*K, 64  },
    { 0xDD, CACHE,  L3,     12,     3*M,    64  },
    { 0xDE, CACHE,  L3,     12,     6*M,    64  },
    { 0xDF, CACHE,  L3,     12, 12*M,   64  },
    { 0xE0, CACHE,  L3,     12, 18*M,   64  },
    { 0xE2, CACHE,  L3,     16, 2*M,    64  },
    { 0xE3, CACHE,  L3,     16, 4*M,    64  },
    { 0xE4, CACHE,  L3,     16, 8*M,    64  },
    { 0xE5, CACHE,  L3,     16, 16*M,   64  },
    { 0xE6, CACHE,  L3,     16, 24*M,   64  },
    { 0xF0, PREFETCH, NA,       NA, 64, NA  },
    { 0xF1, PREFETCH, NA,       NA, 128,    NA  }
};

The problem right now is that I still cannot get the correct size of my L3 cache(when ecx=1, I get 22 i.e. 512K, but the correct value is 6MB). Also, there seems to be some conflicts in terms of the size of my L2 cache(43(when ecx=2) and 21(when ecx=0) )

A: So, your data seems to be reasonably correct, just that you are using an old reference. Unfortunately, Intel's website is either broken presently or it doesn't like Firefox and/or Linux.
76036301
76 means trace cache with 64K ops.
03 means 4 way DATA TLB with 64 entries.
63 is 32KB L1 cache - the source here shows that value, which is not in your docs.
01 means 4 way Instruction TLB with 32 entries.
00f0b5ff gives
00 "nothing"
f0 prefetch, 64 entries.
0b Instruction 4 way TLB for large pages, 4 entries.
b5 is not documented even on that link. [guessing small data TLB]
To get L2 and L3 cache sizes, you need to use CPUID with EAX=4, and set ECX to 0, 1, 2, ... for each caching level. The linked code shows this, and Intel's docs have details on which bits mean what.

A: Intel's Instruction Set Reference has all the relevant information you need (at around page 263), and is actually up to date unlike every other source I have found.
Probably the best way to get the cache info is mentioned in that reference.
When eax = 4 and ecx is the cache level,
Ways = EBX[31:22]

Partitions = EBX[21:12]

LineSize = EBX[11:0]

Sets = ECX

Total Size = (Ways + 1) * (Partitions + 1) * (Line_Size + 1) * (Sets + 1)

So when CUPID is called with eax = 4 and ecx = 3, you can get your L3 cache size by doing the computation above. Using the OP's posted data:
ebx: 02c0003f
ecx: 00001fff

Ways = 63
Partitions = 0
LineSize = 11
Sets = 8191

Total L3 cache size = 6291456
Which is what was expected.


Q: Android 6 Permissions - managing foreign apps permissions Using the package manager I can see what permissions foreign apps request. But is it possible to find out what permissions the user allows for other apps? And can you change the permissions of other apps from your application? These questions apply on non-rooted devices.

A: I solved this problem in a rooted device; the way I follow to manage permission require root privileges:
Process su = Runtime.getRuntime().exec("su");
            DataOutputStream dos = new DataOutputStream(su.getOutputStream());
        dos.writeBytes("pm revoke/grant " + packageName + " " + permissionName);
        dos.flush();
        dos.close();

Maybe studing android security architecture you will be cabable to find a way to solve the problem on non-rooted devices but you'll waste a lot of time.


Q: 0 value not working when import excel sheet for if condition in laravel excel Excel file as below
Id |   pro name | status
1  |   test.          | 0

*

*Laravel 5.6

*PHP 7.2

*Maatwebsite/excel 2.*

Below my Laravel code
$data = Excel::load($path)->get();

if print $data then its show me 0.
echo $data[0]->status; // output:0

if($data[0]->status === ""){
    echo "Status field required"; exit;
}
if($data[0]->status === 0 || $data[0]->status === 1){
    echo "successfully";exit;
}else{
    echo "status format 0 or 1 required"; exit;
}

if I set 0 value in the status column then also print Status field required.
if I set (int)$data[0]->status then Null value show as 0.so how can i solve this issues ?

A: Excel sheet import value always return in string format so you try below code
$status = $data[0]->status;
if(is_null($status)){
    echo "Status field required";exit;
}else{
    $status = (int)$status;
}
if($status === 0 || $status === 1){
    echo "successfully";exit;
}else{
    echo "status format 0 or 1 required"; exit;
}


Q: Attempting to set variable based on conditional statement in Python So today is literally my first day of learning a programming language so I'm very new to Python. I'm taking the online Python for Informatics course at the University of Michigan and our first real assignment is to create a simple gross pay rate calculator.
That was simple enough so I decided I wanted to expand what the program could do to calculate net pay and account for taxes. The trouble I'm having is determining how I can dynamically (if that's even the right word) set the value of the variable "taxrate" based on a series of conditional statements.
I have yet to find the answer in searching through Python's site and Stack Overflow. I think my limited understanding of programming probably is limiting my ability to interpret properly what I have found.
Just looking for a little help:
Code:
#This program is intended to calculate the net pay of employees
#This first section includes a loop for mistakes and finds gross pay

while True:

hours = raw_input('How many hours do you work weekly?')
hours1 = float(hours)
rate = raw_input('What is your hourly rate of pay?')
rate1 = float(rate)
grosspay = hours1 * rate1
taxstatus = raw_input('Do you pay taxes?')

#This secdtion is establishing the tax bracket the user falls into
taxbracket = taxrate
if grosspay <= 1000:
    taxrate = 0.90
if grosspay > range(1000,1500):
    taxrate = 0.78
if grosspay >= 1501:
    taxrate = 0.63

# This section is intended to calculate pay after taxes
grosspay = hours1 * rate1
if taxstatus == 'yes':
    netpay = grosspay * taxrate
print'Your weekly pay after taxes is',netpay
if not taxstatus:
    print grosspay

When I run this in PyCharm it lets me know that "taxrate" hasn't been defined. I ultimately want the program to set the "taxrate" based on what the users "grosspay" is. Is what I'm trying to do possible? I'm assuming it is and that I just don't understand how to do it.
Any help is greatly appreciated and in case someone is wondering what the loop is for I've got a user error checker that I'm working on after this portion of the program completes.

A: Your logic is a bit suspect in if grosspay > range(1000, 1500). What would it mean to be "greater" than a range of numbers? my guess is that the grosspay you input is, in fact, within the range [1000, 1500), so it hits this logic bug in your code and fails to assign it to anything.
The usual way to check if a number is within a range is to use the in operator.
if some_num in range(1, 10):
    print("some_num is 1, 2, 3, 4, 5, 6, 7, 8, or 9")

However you'll notice that some_num MUST be contained in the integer range [1, 9] for this to trigger. If some_num is 7.5, this will fail. This is incredibly likely in the case of gross pay. What are the chances of someone's pay coming out to an exactly even dollar amount?
Instead what you could do is:
if grosspay <= 1000:
    taxrate = 0.90
elif 1000 < grosspay <= 1500:
    taxrate = 0.78
elif 1500 < grosspay:
    taxrage = 0.63

using elif instead of a series of ifs makes the code slightly more efficient, since if/elif/else is by definition one block that is mutually exclusive. In other words:
a = 1
b = 2

if a == 1:
    print("This gets done!")
if b == 2:
    print("This gets done!")

if a == 1:
    print("This gets done!")
elif b == 2:
    print("BUT THIS DOESN'T!")
else:
    print("(this doesn't either...)")


Q: unknown permission android.permission.RECORD_VIDEO Suddenly in my logs in "warn" I've found this :
unknown permission android.permission.RECORD_VIDEO

And this happened on a device that fails to do a MediaRecorder.start() method with simple and uninformative "start fails" error message.
java.lang.RuntimeException: start failed.
    at android.media.MediaRecorder.start(Native Method)
    at com.vladdrummer.headsup.ScreenVideoRecorder.record(ScreenVideoRecorder.java:94)

App is working on many devices, but some have this kind of a problem - it fails to start, although , preparing went fine
So, may be theese two errors are connected? what should I do with "unknown permission android.permission.RECORD_VIDEO" ??

A: There is no permission as
android.permission.RECORD_VIDEO

See here
Ideally you should be using these permission
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Also manifest should have
<uses-feature android:name="android.hardware.Camera"/>


Q: How to edit a user in ASP.NET Identity I am new to the ASP.NET Identity framework and I am trying to do some things. What I want to do is to edit the user who has already register and then update the user details to the database...
Previously, I use entity framework, and then its generated my controller view and model it self. But I want to update my user details and getting a list of users into a list..
How do I do these stuff? I have seen role methods..but I never understand,
How can I do? without using role..Because, I don't need administrator purposes. Only, I want to update my user details.

A: There is a class that comes with asp.net identity called UserManager
this class will help with the user information management you can first find a user using either

*

*FindByIdAsync

*FindByEmailAsync

*FindByUserName

with the user object, you can then update it with new information for the user profile
and then use the method UpdateAsync to update the user information in the database.
when it comes to getting a list of users you can use the IdentityDbContext class to get the list of users from.

A: Create a dbcontext object "context" and you also need to create a model class "UserEdit" and include those fields in it which you wants to edit.
private ApplicationDbContext context = new ApplicationDbContext();
// To view the List of User
 public ActionResult ListUsers ()
        {
            return View(context.Users.ToList());
        }

public ActionResult EditUser(string email)
        {
            ApplicationUser appUser = new ApplicationUser();
            appUser = UserManager.FindByEmail(email);
            UserEdit user = new UserEdit();
            user.Address = appUser.Address;
            user.FirstName = appUser.FirstName;
            user.LastName = appUser.LastName;
            user.EmailConfirmed = appUser.EmailConfirmed;
            user.Mobile = appUser.Mobile;
            user.City = appUser.City;

            return View(user);
        }

    [HttpPost]
    public async Task<ActionResult> EditUser(UserEdit model)
    {

        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
        var manager = new UserManager<ApplicationUser>(store);
        var currentUser = manager.FindByEmail(model.Email);
        currentUser.FirstName = model.FirstName;
        currentUser.LastName = model.LastName;
        currentUser.Mobile = model.Mobile;
        currentUser.Address = model.Address;
        currentUser.City = model.City;
        currentUser.EmailConfirmed = model.EmailConfirmed;
        await manager.UpdateAsync(currentUser);
        var ctx = store.Context;
        ctx.SaveChanges();
        TempData["msg"] = "Profile Changes Saved !";
        return RedirectToAction("ListUser");
    }

// for deleting a user
public ActionResult DeleteUser(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = context.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(context.Users.Find(id));
        }

        public async Task<ActionResult> UserDeleteConfirmed(string id)
        {
            var user = await UserManager.FindByIdAsync(id);

            var result = await UserManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                TempData["UserDeleted"] = "User Successfully Deleted";
                return RedirectToAction("ManageEditors");
            }
            else
            {
                TempData["UserDeleted"] = "Error Deleting User";
                return RedirectToAction("ManageEditors");
            }
        }

Below is the View for ListUser:

@model IEnumerable<SampleApp.Models.ApplicationUser>

@{
    ViewBag.Title = "ListUsers";
}

@ViewBag.Message

ManageEditors

                        S.No.

                        Email

                     EmailConfirmed

                       FirstName

                       LastName

                        Mobile

                @{ int sno = 1;
                   foreach (var item in Model)
                {

                         @(sno++)

                            @Html.DisplayFor(modelItem => item.Email)

                            @Html.DisplayFor(modelItem => item.EmailConfirmed)

                            @Html.DisplayFor(modelItem => item.FirstName)

                            @Html.DisplayFor(modelItem => item.LastName)

                            @Html.DisplayFor(modelItem => item.Mobile)

                            @Html.ActionLink("Edit", "EditUser", new { email=item.Email})
                            @Html.ActionLink("Delete", "DeleteUser", new { id = item.Id })

                }
}

// below is my UserEdit Model
 public class UserEdit
    {
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name = "Mobile")]
        public string Mobile { get; set; }

        [Display(Name = "Address")]
        public string Address { get; set; }

        [Display(Name = "City")]
        public string City { get; set; }

        public bool EmailConfirmed { get; set; }
    }

//below is my IdentityModel.cs class which have ApplicationDbContext class
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace SampleApp.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
        //Extra column added to auto generated Table by Code First approach (ASPNETUSERS) by Entity Framework
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string DOB { get; set; }
        public string Sex { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Mobile { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

Hope this help you :)


Q: ASP.NET C# OData Service + Navigation Property + $expand = null. What am I missing? I will try to explain my problem as thoroughly as possible with a simplified example. Please note that I am NOT using Entity Framework.
I have this model:
public class Person
{
    [Key]
    public Guid Id { get; set; }
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public List<Employment> Employments { get; set; }
}

public class Employment
{
    public string Role { get; set; }
    public Guid? ManagerId { get; set; }
    public virtual Person Manager { get; set; }
}

I create an in-memory data source:
public class MyDataSource
{
    private static MyDataSource instance = null;
    public static MyDataSource Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new MyDataSource();
            }
            return instance;
        }
    }
    public List<Person> Persons  { get; set; }
    private MyDataSource()
    {
        this.Persons = new List<Person>();
        this.Persons.AddRange(new List<Person>
        {
            new Person()
            {
                Id = Guid.Parse("00000000-0000-0000-0000-000000000001"), //Just for simplicity
                GivenName = "John",
                FamilyName = "Doe",
                Employments = new List<Employment>()
                {
                    new Employment()
                    {
                        Role = "Boss"
                    }
                }
            },
            new Person()
            {
                Id = Guid.Parse("00000000-0000-0000-0000-000000000002"), //Just for simplicity
                GivenName = "Clark",
                FamilyName = "Kent",
                Employments = new List<Employment>()
                {
                    new Employment()
                    {
                        Role = "Worker",
                        ManagerId = Guid.Parse("00000000-0000-0000-0000-000000000001"), //Just for simplicity
                    }
                }
            }
        });
    }
}

I have this controller:
[EnableQuery]
public class PersonsController : ODataController
{
    public IHttpActionResult Get()
    {
        return Ok(MyDataSource.Instance.Persons)
    }
}

I configure the EndPoint:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapODataServiceRoute("ODataRoute", "odata", CreateEdmModel());
        config.Select().Expand().Filter().OrderBy().MaxTop(null).Count()
    }

    public static IEdmModel CreateEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        var persons = builder.EntitySet<Person>("Persons");
        builder.ComplexType<Employment>().HasOptional(e => e.Manager, (e, p) => e.ManagerId == p.Id);
        return builder.GetEdmModel();
    }
}

Checking the $metadata I see this:
<NavigationProperty Name="Manager" Type = "MyNamespace.Person">
    <ReferentialConstraint Property="ManagerId" ReferenceProperty="Id" />
</NavigationProperty

Everything looks fine from what I can tell but:
https://example.com/odata/persons?$expand=Employments/Manager
receives everything fine but:
Manager is null for both persons. I was expecting to see John Doe on Clark Kents employment.
What am I missing?

A: I have solved it myself.
I realised that it doesn't work like I thought and that I have to add a reference to the manager directly in MyDataSource. After that it works to $expand the manager.


Q: HH:MM:SS:Msec to HH:MM:SS in stored procedure I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in  Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
@timeEntryID int,
@status int output
as begin
set nocount on;
declare @Date dateTime;
set @Date=GETDATE();
    update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, @Date)%(60*60*24),0),114)),
    IsTaskCompleted=1
    where productionTimeEntryID=@timeEntryID
    set @status=1;
    return @status;
end

A: You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
     @timeEntryID int,
     @status int output
AS BEGIN
   SET NOCOUNT ON;

   DECLARE @Date DATETIME;
   SET @Date = GETDATE();

   UPDATE dbo.Production
   SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, @Date)%(60*60*24),0), 108),
       IsTaskCompleted = 1
   WHERE
       productionTimeEntryID = @timeEntryID

   SET @status = 1;

   RETURN @status;
END

See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!


Q: Add(3)(5) nn.Sequential. How it works? class Add(nn.Module):
    def __init__(self, value):
        super().__init__()
        self.value = value

    def forward(self, x):
        return x + self.value

calculator = nn.Sequential(
    Add(3),
    Add(2),
    Add(5),
)

x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])

I made Add Model. but I can't understand how 'nn.Sequential' works.
at the firsttime, I understood like this
add = Add(torch.tensor([1]))
add(3) # tensor([4])
add = Add(add(3))
add(2) # tensor([6])
add = Add(add(2))
add(5) # tensor([11])

but Add(3)(1) also works.
I can't understand why 'Add(3)(1)' works. help me plz

A: The core thing to remember is that when you instantiate a Module class, you are creating a callable object, i.e. something that can behave like a function.
In plain English and step by step:

*

*When you write something like add5 = Add(5), what you are doing is assigning an "instance" of the PyTorch model Add to add5

*More specifically, you are passing 5 to the Add class's __init__ method, and so its value attribute is set to 5.

*PyTorch Modules are "callable" meaning you can call them like functions. The function you call when you use an instance of a Module is that instance's forward method. So concretely, with our add5 object, if we pass a value, x = 10, by writing something like add5(10) it is like we ran x + add5.value, which equals 10 + 5 = 15.

Now putting this together, we should view the Sequential interface for building neural network models that don't have branching structures as just sequentially invoking each of the instantiated Modules' forward methods.
Omitting the definition of Add and focussing just on calculator as a series of computations we have the following (I've added the comments to show you what you should think of at each step)
calculator = nn.Sequential(
            # given some input tensor x...
    Add(3), # run: x = x + self.value with self.value = 3
    Add(2), # run: x = x + self.value with self.value = 2
    Add(5), # run: x = x + self.value with self.value = 5
)

Now we can see that it's reasonable to expect that if we pass the value 1 (albeit wrapped up as a PyTorch Tensor) we are just doing 1 + 3 + 2 + 5 which of course equals 11. PyTorch returns us back the value still as a Tensor object.
x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])

Finally, Add(3)(5)* works for exactly this same reason! With Add(3) we are getting an instance of the Add class with the value to add being 3. We then use it immediately with the somewhat unintuitive syntax Add(3)(5) to return the value 3 + 5 = 8.
*I think you intended the capitalised class name, not an instance of the class

A: You understand it right, the Sequential class in a nutshell just calls provided modules one by one. Here's the code of the forward method
    def forward(self, input):
        for module in self:
            input = module(input)
        return input

here, for module in self just iterates through the modules provided in a constructor (Sequential.__iter__ method in charge of it).
Sequential module calls this method when you call it using () syntax.
calculator = nn.Sequential(
    Add(3),
    Add(2),
    Add(5),
)
output = calculator(torch.tensor([1]))

But how does it work? In python, you could make objects of a class callable, if you add __call__ method to the class definition. If the class does not contain this method explicitly, it means that it possibly was inherited from a superclass. In case of Add and Sequential, it's Module class that implements __call__ method. And __call__ method calls 'public' forward method defined by a user.
It could be confusing that python uses the same syntax for the object instantiation and function or method call. To make a difference visible to the reader, python uses naming conventions. Classes should be named in a CamelCase with a first capital letter, and objects in a snake_case (it's not obligatory, but it's the rule that better to follow).
Just like in you example, Add is a class and add is a callable object of this class:
add = Add(torch.tensor([1]))

So, you can call add just like you have called a calculator in you example.
>>> add = Add(torch.tensor([1]))
>>> add(2)
Out: tensor([3])

But that won't work:
>>> add = Add(torch.tensor([1]))
>>> add(2)(1)
Out:
----> 3 add(2)(1)
TypeError: 'Tensor' object is not callable

That means that add(2) returns a Tensor object that does not implement __call__ method.
Compare this code with
>>> Add(torch.tensor([1]))(2)
Out:
tensor([3])

This code is the same as the first example, but rearranged a little bit.
--
To avoid confusion, I usually name objects differently: like add_obj = Add(1). It helps me to highlight a difference.
If you are not sure what you're working with, use functions type and isinstance. They would help to find out what's going on.
For example, if you check the add object, you could see that it's a callable object (i.e., it implements __call__)
>>> from typing import Callable
>>> isinstance(add, Callable)
True

And for a tensor:
>>> from typing import Callable
>>> isinstance(add, torch.tensor(1))
False

Hence, it will rase TypeError: 'Tensor' object is not callable in case you call it.
If you'd like to understand how python double-under methods like init or call work, you could read this page that describes python data model
(It could be a bit tedious, so you could prefer to read something like Fluent Python or other book)


Q: DialogFragment return onClick result to MainActivity This has been asked and answered at least a dozen times yet I still can't get mine going. I've tried 4 or more of the listed answers and get no errors, a result simply isn't returned. here's the most recent code that I've tried. I really wanted this solution to work because it was the most readable to me.
I welcome any suggestions, Thanks.
MainActivity
...
private void showAlertDialog() {
    FragmentManager fm = getSupportFragmentManager();
    MyAlertDialogFragment alertDialog =
    MyAlertDialogFragment.newInstance("Some title");
    alertDialog.setTargetFragment(alertDialog, 1);
    alertDialog.show(fm, "fragment_alert");
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intentdata)
{
    // Stuff to do, dependent on requestCode and resultCode
    if(requestCode == 1)  // 1 is an arbitrary number, can be any int
    {
        // This is the return result of your DialogFragment
        if(resultCode == 1) // 1 is an arbitrary number, can be any int
        {
            Toast.makeText(MainActivity.this, "result received",
            Toast.LENGTH_SHORT).show();
            Log.d("onActivityResult", "result received" + resultCode);
        }
    }
}

MyDialogFragment
...
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;

...

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    AlertDialog.Builder alertDialogBuilder = new
    AlertDialog.Builder(getActivity());
    alertDialogBuilder.setTitle(title);
    alertDialogBuilder.setMessage("Are you sure?");
    alertDialogBuilder.setPositiveButton("OK",  new
    DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // on success
        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new
    DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            getTargetFragment().onActivityResult(getTargetRequestCode(),
            1, getActivity().getIntent());
            dialog.dismiss();
        }
    });

    return alertDialogBuilder.create();
}

A: I found it, added a onDialogOKPressed method to my MainActivity and put this inside the onClick of my dialog ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
so now it looks like this
MyDialogFragment
...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setTitle(title);
    alertDialogBuilder.setMessage("Are you sure?");
    alertDialogBuilder.setPositiveButton("OK",  new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // on success
            ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            getTargetFragment().onActivityResult(getTargetRequestCode(), 1, getActivity().getIntent());
            dialog.dismiss();
        }
    });

    return alertDialogBuilder.create();
}

MainActivity
...
public void onDialogOKPressed () {
    // Stuff to do, dependent on requestCode and resultCode
    Toast.makeText(MainActivity.this, "OK pressed", Toast.LENGTH_SHORT).show();
}


Q: Bitbucket call webhook php code not executing git command and when I execute from command prompt same command runs perfectly When I commit my code form source tree bitbucket triggers a webhook that hit php code
exec('cd /d ' . $web_root_dir . ' && '. $git_bin_path  . ' pull origin master');

it won't execute but when I copy the same command by copying from the log on command prompt it execute perfectly.
I've tried my heart out on this but no result.


Q: Android, Java, Eclipse: Syntax Error on token "if", ( expected after this token Why do i get the following Syntax error ?
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
    Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
    if (isFirstLaunch == true) {   // <<<< Syntax Error ?
    // Do Something
    }
}

Error:
Multiple Markers at this line
-Syntax error on token "if", ( expected after this token
-Line breakpoint:LaunchEngine[line:30] - onCreate(Bundle)

A: Try it like this:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
    boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
    if (isFirstLaunch) {   // <<<< Syntax Error ?
    // Do Something
    }
}

A: Try this...

*

*First see that you have declared isFirstLaunch as boolean, if you have it should work.

*No need to use isFirstLaunch == true
if(isFirstLaunch)

A: You are getting a Boolean instead of a boolean. So you should use either :
Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch.booleanValue()) {
}

or :
boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch) {
}

And try to click on the error icon on the left, and choose "Clear all lint marker" (if it's there).


Q: Firefox and IE6 issue with document.ready() I have created an html page with a Tabber tab functionality.

*

*Each tab has its own table that loads when the tab is clicked and only loads once on the initial tab click to stop the tables loading more than once.

*Each tab table exists in its own .jsp html file and is loaded through javascript using the $("#tab1").load('tabqtable.jsp'); call.

I currently have a document.ready() within the individual tab html files to run when each tab loads. The scripts run and work perfectly in Chrome, but the document.ready() functions don't run in Firefox and IE6.
I can put an alert(); outside of the document.ready() function and it works, so I know the script tag is being run. I also tried moving all the javascript to the return function call in the .load() function so the javascript will run when the .load() runs successfully from the m/ain html page, but still ended up with the same result.
I am at a loss and would really appreciate some help on this issue if I could get it. The tables load perfectly, I just don't get any of the functionality I need in order to interact with the table. It's not the scripts I am running either, because they all work with the main html page. Thanks for any help in advance.

A: well it looks like you are already using a framework like jquery...use $(document).ready (assuming that's jquery you are using...) the point of frameworks like jquery is that it (in principle) should be crossbrowser compatible.


Q: How to increase the base address of this string? I'm trying to get a pointer to the fourth element of this array, but I keep getting type mismatch errors when doing so. What am I doing wrong? How do I fix this?
    int main()
    {
        char str[]="0111010";
        str = str+3;
        printf("%s",str);
        return 0;
    }

A: The line
str = str + 3;

isn't legal C code. In C, you can't assign one array variable to another. (There's no fundamental reason why the language couldn't have made this work; it's just not supported.)
That being said, the expression str + 3 is a perfectly legal expression that results in a pointer to the third (zero-indexed) element of the array. You could either print it by writing
printf("%s\n", str + 3);

or by writing
char* midPtr = str + 3;
printf("%s\n", midPtr);

Either approach works. That first one is probably easier if you just need to do this once, and the second one is a bit easier if you plan on using that pointer more than once.


Q: alignment breaks when placed inside other container I am exploring Flexbox and am trying to align some items. The following code works and shows what I want to achieve (successful codepen here):

.labelinput {
  display: flex;
  flex-flow: row;
  margin: 1px;
}
.labelinput > *:first-child {
  flex-basis: 10em;
  flex-grow: 0;
  flex-shrink: 0;
}
.labelinput > *:nth-child(2) {
  flex-grow: 1;
  flex-shrink: 1;
  border: 3px solid purple;
}

1st input

this is just a div

2nd:

  <input type="text" name="foo" value="this is an input box" />

The above code produces the nicely align output shown below:

My reading of the above code is that it works because the first child in every div has a determined size (10em) and is totally inflexible (flex-grow and flex-shrink set to 0) whereas the second child has no determined size and will grow and shrink as appropriately.
What breaks though is when I try to embed the two top-level div elements (of class labelinput) into yet another container (failing codepen here):

#container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  margin: 5px;
  border: 1px solid grey;
}
.labelinput {
  display: flex;
  flex-flow: row;
  margin: 1px;
}
.labelinput > *:first-child {
  flex-basis: 7em;
  flex-grow: 0;
  flex-shrink: 0;
}
.labelinput > *:nth-child(2) {
  flex-grow: 1;
  flex-shrink: 1;
  border: 3px solid purple;
}

1st input

this is just a div

2nd:

    <input type="text" name="foo" value="this is the input box" />

The above produces the following unsatisfactory output:

I can't explain why this fails as I am just inserting the content of the successful case into a container that simply performs the default vertical stacking (flex-direction: column;).
By experimentation I have discovered that removing the align-items property from the outer level container (#container) fixes the problem but I can't explain that either.
I understand that the outermost container (#container) is asked to layout two other containers (of class labelinput) so whatever property I set for align-items in the outermost container should apply to the inner containers as a whole, not change the layout of their internal items.
Moreover I can't explain why the layout is changed based on the element type when there's nothing in my CSS that differentiates between items of element div versus items of element input.

A:
I can't explain why this fails as I am just inserting the content of the successful case into a container that simply performs the default vertical stacking (flex-direction: column).

The difference is that this new primary container has align-items: flex-start.

By experimentation I have discovered that removing the align-items property from the outer level container (#container) fixes the problem but I can't explain that either.

When you nest the .labelinput flex containers in the larger container (#container), then the .labelinput elements become flex items, in addition to flex containers.
Since the #container flex container is set to flex-direction: column, the main axis is vertical and the cross axis is horizontal1.
The align-items property works only along the cross axis. It's default setting is align-items: stretch2, which causes flex items to expand the full width of the container.
But when you override the default with align-items: flex-start, like in your code, you pack the two labelinput items to the start of the container, as illustrated in your problem image:

Because stretch is the default value for align-items, when you omit this property altogether, you get the behavior you want:

I understand that the outermost container (#container) is asked to layout two other containers (of class labelinput) so whatever property I set for align-items in the outermost container should apply to the inner containers as a whole, not change the layout of their internal items.

The outermost container is not changing the layout of the inner container's children. At least not directly.
The align-items: flex-start rule on the outermost container is applying directly to the inner containers. The internal items of the inner containers are just responding to the sizing adjustment of their parent.
Here's an illustration of align-items: flex-start impacting .labelinput (red borders added).

#container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  margin: 5px;
  border: 1px solid grey;
}
.labelinput {
  display: flex;
  flex-flow: row;
  margin: 1px;
  border: 2px dashed red;
}
.labelinput > *:first-child {
  flex-basis: 7em;
  flex-grow: 0;
  flex-shrink: 0;
}
.labelinput > *:nth-child(2) {
  flex-grow: 1;
  flex-shrink: 1;
  border: 3px solid purple;
}

1st input

this is just a div

2nd:

    <input type="text" name="foo" value="this is the input box" />

Moreover I can't explain why the layout is changed based on the element type when there's nothing in my CSS that differentiates between items of element div versus items of element input.

There may be no difference between div and input in your code, but there are intrinsic differences.
Unlike a div, an input element has a minimum width set by the browser (maybe to always allow for character entry).
You may be able to reduce the input width by applying min-width: 0 or overflow: hidden3.

Footnotes
1. Learn more about flex layout's main axis and cross axis here: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?
2. Learn more about the align-items property in the spec: 8.3. Cross-axis Alignment: the align-items and align-self properties
3. Why doesn't flex item shrink past content size?


Q: Matrix multiplication $AB=0$ so $A=0 $ or $B=0$ I have tried with the idea of $AA^T=0 $ and use the trace, but nothing changed.
I have also to prove : if $AB=0 $ then $BA=0$ .

A: The ring of square matrices is not integral  i.e if $AB=0$ then it is not necessary that one of them is the zero matrix.
take for example:
$$
   A= \begin{matrix}
    0 & 0 & 0 \\
    0 & 0 & 0 \\
    0 & 0 & z \\
    \end{matrix}
$$
and
$$
   B= \begin{matrix}
    1 & 0 & 1 \\
    0 & 0 & 0 \\
    0 & 0 & 0 \\
    \end{matrix}
$$
This example also shows (for $z\neq0$) that if $AB=0$ then it does not mean necessarilly that $BA=0$ .


Q: proportion data frame for each factor level based on another column I would like to summarize a data frame by month where each column is the proportion of each factor level based on the Records column in the data frame below. I have been attempting to use dplyr but haven't quite figured it out.
library(dplyr)
set.seed(100)
df=data.frame(Month=rep(c("1/1/2017","2/1/2017","3/1/2017","4/1/2017","5/1/2017","6/1/2017","7/1/2017",

                          "8/1/2017","9/1/2017","10/1/2017","11/1/2017","12/1/2017"),10),

              Records=round(runif(120,6000,10000),0),

              V1=as.factor(sample(c("T","F"),120,replace=TRUE)),

              V2=as.factor(sample(c("A","B","C"),120,replace=TRUE)),

              V3=as.factor(sample(c("X","Y","Z","W"),120,replace=TRUE)),

              V4=as.factor(sample(c("YES","NO","Maybe"),120,replace=TRUE)))

Here is what I would like the output to be
> dput((resultsdf))
structure(list(Month = c("1/1/2017", "2/1/2017", "3/1/2017",
"4/1/2017", "5/1/2017", "6/1/2017", "7/1/2017", "8/1/2017", "9/1/2017",
"10/1/2017", "11/1/2017", "12/1/2017"), V1.F = c(0.4, 0.71, 0.63,
0.35, 0.37, 0.41, 0.37, 0.61, 0.29, 0.5, 0.38, 0.82), V2.T = c(0.6,
0.29, 0.37, 0.65, 0.63, 0.59, 0.63, 0.39, 0.71, 0.5, 0.62, 0.18
), V2.A = c(0.2, 0.28, 0.3, 0.31, 0.29, 0.3, 0.32, 0.45, 0.1,
0.41, 0.3, 0.11), V2.B = c(0.59, 0.33, 0.19, 0.5, 0.51, 0.19,
0.59, 0.22, 0.77, 0.2, 0.41, 0.16), V2.C = c(0.22, 0.38, 0.51,
0.19, 0.21, 0.51, 0.09, 0.32, 0.12, 0.39, 0.29, 0.73), V3.W = c(0.42,
0.11, 0, 0.21, 0.23, 0.3, 0.12, 0.45, 0.32, 0.28, 0.19, 0.19),
    V3.X = c(0.19, 0.32, 0.18, 0.19, 0.19, 0.11, 0.19, 0, 0.27,
    0.11, 0.23, 0.19), V3.Y = c(0.3, 0.29, 0.39, 0.4, 0.18, 0.4,
    0.62, 0.34, 0.21, 0.33, 0.21, 0.1), V3.Z = c(0.09, 0.28,
    0.43, 0.2, 0.4, 0.19, 0.07, 0.2, 0.2, 0.29, 0.38, 0.53),
    V4.Maybe = c(0.4, 0.23, 0.39, 0.38, 0.62, 0.5, 0.2, 0.4,
    0.4, 0.32, 0.3, 0.49), V4.NO = c(0.32, 0.5, 0.39, 0.31, 0.18,
    0.29, 0.22, 0.42, 0.29, 0.3, 0.44, 0.3), V4.YES = c(0.28,
    0.27, 0.22, 0.31, 0.2, 0.21, 0.58, 0.18, 0.3, 0.39, 0.26,
    0.22)), row.names = c(NA, -12L), class = c("tbl_df", "tbl",
"data.frame"), spec = structure(list(cols = list(Month = structure(list(), class = c("collector_character",
"collector")), V1.F = structure(list(), class = c("collector_double",
"collector")), V2.T = structure(list(), class = c("collector_double",
"collector")), V2.A = structure(list(), class = c("collector_double",
"collector")), V2.B = structure(list(), class = c("collector_double",
"collector")), V2.C = structure(list(), class = c("collector_double",
"collector")), V3.W = structure(list(), class = c("collector_double",
"collector")), V3.X = structure(list(), class = c("collector_double",
"collector")), V3.Y = structure(list(), class = c("collector_double",
"collector")), V3.Z = structure(list(), class = c("collector_double",
"collector")), V4.Maybe = structure(list(), class = c("collector_double",
"collector")), V4.NO = structure(list(), class = c("collector_double",
"collector")), V4.YES = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector"))), class = "col_spec"))

A: Please check your expected output. I believe there are some mistakes.
Here is a tidyverse option:
library(tidyverse)
df %>%
    gather(key, value, -Month, -Records) %>%
    group_by(Month, key, value) %>%
    summarise(freq = n()) %>%
    mutate(freq = freq / sum(freq)) %>%
    unite(col, key, value, sep = ".") %>%
    spread(col, freq)
## A tibble: 12 x 13
## Groups:   Month [12]
#   Month  V1.F  V1.T  V2.A  V2.B  V2.C  V3.W  V3.X  V3.Y  V3.Z V4.Maybe V4.NO
#   <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>    <dbl> <dbl>
# 1 1/1/…   0.4   0.6   0.2   0.6   0.2   0.4   0.2   0.3   0.1      0.4   0.3
# 2 10/1…   0.5   0.5   0.4   0.2   0.4   0.3   0.1   0.3   0.3      0.3   0.3
# 3 11/1…   0.4   0.6   0.3   0.4   0.3   0.2   0.2   0.2   0.4      0.3   0.4
# 4 12/1…   0.8   0.2   0.1   0.2   0.7   0.2   0.2   0.1   0.5      0.5   0.3
# 5 2/1/…   0.7   0.3   0.3   0.3   0.4   0.1   0.3   0.3   0.3      0.2   0.5
# 6 3/1/…   0.6   0.4   0.3   0.2   0.5  NA     0.2   0.4   0.4      0.4   0.4
# 7 4/1/…   0.4   0.6   0.3   0.5   0.2   0.2   0.2   0.4   0.2      0.4   0.3
# 8 5/1/…   0.4   0.6   0.3   0.5   0.2   0.2   0.2   0.2   0.4      0.6   0.2
# 9 6/1/…   0.4   0.6   0.3   0.2   0.5   0.3   0.1   0.4   0.2      0.5   0.3
#10 7/1/…   0.4   0.6   0.3   0.6   0.1   0.1   0.2   0.6   0.1      0.2   0.2
#11 8/1/…   0.6   0.4   0.5   0.2   0.3   0.5  NA     0.3   0.2      0.4   0.4
#12 9/1/…   0.3   0.7   0.1   0.8   0.1   0.3   0.3   0.2   0.2      0.4   0.3
## ... with 1 more variable: V4.YES <dbl>

A: Here is an alternative approach which uses the table() and prop.table() functions from base R and dcast() for reshaping to wide format. Unfortunately, I am not fluently enough in dplyr so I resort to data.table for grouping.
library(data.table)
library(magrittr)
setDT(df)[, lapply(.SD, function(.x) table(.x) %>% prop.table %>% as.data.table) %>%
    rbindlist(idcol = TRUE), .SDcols = V1:V4, by = Month] %>%
  dcast(Month ~ .id + .x)

        Month V1_F V1_T V2_A V2_B V2_C V3_W V3_X V3_Y V3_Z V4_Maybe V4_NO V4_YES
 1:  1/1/2017  0.4  0.6  0.2  0.6  0.2  0.4  0.2  0.3  0.1      0.4   0.3    0.3
 2: 10/1/2017  0.5  0.5  0.4  0.2  0.4  0.3  0.1  0.3  0.3      0.3   0.3    0.4
 3: 11/1/2017  0.4  0.6  0.3  0.4  0.3  0.2  0.2  0.2  0.4      0.3   0.4    0.3
 4: 12/1/2017  0.8  0.2  0.1  0.2  0.7  0.2  0.2  0.1  0.5      0.5   0.3    0.2
 5:  2/1/2017  0.7  0.3  0.3  0.3  0.4  0.1  0.3  0.3  0.3      0.2   0.5    0.3
 6:  3/1/2017  0.6  0.4  0.3  0.2  0.5  0.0  0.2  0.4  0.4      0.4   0.4    0.2
 7:  4/1/2017  0.4  0.6  0.3  0.5  0.2  0.2  0.2  0.4  0.2      0.4   0.3    0.3
 8:  5/1/2017  0.4  0.6  0.3  0.5  0.2  0.2  0.2  0.2  0.4      0.6   0.2    0.2
 9:  6/1/2017  0.4  0.6  0.3  0.2  0.5  0.3  0.1  0.4  0.2      0.5   0.3    0.2
10:  7/1/2017  0.4  0.6  0.3  0.6  0.1  0.1  0.2  0.6  0.1      0.2   0.2    0.6
11:  8/1/2017  0.6  0.4  0.5  0.2  0.3  0.5  0.0  0.3  0.2      0.4   0.4    0.2
12:  9/1/2017  0.3  0.7  0.1  0.8  0.1  0.3  0.3  0.2  0.2      0.4   0.3    0.3


Q: Почему не получается принять сложный объект в контролере? Сабж. Есть проект WEB API, в нем есть контролер
[HttpGet]
public string GetRandomDouble(MinMax minMax)
{
    return $"{minMax.Min} --------    {minMax.Min} ";
}

Код класса MinMax
public class MinMax
{
    public double Min { set; get; }

    public double Max { set; get; }
}

При запросе /api/GetRandom?min=1&max=2 выдает
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "00-e07aa3c3d5673c43aea3e3f1b0d6d89b-8a8efb0e3c962647-00"
}

На сколько я понимаю это ошибка говорит о том что мол не те данные переданы в запросе. Но вроде же можно принять сложный объект, просто передать все заполненные поля и контролер сам все сопоставит.
Если делать точно такой же запрос но в контролере принимать два double то все работает.
В чем проблема?
Ну и может быть мне все это не надо, как лучше передавать объекты между микросервисами, мб просто string json?


Q: How to write to file in C++ without locking it? C++ In Windows 7.
When writing to my log file, i sometimes set a breakpoint, or the program gets stuck at something. When i try too peek in my logfile from another program it says "The file cannot be opened because it is in use by another process". Well thats true, however I've worked with other programs that still allows reading from a logfile while they are writing to it, so I know it should be possible. Tried the _fsopen and unlocking the file but without success.
FILE* logFile;
//fopen_s(&logFile, "log.log", "w");
logFile = _fsopen("log.log", "w", _SH_DENYNO);

if (!logFile)
    throw "fopen";

_unlock_file(logFile);

A: If you have the log-file open with full sharing-mode, others are still stopped from opening for exclusive access, or with deny-write.
Seems the second program wants more access than would be compatible.
Also, I guess you only want to append to the log, use mode "a" instead of "w".
Last, do not call _unlock_file unless you called _lock_file on the same file previously.

There is a way to do what you want though:
Open your file without any access, and then use Opportunistic Locks.
Raymond Chen's blog The Old New Thing also has a nice example: https://devblogs.microsoft.com/oldnewthing/20130415-00/?p=4663


Q: in Unix concatenation of two variables i have a file C20140728 I want a variable which will store C and other varibale which will store 20140728(here second variable is current systemdate in %Y%m%d format) and third variable when I echo should concatenatae and show C20140728

A: In general to concatenate two variables you can just write them one after another:
a='C'
b='20140728'
c=$a$b

edit:
to get the current date
b = $(date +'%Y%m%d')


Q: How do I get the maximum value(s) in a (seaborn) JointKDE plot? How do I get the maximum value(s) in a (seaborn) JointKDE plot? Like the image below. I want to get the blue points coordinate like (121.53,31.29) and (121.58,31.27)。
Thanks a lot!


Q: c++ - char const * const * -  I have a variable that is a pointer to a constant pointer to a constant char.
char const * const * words;

I then add the word "dog" to that variable.
words = (char const * const *)"dog";

However, when when I debug the code, it states this about words:
{0x616d7251 Error reading characters of string.}

My question is, how would I properly access the characters of that variable to the point where I can record each individual character of the string.
Here is some example code below:
char const * const *words;
words = (char const * const *)"dog";

for (int i = 0; i < 5; ++i)
{
    char c = (char)words[i]; // Gives me, -52'i symbol', 'd', and then '\0'
    // How do I access the 'o' and 'g'?
}

Thanks for the help in advance.

A: maybe you mean this
char const * const words = "dog";

for (int i = 0; i < strlen(words); ++i)
{
    char c = words[i];
}

now of course in c++ code you should realy be using std::string

A: You are consistently missing the second *.
Ignoring the const stuff, you are declaring a char** word, which is a pointer to a pointer to a single char. You won't get a word or many words into that, and casting just hides the problem.
To get "dog" accessible through such a pointer, you need to take an extra step; make a variable that contains "dog", and put its address into your word.

A: Short answer:
Your program has undefined behavior. To remove the undefined behavior use:
char const * word = "dog";
for (int i = 0; i < std::strlen(word); ++i)
{
    char c = word[i];
}

or
char const * word = dog;
char const * const *words = &word;
for (int i = 0; i < std::strlen(*words); ++i)
{
    char c = (*words)[i];
}

Long answer:
You are forcing a cast from char const* to char const* const* and treating the location of memory that was holding chars as though it is holding char const*s. Not only that, you are accessing memory using an out of bounds index.
Let's say the string "dog" is held in some memory location as (it takes four bytes that includes the null character) and give it an address.
a1
|
v
+---+---+---+----+
| d | o | g | \0 |
+---+---+---+----+

You can treat the address a1 as the value of a pointer of type char const*. That won't be a problem at all. However, by using:
words = (char const * const *)"dog";

You are treating a1 as though it is holding objects of type char const*.
Let's assume for a moment that you have a machine that uses 4 bytes for a pointer and uses little endian for pointers.
words[0] evaluates to a pointer. Its value will be:
 'd' in decimal +
 256 * 'o' in decimal +
 256*256 * 'g' in decimal +
 256*256*256 * '\0' in decimal.

After that, you truncate that value to char, which will give you back the character d, which is not too bad. The fun part (undefined behavior) begins when you access words[1].
words[1] is same as *(words+1). words+1 evaluates to a pointer whose value is the address a2.
                 a2
                 |
                 v
+---+---+---+----+
| d | o | g | \0 |
+---+---+---+----+

As you can see, it points to memory that is beyond what the compiler allocated for you. Dereferencing that pointer is cause for undefined behavior.


Q: Bibliography section has the wrong header I'm writing a thesis document. After the Appendix section I have the Reference section.
My problem is that my References have three pages total, in the first page appears the bibliography title correctly, as the next picture shows:

But in the next two pages the header appears as if it were part of the appendix, like this:

NOTE: This has the same result if I place the bibliography before the appendix, except that in this case the header changes to the one of the last chapter.
EDIT: This is the code where I call the chapters, appendix and bibliography. Hope it helps to find a solution:
\documentclass[oneside,numbers,a4paper,spanish]{ezthesis}

\usepackage[Bjornstrup]{fncychap}
\usepackage{amsmath}
\usepackage{float}

\author{**}
\title{**}
\degree{**}
\supervisor{**}
\institution{**}
\faculty{**}
\department{**}

\makeatletter
\newenvironment{chapquote}[2][2em]
  {\setlength{\@tempdima}{#1}%
   \def\chapquote@author{#2}%
   \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
   \itshape}
  {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
\makeatother

\hyperlinking
\begin{document}

\renewcommand{\tablename}{Tabla}

\include{Chapters/titlepage}

\include{Chapters/gracias}

\tableofcontents

%% # Chapters#
\include{Chapters/1}
\include{Chapters/2}
\include{Chapters/3}
\include{Chapters/4}
\include{Chapters/5}
\include{Chapters/6}

\appendix
\include{appendix/apendiceA}
\include{appendix/apendiceB}
\include{appendix/apendiceC}
\include{appendix/apendiceD}

\bibliography{biblio}

\end{document}

EDIT 2: This link have the ezthesis: EZTHESIS
How could I fix this?

A: Thanks to @barbarabeeton 's comment I could fix my problem. Maybe it wasn't the best way to solve it, but it works.
This is the code to solve the problem:
"put \clearpage and \markboth{Bibliografia}{Bibliografia} before \bibliography{biblio} to reset the running heads". – barbara beeton
Thanks for the help

A: The appendices (non-essential stuff, that just might interest the reader; but probably won't) go after the bibliography. This is an old custom in printing, which you shouldn't challenge without solid reasons.


Q: I want to make the spline chart from highcharts.com smaller in size I want to minify the chart Interface. Currently I am using chart with size 600 x 300 px, which is working fine.
Now I want to show 3 charts at the same place so in order to save space. I want to show 3 charts thumbnails (working charts). If user click on any chart it should appear as full chart. I can show it on the popup or expand it on the page itself.
I checked the Highchart website. It provide option to resize chart using height & width properties.
http://api.highcharts.com/highcharts/chart.height
http://api.highcharts.com/highcharts/chart.width

This option do not actually resize the chart. Char layout get smaller but the title label stay at the same size. I want chart to resize and work in a smaller version with text and chart show in smaller box like 100 x 100 px.
I can use chart.setSize(); function to resize the chart.
Does it make any sense? Please guide me.
I am using highcharts 5.0 version js file.
Here is my code:
 var seriesData1 = {
                    name: "Series1Label",
                    data: Series1Data
                },
                seriesData2 = {
                    "name": "Series2Label",
                    "data": Series2Data
                },
                seriesData3 = {
                    "name": "Series3Label",
                    "data": Series3Data
                },
                completedData = [seriesData2, seriesData3, seriesData1];

 var elem = par.find('<some class>');

    elem.highcharts({
                    chart: {
                        type: 'areaspline'
                    },
                    colors: ['#21d0b8', '#2248B5', '#5B82A1'],

                    title: {
                        text: ""
                    },
                    legend: {
                        layout: 'horizontal',
                        align: 'left',
                        verticalAlign: 'top',
                        useHTML: true,
                        itemDistance: 5,
                    },
                    xAxis: {
                        'title': {
                            text: xAxisTitle
                        },
                        categories: categories,
                        tickmarkPlacement: 'on',
                        title: {
                            enabled: false
                        }
                    },
                    yAxis: {

                        title: {
                            text: ''
                        }
                    },
                    tooltip: {
                        shared: true
                    },
                    credits: {
                        enabled: false
                    },
                    plotOptions: {
                        series: {
                            events: {
                                legendItemClick: function(event) {

                                }
                            }
                        },
                        areaspline: {
                            fillOpacity: 0.8
                        },
                        area: {
                            fillColor: {
                                linearGradient: {
                                    x1: 0,
                                    y1: 0,
                                    x2: 0,
                                    y2: 1
                                },
                                stops: [
                                    [0, Highcharts.getOptions().colors[0]],
                                    [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                                ]
                            },
                            marker: {
                                radius: 2
                            },
                            lineWidth: 1,
                            states: {
                                hover: {
                                    lineWidth: 1
                                }
                            },
                            threshold: null
                        }
                    },
                    series: completedData,

                    exporting: {
                        buttons: {
                            contextButton: {
                                text: 'Export',
                                useHTML: true,
                                align: 'right',
                                symbolY: 15,
                            }
                        }
                    },
                    responsive: {
                        rules: [{
                            condition: {
                                maxWidth: 100
                            },
                            chartOptions: {
                                legend: {
                                    align: 'center',
                                    verticalAlign: 'bottom',
                                    layout: 'horizontal'
                                },
                                yAxis: {
                                gridLineWidth: 0,
                                minorGridLineWidth: 0,
                                    labels: {
                                         enabled:false,
                                    },
                                    title: {
                                        text: null
                                    }
                                },
                                 xAxis: {
                                    labels: {
                                         enabled:false,
                                    },
                                    title: {
                                        text: null
                                    }
                                },
                                title:{
                                                text: '',
                                },
                                subtitle: {
                                    text: null
                                },
                                tooltip:{
                                enabled:false,
                                },
                                legend:{
                                enabled:false,
                                },
                                credits: {
                                    enabled: false
                                }
                            }
                        }]
                    }
                });

The 'elem' chart element occurs 7 times on a single page, so I have made a single code to fill all the charts on different data and trigger them all at single function.
I need all the 7 charts to show in thumbnail and show certain chart in large size on  user click.
using your example when I update my code.
var getChart = ele_.highcharts({.....});

Resize code:
getChart.setSize(100, 100);

Error encountered
getChart.setSize is not a function

Can anyone guide me how to fix this issue?

A: check responsive and set rules accordingly.
For 100 by 100 you should remove all gridlines, credits, labels, title
Example will be

Highcharts.chart('container', {
  chart: {
    type: 'line',
    width: 100,
    height: 100
  },
  legend: {
    align: 'center',
    verticalAlign: 'bottom',
    layout: 'horizontal'
  },
  yAxis: {
    gridLineWidth: 0,
    minorGridLineWidth: 0,
    labels: {
      enabled: false,
    },
    title: {
      text: null
    }
  },
  xAxis: {
    labels: {
      enabled: false,
    },
    title: {
      text: null
    }
  },
  title: {
    useHTML: true,
    text: ''
  },
  subtitle: {
    text: null
  },
  tooltip: {
    enabled: false,
  },
  legend: {
    enabled: false,
  },
  credits: {
    enabled: false
  },

  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
  }]
});
$('#container').highcharts().renderer.text('mini Highcharts', 20, 90)
  .css({
    fontSize: '8px',
    color: '#7d7d7d'
  })
  .add();

check this using chart.setSize();
Fiddle
Update
You could use $(elem).highcharts().setSize(100, 100);
Updated fiddle


Q: Is adding a user needs password In my Ubuntu after login by my user account, I want to create another user I intered bellow commands  :
adduser alex_2 -m

I created new user, but when I want to login, Ubuntu needs passwords and I did not gave that any password, as I mentioned I just typed adduser alex_2 -m. Am I should set a password? Also I can not login even when I set password blank .

A: you can run the command:
sudo passwd username

to create a password for the user. ("username" needs to be changed to the given username)
You could also disable the password, when running the command adduser, by appending the option --disabled-password. But that isn't recommended.

A: You need to open system settings, and go to users. Click unlock, then on the user you want to change, then the Account Disabled, next to password, and choose one of the 3 options from drop down.


Q: Pagination. Why only one page is showing? I have been trying to get pagination to work and I have to a certain extent but it only shows one page of results.
I have 18 listings in my database and have it set to show 6 per page.
Can anyone see what the problem is?
<?php include('includes/configsql.php');

//include header template
include('layout/header.php');

//include navbar template
include('layout/navbar.php');

?>

<?php
$con = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);

$sql = "SELECT COUNT(id) FROM basic WHERE status='active'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);

$rows = $row[0];
$rows = mysqli_num_rows($query);

$page_rows = 6;
$last = ceil($rows/$page_rows);

if($last < 1){
    $last = 1;
}

$pagenum = 1;

if(isset($_GET['pn'])){
    $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}

if ($pagenum < 1) {
    $pagenum = 1;
} else if ($pagenum > $last) {
    $pagenum = $last;
}

$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, name, address, telephone, email, category FROM basic WHERE status='active' ORDER BY name ASC $limit";
$query = mysqli_query($con, $sql);

$textline1 = "Basic Listing ($rows)";
$textline2 = "Page $pagenum of $last";

$paginationCtrls = '';
if($last != 1){
    if ($pagenum > 1) {
        $previous = $pagenum - 1;
        $paginationCtrls .= 'Previous     ';
        for($i = $pagenum-4; $i < $pagenum; $i++){
            if($i > 0){
                $paginationCtrls .= ''.$i.'   ';
            }
        }
    }

    $paginationCtrls .= ''.$pagenum.'   ';
    for($i = $pagenum+1; $i <= $last; $i++){
        $paginationCtrls .= ''.$i.'   ';
        if($i >= $pagenum+4){
            break;
        }
    }
    if ($pagenum != $last) {
        $next = $pagenum + 1;
        $paginationCtrls .= '     Next ';
    }
}
$list = '';
while($row = mysqli_fetch_array($query)){
    $id = $row["id"];
    $name = $row["name"];
    $category = $row["category"];
    $list .= '
'.$name.'  | '.$category.'  - Click the link to view this business
';
}

mysqli_close($con);
?>

<?php echo $textline1; ?>

<?php echo $textline2; ?>

<?php echo $list; ?>

<?php echo $paginationCtrls; ?>

<?php
//include footer template
include('layout/footer.php');
?>

A: I think you have to remove the line:
 $rows = mysqli_num_rows($query);

It is in beginning of the script.
Another way is if you modify the first line like this:
$sql = "SELECT * FROM basic WHERE status='active'";

And remove the next 3 rows
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];

You have to choice one of above, but not both :)


Q: Angular-fullstack get current user ID I'm using https://github.com/DaftMonk/generator-angular-fullstack.
I have 2 schemas:

*

*charts

*

*title: String

*datasets: Array

*_creator: logged in user ID

*users

*

*name

*email

*_id

When I console.log the current user returns

$scope.getCurrentUser = Auth.getCurrentUser();
console.log($scope.getCurrentUser);

But when I try to console log the _id:
$scope.getCurrentUser = Auth.getCurrentUser();
console.log($scope.getCurrentUser._id);

Returns

undefined

Can someone explain what I'm doing wrong?

A: Objects in chrome console get evaluated only when they are first opened.
This means that when you console.log an object like the return value of Auth.getCurrentUser(), the console displays a reference to it - this at the time of the log call contains a promise object, but it's most likely resolved by the time you open it on the console, so you see the property you're looking for.
On the other hand, when you're logging $scope.getCurrentUser._id, that's the result of a property lookup on the promise object - and it prints the current value of the property, which is undefined.
A note about clean code: your scope variable is called getCurrentUser, which makes one think it's a getter function, but it is infact the return value of a getter function. This is confusing.


Q: Permutations of a list with constraints python I am desperately trying to get all the permutations of a list while enforcing position assignment constraints.
I have a list [1,2,3,4,5,6] (6 is just an example, I would like to find something that could work with every lenght) and I want to find all the lists of lenght 3 (also an example) with the following constraints :

*

*position 1 can be occupied by numbers 1 and 2

*position 2 can be occupied by numbers 1,2 and 3

*position 3 can be occupied by numbers 2,3 and 4

*repetions of a same number are not allowed

That would give these lists : [1,2,3],[1,2,4],[1,3,2],[1,3,4],[2,1,3],[2,3,4],[2,1,4]
For those interested, what I am  trying to implement is what is explained pages 5 and 6 of this paper

A: Filter the product() of those subsets:
from itertools import product

for combo in product([1, 2], [1, 2, 3], [2, 3, 4]):
    if len(set(combo)) == 3:
        print(combo)

or as a list comprehension:
[combo for combo in product([1, 2], [1, 2, 3], [2, 3, 4]) if len(set(combo)) == 3]

Output:
>>> from itertools import product
>>> [combo for combo in product([1, 2], [1, 2, 3], [2, 3, 4]) if len(set(combo)) == 3]
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (2, 1, 3), (2, 1, 4), (2, 3, 4)]