问:
problems with wordpress site after changing permalink structure
My wordpress site lies in a folder called /entwurf/cob1 and since I wanted it to be shown by simply typing in www.cob1.org I changed the permalink to cob1.org and now nothing works. I tried changing the htacces to:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /entwurf/cob1/index.php [L]
</IfModule>
</code>```

but this doesnt seem to work either. I want my files who lie in the entwurf/cob1/ folder to be shown when typing in the cob1.org website.
Currently nothing is seen.

答:
Delete .htaccess, log into your wordpress, and let wordpress to generate .htaccess for you. ( Options -> Permanent Links -> Save)

Check is it working? No?

Upload to your web site root phpinfo file (php file with a content of "<?php phpinfo() ?>"), run it via browser.

Check what Server API cell says -> Apache? If yes Check is there mod_rewrite enabled? No? Ask Support to enable it.

If its not a Apache, ask for a help of the person who setup your server.

Body:
My wordpress site lies in a folder called /entwurf/cob1 and since I wanted it to be shown by simply typing in www.cob1.org I changed the permalink to cob1.org and now nothing works. I tried changing the htacces to:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /entwurf/cob1/index.php [L]
</IfModule>

but this doesnt seem to work either. I want my files who lie in the entwurf/cob1/ folder to be shown when typing in the cob1.org website.
Currently nothing is seen.


来源: stackexchange

问:
express middleware redirects not working
I have the next express server i want redirect .js files to the correspond .js.gz file but when i request /static/common.js don't redirects

Response Headers

HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Wed, 29 Mar 2017 14:30:17 GMT
ETag: W/"2b4084-15b1a796ca8"
Content-Type: application/javascript
Content-Length: 2834564
Date: Wed, 29 Mar 2017 16:25:53 GMT
Connection: keep-alive

```<code>// define the folder that will be used for static assets
const staticFolder = './';
app.use(favicon(`${staticFolder}/icons/favicon.ico`));
app.use('/static', Express.static(staticFolder));
app.use('/', Express.static(`${staticFolder}/sw`));
app.use(locale(supported));

app.get('*.js', (req, res, next) => {
  const reqI = req;
  reqI.url += '.gz';
  res.set('Content-Encoding', 'gzip');
  next();
});

// universal routing and rendering
app.get('*', (req, res) => {
</code>```

I am using nginx inside a docker image with the next configuration:

```<code>server {
    listen 80;
    server_name api.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {
 listen 443 ssl http2;
 server_name api.inmoblex.com;
 charset utf-8;

 ssl_certificate /www/certs/fullchain.pem;
 ssl_certificate_key /www/certs/privkey.pem;

 location / {
     proxy_pass http://web:8000;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }
}

server {
    listen 80 default_server;
    server_name inmoblex.com www.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {

   listen 443 ssl http2 default_server;
   server_name inmoblex.com www.inmoblex.com;
   charset utf-8;

   ssl_certificate /www/certs/fullchain.pem;
   ssl_certificate_key /www/certs/privkey.pem;

   location / {
       proxy_pass http://node:3000;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   }

}
</code>```

答:
In this case my error is that the middleware never runs because .js file is served by static middleware.

I solved this issue using compression package before this not worked because i used this after static middleware.

```<code>import { Server } from 'http';
import Express from 'express';
import React from 'react';
import locale from 'locale';
import { sync as globSync } from 'glob';
import { renderToString } from 'react-dom/server';
import match from 'react-router/es6/match';
import RouterContext from 'react-router/es6/RouterContext';
import UAParser from 'ua-parser-js';
import { Provider } from 'react-redux';
import { Map } from 'immutable';
import favicon from 'serve-favicon';
import * as path from 'path';
import { readFileSync } from 'fs';
import { IntlProvider } from 'react-intl';
import routes from './routes';
import NotFoundPage from './components/NotFoundPage';
import configureStore from './stores';
import WithStylesContext from './WithStylesContext';

const compression = require('compression');
const supported = ['es', 'en'];

// initialize the server and configure support for ejs templates
const app = new Express();
const server = new Server(app);

// define the folder that will be used for static assets
const staticFolder = './';
app.use(compression());
app.use(favicon(`${staticFolder}/icons/favicon.ico`));
app.use('/static', Express.static(staticFolder));
app.use('/', Express.static(`${staticFolder}/sw`));
app.use(locale(supported));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the next express server i want redirect .js files to the correspond .js.gz file but when i request /static/common.js don't redirects

Response Headers

HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Wed, 29 Mar 2017 14:30:17 GMT
ETag: W/"2b4084-15b1a796ca8"
Content-Type: application/javascript
Content-Length: 2834564
Date: Wed, 29 Mar 2017 16:25:53 GMT
Connection: keep-alive

// define the folder that will be used for static assets
const staticFolder = './';
app.use(favicon(`${staticFolder}/icons/favicon.ico`));
app.use('/static', Express.static(staticFolder));
app.use('/', Express.static(`${staticFolder}/sw`));
app.use(locale(supported));

app.get('*.js', (req, res, next) => {
  const reqI = req;
  reqI.url += '.gz';
  res.set('Content-Encoding', 'gzip');
  next();
});

// universal routing and rendering
app.get('*', (req, res) => {

I am using nginx inside a docker image with the next configuration:

server {
    listen 80;
    server_name api.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {
 listen 443 ssl http2;
 server_name api.inmoblex.com;
 charset utf-8;

 ssl_certificate /www/certs/fullchain.pem;
 ssl_certificate_key /www/certs/privkey.pem;

 location / {
     proxy_pass http://web:8000;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }
}

server {
    listen 80 default_server;
    server_name inmoblex.com www.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {

   listen 443 ssl http2 default_server;
   server_name inmoblex.com www.inmoblex.com;
   charset utf-8;

   ssl_certificate /www/certs/fullchain.pem;
   ssl_certificate_key /www/certs/privkey.pem;

   location / {
       proxy_pass http://node:3000;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   }

}

Body:
In this case my error is that the middleware never runs because .js file is served by static middleware.

I solved this issue using compression package before this not worked because i used this after static middleware.

import { Server } from 'http';
import Express from 'express';
import React from 'react';
import locale from 'locale';
import { sync as globSync } from 'glob';
import { renderToString } from 'react-dom/server';
import match from 'react-router/es6/match';
import RouterContext from 'react-router/es6/RouterContext';
import UAParser from 'ua-parser-js';
import { Provider } from 'react-redux';
import { Map } from 'immutable';
import favicon from 'serve-favicon';
import * as path from 'path';
import { readFileSync } from 'fs';
import { IntlProvider } from 'react-intl';
import routes from './routes';
import NotFoundPage from './components/NotFoundPage';
import configureStore from './stores';
import WithStylesContext from './WithStylesContext';

const compression = require('compression');
const supported = ['es', 'en'];

// initialize the server and configure support for ejs templates
const app = new Express();
const server = new Server(app);

// define the folder that will be used for static assets
const staticFolder = './';
app.use(compression());
app.use(favicon(`${staticFolder}/icons/favicon.ico`));
app.use('/static', Express.static(staticFolder));
app.use('/', Express.static(`${staticFolder}/sw`));
app.use(locale(supported));


问:
Combining cv2.imshow() with matplotlib plt.show() in real time
I'm trying to combine a feed from webcam using openCV, and then updating a graph using matplotlib.

For getting and showing the frames a basic example:

```<code>import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Display the resulting frame
    cv2.imshow('frame',frame)

    # When to exit loop - terminate program
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

An example of continuously updating a graph (plotting randomly) with matplotlib:

```<code>import numpy as np
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

# x goes from 0-9 numbers
# y goes from 0-100%
fig = plt.figure()
ax = plt.axes(xlim=(0, 9), ylim=(0, 100))
# line, = ax.plot([], [], lw=2)
rects = plt.bar(x, y, color='b')

def animate(i):
    y = random.sample(xrange(100), 10)
    for rect, yi in zip(rects, y):
        rect.set_height(yi)
    return rects

anim = animation.FuncAnimation(fig, animate,
                           frames=200, interval=20, blit=True)

plt.show()
</code>```

So what I want is to combine the two together. The graph should be updated by passing results that I obtain from the frames. The major problem I am facing is getting both windows to update simultaneously side by side. The plt.show() seems to be blocking everything else.

Any idea on how to resolve?

Cheers

答:
Here's an example of converting a plt.figure() to np.array and show it along camera feed with cv2.imshow

```<code>import matplotlib
matplotlib.use('TkAgg')

import numpy as np
import cv2
import matplotlib.pyplot as plt

fig = plt.figure()
cap = cv2.VideoCapture(0)

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

line1, = plt.plot(x1, y1, 'ko-')        # so that we can update data later

for i in range(1000):
    # update data
    line1.set_ydata(np.cos(2 * np.pi * (x1+i*3.14/2) ) * np.exp(-x1) )

    # redraw the canvas
    fig.canvas.draw()

    # convert canvas to image
    img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8,
            sep='')
    img  = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))

    # img is rgb, convert to opencv's default bgr
    img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)

    # display image with opencv or any operation you like
    cv2.imshow("plot",img)

    # display camera feed
    ret,frame = cap.read()
    cv2.imshow("cam",frame)

    k = cv2.waitKey(33) & 0xFF
    if k == 27:
        break
</code>```

Body:
I'm trying to combine a feed from webcam using openCV, and then updating a graph using matplotlib.

For getting and showing the frames a basic example:

import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Display the resulting frame
    cv2.imshow('frame',frame)

    # When to exit loop - terminate program
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

An example of continuously updating a graph (plotting randomly) with matplotlib:

import numpy as np
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

# x goes from 0-9 numbers
# y goes from 0-100%
fig = plt.figure()
ax = plt.axes(xlim=(0, 9), ylim=(0, 100))
# line, = ax.plot([], [], lw=2)
rects = plt.bar(x, y, color='b')

def animate(i):
    y = random.sample(xrange(100), 10)
    for rect, yi in zip(rects, y):
        rect.set_height(yi)
    return rects

anim = animation.FuncAnimation(fig, animate,
                           frames=200, interval=20, blit=True)

plt.show()

So what I want is to combine the two together. The graph should be updated by passing results that I obtain from the frames. The major problem I am facing is getting both windows to update simultaneously side by side. The plt.show() seems to be blocking everything else.

Any idea on how to resolve?

Cheers

Body:
Here's an example of converting a plt.figure() to np.array and show it along camera feed with cv2.imshow

import matplotlib
matplotlib.use('TkAgg')

import numpy as np
import cv2
import matplotlib.pyplot as plt

fig = plt.figure()
cap = cv2.VideoCapture(0)

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

line1, = plt.plot(x1, y1, 'ko-')        # so that we can update data later

for i in range(1000):
    # update data
    line1.set_ydata(np.cos(2 * np.pi * (x1+i*3.14/2) ) * np.exp(-x1) )

    # redraw the canvas
    fig.canvas.draw()

    # convert canvas to image
    img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8,
            sep='')
    img  = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))

    # img is rgb, convert to opencv's default bgr
    img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)

    # display image with opencv or any operation you like
    cv2.imshow("plot",img)

    # display camera feed
    ret,frame = cap.read()
    cv2.imshow("cam",frame)

    k = cv2.waitKey(33) & 0xFF
    if k == 27:
        break


问:
Java closing statements
Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this?
If you do not understand, here is the code.

import java.util.Scanner;

public class BEassignment11
{
  public static void main (String [] args)
  {
    Scanner k = new Scanner (System.in);
    String color;
    String again;

    do
    {

      System.out.println ("Try to guess my favorite color!");
      color = k.next();

      if  (color.equalsIgnoreCase ("blue"))
      {
        System.out.println ("You got the right color!");

      }

      else

        System.out.println ("That is not the right color. Would you like to try again? Yes/No");
        again = k.next();
    }
    while (again.equalsIgnoreCase ("yes"));

  }
}```

答:
You can just break out of the loop with the "break" statement like this:</p>

```<code>if  (color.equalsIgnoreCase ("blue")){
    System.out.println ("You got the right color!");
    break;
}
</code>```

Title: Java closing statements

Body:
You can just break out of the loop with the "break" statement like this:

if  (color.equalsIgnoreCase ("blue")){
    System.out.println ("You got the right color!");
    break;
}


答:
You can use break following System.out.println ("You got the right color!"); within if statement at do..while loop.

Or define a variable before do..while loop, for example var boolFlag = false set variable to true within if statement boolFlag = true, include || boolFlag === true within while condition.

Title: Java closing statements

Body:
Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this?
If you do not understand, here is the code.

import java.util.Scanner;

public class BEassignment11
{
  public static void main (String [] args)
  {
    Scanner k = new Scanner (System.in);
    String color;
    String again;

    do
    {

      System.out.println ("Try to guess my favorite color!");
      color = k.next();

      if  (color.equalsIgnoreCase ("blue"))
      {
        System.out.println ("You got the right color!");

      }

      else

        System.out.println ("That is not the right color. Would you like to try again? Yes/No");
        again = k.next();
    }
    while (again.equalsIgnoreCase ("yes"));

  }
}


问:
My IndexedDB add() in my service worker succeed but I cannot see the data it in the Chrome dev tools Application/Storage
I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,

I managed to get a service worker working, but I must say I am new at this.

I now try to get it to use an IndexedDB and store data in it.

It fetches data from a local web server in http and retrieve it without problem in json format.

The data format is :

```<code>[{"id":"1", "...":"...", ...},
 {"id":"2", "...":"...", ...},
 {"id":"3", "...":"...", ...},
 ...
 {"id":"n", "...":"...", ...}]
</code>```

it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...

```<code>entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
</code>```

But it does not appear in the Chrome dev tools!

Here is my service worker:

```<code>self.addEventListener('install',function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject)resolve()}))
        .then(function()
            {return self.skipWaiting();}));
    });

self.addEventListener('activate', function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject){resolve()}))
        .then(function() {return self.clients.claim();}));
    });

self.addEventListener('message', function(event)
    {
    if(event.data.command=="data.load")
        {
        var options = event.data.options
        var url = new URL(event.data.host+options.source);
        var parameters = {entity:options.name,
                          options:encodeURIComponent(options.options)};
        Object.keys(parameters)
            .forEach(key => url.searchParams.append(key,
                                                    parameters[key]))
        fetch(url).then(function(response)
            {
            if(response.ok)
                {
                response.json().then(function(data_json)
                    {
                    var entityData = data_json;
                    var request = indexedDB.open(options.name);
                    request.onerror = function(event)
                        {
                        console.log("indexedDB.open error :",event);
                        };
                    request.onsuccess = function(event)
                        {
                        console.log("indexedDB.open success :",event)
                        var db = event.target.result;
                        }
                    request.onupgradeneeded = function(event)
                        {
                        console.log("indexedDB.open upgrade :",event)
                        var db = event.target.result;
                        db.createObjectStore(options.options.id, { keyPath: "id" });
                        objectStore.transaction.oncomplete = function(event)
                            {
                            var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
                            for (var i in entityData)
                                {
                                var addRequest = entityObjectStore.add(entityData[i]);
                                addRequest.onerror = function(event)
                                    {
                                    console.log("entityObjectStore.add error :",event);
                                    };
                                addRequest.onsuccess = function(event)
                                    {
                                    console.log("entityObjectStore.add success :",event);
                                    };
                                }
                            }
                        };

                    });
                }
            });
        }
    else if(event.data.command=="data.get")
        {
        var command = event.data;
        var request = indexedDB.open(command.domain);
        request.onerror = function(event)
            {
            console.log("indexedDB.open error :",event);
            };
        request.onsuccess = function(event)
            {
            console.log("indexedDB.open success :", event)
            var db = event.target.result;
            var transaction = db.transaction([command.domain]);
            var objectStore = transaction.objectStore(command.entity);
            var request = objectStore.get(command.id);
            request.onerror = function(event)
                {
                console.log("objectStore.get error :",event);
                };
            request.onsuccess = function(event)
                {
                console.log("objectStore.get success :",event);
                console.log("request.result=" + request.result);
                };
            }
        }
    });
</code>```

Here is the HTML file I use with it :

```<code><!DOCTYPE html>
<html>
    <head>
        <title>My service worker app</title>
    </head>
    <body>
        <button id="update">Update</button>
        <div id="log"></div>
        <script type="text/javascript">
        function sendMessage(message)
            {
            return new Promise(function(resolve, reject)
                {
                var messageChannel = new MessageChannel();
                messageChannel.port1.onmessage = function(event)
                    {
                    if (event.data.error)
                        {
                        reject(event.data.error);
                        }
                    else
                        {
                        resolve(event.data);
                        }
                    };

                });
            }
            if (navigator.serviceWorker.controller)
                {
                var url = navigator.serviceWorker.controller.scriptURL;
                var initData =  [
                                {
                                name:"my_entity_type",
                                source:"/webapp/data",
                                options:{id:"my_entity_type_id"}
                                }
                                ]
                for(var dataIndex in initData)
                    {
                    var data = initData[dataIndex]
                    sendMessage({
                                 command:"data.load",
                                 host: document.location.origin,
                                 options: data
                                 });
                    }
                }
            else
                {
                navigator.serviceWorker.register('/webapp/lt_sw.js')
                    .then(function(registration)
                        {
                        debug('Refresh to allow ServiceWorker to control this client', 'onload');
                        debug(registration.scope, 'register');
                        });
                }

    navigator.serviceWorker.addEventListener('controllerchange',
    function()
        {
        var scriptURL = navigator.serviceWorker.controller.scriptURL;
        debug(scriptURL, 'oncontrollerchange');
        });

    document.querySelector('#update').addEventListener('click',
    function()
        {
        navigator.serviceWorker.ready.then(function(registration)
            {
            registration.update()
                .then(function()
                    {
                    console.log('Checked for update');
                    })
                .catch(function(error)
                    {
                    console.error('Update failed', error);
                    });
                });
            });

        function debug(message, element)
            {
            var target = document.querySelector('#log');
            console.log(element,":",message)
            target.textContent = message;
            }
        </script>
    </body>
</html>
</code>```

Any idea about what I am, doing wrong?

Edit 1:

I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :

```<code>    document.querySelector('#update').addEventListener('click',
    function()
        {
        navigator.serviceWorker.ready.then(function(registration)
            {
            registration.update()
                .then(function()
                    {
                    console.log('Checked for update');
                    sendMessage({
                        command:"data.get",
                        domain:"database_name",
                        entity: "my_entity_type",
                        id: "my_entity_id"
                        });
                    })
                .catch(function(error)
                    {
                    console.error('Update failed', error);
                    });
                });
            });
</code>```

And I added the following line:

```<code>    indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };
</code>```

Just at the beginning of the data look up part:

```<code>    else if(event.data.command=="data.get")
        {
</code>```

To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!

```<code>data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}
</code>```

Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :

```<code>indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };
</code>```

And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...

```<code>db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}
</code>```

Then I had a look inside the object stores ...

```<code>entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
</code>```0

And the entries are there as expected! But not in Application/Storage ...

Edit 2:

The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...

Edit 3:

The answer was as simple as closing and reopening the dev tools ... like @wOxxOm suggested ...

答: You could also check the "Update on reload" button and try hard reset ctrl/shift+f5 to the same effect as @wOxxOm mentioned.

Body:
I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,

I managed to get a service worker working, but I must say I am new at this.

I now try to get it to use an IndexedDB and store data in it.

It fetches data from a local web server in http and retrieve it without problem in json format.

The data format is :

[{"id":"1", "...":"...", ...},
 {"id":"2", "...":"...", ...},
 {"id":"3", "...":"...", ...},
 ...
 {"id":"n", "...":"...", ...}]

it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...

entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}

But it does not appear in the Chrome dev tools!

Here is my service worker:

self.addEventListener('install',function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject)resolve()}))
        .then(function()
            {return self.skipWaiting();}));
    });

self.addEventListener('activate', function(event)
    {
    event.waitUntil(
        (new Promise(function(resolve,reject){resolve()}))
        .then(function() {return self.clients.claim();}));
    });

self.addEventListener('message', function(event)
    {
    if(event.data.command=="data.load")
        {
        var options = event.data.options
        var url = new URL(event.data.host+options.source);
        var parameters = {entity:options.name,
                          options:encodeURIComponent(options.options)};
        Object.keys(parameters)
            .forEach(key => url.searchParams.append(key,
                                                    parameters[key]))
        fetch(url).then(function(response)
            {
            if(response.ok)
                {
                response.json().then(function(data_json)
                    {
                    var entityData = data_json;
                    var request = indexedDB.open(options.name);
                    request.onerror = function(event)
                        {
                        console.log("indexedDB.open error :",event);
                        };
                    request.onsuccess = function(event)
                        {
                        console.log("indexedDB.open success :",event)
                        var db = event.target.result;
                        }
                    request.onupgradeneeded = function(event)
                        {
                        console.log("indexedDB.open upgrade :",event)
                        var db = event.target.result;
                        db.createObjectStore(options.options.id, { keyPath: "id" });
                        objectStore.transaction.oncomplete = function(event)
                            {
                            var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
                            for (var i in entityData)
                                {
                                var addRequest = entityObjectStore.add(entityData[i]);
                                addRequest.onerror = function(event)
                                    {
                                    console.log("entityObjectStore.add error :",event);
                                    };
                                addRequest.onsuccess = function(event)
                                    {
                                    console.log("entityObjectStore.add success :",event);
                                    };
                                }
                            }
                        };

                    });
                }
            });
        }
    else if(event.data.command=="data.get")
        {
        var command = event.data;
        var request = indexedDB.open(command.domain);
        request.onerror = function(event)
            {
            console.log("indexedDB.open error :",event);
            };
        request.onsuccess = function(event)
            {
            console.log("indexedDB.open success :", event)
            var db = event.target.result;
            var transaction = db.transaction([command.domain]);
            var objectStore = transaction.objectStore(command.entity);
            var request = objectStore.get(command.id);
            request.onerror = function(event)
                {
                console.log("objectStore.get error :",event);
                };
            request.onsuccess = function(event)
                {
                console.log("objectStore.get success :",event);
                console.log("request.result=" + request.result);
                };
            }
        }
    });

Here is the HTML file I use with it :

<!DOCTYPE html>

        <title>My service worker app</title>

        <button id="update">Update</button>

Any idea about what I am, doing wrong?

Edit 1:

I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :

    document.querySelector('#update').addEventListener('click',
    function()
        {
        navigator.serviceWorker.ready.then(function(registration)
            {
            registration.update()
                .then(function()
                    {
                    console.log('Checked for update');
                    sendMessage({
                        command:"data.get",
                        domain:"database_name",
                        entity: "my_entity_type",
                        id: "my_entity_id"
                        });
                    })
                .catch(function(error)
                    {
                    console.error('Update failed', error);
                    });
                });
            });

And I added the following line:

    indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };

Just at the beginning of the data look up part:

    else if(event.data.command=="data.get")
        {

To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!

data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}

Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :

indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };

And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...

db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}

Then I had a look inside the object stores ...

indexedDB.open("db3").onsuccess = function(event)
{event.target.result.transaction(["db3"]).objectStore("db3")
    .getAll().onsuccess = function(event)
    {console.log("objectStore.getAll() success :",event.target.result)};};

And the entries are there as expected! But not in Application/Storage ...

Edit 2:

The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...

Edit 3:

The answer was as simple as closing and reopening the dev tools ... like @wOxxOm suggested ...


问:
jquery and change html 5 video source on click
I know this has been asked before but for some reason that strategy doesn't seem to be working for me.

this is my code:

```<code>   $(document).ready(function() {
        $('#foo').click(function() {
        var videoFile = 'video/law_cash.mp4';
        $('#video_container video source').attr('src', videoFile);
        });
    });
</code>```

the click function works and also when I check in firebug the video/law_cash.mp4 shows up in the right area. It just wont load when I click

EDIT: this is what im actually trying to do:

```<code>$(document).ready(function() {

    var knicks = 'video/knicks_therapist.m4v';
        law = 'video/law_cash.mp4';
        fit = 'video/fit_some.mp4';
        texas = 'video/texas_familia.mp4';
        partner = 'video/drug.m4v';
        keyspan = 'video/keyspan_nrg.mov';

    $('#law').click(function() {
        $('#video_container video source').attr('src', law);
        $('#video_container video source').load();
    });

    $('#knicks').click(function() {
        $('#video_container video source').attr('src', knicks);
        $('#video_container video source').load();
    });

    $('#fit').click(function() {
        $('#video_container video source').attr('src', fit);
        $('#video_container video source').load();
    });

    $('#texas').click(function() {
        $('#video_container video source').attr('src', texas);
        $('#video_container video source').load();
    });

    $('#partner').click(function() {
        $('#video_container video source').attr('src', partner);
        $('#video_container video source').load();
    });

    $('#keyspan').click(function() {
        $('#video_container video source').attr('src', keyspan);
        $('#video_container video source').load();
    });
});
</code>```

html:

```<code><a id="law" href="#">BLAH</a>
</code>```

答:
Firefox doesn't support MPEG audio/video formats... dunno why.

EDIT: If you have an onerror event registered then it would fire, and the video element's error object will tell you MEDIA_ERR_SRC_NOT_SUPPORTED

ContentLicense: CC BY-SA 2.5

Body:
I know this has been asked before but for some reason that strategy doesn't seem to be working for me.

this is my code:

   $(document).ready(function() {
        $('#foo').click(function() {
        var videoFile = 'video/law_cash.mp4';
        $('#video_container video source').attr('src', videoFile);
        });
    });

the click function works and also when I check in firebug the video/law_cash.mp4 shows up in the right area. It just wont load when I click

EDIT: this is what im actually trying to do:

$(document).ready(function() {

    var knicks = 'video/knicks_therapist.m4v';
        law = 'video/law_cash.mp4';
        fit = 'video/fit_some.mp4';
        texas = 'video/texas_familia.mp4';
        partner = 'video/drug.m4v';
        keyspan = 'video/keyspan_nrg.mov';

    $('#law').click(function() {
        $('#video_container video source').attr('src', law);
        $('#video_container video source').load();
    });

    $('#knicks').click(function() {
        $('#video_container video source').attr('src', knicks);
        $('#video_container video source').load();
    });

    $('#fit').click(function() {
        $('#video_container video source').attr('src', fit);
        $('#video_container video source').load();
    });

    $('#texas').click(function() {
        $('#video_container video source').attr('src', texas);
        $('#video_container video source').load();
    });

    $('#partner').click(function() {
        $('#video_container video source').attr('src', partner);
        $('#video_container video source').load();
    });

    $('#keyspan').click(function() {
        $('#video_container video source').attr('src', keyspan);
        $('#video_container video source').load();
    });
});

html:

BLAH


问:
How to add jsonobject in to jsonarray which i want
I can do only add jsonobj and json obj like in the left hand side in this picture

but if i want to add data like right hand side  what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}
</code>```

答:
You have to create JSON objects of this way

```<code>JSONObject dataToSend = new JSONObject();
JSONArray arrayData = new JSONArray();
dataToSend.put("profile",arrayData);
</code>```

And if you want to add JSON object to your JSONArray use this

```<code>arrayData.put(JSONObject1);
arrayData.put(JSONObject2);
</code>```

Body:
I can do only add jsonobj and json obj like in the left hand side in this picture

but if i want to add data like right hand side  what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}

Body:
You have to create JSON objects of this way

JSONObject dataToSend = new JSONObject();
JSONArray arrayData = new JSONArray();
dataToSend.put("profile",arrayData);

And if you want to add JSON object to your JSONArray use this

arrayData.put(JSONObject1);
arrayData.put(JSONObject2);


问:
Sum of factoriais to be equal a given number
I'm trying to solve the following problem:

What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)

Example:

Input: 10, Output: 3. (10 = 3! + 2! + 2!)

Input: 25, Output: 2. (25 = 4! + 1!)

My code:

```<code>#include<bits/stdc++.h>

using namespace std;

int a;

int rec(int vet){

    int count = 0;

    a = a - vet;
        if(a >= vet){
            count++;
            rec(vet);
        }
    count++;
    return count;
}

int main(){

    int vet[8] = {1}, count = 0;

    cin >> a;

    for(int i = 2; i <= 8; i++){
        vet[i-1] = vet[i-2]*i;
    }

    for(int i = 7; i >= 0; i--){
        if(a < vet[i]){
            continue;
        }

        count += rec(vet[i]);
    }

    cout << count << endl;
}
</code>```

My logic:

1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;

2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.

This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.

Can you find where am I wrong? Or if my solution is not good and I should try another approach.

Thanks for the help!

答:
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.

A simple solution would be to replace the rec function as follows

```<code>int rec(int vec) {
    int count = a / vec;
    a = a % vec;
    return count;
}
</code>```

Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.

Body:
I'm trying to solve the following problem:

What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)

Example:

Input: 10, Output: 3. (10 = 3! + 2! + 2!)

Input: 25, Output: 2. (25 = 4! + 1!)

My code:

#include<bits/stdc++.h>

using namespace std;

int a;

int rec(int vet){

    int count = 0;

    a = a - vet;
        if(a >= vet){
            count++;
            rec(vet);
        }
    count++;
    return count;
}

int main(){

    int vet[8] = {1}, count = 0;

    cin >> a;

    for(int i = 2; i <= 8; i++){
        vet[i-1] = vet[i-2]*i;
    }

    for(int i = 7; i >= 0; i--){
        if(a < vet[i]){
            continue;
        }

        count += rec(vet[i]);
    }

    cout << count << endl;
}

My logic:

1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;

2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.

This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.

Can you find where am I wrong? Or if my solution is not good and I should try another approach.

Thanks for the help!

Body:
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.

A simple solution would be to replace the rec function as follows

int rec(int vec) {
    int count = a / vec;
    a = a % vec;
    return count;
}

Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.


问:
How to parse data which starts with an array [?
So in my swift 3 xcode project, I want to parse some data using JSOmN by consuming a web service called "http://tour-pedia.org/api/"
And the data within it for example is set like this:

```<code>[
    {
     "address": "Science Park 904",
     "category": "attraction",
     "id": 30884,
     "lat": 52.355320008998,
     "lng": 4.9574317242814,
     "location": "Amsterdam",
     "name": "Dakterras Science Park",
     "originalId": "4d8b3370bc848cfa1043ea2b",
     "polarity": 0,
     "subCategory": "Scenic Lookout",
    },
   {
     "address": "Science Park 201",
     "category": "attraction",
     "id": 30661,
     "lat": 52.356701093273,
     "lng": 4.9529844809109,
     "location": "Amsterdam",
     "name": "In 'de Natuur' rondom Science Park",
     "originalId": "4da2ede7c6e96ea85e1ede5d",
     "polarity": 0,
     "subCategory": "Field",
     }
]
</code>```

I want to use the address, location and name field.

so far i have done this:

```<code>func fetchInfos(){

    let urlRequest = URLRequest(url: URL(string: "http://tour-pedia.org/api/")!)
    let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in

        if error != nil {
            print(error)
            return
        }

        do{

            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

        } catch let error {
            print(error)
        }

    }

}
</code>```

but i don't know how to continue on from here.

Any help will be appreciated, thank you!

答:
Let us assume your string s is the json with sqaure brackets
String s = "[{\"a\":\"b\"}]";

s = s.substring(1, s.length() - 1);
//do all your processing on s now, as the sqaure brackets will be removed !!

Body:
So in my swift 3 xcode project, I want to parse some data using JSOmN by consuming a web service called "http://tour-pedia.org/api/"
And the data within it for example is set like this:

[
    {
     "address": "Science Park 904",
     "category": "attraction",
     "id": 30884,
     "lat": 52.355320008998,
     "lng": 4.9574317242814,
     "location": "Amsterdam",
     "name": "Dakterras Science Park",
     "originalId": "4d8b3370bc848cfa1043ea2b",
     "polarity": 0,
     "subCategory": "Scenic Lookout",
    },
   {
     "address": "Science Park 201",
     "category": "attraction",
     "id": 30661,
     "lat": 52.356701093273,
     "lng": 4.9529844809109,
     "location": "Amsterdam",
     "name": "In 'de Natuur' rondom Science Park",
     "originalId": "4da2ede7c6e96ea85e1ede5d",
     "polarity": 0,
     "subCategory": "Field",
     }
]

I want to use the address, location and name field.

so far i have done this:

func fetchInfos(){

    let urlRequest = URLRequest(url: URL(string: "http://tour-pedia.org/api/")!)
    let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in

        if error != nil {
            print(error)
            return
        }

        do{

            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

        } catch let error {
            print(error)
        }

    }

}

but i don't know how to continue on from here.

Any help will be appreciated, thank you!


问:
Can't extract machine code from Cortex-M3 firmware
I want to extract machine code from XBee DigiMesh firmware (Cortex-M3, EM357), so I have SREC file with 3 sections inside. I suppose that one of these sections is a code section, but arm-none-eabi-objdump reports "unknown instruction" very often. Does anyone know why this happens?

This is how I try to do this:

```<code>arm-none-eabi-objcopy --input-target=srec --output-target=binary -j .sec2 xbp24-dm_8073.ehx2.dec sec2.bin
arm-none-eabi-objdump -D -bbinary -marm -Mforce-thumb sec2.bin
</code>```

Firmware: http://tmp.nazaryev.ru/xbp24-dm_8073.ehx2.dec

EM357 datasheet: https://www.silabs.com/documents/public/data-sheets/EM35x.pdf

Update: there is answer at https://reverseengineering.stackexchange.com/questions/15049/cant-extract-machine-code-from-cortex-m3-firmware

答:
The cortex-m3 supports thumb2, which is variable instruction length, you cannot simply start at the beginning and disassemble a variable length instruction set you can/will easily get out of sync and the output turns to garbage and remain that way forever.  Likely not in this case, but you will have errors, this is expected.  it is quite possible they added items to confuse a disassembler as well.

Also you could have a lot of data here, or it could be compressed code, or who knows what else...

Being a cortex-m the first chunk of words are not a vector table, so what is this code.  If you examine the output in the way you have used the gnu tools, this does not look like real code, so perhaps encrypted or compressed or other.  Do you see stack frames being built and functions ending with a pop (ldmia) that contains the link register with some static words after that then what looks like the beginning of the next function?  Granted it might not all be compiled code, but some of it should look like compiled code.

if you are trying to hack some firmware you should perhaps figure out how/where this is loaded and create/use an instruction set simulator.  without a vector table to start with though, have fun.

the way you did your disassembly you lost the address content

```<code>S123110001BE8110204D5401BE96102452...
0x1100 : 0x01BE
0x1102 : 0x8110
0x1104 : 0x204D
0x1108 : 0x5401
0x110C : 0xBE96
0x110E : 0x1024
</code>```

and so on, that or probably byteswapped

```<code>0x1100 : 0xBE01
0x1102 : 0x1081
</code>```

You could take that srec and create a program:

```<code>.hword 0xbe01
.hword 0x1081
</code>```

one for each contiguous address range of items, when the address jumps start a new file, create a linker script to cover the start addresses of each section, assemble, make a _start label in one of them, link with the script then you have an elf you can disassemble, I still expect it to be problematic, but some of the relative addressing would make sense and or absolute addressing.

Also note your entry point

```<code>S903189351
</code>```

assuming that is real, no reason to assume that it is.

Body:
I want to extract machine code from XBee DigiMesh firmware (Cortex-M3, EM357), so I have SREC file with 3 sections inside. I suppose that one of these sections is a code section, but arm-none-eabi-objdump reports "unknown instruction" very often. Does anyone know why this happens?

This is how I try to do this:

arm-none-eabi-objcopy --input-target=srec --output-target=binary -j .sec2 xbp24-dm_8073.ehx2.dec sec2.bin
arm-none-eabi-objdump -D -bbinary -marm -Mforce-thumb sec2.bin

Firmware: http://tmp.nazaryev.ru/xbp24-dm_8073.ehx2.dec

EM357 datasheet: https://www.silabs.com/documents/public/data-sheets/EM35x.pdf

Update: there is answer at https://reverseengineering.stackexchange.com/questions/15049/cant-extract-machine-code-from-cortex-m3-firmware

Body:
The cortex-m3 supports thumb2, which is variable instruction length, you cannot simply start at the beginning and disassemble a variable length instruction set you can/will easily get out of sync and the output turns to garbage and remain that way forever.  Likely not in this case, but you will have errors, this is expected.  it is quite possible they added items to confuse a disassembler as well.

Also you could have a lot of data here, or it could be compressed code, or who knows what else...

Being a cortex-m the first chunk of words are not a vector table, so what is this code.  If you examine the output in the way you have used the gnu tools, this does not look like real code, so perhaps encrypted or compressed or other.  Do you see stack frames being built and functions ending with a pop (ldmia) that contains the link register with some static words after that then what looks like the beginning of the next function?  Granted it might not all be compiled code, but some of it should look like compiled code.

if you are trying to hack some firmware you should perhaps figure out how/where this is loaded and create/use an instruction set simulator.  without a vector table to start with though, have fun.

the way you did your disassembly you lost the address content

S123110001BE8110204D5401BE96102452...
0x1100 : 0x01BE
0x1102 : 0x8110
0x1104 : 0x204D
0x1108 : 0x5401
0x110C : 0xBE96
0x110E : 0x1024

and so on, that or probably byteswapped

0x1100 : 0xBE01
0x1102 : 0x1081

You could take that srec and create a program:

.hword 0xbe01
.hword 0x1081

one for each contiguous address range of items, when the address jumps start a new file, create a linker script to cover the start addresses of each section, assemble, make a _start label in one of them, link with the script then you have an elf you can disassemble, I still expect it to be problematic, but some of the relative addressing would make sense and or absolute addressing.

Also note your entry point

S903189351

assuming that is real, no reason to assume that it is.


问:
BackgroundWorker thread in ASP.NET
Is it possible to use BackGroundWorker thread in ASP.NET 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time?

Scenario

The browser requests a page, say SendEmails.aspx

SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails.

The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent.

Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete.

My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.

答:
If you want using multitheading in your ASP page, you might using simple threading model like this:

```<code>{
    System.Threading.Thread _thread = new Thread(new ThreadStart(Activity_DoWork));
    _thred.Start();
}
Activity_DoWork()
{
    /*Do some things...
}
</code>```

This method is correct working with ASP pages. The ASP page with BackgroundWorker will not start while BackgroundWorker will finish.

OwnerDisplayName: kudlur

Title: BackgroundWorker thread in ASP.NET

LastEditorDisplayName: Gulzar

Body:
If you want using multitheading in your ASP page, you might using simple threading model like this:

{
    System.Threading.Thread _thread = new Thread(new ThreadStart(Activity_DoWork));
    _thred.Start();
}
Activity_DoWork()
{
    /*Do some things...
}

This method is correct working with ASP pages. The ASP page with BackgroundWorker will not start while BackgroundWorker will finish.

OwnerDisplayName: Andry Ukraine

LastEditorDisplayName: John Sheehan


答:
Just use javascript</p>

```<code>video.src = 'new/url/video.ogv';
video.load();  // Load the new video
video.play();  // Play it
</code>```

Title: jquery and change html 5 video source on click

Body:
Just use javascript

video.src = 'new/url/video.ogv';
video.load();  // Load the new video
video.play();  // Play it


问:
How can html5 routing be achieved in angular2?
In angular 1, I can enable/disable the html routing with $routeProvider. How can that be achieved in angular 2 with direct url access to the page?</p>

答:
RouterModule.forRoot(routes, { useHash: true })

explained here https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles


问:
vertx LoggerHandler not adding logback
I am trying to use LoggerHandler to log all incoming requests. I am using logback.xml to specify appenders. I am setting system property for logging.

```<code>System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");
</code>```

Still it is logging everything in console not in file.

答:
This worked for me with Vert.x 3.4.1:

```<code>    import static io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME;
    import io.vertx.core.logging.LoggerFactory;

    // ...

    setProperty (LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName ());
    LoggerFactory.getLogger (LoggerFactory.class); // Required for Logback to work in Vertx
</code>```

The key is to get a logger, which I guess initializes the Logging subsystem, the class that you use to get a Logger seems irrelevant as I tried with two different ones.

I run these lines as the first ones of the program in production code and in the tests to work properly in both contexts.

Title: vertx LoggerHandler not adding logback

Body:
I am trying to use LoggerHandler to log all incoming requests. I am using logback.xml to specify appenders. I am setting system property for logging.

System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

Still it is logging everything in console not in file.

Body:
This worked for me with Vert.x 3.4.1:

    import static io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME;
    import io.vertx.core.logging.LoggerFactory;

    // ...

    setProperty (LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName ());
    LoggerFactory.getLogger (LoggerFactory.class); // Required for Logback to work in Vertx

The key is to get a logger, which I guess initializes the Logging subsystem, the class that you use to get a Logger seems irrelevant as I tried with two different ones.

I run these lines as the first ones of the program in production code and in the tests to work properly in both contexts.


问:
golang: Omit name of struct in xml.Marshal
Trying to get a particular output for XML:

```<code><RESPONSE>
    <DELIMITER value="09"></DELIMITER>
    <COLUMNS>Id FirstName   LastName    Company Initials</COLUMNS>
     <DATA>87734    Some Guy    Keller Williams Realty Empire   </DATA>
     <DATA>87739    Another Guy Level Group, Inc.   </DATA>
     <DATA>87741    Some Gal    Kian Realty NYC, LLC    </DATA>
</RESPONSE>
</code>```

instead I am getting:

```<code><RESPONSE>
 <compactData>
        <DELIMITER value="09"></DELIMITER>
        <COLUMNS>Id FirstName   LastName    Company Initials</COLUMNS>
        <DATA>87734 Some Guy    Keller Williams Realty Empire   </DATA>
        <DATA>87739 Another Guy Level Group, Inc.   </DATA>
        <DATA>87741 Some Gal    Kian Realty NYC, LLC    </DATA>
 </compactData>
</RESPONSE>
</code>```

I am trying not to output the <compactData> tag at all. (everything else is a-ok)

my struct that I am marshal-ing looks like this:

```<code>type delimiter struct {
    Value string `xml:"value,attr"`
}

type innerData struct {
    Data string `xml:",innerxml"`
}

type compactData struct {
    Delimiter delimiter    `xml:"DELIMITER"`
    Columns   *innerData   `xml:"COLUMNS"`
    Records   []*innerData `xml:"DATA"`
}
</code>```

I have tried putting in

```<code>XMLName   xml.Name
</code>```

or

```<code>XMLName   xml.Name `xml:""`
</code>```

to no avail- the xml.MarshalIndent just says 'yeah that looks like crap taking the struct name instead'.

I feel as though I just may need to reorganize the struct a bit, but I am stumped as to the magic structure needed.

Thanks!

Edit: the <RESPONSE> tag is added as the http.reponse is sent, after this formatting is done, trying to keep this signature the same as JSON and XML encoding...

like so:

```<code>func createResponse(obj interface{}, format string) (*Response, error) {
    var data []byte

    var f func(interface{}, string, string) ([]byte, error)

    switch format {
    case FORMAT_JSON:
        f = json.MarshalIndent
    case FORMAT_COMPACT:
        f = compact.MarshalIndent
    default:
        f = xml.MarshalIndent
    }
    data, err := f(obj, " ", "    ")
    if err != nil {
        log.Println(err)
        return nil, err
    }
    return &Response{Data: string(data)}, nil

}
</code>```

答:
If RESPONSE is another struct you could embed compactData in it and let encoding/xml do what you want.

```<code>type RESPONSE struct {
    compactData
}
</code>```

https://play.golang.org/p/hN1hDY7pnV

Update:
Actually you can do what you want, if I understood you correctly, by implementing the xml.Marshaler interface. E.g. something like this: https://play.golang.org/p/Uwm0pP1pWh.

Body:
Trying to get a particular output for XML:

<RESPONSE>
    <DELIMITER value="09"></DELIMITER>
    <COLUMNS>Id FirstName   LastName    Company Initials</COLUMNS>
     <DATA>87734    Some Guy    Keller Williams Realty Empire   </DATA>
     <DATA>87739    Another Guy Level Group, Inc.   </DATA>
     <DATA>87741    Some Gal    Kian Realty NYC, LLC    </DATA>
</RESPONSE>

instead I am getting:

<RESPONSE>
 <compactData>
        <DELIMITER value="09"></DELIMITER>
        <COLUMNS>Id FirstName   LastName    Company Initials</COLUMNS>
        <DATA>87734 Some Guy    Keller Williams Realty Empire   </DATA>
        <DATA>87739 Another Guy Level Group, Inc.   </DATA>
        <DATA>87741 Some Gal    Kian Realty NYC, LLC    </DATA>
 </compactData>
</RESPONSE>

I am trying not to output the <compactData> tag at all. (everything else is a-ok)

my struct that I am marshal-ing looks like this:

type delimiter struct {
    Value string `xml:"value,attr"`
}

type innerData struct {
    Data string `xml:",innerxml"`
}

type compactData struct {
    Delimiter delimiter    `xml:"DELIMITER"`
    Columns   *innerData   `xml:"COLUMNS"`
    Records   []*innerData `xml:"DATA"`
}

I have tried putting in

XMLName   xml.Name

or

XMLName   xml.Name `xml:""`

to no avail- the xml.MarshalIndent just says 'yeah that looks like crap taking the struct name instead'.

I feel as though I just may need to reorganize the struct a bit, but I am stumped as to the magic structure needed.

Thanks!

Edit: the <RESPONSE> tag is added as the http.reponse is sent, after this formatting is done, trying to keep this signature the same as JSON and XML encoding...

like so:

func createResponse(obj interface{}, format string) (*Response, error) {
    var data []byte

    var f func(interface{}, string, string) ([]byte, error)

    switch format {
    case FORMAT_JSON:
        f = json.MarshalIndent
    case FORMAT_COMPACT:
        f = compact.MarshalIndent
    default:
        f = xml.MarshalIndent
    }
    data, err := f(obj, " ", "    ")
    if err != nil {
        log.Println(err)
        return nil, err
    }
    return &Response{Data: string(data)}, nil

}

Body:
If RESPONSE is another struct you could embed compactData in it and let encoding/xml do what you want.

type RESPONSE struct {
    compactData
}

https://play.golang.org/p/hN1hDY7pnV

Update:
Actually you can do what you want, if I understood you correctly, by implementing the xml.Marshaler interface. E.g. something like this: https://play.golang.org/p/Uwm0pP1pWh.


问:
Find duplicate keys in Two Arrays of Dictionaries to update old Array dictionary with new Array dictionary
I want to update a saved dictionary with a new dictionary. New values need to be appended to the dictionary if no value exists. Also update old existing value with new value for a dictionary.

old saved array of dictionaries I have:

```<code> var savedDict = [
             ["id":"1","pic":"Alice.png","name":"Alice Smith","position":"Nurse"],
             ["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
             ["id":"12","pic":"bob.png","name":"Bob Smith PhD","position":"Hospital Coordinator"],
            ]
</code>```

new download Array of dictionaries:

```<code>let newDict =   [
             ["id":"1","pic":"alice.png","name":"Alice Smith","position":"Nurse"],
             ["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
             ["id":"3","pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
             ["id":"4","pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
             ["id":"5","pic":"user.png","name":"John Banks MD","position":"Cardiologist"],
             ["id":"6","pic":"tammie.png","name":"Tammie Summers","position":"Case Manager"]
            ]
</code>```

I want to:

1.update "Alice.png" to "alice.png" for "id" = 1,

2.ignore "id" = 2 because same for both Array of dicts,

3. append all the new items from newDict into savedDict

final dict should be:

```<code> upToDateDict = [
             ["id":"1","pic":"alice.png","name":"Alice Smith","position":"Nurse"],
             ["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
             ["id":"12","pic":"bob.png","name":"Bob Smith PhD","position":"Hospital Coordinator"],
             ["id":"3","pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
             ["id":"4","pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
             ["id":"5","pic":"user.png","name":"John Banks MD","position":"Cardiologist"],
             ["id":"6","pic":"tammie.png","name":"Tammie Summers","position":"Case Manager"]
            ]
</code>```

I tried this so far:

```<code> import UIKit
 import Foundation

 func arrayContains(array:[[String:String]], value:[String:String]) -> Bool {
     for item in array {
         if item == value {
             return true
         }
     }
     return false
 }

 var upToDateDict = savedDict//Array<Dictionary<String,String>>()

 //Save all of the dictionaries from the 1st array (savedDict) that aren't in the 2nd array (newDict)
 for item in newDict {
     if !arrayContains(array: savedDict, value: item) {
         upToDateDict.append(item)
     }
 }

 print(upToDateDict)

 //find duplicate keys and check if need to update saved dict with new dict

 let key = "id"

 for dict1 in savedDict {
     if let value = dict1[key] {
         for dict2 in newDict {
             if dict2[key] == value { //if true duplicate "id" key's  found

                 if dict1 != dict2 { //not duplicate for all keys, so update saved with new dictionary

                     print("found \(key):\(value) in both arrays")
                     print("dict1:\(dict1)")
                     print("dict2:\(dict2)")

                     savedDict[dict1] = dict2 //what I want to do but will not build

                 } else {}//all keys duplicate in dict1 and dict2

             }
         }
     }
 }
</code>```

I just want to overwrite this dictionary with new so I update ["id":"1","pic":"Alice.png"... to ["id":"1","pic":"alice.png"... but this is not working:

```<code> savedDict[dict1] = dict2
</code>```

答:
you should create

```<code>class Employee {
    var id: String
    var pic: String
    var name: String
    var position: String

    init(id: String, pic: String, name: String, position: String) {
        self.id = id
        self.pic = pic
        self.name = name
        self.position = position
    }
}
</code>```

then you will have

```<code>var oldEmployes: [Employee] = [Employee(id: "1", pic: "pic.png", name: "Name", position: "Position"),
                               Employee(id: "2", pic: "pic2.png", name: "Name2", position: "Position2")]
var newEmployes: [Employee] = [Employee(id: "2", pic: "pic21.png", name: "Name21", position: "Position2"),
                               Employee(id: "3", pic: "pic3.png", name: "Name3", position: "Position3")]
</code>```

to update array do something like (can be much more presentable using high level functions, but I think this way it looks clear)

```<code>for employee in newEmployes {
     var isNew = true
     for oldEmployee in oldEmployes {
           if oldEmployee.id == employee.id {
               oldEmployee.name = employee.name
               oldEmployee.pic = employee.pic
               oldEmployee.position = employee.position
               isNew = false
           }
     }
     if isNew {
         oldEmployes.append(employee)
     }
}
</code>```

Body:
I want to update a saved dictionary with a new dictionary. New values need to be appended to the dictionary if no value exists. Also update old existing value with new value for a dictionary.

old saved array of dictionaries I have:

 var savedDict = [
             ["id":"1","pic":"Alice.png","name":"Alice Smith","position":"Nurse"],
             ["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
             ["id":"12","pic":"bob.png","name":"Bob Smith PhD","position":"Hospital Coordinator"],
            ]

new download Array of dictionaries:

let newDict =   [
             ["id":"1","pic":"alice.png","name":"Alice Smith","position":"Nurse"],
             ["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
             ["id":"3","pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
             ["id":"4","pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
             ["id":"5","pic":"user.png","name":"John Banks MD","position":"Cardiologist"],
             ["id":"6","pic":"tammie.png","name":"Tammie Summers","position":"Case Manager"]
            ]

I want to:

1.update "Alice.png" to "alice.png" for "id" = 1,

2.ignore "id" = 2 because same for both Array of dicts,

3. append all the new items from newDict into savedDict

final dict should be:

 upToDateDict = [
             ["id":"1","pic":"alice.png","name":"Alice Smith","position":"Nurse"],
             ["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
             ["id":"12","pic":"bob.png","name":"Bob Smith PhD","position":"Hospital Coordinator"],
             ["id":"3","pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
             ["id":"4","pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
             ["id":"5","pic":"user.png","name":"John Banks MD","position":"Cardiologist"],
             ["id":"6","pic":"tammie.png","name":"Tammie Summers","position":"Case Manager"]
            ]

I tried this so far:

 import UIKit
 import Foundation

 func arrayContains(array:[[String:String]], value:[String:String]) -> Bool {
     for item in array {
         if item == value {
             return true
         }
     }
     return false
 }

 var upToDateDict = savedDict//Array<Dictionary<String,String>>()

 //Save all of the dictionaries from the 1st array (savedDict) that aren't in the 2nd array (newDict)
 for item in newDict {
     if !arrayContains(array: savedDict, value: item) {
         upToDateDict.append(item)
     }
 }

 print(upToDateDict)

 //find duplicate keys and check if need to update saved dict with new dict

 let key = "id"

 for dict1 in savedDict {
     if let value = dict1[key] {
         for dict2 in newDict {
             if dict2[key] == value { //if true duplicate "id" key's  found

                 if dict1 != dict2 { //not duplicate for all keys, so update saved with new dictionary

                     print("found \(key):\(value) in both arrays")
                     print("dict1:\(dict1)")
                     print("dict2:\(dict2)")

                     savedDict[dict1] = dict2 //what I want to do but will not build

                 } else {}//all keys duplicate in dict1 and dict2

             }
         }
     }
 }

I just want to overwrite this dictionary with new so I update ["id":"1","pic":"Alice.png"... to ["id":"1","pic":"alice.png"... but this is not working:

 savedDict[dict1] = dict2

Body:
you should create

class Employee {
    var id: String
    var pic: String
    var name: String
    var position: String

    init(id: String, pic: String, name: String, position: String) {
        self.id = id
        self.pic = pic
        self.name = name
        self.position = position
    }
}

then you will have

var oldEmployes: [Employee] = [Employee(id: "1", pic: "pic.png", name: "Name", position: "Position"),
                               Employee(id: "2", pic: "pic2.png", name: "Name2", position: "Position2")]
var newEmployes: [Employee] = [Employee(id: "2", pic: "pic21.png", name: "Name21", position: "Position2"),
                               Employee(id: "3", pic: "pic3.png", name: "Name3", position: "Position3")]

to update array do something like (can be much more presentable using high level functions, but I think this way it looks clear)

for employee in newEmployes {
     var isNew = true
     for oldEmployee in oldEmployes {
           if oldEmployee.id == employee.id {
               oldEmployee.name = employee.name
               oldEmployee.pic = employee.pic
               oldEmployee.position = employee.position
               isNew = false
           }
     }
     if isNew {
         oldEmployes.append(employee)
     }
}


问:
What will happen when you put variable as counter in a for statement?
Can anyone tell the value of counter at each iteration?</p>

```<code>Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim x As Integer
        For x = 1 To 10 Step (x)
            x = x + 1
            MsgBox(x)
        Next
    End Sub

End Class
</code>```

答: 2-11 - Step(x) is evaluated when first called.  (I'm right, yes - do I get a cookie?)</p>

Body:
Can anyone tell the value of counter at each iteration?

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim x As Integer
        For x = 1 To 10 Step (x)
            x = x + 1
            MsgBox(x)
        Next
    End Sub

End Class


问:
R Neural Network Forecasting - Aspect of Randomness?
I have been trying different methods of forecasting and stumbled upon the
    nnetar()
function in the forecast package of R. I soon quickly realized that while this does work to forecast, it gives me something different every time I run it. Could anybody help to explain why this happens? I thought I had a decent understanding of neural nets and I don't see what could make drastic differences in forecasts, unless the nnetar() function randomly selects the number of nodes or something. Any help? </p>

答:
20, by default, networks are trained with random starting values and then their predictions are averaged when you use the function.

Because the function uses random starting values for each run, the forecasts will be different for each call too.

EDIT: new question from OP in the comments

In order to control the function and get the same random starting values each time, you can simple use the function set.seed() with the value of your choice.

For example:

```<code>    set.seed(666)
    forecast(nnetar(...),...)

    set.seed(666)
    forecast(nnetar(...),...)

    set.seed(666)
    forecast(nnetar(...),...)
</code>```

will give the same results every time you run it with this "seed" value (666). You have to run set.seed(666) before every run of the rest of you code of course.

EDIT 2: new new question from OP in the comments

In order to have 100 different networks to fit with random starting weights:

```<code>nnetar(...,repeats=100,...)
</code>```

Body:
20, by default, networks are trained with random starting values and then their predictions are averaged when you use the function.

Because the function uses random starting values for each run, the forecasts will be different for each call too.

EDIT: new question from OP in the comments

In order to control the function and get the same random starting values each time, you can simple use the function set.seed() with the value of your choice.

For example:

    set.seed(666)
    forecast(nnetar(...),...)

    set.seed(666)
    forecast(nnetar(...),...)

    set.seed(666)
    forecast(nnetar(...),...)

will give the same results every time you run it with this "seed" value (666). You have to run set.seed(666) before every run of the rest of you code of course.

EDIT 2: new new question from OP in the comments

In order to have 100 different networks to fit with random starting weights:

nnetar(...,repeats=100,...)


问:
JSON and ANDROID
I have a JSONArray:

myArray => [{"key1" : "value1", "key2" : "value2"}, {"key3" : "value3", "key4" : "value4"}]

If I do
    myArray.get(1);
I get a Object.

I want the single keys and values of myArray[1]. How can I do this?
There is a way to have a HashMap that contains {"key3" : "value3", "key4" : "value4"} ?

Please help me, thanks.

答: Use getJSONObject(1).getString("key3"); and put the returned value in your HashMap. I am not sure if there is an "automatic" way to do this.  You can look at the documentation for more examples.

Title: JSON and ANDROID


问:
Where are sitecore logs on azure?
Sitecore 6.6 was deployed on azure using Sitecore Azure 3.0 tool. I'm looking for sitecore logs,because I need to see who changed particular item, but I can't find them. So I'm interested in AUDIT log lines.

I was looking in blob storage, but there are only containers: cacheclusterconfigs, publishtargets, sitecore-auto-deploy, wad-control-container, wad-iis-logfiles.

I was looking in table storage, using azure storage explorer, but there are only tables: WADDiagonsticInfrastructureTable, WADDirectoriesTable, WADLogsTable, WADPerformanceCountersTable, WADWindowsEventLogsTable.

Where are audit logs stored?

答:
With Sitecore Experience Platform 8.2, the location of the log files has been updated: https://kb.sitecore.net/articles/911837

Logs can now be accessed via Application Insights.  Find the proper Application Insights object:

Select the object, which will launch a new window:

Open a new tab (query) and enter the following query exactly:

```<code>traces
| extend scinstancename=parsejson(customDimensions).InstanceName
| where timestamp > now(-1d)
| summarize count(), any(tostring(scinstancename)) by cloud_RoleInstance
| extend InstanceName=any_scinstancename
| extend CloudRole=cloud_RoleInstance
| project InstanceName, CloudRole
| order by InstanceName asc
</code>```

Hit 'GO'.

Find the instance you wish to view the logs of, and take note of the CloudRole column:

Lastly, run the following query in a new tab, swap out the 'CloudRole' with the role you found from the previous step:

```<code>traces
| where cloud_RoleInstance == 'REPLACE_THIS_ROLE'
| where timestamp > now(-14d)
| project timestamp, message
| sort by timestamp desc
</code>```

The log file is displayed below:

Results may be exported to CSV if desired:

Title: Where are sitecore logs on azure?

Body:
With Sitecore Experience Platform 8.2, the location of the log files has been updated: https://kb.sitecore.net/articles/911837

Logs can now be accessed via Application Insights.  Find the proper Application Insights object:

Select the object, which will launch a new window:

Open a new tab (query) and enter the following query exactly:

traces
| extend scinstancename=parsejson(customDimensions).InstanceName
| where timestamp > now(-1d)
| summarize count(), any(tostring(scinstancename)) by cloud_RoleInstance
| extend InstanceName=any_scinstancename
| extend CloudRole=cloud_RoleInstance
| project InstanceName, CloudRole
| order by InstanceName asc

Hit 'GO'.

Find the instance you wish to view the logs of, and take note of the CloudRole column:

Lastly, run the following query in a new tab, swap out the 'CloudRole' with the role you found from the previous step:

traces
| where cloud_RoleInstance == 'REPLACE_THIS_ROLE'
| where timestamp > now(-14d)
| project timestamp, message
| sort by timestamp desc

The log file is displayed below:

Results may be exported to CSV if desired:


问:
Thread data encapsulation best practices
I have a question how to encapsulate data gracefully in such case.
Let's think we want to make some class that can asynchronous download images from internet. Let us have unblocking method:

```<code>void download(string url)
</code>```

This method will create thread and start downloading, and then invoke callback:

```<code>void callback(char* data)
</code>```

What is best: allocate memory for data in Downloader or allocate it out of Downloader class? In first case we will need to copy data returned in callback and if data is big - it is not good, otherwise we will allocate memory in Downloader class and release it somewhere else. In second case we need to allocate memory for data and pass it as parameter in download method:

```<code>char *data = new char[DATA_SIZE];
downloader.download(url, data);
</code>```

But how can we protect this allocated data from changing it from callable thread, while it used by downloader thread. I think there is some way to make it without synchronization in callable thread some way to make this logic invisible for client.

Hope you get my mind right

答:
Some sprinkling of C++ Standard Library classes would probably be good.

```<code>std::future<std::vector<unsigned char>> download(std::string url) {
    std::promise<std::vector<unsigned char>> promise;
    std::future<std::vector<unsigned char>> future = promise.get_future();
    //I'm like 99% certain that both promise and future ref-count their shared state
    //so it's probably safe to move and later even delete the promise object.
    func_which_begins_asynchronous_process(url, std::move(promise));
    return future;
}

void callback(std::vector<unsigned char> data, std::promise<std::vector<unsigned char>> promise) {
    promise.set_value(std::move(data));
}

int main() {
    auto future = download("google.com");
    //Do whatever
    std::vector<unsigned char> result = future.get();
    //Do whatever
    return 0;
}
</code>```

This will both make the code easy to reason about, and will reliably handle the "pointer ownership" issue you discussed in your original post.

I don't know the exact semantics/requirements of your code, so my code won't work in your solution "as-is", but this should give you a pretty good idea of the kind of paradigm that will solve your problem.

Body:
I have a question how to encapsulate data gracefully in such case.
Let's think we want to make some class that can asynchronous download images from internet. Let us have unblocking method:

void download(string url)

This method will create thread and start downloading, and then invoke callback:

void callback(char* data)

What is best: allocate memory for data in Downloader or allocate it out of Downloader class? In first case we will need to copy data returned in callback and if data is big - it is not good, otherwise we will allocate memory in Downloader class and release it somewhere else. In second case we need to allocate memory for data and pass it as parameter in download method:

char *data = new char[DATA_SIZE];
downloader.download(url, data);

But how can we protect this allocated data from changing it from callable thread, while it used by downloader thread. I think there is some way to make it without synchronization in callable thread some way to make this logic invisible for client.

Hope you get my mind right

Body:
Some sprinkling of C++ Standard Library classes would probably be good.

std::future<std::vector<unsigned char>> download(std::string url) {
    std::promise<std::vector<unsigned char>> promise;
    std::future<std::vector<unsigned char>> future = promise.get_future();
    //I'm like 99% certain that both promise and future ref-count their shared state
    //so it's probably safe to move and later even delete the promise object.
    func_which_begins_asynchronous_process(url, std::move(promise));
    return future;
}

void callback(std::vector<unsigned char> data, std::promise<std::vector<unsigned char>> promise) {
    promise.set_value(std::move(data));
}

int main() {
    auto future = download("google.com");
    //Do whatever
    std::vector<unsigned char> result = future.get();
    //Do whatever
    return 0;
}

This will both make the code easy to reason about, and will reliably handle the "pointer ownership" issue you discussed in your original post.

I don't know the exact semantics/requirements of your code, so my code won't work in your solution "as-is", but this should give you a pretty good idea of the kind of paradigm that will solve your problem.


问:
Where in laravel 5.2
I am trying to retrieve zipcodes from the database where I am getting an error- Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given. I am not sure if my where in query is correct. Thanks in advance.

$countiesList array looks like = ["Beaverhead", "Big Horn",......]

function in the model is:

```<code>public static function counties_zip($countiesList)
    {

        $zipCodes= Zip::select('ZIPCode')
                  ->distinct()
                  ->whereIn('CountyName', $countiesList)
                  ->orderBy('ZIPCode', 'asc')
                  ->get();
        return $zipCodes;
    }
</code>```

In the controller:

```<code>public function zipCodes(Request $request) {

        $zipCodes = Zip::counties_zip($request->counties);

        return json_encode($zipCodes);

    }
</code>```

and my jS:

```<code>$(".submit").on("click", function(){
        myList = [];
        $('.select2 option:selected').each(function() {
            myList.push($(this).val())
        });
        $countiesList=myList;

        console.log($countiesList);
        $.ajax({
                    type: "get",
                    url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
                    data: { counties: $countiesList},
                    dataType: "json",
                    success: function (data) {
                        var htmlText = '';
                        for ( var i=0;i<data.length;i++ ) {
                            htmlText += '<div class="div-conatiner">';
                            htmlText += '<input type="checkbox">' +  data[i].ZipCode;
                            htmlText += '<div>';
                        }
                        $(".main-div").append(htmlText);
                    }
                });
    });
</code>```

答:
In the javascript I used JSON.stringify to convert the javascript array to JSON array. Then in the model I decoded the JSON string using json_decode.
JS:

```<code> $(".submit").on("click", function(){
            myList = [];
            $('.select2 option:selected').each(function() {
                myList.push($(this).val())
            });
            $countiesList=myList;

            console.log($countiesList);
            $.ajax({
                        type: "get",
                        url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
                        data: { counties: $countiesList},
                        dataType: "json",
                        success: function (data) {
                            var htmlText = '';
                            for ( var i=0;i<data.length;i++ ) {
                                htmlText += '<div class="div-conatiner">';
                                htmlText += '<input type="checkbox">' +  data[i].ZipCode;
                                htmlText += '<div>';
                            }
                            $(".main-div").append(htmlText);
                        }
                    });
        });
</code>```

Model:

```<code>public static function counties_zip($countiesList)
    {
        $county= json_decode($countiesList, true);
        $zipCodes= Zip::select('ZIPCode')
                  ->distinct()
                  ->whereIn('CountyName', $county)
                  ->orderBy('ZIPCode', 'asc')
                  ->get();
        return $zipCodes;
    }
</code>```

Title: Where in laravel 5.2

Body:
I am trying to retrieve zipcodes from the database where I am getting an error- Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given. I am not sure if my where in query is correct. Thanks in advance.

$countiesList array looks like = ["Beaverhead", "Big Horn",......]

function in the model is:

public static function counties_zip($countiesList)
    {

        $zipCodes= Zip::select('ZIPCode')
                  ->distinct()
                  ->whereIn('CountyName', $countiesList)
                  ->orderBy('ZIPCode', 'asc')
                  ->get();
        return $zipCodes;
    }

In the controller:

public function zipCodes(Request $request) {

        $zipCodes = Zip::counties_zip($request->counties);

        return json_encode($zipCodes);

    }

and my jS:

$(".submit").on("click", function(){
        myList = [];
        $('.select2 option:selected').each(function() {
            myList.push($(this).val())
        });
        $countiesList=myList;

        console.log($countiesList);
        $.ajax({
                    type: "get",
                    url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
                    data: { counties: $countiesList},
                    dataType: "json",
                    success: function (data) {
                        var htmlText = '';
                        for ( var i=0;i<data.length;i++ ) {
                            htmlText += '
';
                            htmlText += '<input type="checkbox">' +  data[i].ZipCode;
                            htmlText += '
';
                        }
                        $(".main-div").append(htmlText);
                    }
                });
    });

Body:
In the javascript I used JSON.stringify to convert the javascript array to JSON array. Then in the model I decoded the JSON string using json_decode.
JS:

 $(".submit").on("click", function(){
            myList = [];
            $('.select2 option:selected').each(function() {
                myList.push($(this).val())
            });
            $countiesList=myList;

            console.log($countiesList);
            $.ajax({
                        type: "get",
                        url: http_host + '/leads/regions/counties/zipcodes?counties=' + $countiesList,
                        data: { counties: $countiesList},
                        dataType: "json",
                        success: function (data) {
                            var htmlText = '';
                            for ( var i=0;i<data.length;i++ ) {
                                htmlText += '<div class="div-conatiner">';
                                htmlText += '<input type="checkbox">' +  data[i].ZipCode;
                                htmlText += '<div>';
                            }
                            $(".main-div").append(htmlText);
                        }
                    });
        });

Model:

public static function counties_zip($countiesList)
    {
        $county= json_decode($countiesList, true);
        $zipCodes= Zip::select('ZIPCode')
                  ->distinct()
                  ->whereIn('CountyName', $county)
                  ->orderBy('ZIPCode', 'asc')
                  ->get();
        return $zipCodes;
    }


问:
problems with wordpress site after changing permalink structure
My wordpress site lies in a folder called /entwurf/cob1 and since I wanted it to be shown by simply typing in www.cob1.org I changed the permalink to cob1.org and now nothing works. I tried changing the htacces to:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /entwurf/cob1/index.php [L]
</IfModule>
</code>```

but this doesnt seem to work either. I want my files who lie in the entwurf/cob1/ folder to be shown when typing in the cob1.org website.
Currently nothing is seen.

答:
If you have access to the Worpdress admin panel go to
Setting > General
and make sure the Wordpress URL and Site URL are correct. They should be your new address. Change those and save it if you want to rewrite all the old URLS in the database.

If you don't have access to the WP admin panel try using this to manually make the changes to your database.

https://interconnectit.com/products/search-and-replace-for-wordpress-databases/

Body:
My wordpress site lies in a folder called /entwurf/cob1 and since I wanted it to be shown by simply typing in www.cob1.org I changed the permalink to cob1.org and now nothing works. I tried changing the htacces to:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /entwurf/cob1/index.php [L]
</IfModule>

but this doesnt seem to work either. I want my files who lie in the entwurf/cob1/ folder to be shown when typing in the cob1.org website.
Currently nothing is seen.