text:
Q: How solve IndexError: arrays used as indices must be of integer (or boolean) type in ConvNet? I don't know how solve the error IndexError: arrays used as indices must be of integer (or boolean) type in my ConvNet. First of all I created the array that contents DICOM images from a folder. The goal is display the 3D plot of this np.array called train_patient. Moreover 'patient = load_scan (path)', so the variable in which 'download' the path of the images.
I read many questions on this platform and applied answers to my code but the error remains. So here there is my code:
def resample(image, scan, new_spacing=[1,1,1]):
    # Determine current pixel spacing
    spacing = np.array([scan[0].SliceThickness] + list(scan[0].PixelSpacing), dtype=np.float32)

    resize_factor = spacing / new_spacing
    new_real_shape = image.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize_factor = new_shape / image.shape
    new_spacing = spacing / real_resize_factor

    image = scipy.ndimage.interpolation.zoom(image, real_resize_factor, mode='nearest')

    return image, new_spacing

Apply the above function:
pix_resampled, spacing = resample(train_patient, patient, [1,1,1])
print("Shape before resampling\t", train_patient.shape)
print("Shape after resampling\t", pix_resampled.shape)

It results:
Shape before resampling  (129, 512, 512)
Shape after resampling   (206, 400, 400)

Define the 3D plot function:
def plot_3d(image, threshold=-300):

    # Position the scan upright,
    # so the head of the patient would be at the top facing the camera
    p = image.transpose(2,1,0)

    verts, faces = measure.marching_cubes_classic(p, threshold)

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')

    # Fancy indexing: `verts[faces]` to generate a collection of triangles
    mesh = Poly3DCollection(verts[faces], alpha=0.70)
    face_color = [0.45, 0.45, 0.75]
    mesh.set_facecolor(face_color)
    ax.add_collection3d(mesh)

    ax.set_xlim(0, p.shape[0])
    ax.set_ylim(0, p.shape[1])
    ax.set_zlim(0, p.shape[2])

    plt.show()

def largest_label_volume(im, bg=-1):
    vals, counts = np.unique(im, return_counts=True)

    counts = counts[vals != bg]
    vals = vals[vals != bg]

    if len(counts) > 0: # >
        return vals[np.argmax(counts)]
    else:
        return None

def segment_lung_mask(image, fill_lung_structures=True):

    # not actually binary, but 1 and 2.
    # 0 is treated as background, which we do not want
    binary_image = np.array(image > -320, dtype=np.int8)+1 # >
    labels = measure.label(binary_image)

    # Pick the pixel in the very corner to determine which label is air.
    #   Improvement: Pick multiple background labels from around the patient
    #   More resistant to "trays" on which the patient lays cutting the air
    #   around the person in half
    background_label = labels[0,0,0]

    #Fill the air around the person
    binary_image[background_label == labels] = 2

    # Method of filling the lung structures (that is superior to something like
    # morphological closing)
    if fill_lung_structures:
        # For every slice we determine the largest solid structure
        for i, axial_slice in enumerate(binary_image):
            axial_slice = axial_slice - 1
            labeling = measure.label(axial_slice)
            l_max = largest_label_volume(labeling, bg=0)

            if l_max is not None: #This slice contains some lung
                binary_image[i][labeling != l_max] = 1

    binary_image -= 1 #Make the image actual binary
    binary_image = 1-binary_image # Invert it, lungs are now 1

    # Remove other air pockets insided body
    labels = measure.label(binary_image, background=0)
    l_max = largest_label_volume(labels, bg=0)
    if l_max is not None: # There are air pockets
        binary_image[labels != l_max] = 0

    return binary_image

Apply the above functions:
segmented_lungs = segment_lung_mask(pix_resampled, False)
segmented_lungs_fill = segment_lung_mask(pix_resampled, True)
plot_3d(segmented_lungs, 0)

The code gives me:

IndexError                                Traceback (most recent call last)
<ipython-input-289-2e5dea6ade8b> in <module>()
      1 segmented_lungs = segment_lung_mask(pix_resampled, False)
      2 segmented_lungs_fill = segment_lung_mask(pix_resampled, True)
----> 3 plot_3d(segmented_lungs, 0)

1 frames
<ipython-input-287-c4ec00976999> in plot_3d(image, threshold)
      5     p = image.transpose(2,1,0)
      6
----> 7     verts, faces = measure.marching_cubes_classic(p, threshold)
      8
      9     fig = plt.figure(figsize=(10, 10))

/usr/local/lib/python3.7/dist-packages/skimage/measure/_marching_cubes_classic.py in marching_cubes_classic(volume, level, spacing, gradient_direction)
    130
    131     # Fancy indexing to define two vector arrays from triangle vertices
--> 132     faces = _correct_mesh_orientation(volume, verts[faces], faces, spacing,
    133                                       gradient_direction)
    134

IndexError: arrays used as indices must be of integer (or boolean) type

Anyone know how this can be solved? Thank you for your time and help


text:
Q: Can I set the visibility of a TTextBox in a function? I tried
function hilfe() {
    $this->hilfe_txt->Visible->true;
}

to set the visibility of
<com:TTextBox id="hilfe_txt" Visible="false" Text""/>

error is: [Notice] Trying to get property of non-object
Any ideas to solve that problem?

A: Solved it!
$this->hilfe_txt->Visible=true;

Simple but took a long time to find.

redpajama_set_name: RedPajamaStackExchange


text:
Q: gitlab pipeline: get hostname inside gitlab-ci.yml I run several docker commands in gitlab-ci.yml.
Some of them require current machine IP address to be passed to them, like this:
docker build --pull -t my_image . --add-host=<my service>:<current ip>

$CI_SERVER_HOSTNAME is not the one, its value is gitlab.com. I need actual IP address of the CI machine as ifconfig would see it from .gitlab-cy.yml file.
I am not finding any $CI_... variable for that. I know extraction from ifconfig is possible, but won't work when the docker commands executed one-by-one on Mac.
Note: I know it's usually something like 172.0.0.x, but need an exact one plus I wonder if the variable for it exists.

A: In order to get the ip address of the machine that the runner is executed.

We will use the Gitlab API https://docs.gitlab.com/ee/api/runners.html#get-runners-details
GET /runners/:id

This API call will return the details of the runner with this specific :id. When a job executes this id is available on CI_RUNNER_ID predefined variable.

By combining all this and utilizing jq and sed
 We get the following one liner that returns the ip address of the runner that is executing the current job
curl -s --header "PRIVATE-TOKEN: <your access token>" https://gitlab.com/api/v4/runners/${CI_RUNNER_ID}  | jq '.ip_address' | sed 's/^"\(.*\)"$/\1/'


text:
Q: How to find process ID in WinCe? I am using an Win Ce 5.0 that was "sliced" by the Manufacturer because of Memory Problems. It starts an application ( an BIN image is made using Platform Builder ) that consumes some memory.
When I want to start debugging it freezes the first application and start the new one that i have been developing ( VS 2008 Pro ). It it not clear for me if the first application consumes some memory ( because i know that some fileds are static ) and some data points are STUBBED.
Main problem is that , Win Ce is only a boot loader that starts the First Application. I can't disable it , switch it or do anything on it, because it is running and it start the ActiveSync ( that's the way that i have communication to my PC / VS 2008 Pro )
Please help me with the solution:
 1. How to find the First Application Process ID ( GetProcessById didn't worked , GetProcessByName is unavailable from the .Net Ce Framework )
 2. How to dispose all memory that is loaded by the First Applicaiton - i want to have as much memory available as possible )
 3. Best option it would be to have a watchdog class for testing if the first application is not doing anything ( not starting any process / method )
Willing to offer my points and honor to the person who can help me :)

Another problem is with the USB debugging : device has a wrong driver (issue)
USb connection with device
-   After reset – not working ( it detects as AT9S81) - used for flashing device
-   After device – not working ( it detects as AT9S81) - used for flashing device
-   It needs some time to detect as Active Sync (PROTOTYPE--Remember to change idVendor)
Is this a OS problem / device driver / windows 7 problem ?

A: Are you saying you have an older, unsupported CE device that you are trying to make use of?

*

*Getting process info is done with the ToolHelp APIs.  You must P/Invoke these with the CF.  The SDF has a full complement of ToolHelp objects of you don't want to write them.

*You can't "dispose of" memory in another process.  The other process manages its own memory.  You could terminate that process, which would release all of its memory to the OS.

*How do you propose to know if the other process is "doing anything"?  If it doesn't tell you when it's doing something, it's difficult to know if it's running code (it can be done by using a celog intercept to look at the OS scheduler, but that's pretty advanced stuff and I wouldn't recommend it as a first or even second course of action).

If you have access to run code on the device, I'd recommend modifying the OS to not run whatever app it's running in the first place.  Adjust the HKLM\Init registry entries or whatever is launching it.


text:
Q: Extract all url from sitemap.xml with PHP CURL I want to extract all url from sitemap.xml with PHP and CURL. My code work with content sitemap (e.g: http://www.phanmemtoday.com/sitemap.xml?page=1) but does not work with sitemap index (e.g: http://www.phanmemtoday.com/sitemap.xml).
Please help me. Thank you!
<?php
$sUrl="http://domain.com/sitemap.xml";

$aXmlLinks = array($sUrl);
$aOtherLinks = array();
while (!empty($aXmlLinks)) {
    foreach ($aXmlLinks as $i =>$sTmpUrl){
        unset($aXmlLinks[$i]);
        $aTmp = getlinkfromxmlsitemap($sTmpUrl);
        echo "Array temp link:
";
        print_r($aTmp);
        foreach ($aTmp as $sTmpUrl2) {
            if (strpos($sTmpUrl2, '.xml') !== false) {
                array_push($aXmlLinks,$sTmpUrl2);
            } else {
                array_push($aOtherLinks,$sTmpUrl2);
            }
        }
    }
    echo "
Array xml link:
";
    print_r($aXmlLinks);
    echo "
Array product link:
";
    print_r($aOtherLinks);
    echo "
-----------------------------------------
";
}
print_r($aOtherLinks);

function getlinkfromxmlsitemap($sUrl) {
    // echo "Get link from: $sUrl
";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
    curl_setopt($ch, CURLOPT_URL, $sUrl);
    $data = curl_exec($ch);
    curl_close($ch);
    $links = array();
    $count = preg_match_all('@<loc>(.+?)<\/loc>@', $data, $matches);
    for ($i = 0; $i < $count; ++$i) {
        $links[] = $matches[0][$i];
    }
    return $links;
}
?>

A: Your code works well, but you can improve some things please check the following example thar will return a nested array with the links your looking:
<?php
$sUrl1="http://www.phanmemtoday.com/sitemap.xml?page=1";
$sUrl2="http://www.phanmemtoday.com/sitemap.xml";

$aXmlLinks = array($sUrl1,$sUrl2);
$aOtherLinks = array();
while (!empty($aXmlLinks)) {
    foreach ($aXmlLinks as $i =>$sTmpUrl){
        unset($aXmlLinks[$i]);
        $aTmp = getlinkfromxmlsitemap($sTmpUrl);
        array_push($aOtherLinks,$aTmp);
    }
    echo "
Array xml link:
";
    print_r($aXmlLinks);
    echo "
Array product link:
";
    print_r($aOtherLinks);
    echo "
-----------------------------------------
";
}
print_r($aOtherLinks);

function getlinkfromxmlsitemap($sUrl) {
    // echo "Get link from: $sUrl
";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
    curl_setopt($ch, CURLOPT_URL, $sUrl);
    $data = curl_exec($ch);
    $error= curl_error($ch);
    curl_close($ch);
    $links = array();
    $count = preg_match_all('@<loc>(.+?)<\/loc>@', $data, $matches);
    for ($i = 0; $i < $count; ++$i) {
        $links[] = $matches[0][$i];
    }
    return $links;
}
?>


text:
Q: WordPress Move only Javascript to footer Right now I am using a very simple function to move the javascript of WordPress to the footer:
function move_javascripts() {
    remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );
    add_action( 'wp_footer', 'wp_enqueue_scripts', 5 );
}

The problem though is that this code seems to bring all the "scripts" to the footer, even the CSS... I've tried to find a way to move only the .js part but I can't find any...
So is there some way to only target the javascripts and move them to the footer without the CSS?

A: You are pretty much overkilling the whole WordPress Script system with this and to be honest - this is completely, I mean totally wrong. When you enque a script into WordPress you do this by wp_enqueue_script.
This function takes 5 parameters, of which the last one can be set to true, in order to load it in the footer.
Here is an excerpt of my functions.php:
if (!function_exists('wp_template_setup')) {

    wp_enqueue_script('modernizr-script', get_template_directory_uri() .   '/js/libs/modernizr.custom.js', '', '', true);
}
add_action('wp_enqueue_scripts', 'wp_template_setup');

The last paramter is set to true, which means that it will be loaded in the footer.
See the WordPress Codex for details: https://developer.wordpress.org/reference/functions/wp_enqueue_script/

A: In your wp_register_script() calls (where the scripts are enqueued), there is a 5th parameter called $in_footer which is designed for this very thing. Throw a true in there and it'll move the script to the footer. Note, you'll have to the do this on each wp_register_script() call.


text:
Q: NDSolve causing my PC to crash I'm trying to integrate a complicated Fokker-Planck PDE
$\frac{dP}{\partial L}(L,g,h,q) = \frac{A_3^2}{2}q^2\frac{\partial^2P}{\partial g^2}+A_3^2gq\frac{\partial^2P}{\partial g\partial q} + (A_1^2+A_2^2+A_3^2\frac{q^2}{g^2})\frac{\partial^2P}{\partial h^2} + A_3^2g^2\frac{\partial^2P}{\partial q^2}+(\frac{A_3^2}{2}-A_4)g\frac{\partial P}{\partial g} + (\frac{A_3^2}{2}+A_4)q\frac{\partial P}{\partial q}-A_5\frac{\partial P}{\partial h}$
with initial condition
$P(L=0,g,h,q) = \delta(g)\delta(h)\delta(q-1),$
approximated via hyperbolic tan functions. My code is
A1 = .05;
A2 = 2;
A3 = .3;
A4 = .5;
A5 = .9;
n = 10;
FPE = D[P[LL, g, h, q], LL] - (.5*A3^2*q^2)*
   D[P[LL, g, h, q], {g, 2}] - (A3^2*q*g)*
   D[P[LL, g, h, q], g] - (A1^2 + A2^2 + A3^2*(q/g)^2)*
   D[P[LL, g, h, q], {h, 2}] - (A3^2*g^2)*
   D[P[LL, g, h, q], {q, 2}] - (.5*A3^2 - A4)*g*
   D[P[LL, g, h, q], g] - (.5*A3^2 + A4)*q*D[P[LL, g, h, q], q] +
  A5*D[P[LL, g, h, q], h]

s = NDSolve[{FPE == 0,
   P[0, g, h, q] ==
    D[Tanh[n (q - 1)], q]*D[Tanh[n *g], g]*D[Tanh[n *h], h]},
  P, {LL, 0.01, 5}, {g, 0.01, 5}, {h, 0.1, 5}, {q, 1, 5}]

anyone got ideas? It crashes my whole system.


text:
Q: compare arrays in jquery and return the values that are no the same I would like to compare two arrays in jquery and return a new array of all the elements that do not match. so if I build a function like so:
function (parent, child) {}
I should compare child to parent and return a new array of all the elements in child that do not match parent. an example would be
parent = ['apple', 'banana'];
child = ['fruit'];

compare child to parent and get back and array: ['fruit'] as fruit is not in parent. I looked for methods to do this and saw this solution but I am not sure if this is what I want or not.

A: You might want to look at Underscore.js (http://underscorejs.org/#difference), which has a function just for that. It returns the values from array that are not present in the other arrays.
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

To justify the use of yet another library: you might find tons of other useful utilities there ;)

A: Be careful, using the keyword 'parent' may have unexpected side effects. In the version of Chrome I'm using, it seems to refer to Window.
Vanilla JavaScript solution, quick and easy:
var findDifference = function (elder, sibling) {

  var difference = [];

  for(var i = 0; i < sibling.length; i++){
    if(elder.indexOf(sibling[i]) < 0){
      difference.push(sibling[i]);
    }
  }
  return difference;
};

var elder = ['apple', 'banana'];
var sibling = ['fruit'];

findDifference(elder, sibling); // => ['fruit']


text:
Q: ActionScript 3.0 - Alternative Event Listener Declarations? I have some in-file actionscript 3.0 code. This code controls a number of elements on it's stage. These elements each have an Over, an Out, and a Click event.
I currently define these event listeners as so:
mc_hotspot.addEventListener(MouseEvent.MOUSE_OVER, lift);
mc_hotspot.addEventListener(MouseEvent.MOUSE_OUT, setDown);
mc_hotspot.addEventListener(MouseEvent.CLICK, select);;
mc_spinspot.addEventListener(MouseEvent.MOUSE_OVER, spinspotOver);
mc_spinspot.addEventListener(MouseEvent.MOUSE_OUT, spinspotOut);
mc_spinspot.addEventListener(MouseEvent.CLICK, spinClick);
mc_spinspot2.addEventListener(MouseEvent.MOUSE_OVER, spinspot2Over);
mc_spinspot2.addEventListener(MouseEvent.MOUSE_OUT, spinspot2Out);
mc_spinspot2.addEventListener(MouseEvent.CLICK, spin2Click);
btn_back.addEventListener(MouseEvent.MOUSE_OVER, backOver);
btn_back.addEventListener(MouseEvent.MOUSE_OUT, backOut);
btn_back.addEventListener(MouseEvent.CLICK, backClick);

As you can see, this is a very long and convoluted way of defining the events for these elements and there is also an event triggered function to go with each of these.
I'll be expanding the project to add three more spinspots and one or two more buttons soon and I was just wondering if there was any other way to define and cater for these events.
In the case of the spinspots all the over and out events are the same but each have their own duplicate function and listener.
Thanks in advance

A: You could just build a function like:
function addButtonEvents(mc:*,over:Function,out:Function,click:Function = null) {
    mc.addEventListener(MouseEvent.MOUSE_OVER,over,false,0,true);
    mc.addEventListener(MouseEvent.MOUSE_OUT,out,false,0,true);

    //if we have an optional click event
    if (click != null)
         mc.addEventListener(MouseEvent.CLICK,click,false,0,true);

}

then you can add all three events in one call i.e
addButtonEvents(mc_spinspot, spinspotOver, spinspotOut, spinClick);

A: best way is via encapsulation, ususaly the over and out states only effect the item that is being over or out, therefore you can make a spinspot class and make over and out handlers in that and only worry about the click handler in the parent class.
otherwise you can have one over, out and click handler and then sort the action by target of the event (if (ev.target == mc_spinspot)) etc. doing that you can also have a assignEvents function that gives the over, out and click responders to the passed variable
private function addEvents(obj:Sprite){
    obj.addEventListener(MouseEvent.MOUSE_OVER, overHandler);
    obj.addEventListener(MouseEvent.MOUSE_OUT, outHandler);
    obj.addEventListener(MouseEvent.CLICK, clickHandler);

}
addEvents(mc_spinspot);


text:
Q: PHP is not working on local Apache Webserver I am trying to setup a local wordpress installation and followed this tutorial to setup LAMP.
Unfortunately my Server does not seem to process PHP but I can't find the issue. If I create a file info.php, as described in the tutorial and try to display it in the browser it just shows a blank page.
How can I enable php on the server?


text:
Q: Tom-Select as Django Widget I would like to use tom-select as an Django autocomplete select-widget.
In the corresponding database table (Runners) are several hundred rows, so that I can't load all into the html page.
In the model RaceTeam I have a ForeignKey to Runner.
The select widget will be used in whole pages and in html fragments (via htmx).
I tried subclass django.forms.Select, but this sucks all db rows into widget.choices.

A: I use this solution:
I copy the tom-select JS+CSS to static/relayrace/vendor/.
class RunnerSelectWidget(Select):
    class Media:
        css = {
            'all': ('relayrace/vendor/tom-select.css',)
        }
        js = ('relayrace/vendor/tom-select.complete.min.js',)

    def set_choices(self, value):
        # there can be several thousand choices. We don't want them here
        self._choices = []

    def get_choices(self):
        choices = list(self._choices)
        return choices

    choices = property(get_choices, set_choices)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['attrs']['class']='runner-select'
        return context

    def optgroups(self, name, value, attrs=None):
        # Make the initial value available
        self._choices = [(id, runner_to_select_text(Runner.objects.get(pk=id))) for id in value]
        return super().optgroups(name, value, attrs)

def runner_select_json(request):
    # You might want to add some permission checking here. Otherwise everybody
    # can get data via this endpoint.
    query = request.GET.get('q', '').strip()
    qs = get_queryset(query)
    items = [dict(value=r.pk, text=runner_to_select_text(r)) for r in qs]
    return JsonResponse(dict(items=items, total_count=len(items)))

def runner_to_select_text(runner):
    return f'{runner.user.first_name} {runner.user.last_name}'

def get_queryset(query):
    if not query:
        return Runner.objects.none()
    return Runner.objects.filter(Q(user__username__icontains=query)|
                                     Q(user__first_name__icontains=query)|
                                     Q(user__last_name__icontains=query)).order_by('user__username')

Usage of the widget:
class RaceTeamForm(forms.ModelForm):
    class Meta:
        model = RaceTeam
        widgets = {
            'leader': RunnerSelectWidget(),
        }

JS to init the widget on whole page load and on fragment load:
htmx.onLoad(function(elt) {
    var allSelects = htmx.findAll(elt, ".runner-select")
    for( select of allSelects ) {
      new TomSelect(select, {
        // fetch remote data
        load: function(query, callback) {

            var url = '/runner_select_json?q=' + encodeURIComponent(query);
            fetch(url)
                .then(response => response.json())
                .then(json => {
                    callback(json.items);
                }).catch(()=>{
                    callback();
                });

        }
    })}});

urls.py
url('runner_select_json', runner_select_json, name='runner_select_json')


text:
Q: HomeKit throws Error 77 & 78 Every time I make a call to HomeKit on my iPod Touch 5th gen, I consistently get this error:
Printing description of error:

Error Domain=HMErrorDomain Code=78 "The operation couldn't be completed. (HMErrorDomain error 78.)"

This is on a call to homeManager.addHomeWithName(). I think that code 78 is
CloudDataSyncInProgress
This has been happening for days, though. What can I do to fix it?
If I sign out of iCloud and try again, I get code 77 (KeychainSyncNotEnabled).

A: Reference for the error codes are provided in NSError+HomeKit.m in the HMCatalog sample project for HomeKit.  (See "https://developer.apple.com/homekit/")  Note that you do not need to be a developer to access these resources.
The relevant error code pairs from the dictionary provided in that file are:
(int)76 : @"Keychain Sync Not Enabled"
(int)77 : @"Cloud Data Sync In Progress"
(int)78 : @"Network Unavailable"
At first glance, I would think this indicates a poor WiFi connection?
To clean up the iCloud Keychain for HomeKit, I found the following process worked.

*

*note: when you follow this process, all home information needs to be rebuilt

1) navigate to Settings > iCloud > Keychain
   disable the iCloud Keychain setting.
2) navigate to Settings > Privacy > HomeKit
   select the "Reset HomeKit Configuration..."
3) navigate to Settings > iCloud > Keychain
   enable iCloud Keychain setting

A: I am using iOS 9 beta and I had the same error 77 "Cloud Data Sync In Progress" and tried steps 1,2,3 over and over again and couldn't get it to work.
To finally get the app to work I did the following

*

*Removed the app.

*Turned off keychain. (Settings > iCloud > Keychain disable the iCloud Keychain setting)

*Signed out of iCloud. (Settings > iCloud -> Sign Out)

*Reset Homekit (Settings > Privacy > HomeKit select the "Reset HomeKit Configuration")

*Signed in to iCloud. (Settings > iCloud -> Sign In)

*Turned on keychain through security code. (Settings > iCloud > Keychain enable iCloud Keychain setting)

*Installed app.

*Gave app permission to HomeKit home data.


text:
Q: SDK location not found in Opentok-Chat-sample Code I have downloaded "Opentok chat sample" code from github and i opened project in android studio.But i got below compilation error.

 "SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable."

While i have set ANDROID_HOME environment variable.
and also i set sdk.dir in local.properties file.
How i resolve this error?
please help me.

A: Close project
Close the current project and you'll be pop up with dialog, then proceed  to Configure option.
Configure -> Project Defaults -> Project Structure -> SDKs on left column -> Android SDK Home Path -> give the exact path as you did on local.properties and select Valid Target.

A: Not a solution but suggestion,
its not the problem with your SDK location,
Build the new project by copying the res and src folder to your project, That works


text: Q: Python Venv with Windows Linux Subsystem Just started using Ubuntu on Windows and was impressed with what it could interact with that was Windows things, files and some programs, etc. but I was wondering if anyone has tried or knew more about the possibility of setting up a virtual environment for python that could be used by both windows and the Linux subsystem. Ideally my thought process would be to have the venv that I could install packages to from either a windows pip command or a Linux pip command. Would this work?


text:
Q: redirect the sql query will add all the files in that directory I have shell script as below
query="SELECT * from [myDB.myTable]"
echo $(date +"%Y-%m-%d %H:%M:%S")'|'land'|'Failure'|||'twice'|'$query > test.log

When I run above in some directory in my Unix PC, the test.log shows the result as below
2017-12-13 06:54:03|land|Failure|||twice| SELECT temp1.txt test tmp.log tt.sh from [myDB.myTable]

Actually I wanted query to be redirected as it is in the log file, instead it printed all the file names of that directory.
How can I fix this issue?

A: The dreaded pathname expansion strikes again! You can attribute that list of filenames to having a * in an unquoted expression.
echo "$(date +'%Y-%m-%d %H:%M:%S')'|'land'|'Failure'|||'twice'|'$query" > "test.log"
#    ^                                                                ^

cat "test.log"
> 2017-12-13 06:54:03|land|Failure|||twice| SELECT * from [myDB.myTable]

A: Use double quotes for your complete echo, the single quotes can be deleted:
echo "$(date +"%Y-%m-%d %H:%M:%S")|land|Failure|||twice|${query}" > test.log

I also have put curly braves in ${query}, that is not a solution for your problem but a good habit for future scripts.


text:
Q: junit - share a fixture between testcase I wonder whether it is possible to have a fixture that can be shared between testcases, for instance a hibernate session.

A: You want all your tests (not testcases) to share the same hibernate session ?
Create it in your setUp() method, only if it has not been already created, and store it in a static member of your testcase class, similar to a singleton implementation.


text:
Q: SPF issue with SpamAssassin I have an internal management app for a small company, written in Python and running on a Linode VPS, with which users can send occasional emails to their customers. The emails are quite straightforward: a text part (i.e. not HTML) with a PDF invoice attachment, created with the email stdlib module and sent via an external SMTP server (which is not hosted on the VPS).
Everything has been running quite smoothly for a while, but then lately I've been receiving complaints that the emails are often classified as spam by the receiving mail servers. I sent a test email to http://www.mail-tester.com and discovered that adding a few missing headers (Date and Message-ID in particular) helped to reduce the "spaminess" level of my messages. However there is one SPF-related SpamAssassin problem that still eludes me:
SPF_HELO_SOFTFAIL   SPF: HELO does not match SPF record (softfail)

I tried sending the test email to my Gmail account and here are the relevant headers that can be found when I do "Show Original":
Received-SPF: pass (google.com: domain of <sender_address> designates <ip_smtp_server> as permitted sender) client-ip=<ip_smtp_server>;
Received: from [<ip_linode_vps>] (helo=<domain_name_linode_vps>)

From this and some additional informations I gathered here and there, I'm pretty sure that this problem could be fixed by somehow modifying the SPF record of the SMTP server domain (which already exists, as a TXT record with a "v=spf1 a mx... ~all" string containing an ip4 reference to <ip_smtp_server>), but my current understanding is not enough to do so, so I'd appreciate any help.
Update:
<ip_linode_vps> = 69.164.216.89
<domain_name_linode_vps> = li131-89.members.linode.com
<ip_smtp_server> = 192.99.17.51
<domain_name_smtp_server> = mail.roucet.com
<already_existing_spf_record> = "v=spf1 a mx ip4:192.99.17.51 ip4:158.85.89.116 ip4:158.85.77.121 ~all"

A: All authorized mail servers should be listed in the SPF record.  As you now have a new authorized mail server, it should be added. Some SPAM checks differentiate between listed (A, MX) and permitted (~all), and will not treat unlisted address as a pass.  This penalizes senders who don't send via an approved server (often spambots).  The ~all policy indicates that the user doesn't really care who uses their domain, as compared to the -all policy that could get the email blocked or quarantined.
The alternative approach is to configure the new server to relay messages using the existing server.  It is common for applications to allow an email relay server to be configured.  In python, you would configure your VPS server name instead of localhost.
Whichever server is sending email, it should add the required headers when receiving the message from your application.  Alternatively, you can add the headers in the application.  There is a defined format for the date in the Date header.  The Message-id header has a defined format, but it not as strict. Message ids resemble an email address, but the left side should be a unique id.


text:
Q: Neo4j cq driver failed with "Unrecognized transaction id. Transaction may have timed out and been rolled back." I have recently moved our staging environment from a neo4j 2.2.2 community edition docker container to a 2.3.0-RC1 HA cluster.
This go script provides an API end-point for authenticated users to upload a csv file which then gets processed in a way that it matches the id of a product (upc) with the existing product data. On a match the user's associated distributor creates a relationship to the found product and adds information available in the csv file onto that created relationship.
My problem is that I'm getting a failure from Neo4j in the new environment that I can't track down: "Unrecognized transaction id. Transaction may have timed out and been rolled back." when the user tries to upload the file.
Here's the complete script (my second golang script, so pointers on style are welcome, too).
package main

import (
    "database/sql"
    "encoding/csv"
    "fmt"
    _ "gopkg.in/cq.v1"
    _ "gopkg.in/cq.v1/types"
    "net/http"
    "os"
    "strconv"
    "strings"
)

type ProductInfo struct {
    Upc       uint64
    InStock   uint64
    BasePrice float64
    LeadMin   uint64
    LeadMax   uint64
    Sku       string
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    file, _, err := r.FormFile("file")

    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    defer file.Close()

    distributor := strings.Split(r.URL.Path, "/")[2]

    reader := csv.NewReader(file)
    reader.FieldsPerRecord = 6
    reader.TrimLeadingSpace = true

    rawCSVdata, err := reader.ReadAll()

    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    db, err := sql.Open("neo4j-cypher", os.Getenv("MINAMI_NEO4J_URL"))
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }
    defer db.Close()

    tx, err := db.Begin()
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    stmt, err := tx.Prepare(`
        MATCH (d:Distributor {slug:'` + distributor + `'})
        MATCH (p:Product {upc: {0}})
        MERGE (d)-[r:SELLS]->(p)
        SET r.inStock = {1}, r.sellsFor = {2}, r.leadMin = {3}, r.leadMax = {4}, r.sku = {5}
        RETURN p LIMIT 1
    `)

    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    var Row ProductInfo

    for _, each := range rawCSVdata {
        Row.Upc, _ = strconv.ParseUint(each[0], 10, 0)
        Row.InStock, _ = strconv.ParseUint(each[1], 10, 0)
        Row.BasePrice, _ = strconv.ParseFloat(each[2], 0)
        Row.LeadMin, _ = strconv.ParseUint(each[3], 10, 0)
        Row.LeadMax, _ = strconv.ParseUint(each[4], 10, 0)
        Row.Sku = each[5]

        stmt.Exec(Row.Upc, Row.InStock, Row.BasePrice, Row.LeadMin, Row.LeadMax, Row.Sku)
    }

    err = tx.Commit()
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    fmt.Fprintf(w, "File uploaded and products in store updated.")
}

func main() {
    http.HandleFunc("/", uploadHandler)
    http.ListenAndServe(":8888", nil)
}

I'm using haproxy to know who's master and who are the slaves in the HA cluster. The environment variable MINAMI_NEO4J_URL is set to the master via haproxy in this form: http://{haproxyip}:{masterport}


text:
Q: how does kafka synchronize data timestamps between different brokers and how is timestamp created in kafka How does Apache Kafka manage synchronizing timestamps between different brokers in a cluster, which time is actually recorded and converted as the message creation timestamp
and how does Kafka verify it's time precision

A: The record timestamp is stored as part of the record's bytes. The bytes of each record are copied between brokers, including the timestamp.
By default (depending on the client), the producer client generates/sets the timestamp of the record, not the broker
You otherwise might want to look at the broker properties for message timestamps

log.message.timestamp.difference.max.ms

The maximum difference allowed between the timestamp when a broker receives a message and the timestamp specified in the message. If log.message.timestamp.type=CreateTime, a message will be rejected if the difference in timestamp exceeds this threshold. This configuration is ignored if log.message.timestamp.type=LogAppendTime

Type: long
Default:  9223372036854775807


text:
Q: Display info on listview from 2 (or more) tables There is way to populate ListView from 2 (or more) tables that not connected one to other?
Example:
I have 2 tables:

firstTable , secTable

each table include different columns.. ex:

firstTable include: id, name, city, display (bit)
SecondTable include: id, name, country , display (bit)

*

*The tables already used in site so it cant be change their counstractour

I want to display in List View

name (from firstTable)
name(from SecondTable)
Where display = True

I've been tried to do that with SqlDataSource without success.
The details on the listview display on seperate blocks (like news blocks).
It is possible?

A: It is possible with SqlDataSource but the Selectcommand should use statement like:
 Select f.name, s.name from firstTbl as f inner join secondTbl as s on f.ID = s.ID
                       where f.display='true'


text:
Q: Selecting the first and the last word from a 3 word long string in PLSQL For example I have names like these:
John Lucas Smith
Kevin Thomas Bacon

I need to do it with regexp_substr, or replace or something like that.
and what I want to get is:
John Smith
Kevin Bacon

Thank you!

A: Something like this?
SQL> with test (col) as
  2    (select 'John Lucas Smith'   from dual union
  3     select 'Kevin Thomas Bacon' from dual union
  4     select 'Little Foot'        from dual
  5    )
  6  select regexp_substr(col, '^\w+') ||' '||
  7         regexp_substr(col, '\w+$') first_and_last
  8  from test;

FIRST_AND_LAST
-------------------------------------
John Smith
Kevin Bacon
Little Foot

SQL>


text:
Q: Infopath 2010 setting focus on a field in .NET Code? I'm building a desktop (thick) Infopath 2010 form with code-behinds that need to set form focus on certain fields so that they are on the field in question for easier entry.  Is there a way to do this in .NET?  Offhand I can't seem to find a way.

A: Use the SelectText method of the View class
Link for script
http://msdn.microsoft.com/en-us/library/bb251012(v=office.12).aspx
Link for managed code
http://msdn.microsoft.com/en-us/library/microsoft.office.infopath.view.selecttext.aspx


text:
Q: Show both staged & working tree in git diff? If I run git diff I see the changes in my working tree, and if I run git diff --staged (alternatively --cached) then I see the changes that are staged (w/ git add) but is there a way with git diff to see all in one go?

A: If you mean the changes between the working tree and your HEAD commit (i.e. both staged and unstaged changes together) this is just done with:
git diff HEAD

A: The diffuse visual diff tool can do that: It will show three panes if some but not all changes are staged. In the case of conflicts, there will even be four panes.

Invoke it with
diffuse -m

in your Git working copy.
If you ask me, the best visual differ I've seen for a decade.

A:
Is there a way with git diff to see all in one go?

There is, with Git 2.4.0+ (April 2015).
See commit 4055500 from Michael J Gruber mjg:

commit/status: show the index-worktree diff with -v -v (or -vv)
git commit and git status in long format show the diff between HEAD
  and the index when given -v. This allows previewing a commit to be made.
They also list tracked files with unstaged changes, but without a diff.
Introduce '-v -v' (or -vv) which shows the diff between the index and the
  worktree in addition to the HEAD index diff. This allows a review of unstaged changes which might be missing from the commit.
In the case of '-v -v' (or -vv), additional header lines
Changes to be committed:

and
Changes not staged for commit:

are inserted before the diffs, which are equal to those in the status part; the latter preceded by 50*- to make it stick out more.

In the OP's case, a simple git status -v -v (or git status -vv) will show both staged and unstaged diffs.


text:
Q: Can Veracrypt decrypt disk after alter one bit from 0 to 1? I use Veracrypt to encrypt my removable hard disk.As my removable hard disk is HDD,there's very little probability write 1 when should write 0.
If there's one bit error,can Veracypt successfully decrypt my removable hard disk?


text:
Q: QFiledialog returns the incorrect directory A snippet of what i'm using looks like this
QDir lastDir;
QFileDialog dial(this);

dial.getOpenFileName(this,
                     tr("Open File"),
                     QString("/home"),
                     tr("Raw Images (*.nef *.NEF *.dng *.DNG)"));

lastDir = dial.directory();
qDebug() << lastDir;

The output, is completely wrong, no matter which directory I end up in. However, the incorrect directory is always the same.
AFAICT i'm doing nothing wrong here. What is going on here? Cheers

A: getOpenFileName() is a static function which immediately opens a "file picker" dialog and returns, once the user is finished with the dialog, "an existing file selected by the user". You use it like this (note the use of :: and the class name QFileDialog instead of the object name):
QString fileName = QFileDialog::getOpenFileName(this,
                 tr("Open File"),
                 QString("/home"),
                 tr("Raw Images (*.nef *.NEF *.dng *.DNG)"));

directory() is non-static and returns "the directory currently being displayed in the dialog". This function is meant to be called while the dialog is still open, it's intended for use cases which are not covered by the static calls.

What is happening here is you have instantiated an object, called a static function on it (which won't affect its state), and then called directory() which will just reflect the original state of the object, which is probably the working directory. Instead, you need to store the return value of the getOpenFileName() call in a variable, as shown above.
If you want to ask the user to just choose a directory, you could consider using getExistingDirectory() instead. Alternatively, if you want to extract the directory from the filename, the QDir class has some functions useful for this.


text:
Q: Android, application stopped I have an android (4.1) application which reportedly (can't recreate) chrashes with the message "app as stopped". The problem, however, is that the user has to press "OK" in the alert that pops up. The chrash only occur when the app is not active (on screen). This indicates that Android kills of my app because of memory or naughtiness. I'f been investigating for memory leaks, because i handle bitmaps in the app, that did not pay off.
I have a catch and log all default handler like this:
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            public void uncaughtException(Thread thread, Throwable ex) {
                Log.e(StaticData.LogTag, "Unhandled exception app", ex);
            }
        });

To log all exceptions. Afterwards i call original exceptionhandler. This handler is put on the Apps main activity. The method is never called when the "stopped" chrash happens, but is in other cases.
My app uses IntentService to send data to a server in background. This is not a long running service, 1-10s. I will try to put a default exception handler on the service as well. I mention the service because the app is killed when "off screen", so I thought that might have a connection to the problem, but the cause evades me.
Furthermore I use BroadcastReceiver to notify the apps main activity about network connection changes, because the app is used in turbulent network conditions. This is relevant because I'f seen BroadcastReceiver mentioned when people talk about possible memory leak issues. My implementation of BradcastReceiver goes like this:
Serivce side:
sendOrderedBroadcast(uploadedIntent, null);

Activity side:
public static class NetworkStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent in) {
        // super.onReceive(context, intent);
        Log.d(StaticData.LogTag, "Network connectivity change");
        if (in.getExtras() != null) {
            NetworkInfo ni = (NetworkInfo) in.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
                Log.i(StaticData.LogTag, "Network " + ni.getTypeName() + " connected");
                ...
            }
        }
        if (in.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
            Log.d(StaticData.LogTag, "There's no network connectivity");
        }
    }
}

As i mentioned in the beginning, the problem is mainly an annoyance for the user because he has to press ok on a popup when looking at mails or taking a call. The app is robust enough to handle that it gets killed from time to time, however, I would like to figure out why my app is knocked out.
PS. I have tried to get the users to send be bug reports via mx log logcollector, but no cigar.

A: I seem to have solved this problem. I think the culprit was a static reference to the main activity in the application. I was using this static to get a reference to the applications Context. This however this is unnecessary in Service and BroadcastReceiver, because they have their own ref to a "Context".
Why the long face?
A static reference to a Android view, like Activity, is kept in memory and can't be freed by the garbage collector. This was the idea behind making it static. I wanted to have a future reference to the object, but is the wrong approach.
When changing orientation (eg.), Android recreates the current activity (and children views), and the old is freed for GC. When you have a static ref to a view, its not collected, and now you have 2 instances of the Activity. Do the math and realize that this obviously fills memory over time (leak) and Android will nuke the app at some point.
When facing this problem you have to realize that you have to carry your data/states over to the new Activity, for example by using shared memory, a local database or a savedInstanceState:
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
       int value = savedInstanceState.getInteger("key");
    }
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
    outState.putInteger("key", value);
}


text:
Q: Line 34: TypeError: __init__() takes exactly 3 arguments (1 given) class Solution:
    def __init__(self, secret, guess):
        self.secret = secret
        self.guess = guess
    def getHint(self):
        right=0; wrong=0
        listSecret = list(self.secret)
        listGuess = list(self.guess)
        for i in range(len(listSecret)):
            if listSecret[i] == listGuess[i]:
                right = right + 1
            else:
                wrong = wrong + 1
        return str(right)+ "A" + str(wrong) + "B"
guessG = raw_input("")
secretS = raw_input("")
print Solution(str(guessG), str(secretS)).getHint()

When I run the code in pycharm, it works. However, when I submit the code to leetcode, it warns "runtime error", see the picture.

A: This is a leetcode service issue
In contrast to the popular format when communication between the test driver and your program is done with standard IO, this service provide another way.
In the begining you are given a code snippet that states communcation interface implicitly. You should not change it, i.e change method signatures including constructor signature. Your input is then passed as arguments to the code snippet method with result expecting to be its method return value.
How all it works and way strange error is generated
The code you pass in your online editor is enreached with some additional code that generates that behaviour.
To check this idea I've written a program that prints its own code (by modifying given snippet):
class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """

import sys
print sys.argv ## this prints program arguments

## argv[0] is the name of file being executed. Just print it!
with open(sys.argv[0], 'r') as fin:
    print fin.read()

The result of execution on the codeleet service was
['/usr/lib/gcc/x86_64-linux-gnu/4.9.1/.cache/prog_joined.py', '-recursion_limit', '8100']
# coding: utf-8
from precompiled.__serializer__ import __Serializer__
from precompiled.__deserializer__ import __Deserializer__
from precompiled.__utils__ import __Utils__
from precompiled.listnode import ListNode
from precompiled.interval import Interval
from precompiled.treenode import TreeNode
from precompiled.treelinknode import TreeLinkNode
from precompiled.undirectedgraphnode import UndirectedGraphNode
from precompiled.randomlistnode import RandomListNode
from precompiled.point import Point
import precompiled.__settings__
import array
import bisect
import collections
import copy
import heapq
import itertools
import math
import operator
import re
import sets
import string

# user submitted code insert below
class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """

import sys
print sys.argv

with open(sys.argv[0], 'r') as fin:
    print fin.read()
import sys
def _driver():
    SEPARATOR = "\x1b\x09\x1d"
    f = open("user.out", "w", 0)
    lines = __Utils__().read_lines()
    while True:
        try:
            line = lines.next()

            param_1 = __Deserializer__().to_string(line)
            line = lines.next()
            param_2 = __Deserializer__().to_string(line)

            ret = Solution().getHint(
                param_1, param_2
            )
            out = __Serializer__().serialize(ret)

            print >> f, "%s" % out
            sys.stdout.write(SEPARATOR)
        except StopIteration:
            break

if __name__ == '__main__':
    _driver()

This shows the whole program being executed. As you can note it is a bit expanded version of your own code. The version has the following lines:
ret = Solution().getHint(
                    param_1, param_2
                )

They are the source of your problem


text:
Q: Why do powers of 10 print in scientific notation at the 5th power? I would like to know if and how the powers of 10 are related to the printing of scientific notation in the console.  I've searched R docs and haven't found anything relevant, or that I really understand.
First off, my scipen and digits settings are
unlist(options("scipen", "digits"))
# scipen digits
#      0      7

Now, powers of 10 are printed normally up to the 4th power, and then printing switches to scientific notation at the 5th power.
10^(1:4)
# [1]    10   100  1000 10000
10^(1:5)
# [1] 1e+01 1e+02 1e+03 1e+04 1e+05

Interestingly, this does not happen for some other numbers larger than 10.
11^(1:5)
# [1]     11    121   1331  14641 161051

Judging from the following, 5 digits seem significant.
100^(1:2)
# [1]   100 10000
100^(1:3)
# [1] 1e+02 1e+04 1e+06

So my questions then are:
Why is scientific notation activated between the 4th and 5th power for 10 and not for other numbers? Is the number 5 significant? Furthermore, why 5 and not a number closer to the maximum digits option of 22?

A: I'm confused as to what exactly is your question; or, more specially, how you would use an answer to this question to somehow change/control the behavior of R. You you trying to format numbers a certain way? There are better ways to do that.
When you type values like that, the results are implicitly run though one of the print() commands to be formatted "nicely" to the console. Whenever things have to look "nice" on screen, the code to do that is often ugly. Here most of the that code is taken care of by the formatReal function, and the helper  scientific function. The latter tracks the following information for a number
/* for a number x , determine
 *  sgn    = 1_{x < 0}  {0/1}
 *  kpower = Exponent of 10;
 *  nsig   = min(R_print.digits, #{significant digits of alpha})
 *  roundingwidens = 1 if rounding causes x to increase in width, 0 otherwise
 *
 * where  |x| = alpha * 10^kpower   and  1 <= alpha < 10
 */

Then the former function uses this information to try to make "nice" looking numbers by balancing values to the left and the right of the decimal place. It's a combination of many things like the order of magnitude of the number and the number of significant digits as well as environmental influences form the scipen option, etc.
print() is only meant to make things look "nice." What exactly is nice depends on all the values in a vector. You'll find few hard cutoffs in that code; it's very adaptive. There is no easy way to concisely describe everything it does in the general case (which is what it sounds like you are asking for).
The only thing that is certain is that if you need to have your numbers formatted in a certain way, use a function like sprintf() or formatC() that allows for precise control.
Of course this behavior is dependent on class() and i've pointed the the formatReal stuff since that's where most tricky things happen. But observe the difference when you use integers
c(10, 100, 1000, 10000, 100000)
# [1] 1e+01 1e+02 1e+03 1e+04 1e+05
c(10L, 100L, 1000L, 10000L, 100000L)
# [1]     10    100   1000  10000 100000

A: Well, the answer is actually there in the definition of scipen in ?options, although it's pretty hard to understand what it means without playing around with some examples:

'scipen': integer.  A penalty to be applied when deciding to print
       numeric values in fixed or exponential notation.  Positive
       values bias towards fixed and negative towards scientific
       notation: fixed notation will be preferred unless it is more
       than 'scipen' digits wider.

To see what that means, examine the following three pairs of exactly identical numbers. In the first two cases, the width in characters of the fixed notation that is less than or equal to the width of the scientific, so fixed notation is preferred.
In the third case, though, the fixed notation is wider (i.e. "more than 0 digits wider"), because the 5 zeros amount to more characters than the 4 characters used to represent the same value using e+nn. As a result, in that case scientific notation is preferred.
1e+03
1000
# [1] 1000

1e+04
10000
# [1] 10000

1e+05
100000      ## <- wider
# [1] 1e+05

Next, examine some numbers that also end with lots of zeros, but whose representation in scientific notation will require use of a .. For these numbers, scientific notation will be used once you have 6 or more zeros (i.e. more than the 5 characters taken up by one . and the characters e+nn).
1.1e+06
1100000
# [1] 1100000

1.1e+07
11000000     ##  <- wider
# [1] 1.1e+07

Reasoning about the tradeoff gets a bit trickier for most other numbers, for which the values of both options("scipen") and options("digits") come into play, but the general  idea is exactly the same.
To see some of the slightly surprising complications that come into play, you might want to paste the following into your console (perhaps after first trying to predict where within each series the switch to scientific notation will occur).
100001
1000001
10000001
100000001
1000000001
10000000001
100000000001
1000000000001

111111
1111111
11111111
111111111
1111111111
11111111111
111111111111
1111111111111


text:
Q: Visual Studio 2015 - C# Windows Universal App missing assembly reference Today I cloned my windows universal app project from github onto a new machine running a new install of Visual Studio 2015.
After the project loaded, I noticed that all of my pages and properties were underlined red with many errors
CS0246 C# The type or namespace name "<name>" could not be found (are you missing a using directive or an assembly reference?)
as well as others such as
CS0518  C# Predefined type 'System.Void' is not defined or imported
CS0012  C# The type '' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
CS1545  C# Property, indexer, or event 'Application.Suspending' is not supported by the language; try directly calling accessor methods 'Application.add_Suspending(SuspendingEventHandler)' or 'Application.remove_Suspending(EventRegistrationToken)'
I noted that CS0012 actually gives information about what is needed to address the issue:

You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Looking in my project.json file, however, I could see
"dependencies": {
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
}

As a result the project will not build or run, just lists lots of errors, how can you fix this?

A: Looking in the References of the project in the Solution Explorer it can be seen that even though Microsoft.NETCore.UniversalWindowsPlatformis listed as a dependency, it's missing from the project and this is causing the issue.
Visual studio knows that the assembly is a dependency and needs to be referenced but it doesn't seem to come preinstalled with Visual Studio 2015, even when you install all of the Windows 10 development tools during setup, and it doesn't seem to autofetch the package even when it knows it needs it!
To fix, you need to manually install the package using NuGet and it will then be resolved correctly as a reference.
To do this, right click on References, then click Manage NuGet Packages....
On the NuGet Package Manager screen, search for Microsoft.NETCore.UniversalWindowsPlatform and it will be an exact match.
Click on Install in the details pane on the right hand side and Visual Studio will fetch the package and include it as a reference in your project
The red underlining will then all disappear and you can continue working on your project!

A: I had similar problem. universal project I create my self had reference there. Some of the samples for windows iot sites didn't have reference when downloaded. NUGET said it was already installed. for me the solution was to build the solution and it repaired itself.

A: what worked for me was
Tools -> nuget package Manager -> manage nuget packages for solution
and update the packages for the solution
it adds a lot of stuff and then updates your solution
hope it works for you

A: Have you installed the SDKs? Its possible that it cant find the files assosiated with the references.
windows 10 sdk
windows 8.1 sdk


text:
Q: Large difference in key transformation rounds for KeePass and KeePassX that I would like explained Below I am using v2.32 of KeePass and v2.0.2 for KeePassX, and I am using Linux.
I was messing around with the number of transform rounds and noticed when choosing one second delay in KeePassX (this is called benchmark on KeePassX) gives 21760000 rounds and KeePass gives 522174. KeePassX opens both files very quickly, taking about a second on the 21760000 rounds one, while KeePass opens the 21760000 round file in around 43 seconds. To rub salt in the wound, Keepass2Android opens the 21760000 file in around 4 seconds, and the other pretty close to instantly.

What is causing such a large difference in performance between the key transformation rounds for KeePass and KeePassX?

It appears KeePass is doing something wrong, at least on the Linux version. Also note 21760000/43 is approximately 522174. I am somewhat worried that KeePass could be giving a false sense of security, since it appears an attacker could potentially be more far efficient at brute forcing than KeePass lets on.
(I know KeePass and KeePassX are not exactly related to each other)
Update: I tested on my laptop at work (which is older, and the hardware isn't nearly as good), with more up to dated software and KeePass v2.34 took about 25 seconds and KeePassX(v2.0.3) took about 7 seconds. When I get a chance I will update software on my home desktop, but it seems the question is still valid since those are the most up to date software and that is still a pretty big difference.


text:
Q: Estruturação com html/div e css Sou iniciante/entusiasta e estou com dificuldades para largar de vez o "table", estou com problemas para fazer esta relação abaixo sem deixar um valor em pixels fixo.

Bom, foi resolvido e este foi o resultado:

*{
    margin: 0;
    padding: 0;
    font-family: "Open Sans";
}

/* menu superior */
.links{
    width: 100%;
    height: 50px;
    position: fixed;
    display: flex;
}

.links label{
    padding: 12px 0;
    flex-grow: 1;
    cursor: pointer;
    transition: all .4s;
    text-align: center;
    font-size: 100%;
    font-weight: Bold;
    color: #ffffff;
    background-color: rgba(000,000,000,.3);
}

.links label:hover{
    background-color: rgba(255,255,255,.3);
    color: #111111;
}
/* Botões */
.scroll{
    display: flex;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}

.scroll input{
    display: none;
}

.bloc{
    width: 100vw;
    height: 100vh;
    justify-content: center;
    align-items: center;
    display: flex;
}

/* páginas */
#inicio{
    background-color: #ffffff;
}

#sobre{
    background-color: #1aaf0b;
}

#processo{
    background-color: #d0d702;
}

#receitas{
    background-color: #d98000;
}

#social{
    background-color: #ffffff;
}

/* rolamento e transição de páginas */
.sections{
    transition: all .4s;
}

#rd_sobre:checked ~ .sections{
    margin-top: -100vh;
}

#rd_processo:checked ~ .sections{
    margin-top: -200vh;
}

#rd_receitas:checked ~ .sections{
    margin-top: -300vh;
}

#rd_social:checked ~ .sections{
    margin-top: -400vh;
}

/* TESTES */

#content
{
    position:relative;
    height:80%;
    width:80%;

}
#esquerda
{
    height:100%;
    width:32%;
    float:left;
}
#dirsup
{
    height:25%;
    width:66%;
    float:right;
    border: 1px solid black;
    background: green;
}
#dirinf
{
    position:absolute;
    height:69%;
    width:66%;
    border: 1px solid black;
    background: yellow;
    position: absolute;
    right: 0;
    bottom: 0;
}

#centlogo{
    position: relative;
    top: 40%;
    transform: translateY(-50%);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link href="css/bootstrap.css" rel="stylesheet">

        ÍNICIO
        SOBRE
        PROCESSO
        RECEITAS
        SOCIAL

        <input type="radio" name="grupo" id="rd_inicio" checked="true">
        <input type="radio" name="grupo" id="rd_sobre">
        <input type="radio" name="grupo" id="rd_processo">
        <input type="radio" name="grupo" id="rd_receitas">
        <input type="radio" name="grupo" id="rd_social">

Teste

TESTE

A: Basicamente você pode fazer desta forma:

Qual dificuldade está encontrando ? Se não for isso, comenta que nós ajustamos...

A: Olá, você poderia utilizar um sistema de grid para estruturar seu site, eu faria algo assim:

*{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

aside{
  background-color: #27ae60;
  margin: 0 3.33%;
  min-height: 70%;
  width:40%;
}

aside, #secao{
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
}

body, html{
  height: 100%;
}

header{
  background-color: #34495e;
  diplay: block;
  padding: 40px;
}

#secao{
  background-color: #27ae60;
  width: 50%;
}

#secao > h2{
  padding: 20px;
}

#secao > section{
  background-color: #f39c12;
  border-top: 40px solid #fff;
  padding: 20px;
}

Sua imagem aqui

título da seção

Sub título

Observe que os elementos aside e a section#secao estão com display inline-block e a margin é calculada para não quebrar a estrutura.
Enfim existem várias formas de fazer, qualquer dúvida só comentar.


text:
Q: Insert text into any arbitrary textbox-like element (not necessarily simple HTML) on page using Javascript in Chrome Extension I'm trying to create a Chrome Extension that allows a user to press a keyboard shortcut and have a visual keyboard appear near the textbox they're currently editing.
Currently, when the user presses the shortcut, I check if there is an active element that is a textbox using the following snippet:
/* Get the active textbox on the window, ie. the one with the blinking cursor the user is typing in */
function get_active_textbox() {
    let activeElement = document.activeElement;

    // Is there an active element, and if so, is it of type `text`? Other types of active elements could be checkboxes
    // or radio buttons
    if (activeElement && activeElement.type === "text") {
        return activeElement;
    }
}

Once I have the textbox, I can easily insert my text into it. This works perfectly for normal textboxes, but not situations where the textbox is a little more... complicated... such as a draft in Google Inbox:

this is some text

or the compose box in Facebook Messenger:

this is some text

Is there a more general purpose solution that would allow me to find and insert text into any arbitrary textbox-like element on a page?


text:
Q: PHP session cleared after page loads in ie I'm working on a site that has a My Account section that the user has to login to. I'm storing the users basic information in the session after they have logged in.
I'm having no problem in Chrome or Firefox with this. However, in IE 8 I login, and it redirects to the main back office page. It loads, but right after the session is cleared.  I tested this by printing the session after session_start() then again at the end of the page.  All the information is there when the page loads.  If I open a separate page and print out the session right after, it's already cleared. Again, only in IE does this happen.
Is there something I'm missing here?
CODE
This is the code on all of the Account pages.
    <?php
require_once('inc_session.php');
require_once('bo_session_check.php');

?>

On the page logged into (backoffice.php), the only other time the session is used, is when it is read to determine what kind of account the person has logged into, for example:
 <?php if($_SESSION['user_type']=='member'){?>

Code for inc_session.php
    <?php

if(!isset($_SESSION['is_mobile'])){

$mobile_browser = '0';

    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
        $mobile_browser++;
    }

    if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
        $mobile_browser++;
    }

    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
    //echo $_SERVER['HTTP_USER_AGENT'];
    $mobile_agents = array(
        'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
        'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
        'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
        'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
        'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
        'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
        'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
        'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
        'wapr','webc','winw','winw','xda ','xda-');

    if (in_array($mobile_ua,$mobile_agents)) {
        $mobile_browser++;
    }

    if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0) {
        $mobile_browser++;
    }

    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'ipad') > 0) {
        $mobile_browser++;
    }

    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
        $mobile_browser = 0;
    }

    if ($mobile_browser > 0) {
       $_SESSION['is_mobile']='yes';
    }
    else {
       $_SESSION['is_mobile']='no';
    }

}

/* TURN MOBILE SITE OFF */
//$_SESSION['is_mobile']='no';

$page=strtok($_SERVER["REQUEST_URI"],'?');
if(substr($page, 0, 3)!="/m/" && $_SESSION['is_mobile']=='yes' && substr($page,-3) =='php'){
    if( isset($_SERVER['HTTPS'] )  && $_SERVER['HTTPS'] != 'off' ){
            $heading='https://';
        }else{
            $heading='http://';
        }
   header("Location: " . $heading . $_SERVER["SERVER_NAME"] . "/m" . $_SERVER["REQUEST_URI"]);
   exit();

}

$page=substr($page, strrpos($page, '/', -1));
$ssl_pages=array('/backoffice.php', '/login.php', '/login-partner.php', '/checkout.php', '/checkout_member.php', '/membership.php', '/partner.php');

if(in_array($page, $ssl_pages) || substr($page, 0, 3)=='/bo'){
    if($_SERVER[HTTP_HOST]!='domain.com'){
        header("Location: https://domain.com" . $_SERVER["REQUEST_URI"]);
    }elseif($_SERVER["HTTPS"] != "on") {
       header("HTTP/1.1 301 Moved Permanently");
       header("Location: https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
       exit();
    }
}else{
    if($_SERVER["HTTPS"] == "on"){
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
        exit();
    }
}

ini_set("session.cookie_domain", "domain.com");

session_start();

?>

This is bo_session_check.php

if(isset($_SESSION['agreed']) && $_SESSION['agreed']!="yes" && $_SESSION['admin']!="yes"){
    /*
    DEPRECIATED
    header("location: bo_terms.php");
    exit();
    */
    $_SESSION['agreed']="yes";
}elseif(isset($_SESSION['user_id']) && $_SESSION['user_id']!=""){
    /*ALL GOOD*/
}else{
    /*YOU GOTTA GO*/
    header("location: login.php");
    exit();
}

?>

Here is the PHP Session Info

A: Since $_SESSION is handled server-side -- this is going to mean that cookies are disabled in IE8 -

A: You have session.use_only_cookies = On, which is fine, but just be aware that anyone with cookies turned off will fail to load your site properly.
However, this is not what is causing the issue.
From other StackOverflow answer:

Try putting [PHP code below] prior to starting the session - this would ensure that the session cookie will not expire until the browser is closed.

session_set_cookie_params(0);

Hope this helps solve your problem.  Worst case scenario, pass the SESSION ID (SID) through the URLs in between page loads and redirects.  Refer to this page in the PHP Manual on passing Session IDs.  You would have to do this through the Location: http://URL that you have.


text:
Q: Is it possible to call local functions from imported in Vuex? I have simple file called _mixin.js which consists of:
const mutations = {
    _set(state, data) {
        for (let key in data) {
            if (key in state) {
                state[key] = data[key];
            }
        }
    },

    _reset(state) {
        const s = initialState();

        Object.keys(s).forEach(key => {
            state[key] = s[key];
        });
    }
};

export default {
    mutations
};

What I'm trying to do is share this two methods between all existing modules mutation like this:
import _MIXINS from 'store/modules/_mixins';

function initialState() {
    return {
        id: null,
        email: null,
        password: null,
        name: null,
    };
}

const state = initialState();

const mutations = {
    ..._MIXINS.mutations,

    setId(state, id) {
        state.id = id;
    }
};

The problem is that browser says it cant find function initialState as its not in same file.

A: Just do like this:
// sharedLogic.js
export function initialState () {
    // your logic
}

// store module
import { initialState } from '<pathTo sharedLogic.js>'
const state = initialState();

// mixin module
import { initialState } from '<pathTo sharedLogic.js>'
const mutations = {
   ...
    _reset(state) {
        const s = initialState();

        Object.keys(s).forEach(key => {
            state[key] = s[key];
        });
    }
};


text:
Q: XML De/Serialization : How to define different name for same property of different instance of the class I'm trying to serialize an object which contains two lists of the same object.
public class Foo
{
   public List<ClassA> DataA {get;set;}
   public List<ClassA> DataB {get;set;}
}

public class ClassA
{
  public string Code {get;set;}
  public string Value {get;set;}
}

In the xml file I would like that the properties of the class have different name. Something like this :
<Foo>
  <DataA>
    <ClassA>

      <Value></Value>
    </ClassA>
  </DataA>
  <DataB>
    <ClassA>
      <Name></Name>
      <Text></Text>
    </ClassA>
  </DataB>
</Foo>

I tried to use "XmlAttributeOverrides" but the property name is modified for all instance, not just one.
Is there a way to do this ? Maybe a custom XmlSerializer ?
Thanks

A: Copy the input XML into your Clipboard
<Foo>
  <DataA>
    <ClassA>

      <Value></Value>
    </ClassA>
    <ClassA>

      <Value></Value>
    </ClassA>
  </DataA>
  <DataB>
    <ClassA>
      <Name></Name>
      <Text></Text>
    </ClassA>
    <ClassA>

        <Value></Value>
    </ClassA>
  </DataB>
</Foo>

and in Visual Studio add a new class file to your project.
Select and clear all content of the newly created file  inside the namespace an use Edit->paste Special->insert XML as code (or something similar, I have a german IDE)

should give you something like this (after some reorganizing)
namespace SandBoxApp
{

  // HINWEIS: Für den generierten Code ist möglicherweise mindestens .NET Framework 4.5 oder .NET Core/Standard 2.0 erforderlich.
  /// <remarks/>
  [System.SerializableAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
  [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
  public partial class Foo
  {

    private FooClassA[] dataAField;

    private FooClassA[] dataBField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("ClassA", IsNullable = false)]
    public FooClassA[] DataA
    {
      get
      {
        return this.dataAField;
      }
      set
      {
        this.dataAField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("ClassA", IsNullable = false)]
    public FooClassA[] DataB
    {
      get
      {
        return this.dataBField;
      }
      set
      {
        this.dataBField = value;
      }
    }
  }

  /// <remarks/>
  [System.SerializableAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
  public partial class FooClassA
  {

    private object codeField;

    private object valueField;

    /// <remarks/>
    public object Code
    {
      get
      {
        return this.codeField;
      }
      set
      {
        this.codeField = value;
      }
    }

    /// <remarks/>
    public object Value
    {
      get
      {
        return this.valueField;
      }
      set
      {
        this.valueField = value;
      }
    }
  }

You may want to refactor to your needs, but it should give you the direction.
To sum up,  I think you miss the Attribute:
 [System.Xml.Serialization.XmlArrayItemAttribute("ClassA", IsNullable = false)]

on your list-Poperties


text:
Q: Selenium "Unrecognized command: actions" I am trying to do a mouse click base on position. However, I can't seem to make action work an always get the following message. I reproduced the problem by trying to double click on google.com main search bar.

For help, see: https://nodejs.org/en/docs/inspector
  (node:38864) UnhandledPromiseRejectionWarning: UnknownCommandError: Unrecognized command: actions
  warning.js:18
      at buildRequest (c:\GitRepo\MMT4\src\javascript\Web.Tests\node_modules\selenium-webdriver\lib\http.js:375:9)
      at Executor.execute (c:\GitRepo\MMT4\src\javascript\Web.Tests\node_modules\selenium-webdriver\lib\http.js:455:19)
      at Driver.execute (c:\GitRepo\MMT4\src\javascript\Web.Tests\node_modules\selenium-webdriver\lib\webdriver.js:696:38)
      at process._tickCallback (internal/process/next_tick.js:68:7)
  (node:38864) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
  warning.js:18
  (node:38864) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

imported the packages with npm
"devDependencies": {
    "@types/node": "^10.12.0"
},
"dependencies": {
    "chromedriver": "^2.43.0",
    "selenium-webdriver": "^4.0.0-alpha.1"
}

According to the documentation I found here, it should to work
https://seleniumhq.github.io/selenium/docs/api/javascript/index.html
https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/input_exports_Actions.html
Also found different example on web which support it should work, but cannot see what is missing in this basic example:
"use strict";
require('chromedriver');
const { Builder, By, Key, until, ActionSequence } = require('selenium-webdriver');
(async function run() {
    let driver = await new Builder().forBrowser('chrome').build();
    try {
        await driver.get('http://www.google.com');

        await driver
            .actions()
            .doubleClick(By.id('lst-ib'))
            .perform();
    }
    finally {
        await driver.quit();
    }
})();

Also tested in a project with protractor and it seem to work, but I don't see why I would need protractor in this project since it does not use Angular.
Thanks

A: I found solution
i tried downgrade selenium-webdriver version 3.6.0
then, maybe it's possible working
and keydown method only 4 ways execute(i need use keyboard!)
key.CONTROL
key.SHIFT
key.ALT
key.COMMAND

so if you need another keyboard action, use sendKeys method(i used Tab key)
here i referenced link
https://github.com/SeleniumHQ/selenium/issues/5428


text:
Q: Show two countries in Google Visualization: Geochart I want to show a map with two countries near each others, let's say USA and CANADA. As far as I can see, google allows me show either, the world, a zone(with many countries: eg North America), Region, or a country, but what I want actually to see is two adjacent countries.

A: Thats not possible. one way to do that is to display the two countries seperatly then play with the DOM  to make them close to each other


text:
Q: Are the libraries different that is building from android-ndk in different platform I want to release my SDK. but I have no idea Do I have some unknown problems if I compile the .so from different platforms (Mac or Window using same ndk version).
I think it is same between different platforms but I didn't have windows platform to confirm.
So Are the libraries different build from different platforms?

A: Bluntly, you should not believe that compilers produce the same code on the same input deterministically. Many do, but many do not. This is especially true when using optimization. (This situation is improving now the problem is recognized). The consequence of this is no matter what you build on you must only release the exact binary you have tested.
That said, you can totally build with the NDK on multiple platforms. Many of the large games studios use Windows and Macs for development, and production builds are done on Linux continuous integration systems, so this is done in practice all the time. You are far more likely to run into trouble with any extra tooling you have than the ndk itself.

A: You can safely mix Android binaries built on Mac and Windows, but please make sure you use the same NDK release and same parameters (most notably, same APP_STL).
You can send your native libraries built on Mac to Java developers who work on Windows. They don't even need NDK and don't care which release you were using (as long as it works).


text:
Q: Express and Angular directory structure I want to build a website with Express and Angular (no SQL) so I started wondering what is the right structure for this kind of app.
For Angular there is a directory structre I really like from here:
app/
----- shared/   // acts as reusable components or partials of our site
---------- sidebar/
--------------- sidebarDirective.js
--------------- sidebarView.html
---------- article/
--------------- articleDirective.js
--------------- articleView.html
----- components/   // each component is treated as a mini Angular app
---------- home/
--------------- homeController.js
--------------- homeService.js
--------------- homeView.html
---------- blog/
--------------- blogController.js
--------------- blogService.js
--------------- blogView.html
----- app.module.js
----- app.routes.js
assets/
----- img/      // Images and icons for your app
----- css/      // All styles and style related files (SCSS or LESS files)
----- js/       // JavaScript files written for your app that are not for angular
----- libs/     // Third-party libraries such as jQuery, Moment, Underscore, etc.
index.html

For Express I don't really no where it should be because I have no a lot of experience with Express, where can I put express with the correct structure.

A: If your express backend acts as an api server, you can simply put it with app's parent folder side by side, i.e.
backend/
----gruntfile.js
----express.js
----router/
----package.json
----node_modules/
frontend/
----app/


text:
Q: LaTeX tables / vertical alignment / spacing I have looked through so many tutorials regarding tables, vertical alignment, tried to do it on my own, tried to do it with excel2latex Excel addin - still having troubles with my table. I would really appreciate your help.
\begin{table}[htbp]
\centering
\caption{Add caption}
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|}
\toprule
\multirow{2}[4]{*}{long text} & \multirow{2}[4]{*}{text} &
\multirow{2}[4]   {*}{\begin{sideways}text\end{sideways}} &
\multirow{2}[4]  {*}{\begin{sideways}vertical long text\end{sideways}} &
\multicolumn{6}{c|}{long text} \\
\cmidrule{5-10}          &       &       &       & 1    & 2    & 3     & 4    & 5     & 6 \\
\midrule
...    & ...    & ...    & ...    & ...   & ...   & ...    & ...   & ...     & ...  \\
...    & ...    & ...    & ...    & ...   & ...   & ...     & ...  & ...     & ... \\
...    & ...    & ...    & ...    & ...   & ...   & ...     & ...   & ...     & ... \\
...     & ...   & ...   & ...   & ...   & ...   & ...     & ...   & ...     & ... \\
...    & ...    & ...    & ...    & ...   & ...   & ...     & ...  & ...     & ...  \\
...     & ...   & ...   & ...   & ...   & ...   & ...     & ...   & ...     & ... \\
...    & ...    & ...    & ...    & ...   & ...  & ... & ... & ...     & ... \\
\midrule
\multicolumn{10}{|c|}{long long note)} \\
\bottomrule
\end{tabular}
\label{tab:addlabel}
\end{table}

The table should look like this

But instead it comes out like this
Please help me solve this mystery!

A: A solution based on makecell, which allows for line breaks in table cells:
\documentclass{article}
\usepackage[utf8]{inputenc}
 \usepackage{booktabs}
\usepackage{multirow, makecell, caption}
\usepackage{rotating, graphicx}

\begin{document}

\begin{table}
\setlength{\bigstrutjot}{4pt} % Additional height: 4pt
\settowidth\rotheadsize{long text}
\caption{Add caption}
\begin{tabular}{cccccccccc}
\toprule\addlinespace
\multirowcell{2}{long text \\ long text \\ long text} & \multirowcell{3}{text} & & &
\multicolumn{6}{c}{horizontal long long text} \\[1ex]
\cmidrule(lr){5-10}\addlinespace
 & &\raisebox{3ex}[0pt][0pt]{\rotcell[cc]{text}} &
\raisebox{3ex}[0pt][0pt]{\rotcell[cc]{vertical \\ long text}}& 1 & 2 & 3 & 4 & 5 & 6 \\
\addlinespace
\midrule
… & … & … & … & … & … & … & … & … & … \\
… & … & … & … & … & … & … & … & … & … \\
… & … & … & … & … & … & … & … & … & … \\
… & … & … & … & … & … & … & … & … & … \\
… & … & … & … & … & … & … & … & … & … \\
… & … & … & … & … & … & … & … & … & … \\
… & … & … & … & … & … & … & … & … & … \\
\midrule
\multicolumn{10}{c}{long long note)} \\
\bottomrule
\end{tabular}
\end{table}

\end{document}

A: You are using the commmands \toprule, \midrule and \bottomrule from the package booktabs. In the package documentation, in section 4, the author explicitly states:

[...] The rules generated by the new commands are in no way
  guaranteed to connect with verticals generated by {|}
  characters in the preamble.
  This is a feature [...].  You should not use vertical rules in tables, end of
  story.

So this behavior is intended, as you should not use vertical rules (vertical lines). The reason for this is presented earlier in the same document, where the author gives guidelines for creating professional tables:

*

*Never, ever use vertical rules.

*Never use double rules.

*Put the units in the column heading (not in the body of the table).

*Always precede a decimal point by a digit; thus 0.1 not just .1

*Do not use `ditto' signs or any other such convention to repeat a previous value.  In many circumstances a blank will serve just as well.  If it won't, then repeat the value

Then, you have a problem with the combination of multirow and sideways. You can tweak this manually, by adding \bigstrut to both header rows, which enlarges their size. I chose an additional height of 4pt, which looks quite good in my opinion.
Then, by putting the text inside a \parbox of e.g. 1.5cm width, you make
sure this text is not wider than this.
Together, this gives a quite pleasing result:

\documentclass{article}
\usepackage{booktabs}
\usepackage{multirow,bigstrut}
\usepackage{rotating}

\begin{document}

\setlength{\bigstrutjot}{4pt}    % Additional height: 4pt

\begin{tabular}{cccccccccc}
\toprule\bigstrut
\multirow{2}{*}{long text} & \multirow{2}[4]{*}{text} &
\multirow{2}{*}[-1ex]{\begin{sideways}text\end{sideways}} &
\multirow{2}{*}[1ex]{\begin{sideways}\parbox{1.5cm}{vertical long text}\end{sideways}} &
\multicolumn{6}{c}{long text} \\
\cmidrule{5-10}\bigstrut          &       &       &       & 1    & 2    & 3     & 4    & 5     & 6 \\
\midrule
...    & ...    & ...    & ...    & ...   & ...   & ...    & ...   & ...     & ...  \\
...    & ...    & ...    & ...    & ...   & ...   & ...     & ...  & ...     & ... \\
...    & ...    & ...    & ...    & ...   & ...   & ...     & ...   & ...     & ... \\
...     & ...   & ...   & ...   & ...   & ...   & ...     & ...   & ...     & ... \\
...    & ...    & ...    & ...    & ...   & ...   & ...     & ...  & ...     & ...  \\
...     & ...   & ...   & ...   & ...   & ...   & ...     & ...   & ...     & ... \\
...    & ...    & ...    & ...    & ...   & ...  & ... & ... & ...     & ... \\
\midrule
\multicolumn{10}{c}{long long note)} \\
\bottomrule
\end{tabular}

\end{document}

A: This is quite straightforward using ConTeXt natural tables.
\setupcaption[table][location=top]

\starttext

\placetable[tab:addlabel]{Add caption}{
  \startTABLE[align={middle,lohi}]
    \NC[ny=2] long text \NC[ny=2] text \NC[ny=2] \rotate[90]{text} \NC[ny=2] \rotate[90]{vertical long text} \NC[nx=6] long text \NC\NR
    \NC 1 \NC 2 \NC 3 \NC 4 \NC 5 \NC 6 \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC ... \NC\NR
    \NC[nx=10] long long note \NC\NR
  \stopTABLE
}

\stoptext


text:
Q: Delete function only can run half until **arrayList.remove(which_item);** show the problen i have a problem, code run till half showing error, this is the delete function at **arrayList.remove(which_item);** this line have problem showing
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.remove(int)' on a null object reference
Can someone tell what happen to this?
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final int which_item = position;

                new AlertDialog.Builder(addProduct.this)
                        .setIcon(android.R.drawable.ic_delete)
                        .setTitle("Are you sure?")
                        .setMessage("Do you want to delete this item")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                **arrayList.remove(which_item);**
                                adapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("No",null)
                        .show();
                return true;
            }
        });

A: The function onClick does not know the which_item, shouldn't it be which.


text:
Q: How do I serve a torrent from my web server? I have some files that I have the legal right to distribute (I made them), and I want to give people the option to get them via bittorrent.
Following instructions I've read, I've used the program Transmission to create a .torrent file, and when I was prompted to provide trackers, I used this list.
So now I have a .torrent file and the seed files sitting on my local computer. But I want to serve the seed files from my web server. Do I just upload everything to a directory on my web server?
Also, no instructions I've seen make it clear how I let file sharing sites know my files exist. Once I upload the seed files and my .torrent file to my server, what then?

A: What you really want is web seeding. You add a plain URL to your torrent (doesn't change the info hash) and torrent clients will fall back to downloading from there if no other (or not enough) parts are available.
So now that you have the torrent file ready, you'll need to upload your file(s) to a publicly accessible HTTP location. Be aware: The URL can be extracted from the torrent file easily, so you should probably configure a bandwidth limit for your web seed files, otherwise people will just download them directly.
I recommend editing the torrent file with BEncode Editor. Add a key named url-list of type "List" directly on the ROOT item. On this key, add any number of URLs with type "Binary as String".
There are also Seedbox services. Never used them, though.

A: You have to install and run a torrent client on your server.
I suggest running rtorrent instide tmux.
Your server will then act as a seeder. You can upload the torrent contents either manually using rsync, for instance, or you can just start the torrent client and let it leech the files from your computer.
I suggest linking the .torrent file somewhere on your webserver.
You said you've added trackers to your torrent file. You have to upload the .torrent file to tracker websites. For instance nyaa.se has a button called "Upload", and there you simply upload the .torrent file, etc.

A: The server keep tracking of all clients. In order for your torrent to be downloadable, you need at least one client to seed it.
Note that the primary client seeder can be physically on the same server with the tracker.


text:
Q: How can I configure Ditto so that it always pastes the plaintext of the selected clip? I found Text Only Paste but it doesn't seem to work and anyway likely doesn't apply to clips that aren't the last saved clip:

I use Ditto with Microsoft Windows 10.

A: When pasting the selected entry in Ditto, use SHIFT + ENTER instead of ENTER. This will paste the selected entry as plain text.


text:
Q: How to change the value of a variable with its address stored on the stack? I'm currently trying to push the address of a data variable to the stack. In a separate procedure, how would I change the actual value of this data variable located on the stack?
I'm using Visual Studio as my assembler and using the Irvine32.lib library for this code. This is what I've been trying but there is an error.
I expect the value of 'counter' to be changed from 1 to 2 but it doesn't work. How would I go about this? Thanks!
include Irvine 32.inc

.data
counter dword 1

.code
main proc
    mov eax, counter
    call writeDec       ; should print 1

    push offset counter ; push address of 'counter' on stack
    call foo            ; this procedure changes counter from 1 to 2

    mov eax, counter    ; store counter in eax for writeDec procedure
    call writeDec       ; should print 2
    exit
main endp

foo proc
    push eax            ; save eax register state
    mov eax, esp        ; store the stack pointer into eax
    add eax, 8          ; navigate through the stack

    ; this doesn't assemble
    mov [eax], 2        ; dereference the stack pointer and set it to 2
    pop eax             ; restore eax register state
    ret
foo endp
end main


text:
Q: Unit Testing with Sitecore and FakeDB - Field values are lost on items I am trying to run a unit test against a FakeDB setup using NUnit and Moq.  The sitecore query is being abstracted through an interface which I'm Mocking.  When I intially call the query it correctly creates the items with Field values.  When the query results are used by the test method calling the repository - the field values all of the sudden go away.
I shortened the test and put it into this file.  It has the bare minimum to run:

using System;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.FakeDb;

namespace NYL.UnitTests.FakeDB
{
    [TestFixture]
    public class FakeDbFieldValueTest
    {
        private readonly Mock<IRepository> _repo = new Mock<IRepository>();
        private readonly ID _someItemTemplateId = ID.NewID;

        [SetUp]
        public void SetUp()
        {
            //database = FakeDatabase();
            _repo.Setup(m => m.GetListOfItems()).Returns(Mock_GetListOfItems());
        }

        [Test]
        public void Test_FakeDbFieldRetention()
        {
            // arrange
            var items = _repo.Object.GetListOfItems();

            // assert
            items.Should().NotBeNull();
            items.Should().HaveCount(3);

            foreach (var item in items)
            {
                // Fields are null after passed back through mock
                item.Fields["Some Field"].Should().NotBeNull();
                item["Some Field"].Should().NotBeNullOrEmpty();
            }
        }

        private IDisposable FakeDatabase()
        {
            return new Db
            {
                new DbItem("Home")
                {
                    new DbItem("First Child", ID.NewID, _someItemTemplateId)
                    {
                        {"Some Field", "Value One"}
                    },
                    new DbItem("Second Child", ID.NewID, _someItemTemplateId)
                    {
                        {"Some Field", "Value Two"}
                    },
                    new DbItem("Third Child", ID.NewID, _someItemTemplateId)
                    {
                        {"Some Field", "Value Three"}
                    }
                }
            };
        }

        private Item[] Mock_GetListOfItems()
        {
            using (FakeDatabase())
            {
                var query = string.Format("fast:/sitecore/content/Home//*[@@templateid = '{0}']", _someItemTemplateId);
                var items = Sitecore.Context.Database.SelectItems(query);

                foreach (var item in items)
                {
                    // Field Values render fine at creation
                    item.Fields["Some Field"].Should().NotBeNull();
                    item["Some Field"].Should().NotBeNullOrEmpty();
                }

                return items;
            }
        }
    }

    public interface IRepository
    {
        Item[] GetListOfItems();
    }
}

The method Test_FakeDbFieldRetention fails spectacularly with the fields being completely removed. In my comments you can see where the fields are found, so they are being set initially. However when passed through the repository interface they just disappear.
Can anyone help spot this error?

A: Have you tried adding a DbTemplate for _someItemTemplateId? I'm not sure how FakeDb implements it but, with the sql provider, if the fields can't be found on the template the values are not saved.

A: I always do my Asserts inside the using statement when using FakeDb. You should check that the IDisposable is not tearing down you FakeDb items.

A: Hey you can checkout template inheritance section, and ensure your getting the item properly.


text:
Q: XCode 5 storyboard toolbar In XCode 5 storyboard (and maybe previous versions) I can drag a UIToolbar to the black area that shows underneath the view, so I have a view, first responder, toolbar and exit button.
But I can't seem to find any documentation that states the purpose of adding a toolbar there rather than in the view itself.
Does anyone know what this is for?
Thanks,
AJ

A: You can drag anything you like in there really, not just a toolbar.
The purpose is to have those objects instantiated along with the main view so that they are accessible from the ViewController (hook them up via IBOutlets).


text:
Q: Which sensor for rotating android? Hi which sensor(s) would I need to manage for my joystick app to capture the  following movement;
Device is in landscape, held in front of you with both hands with the device tilted forward towards TV i.e. somewhat gamepad like.
Now push or pull left or right edge of device away or towards you.
Thanks,

A: You can use the accelerometer sensor to capture the x, y and z position of device


text:
Q: In the Time and Tide area, how can I go right on the procedurally dropping floors? On level four, through the Time and Tide portal, how do I go right when I have to move across the long open/shut floor thing? Do I just have to be fast and run over there before those re-open? I've been trying that, and it doesn't seem to be working.

Looking at the map, it seems to just be a 1x1 room. What's over there?

A: There is a hidden switch in the right hand wall as you start going down the collapsing hallway, which slides open a section of wall a bit further ahead on the right, letting you get back there and grab the Chitin Mask from a wall nook.
I don't remember the exact square which has the switch, but as you start going down the collapsing hallway, it'll be a loose rock in the wall on your right. I've marked roughly where I think it is on the map (I might be off by a square), as well as marking the wall section which slides open and where the mask is contained.

A: in the first opening to the right there's a hidden button that opens an area to the right a bit later, that gets you a secret (just fyi, not needed to continue but secrets are cool)
After that, continue on and in the second to last step you turn yourself left and see a floor switch at the end, throw a rock and that should let you continue to the exit