Q: How to cache pages using background jobs? Definitions: resource = collection of database records, regeneration = processing these records and outputting the corresponding html
Current flow:

*

*Receive client request

*Check for resource in cache

*If not in cache or cache expired, regenerate

*Return result

The problem is that the regeneration step can tie up a single server process for 10-15 seconds. If a couple of users request the same resource, that could result in a couple of processes regenerating the exact same resource simultaneously, each taking up 10-15 seconds.
Wouldn't it be preferrable to have the frontend signal some background process saying "Hey, regenerate this resource for me".
But then what would it display to the user? "Rebuilding" is not acceptable. All resources would have to be in cache ahead of time. This could be a problem as the database would almost be duplicated on the filesystem (too big to fit in memory). Is there a way to avoid this? Not ideal, but it seems like the only way out.
But then there's one more problem. How to keep the same two processes from requesting the regeneration of a resource at the same time? The background process could be regenerating the resource when a frontend asks for the regeneration of the same resource.
I'm using PHP and the Zend Framework just in case someone wants to offer a platform-specific solution. Not that it matters though - I think this problem applies to any language/framework.
Thanks!

A: With Varnish you can proactively cache page content and use grace to display stale, cached content if a response doesn't come back in time.

Enable grace period (varnish serves stale (but cacheable) objects while retriving object from backend)

You may need to tweak the dials to determine the best settings for how long to serve the stale content and how long it takes something to be considered stale, but it should work for you. More on the Varnish performance wiki page.

A: I recommend caching in webserver level rather than the application

A: I have done just this recently for a couple of different things, in each case, the basics are the same - in this instance the info can be pre-generated before use.

A PHP job is run regularly (maybe from
  CRON) which generates information into
  Memcached, which is then used
  potentially hundreds of times till
  it's rebuilt again.

Although they are cached for well-defined periods (be it 60 mins, or 1 minute), they are regenerated more often than that.  Therefore, unless something goes wrong, they will never expire from Memcache, because a newer version is cached before they can expire.  Of course, you could just arrange for them to never expire.
I've also done similar things via a queue - you can see previous questions I've answered regarding 'BeanstalkD'.

A: Depending on the content the jQuery.load() might be an option.
(I used it for a twitter feed)
Step 1
Show the cached version of the feed.
Step 2
Update the content on the page via jQuery.load() and cache the results.
.
This way the page loads fast and displays up2date content (after x secs offcourse)
But if rebuilding/loading a full page this wouldn't give a nice user experience.

A: You describe a few problems, perhaps some general ideas would be helpful.
One problem is that your generated content is too large to store entirely so you can only cache a subset of that total content, you will need: a method for uniquely identifying each content object that can be generated, a method for identifying if a content object is already in the cache, a policy for marking data in the cache stale to indicate that background regeneration should be run, and a policy for expiring and replacing data in the cache. Ultimately keeping the unique content identification simple should help with performance while your policy for expiring objects and marking stale objects should be used to define the priority for background regeneration of content objects. These may be simple updates to your existing caching scheme, on the other hand it may be more effective for you to use a software package specifically made to address this need as it is not an uncommon problem.
Another problem is that you don't want to duplicate the work to regenerate content. If you have multiple parallel generation engines with differing capabilities this may not be so bad of a thing and it may be best to queue a task to each and remove the task from all other queues when the first generator completes the job. Consider tracking the object state when a regeneration is in progress so that multiple background regeneration tasks can be active without duplicating work unintentionally. Once again, this can be supplanted into your existing caching system or handled by a dedicated caching software package.
A third problem is concerned with what to do when a client requests data that is not cached and needs to be regenerated. If the data needs to be fully regenerated you will be stuck making the client wait for regeneration to complete, to help with long content generation times you could identify a policy for predictive prefetching content objects into cache but requires a method to identify relationships between content objects. Whether you want to serve the client a "regenerating" page until the requested content is available really depends on your client's expectations. Consider multi-level caches with compressed data archives if content regeneration cannot be improved from 10-15 seconds.
Making good use of a mature web caching software package will likely address all of these issues. Nick Gerakines mentioned Varnish which appears to be well suited to your needs.


Q: picking a DataRow Based on maximum of certain field and criteria using LINQ here is my code (which doesn't work, obviously) .But, Could not figure out how to achieve this...
DataRow dRow =  dsMain.tblStudentMaster.Select("stM_ClassNo=VI")).Max<DataRow>(row => row["StudentRollNo"]);

In a particular ClassRoom, I want to pick up student having Maximum Roll No.
Well, I want that DataRow and not the RollNo (which is obviously available once I get that row).

A: You have to order the rows accordingly:
DataRow dRow =  dsMain.tblStudentMaster.AsEnumerable()
    .OrderByDescending(r => r.Field<int>("StudentRollNo"))
    .FirstOrDefault();

(assuming that the type of the column StudentRollNo is int)

A: You can also try MaxBy extension method from MoreLINQ
dsMain.tblStudentMaster.MaxBy(item => item.FieldYouWantMaxFrom);


Q: Allowing Ping from Mininet to External VM how do I allow pinging from hosts inside Mininet to External VM using RYU controller.
In terms of pinging, i am able to ping as the following:

*

*hosts to hosts

*hosts to switches

*RYU controllers / S1-3 Switches to internet

*RYU controllers / S1-3 Switches to External VM.

Hence, I am looking for solutions on how to allow host (h1-6) to connect to the internet or external vm.
enter image description here

A: This is possible via configuring VirtualBox (if you are using it). There are more than one way to do it, but take a look at this tutorial


Q: Tarfile recursively opens in windows, but not in Linux [Python] I have a Python program which extracts a zip file. The zip file looks like this:
a.zip
  |
  |
  --- b.tar.gz
  .     |
  .     |
  .     --- c.tar

Here is my code:
with zipfile.ZipFile("a.zip", 'r') as zipRef:
    with zipRef.open("b.tar.gz") as x:
        x_filedata = io.BytesIO(x.read())
        with tarfile.open(fileobj=x_filedata) as tarRef:
            tarFiles = tarRef.getmembers()
            for fileInTar in tarFiles:
                print(fileInTar)

In Windows, this code recursively opens c.tar too and prints the contents of c.tar file. But in Centos, it prints c.tar. Why is this happening?


Q: WPF - DataGridColumnHeader text does not bind I am trying to initiate a DataGrid in C#/WPF and have the text of the respective column headers bind to a value in the ViewModel. However, this does not seem to work. Here is the xaml for the DataGrid:
      <DataGrid ItemsSource="{Binding Measurements}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Timestamp}" Width="Auto">
                    <DataGridTextColumn.Header>
                        <TextBlock Foreground="Black" Text="{Binding Text_Header1}"/>
                    </DataGridTextColumn.Header>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>

And here is the value in my ViewModel
        public string Text_Header1 { get { return local.Header1Text; } }
All the other Databinding for the DataGrid works just fine. It's just the title of the headers that doesn't seem to work.
I tried changing the Text property to a non-binding value and that one shows. So this seems to be the right way to set the text. I also tried having the Text_Header1 just return "Test" or bind it to other values that I know word in other elements and that did not work either. The column header just appears as empty when the Binding is set.
I have also tried setting the Binding up like this
<TextBlock Text="{Binding Text_Time, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Foreground="Black"/>

and it has also not worked. The header stays blank.


Q: Creating Google Maps Control that you can drag and drop markers onto map to get their coordinates I am creating a GoogleMaps v3 Custom Control that is similar the the little yellow man on google maps. The control has an icon in the top left corner of maps. The user will drag and drop that icon onto the map. Then I just want to get the latlng for that location.
It is not the same as a marker even though it seems like one.
here is what I have so far:
var draggableMarkerControl = document.createElement('div');
draggableMarkerControl.setAttribute('class', 'gm-draggable-container'); //h&w of 75px
map.controls[google.maps.ControlPosition.TOP_LEFT].push( draggableMarkerControl );

Does anyone have any thoughts on what to do next? Maybe help find some similar code to work from?

A: I found your question whilst looking for essentially the same thing for my own project. I did find https://groups.google.com/forum/#!topic/google-maps-js-api-v3/7oWus3T5Ycw which I'm sure could be adapted, but if you look at the source of the example it says the code "is available for a fee".
My approach was going to be to place a temporary marker on the map at a certain position in the window, but then it would have to be recalculated and moved each time the map was moved or zoomed.

A: An alternative approach is to use the Drawing Library, as suggested on my post by Suvi Vignarajah
Positioning a draggable map marker at top-left of map window (there's a jsFiddle in the comments that shows my final solution)
I'm still thinking your idea of a custom control is actually the best in terms of intuitive UX


Q: Entity Framework doesn't delete children, instead sets references to null I have the following situation:
First the only relevant table/class (all auto generated from DB (MySQL)):

The relevant part of the edmx file:
     <Association Name="navigationitem_ibfk_1">
      <End Role="navigationitem" Type="Model.Store.navigationitem" Multiplicity="0..1">
        <OnDelete Action="Cascade" />
      </End>
      <End Role="navigationitem1" Type="Model.Store.navigationitem" Multiplicity="*" />
      <ReferentialConstraint>
        <Principal Role="navigationitem">
          <PropertyRef Name="id" />
        </Principal>
        <Dependent Role="navigationitem1">
          <PropertyRef Name="navigationitemid" />
        </Dependent>
      </ReferentialConstraint>
    </Association>

I think there aren't many more words needed: It's a navigation table, each navigationitem can have children (but it's not a must).
Now when I try to remove a top level item which has a child:
context.Remove(topLevelNode);
context.SaveChanges();

It deletes the top level node in the DB, but at the child nodes it just sets the navigationitemid to null (and yes - I have defined on delete cascade in the DB, when I delete it directly there it works).
So what I think it's going on is, that when I delete the parent node, the framework sets all navigationitemid of all children to NULL, then when the navigation should be saved to the DB it won't cascade the delete because the navigationitemid of the children are NULL.
What can I do? Thank you.

A: The obvious thing one would like to do is define cascade deletes on the association in the context. But trying it I found out that either sql server does not support it or EF needs help:

*

*Defining cascade delete on the foreign key constraint (using code-first) throws a sql server exception:

Introducing FOREIGN KEY constraint 'xxx' on table 'yyy' may cause cycles or multiple cascade paths. (See here.)

*Cascade delete in EF model: now when deleting a parent the child records are not deleted. Even worse: the FK fields are not nullified and the foreign key constraint violation will throw an exception. The remedy is to load the child collection before deleting the parent.

Especially when deleting a tree of navigationitems this is not a very attractive option, but I'm afraid it's all you've got at the moment.


Q: How to test angular2 app who implements jquery library I have an angular2 components who encapsulate some jquery library (timelineJS3). All works well, but i need write tests. Specifically i want listen click events. To do this i used Renderer2. But it's doesn't work properly with karma.
See my code in plunkr https://embed.plnkr.co/7ROP9O2CgQolVeO5ItCb/
describe('- EventArray - ', () => {

let events = cosmological.events;

it('test click in next (idk how to fire jquery event)', async(() => {
  var i = 0;
  component.clicked.subscribe((ev: any) => {
    expect(ev.unique_id).toEqual(cosmological.events[i++].unique_id);
  });

  //init
  component.events = events;
  component.ngAfterViewInit();

  // trigger the click
  spyOn(component.clicked, 'emit');
  let button = fixture.nativeElement.querySelector('.tl-slidenav-next .tl-slidenav-content-container');
  button.dispatchEvent(new Event('click'));
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    expect(component.clicked.emit).toHaveBeenCalled();
  })
}));

});

this piece of code doesn't fire event in karma. Idk why.
let button = fixture.nativeElement.querySelector('.tl-slidenav-next .tl-slidenav-content-container');
button.dispatchEvent(new Event('click'));

A: First of all you should use debugElement of your fixture which will give you some useful methods for testing. One is triggerEventHandler which will help you with your issue (and just to mention: query would be another method that you will probably want to use often since it's way more powerful than querySelector and will return again a debugElement).
let button: DebugElement = fixture.debugElement.query(By.css('.tl-slidenav-next .tl-slidenav-content-container'));
button.triggerEventHandler('click', null); // where null is the event being passed if it's used in the listener

Hope it helps.


Q: Python script waiting for some program being launched and then starting another program. (Windows) I would like to write a python script that will finally be converted to .exe (with pyinstaller lets say) and added  to windows startup applications list. This program (once launched) should 'monitor' user and wait until user will start a specified program (say program1.exe) and then my python program should launch another specified program (program2.exe).
I know that there is something like subprocess to launch another program from python script but I was not able to make it work so far ;/ And as it comes to this part where I need to monitor if user does start specified program I have no idea haw to bite on this. I don't expect a complete solution (although it would be very nice to find such ;p)  but any guides or clues would be very helpfull.

A: For the monitoring whether or not the user has launched the program, I would use psutil: https://pypi.python.org/pypi/psutil
and for launching another program from a python script, I would use subprocess.
To launch something with subprocess you can do something like this:
PATH_TO_MY_EXTERNAL_PROGRAM = r"C:\ProgramFiles\MyProgram\MyProgramLauncher.exe"
subprocess.call([PATH_TO_MY_EXTERNAL_PROGRAM])

If it is as simple as calling an exe though, you could just use:
PATH_TO_MY_EXTERNAL_PROGRAM = r"C:\ProgramFiles\MyProgram\MyProgramLauncher.exe"
os.system(PATH_TO_MY_EXTERNAL_PROGRAM)

Hope this helps.
-Alex


Q: How to Save Shared Preference Value in ClearData Application?[Android] In clear Data Android, Shared Preference is clear. I don't want it clear.

A: If you clear the app data, shared preferences will also be cleared, you have to store in your database or cloud.

A: there is a trick for that, it is not a normal way but works:
<application android:label="MyApp" android:icon="@drawable/icon"
                 android:manageSpaceActivity=".ActivityOfMyChoice">

by adding this line to your manifest instead of "Clear Data" button for "Manage Space" which launches ActivityOfMyChoice will be shown, it calls your activity and the Activity and you can finish your activity there like this:
public class ActivityOfMyChoice extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        finish();

    }
}

for me, this method worked!
let me know about the result
for more info, if you want to save your data even after "clear data" you might use the database to save your data and save your database in a file out of your application place in the device.


Q: Django image doesn't show up in template I bought bootstrap theme and tried to apply it on my django project.
I almost done with it(css, js) except image files.
This is what it looks like :

Left one is my django project's view, right one is downloaded-source itself.  As you can see here, css, js work well but only image doesn't show up.
setting.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'collect_static')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'collect_media')

My project tree :
├── chacha_dabang
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-35.pyc
│   │   ├── settings.cpython-35.pyc
│   │   ├── urls.cpython-35.pyc
│   │   └── wsgi.cpython-35.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── intro
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-35.pyc
│   │   ├── admin.cpython-35.pyc
│   │   ├── urls.cpython-35.pyc
│   │   └── views.cpython-35.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-35.pyc
│   ├── templates
│   │   └── intro
│   │       └── index.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── static
│   ├── css
│   │   ├── animate.min.css
│   │   ├── blue.css
│   │   ├── bootstrap.min.css
│   │   ├── gray.css
│   │   ├── green.css
│   │   ├── main.css
│   │   ├── navy.css
│   │   ├── orange.css
│   │   ├── owl.carousel.css
│   │   ├── owl.transitions.css
│   │   ├── pink.css
│   │   ├── purple.css
│   │   └── red.css
│   ├── fonts
│   │   ├── fontello
│   │   │   ├── fontello-.eot
│   │   │   ├── fontello-circle.eot
│   │   │   ├── fontello-circle.svg
│   │   │   ├── fontello-circle.ttf
│   │   │   ├── fontello-circle.woff
│   │   │   ├── fontello-social-.eot
│   │   │   ├── fontello-social.eot
│   │   │   ├── fontello-social.svg
│   │   │   ├── fontello-social.ttf
│   │   │   ├── fontello-social.woff
│   │   │   ├── fontello.eot
│   │   │   ├── fontello.svg
│   │   │   ├── fontello.ttf
│   │   │   └── fontello.woff
│   │   └── fontello.css
│   ├── images
│   │   ├── art
│   │   │   ├── client01.jpg
│   │   │   ├── client02.jpg
│   │   │   ├── client03.jpg
│   │   │   ├── client04.jpg
│   │   │   ├── client05.jpg
│   │   │   ├── client06.jpg
│   │   │   ├── client07.jpg
│   │   │   ├── client08.jpg
│   │   │   ├── client09.jpg
│   │   │   ├── client10.jpg
│   │   │   ├── client11.jpg
│   │   │   ├── client12.jpg
│   │   │   ├── human01.jpg
│   │   │   ├── human02.jpg
│   │   │   ├── human03.jpg
│   │   │   ├── human04.jpg
│   │   │   ├── human05.jpg
│   │   │   ├── human06.jpg
│   │   │   ├── humans01.jpg
│   │   │   ├── image-background01.jpg
│   │   │   ├── image-background02.jpg
│   │   │   ├── image-background03.jpg
│   │   │   ├── image-background04.jpg
│   │   │   ├── office01.jpg
│   │   │   ├── office02.jpg
│   │   │   ├── office03.jpg
│   │   │   ├── pattern-background01.jpg
│   │   │   ├── pattern-background02.png
│   │   │   ├── pattern-background03.png
│   │   │   ├── photograph01-lg.jpg
│   │   │   ├── photograph02.jpg
│   │   │   ├── photograph03.jpg
│   │   │   ├── photograph04-lg.jpg
│   │   │   ├── product01.jpg
│   │   │   ├── product02.jpg
│   │   │   ├── product03.jpg
│   │   │   ├── product04.jpg
│   │   │   ├── product05.jpg
│   │   │   ├── product06.jpg
│   │   │   ├── screen-container.png
│   │   │   ├── service01.jpg
│   │   │   ├── slider01.jpg
│   │   │   ├── slider02.jpg
│   │   │   ├── slider03.jpg
│   │   │   ├── slider04.jpg
│   │   │   ├── slider05.jpg
│   │   │   ├── slider06.jpg
│   │   │   ├── work01-lg.jpg
│   │   │   ├── work01.jpg
│   │   │   ├── work02-lg.jpg
│   │   │   ├── work02.jpg
│   │   │   ├── work03.jpg
│   │   │   ├── work04.jpg
│   │   │   ├── work05.jpg
│   │   │   ├── work05a.jpg
│   │   │   ├── work06-lg.jpg
│   │   │   ├── work06.jpg
│   │   │   ├── work07.jpg
│   │   │   ├── work08-lg.jpg
│   │   │   ├── work08.jpg
│   │   │   ├── work08a-lg.jpg
│   │   │   ├── work08a.jpg
│   │   │   ├── work08b-lg.jpg
│   │   │   ├── work08b.jpg
│   │   │   ├── work08c-lg.jpg
│   │   │   ├── work08c.jpg
│   │   │   ├── work08d-lg.jpg
│   │   │   ├── work08d.jpg
│   │   │   ├── work08e.jpg
│   │   │   ├── work08f-lg.jpg
│   │   │   ├── work08f.jpg
│   │   │   ├── work08g-lg.jpg
│   │   │   ├── work09-lg.jpg
│   │   │   ├── work09.jpg
│   │   │   ├── work10.jpg
│   │   │   ├── work11.jpg
│   │   │   ├── work12.jpg
│   │   │   ├── work13.jpg
│   │   │   ├── work14-lg.jpg
│   │   │   ├── work15-lg.jpg
│   │   │   ├── work15.jpg
│   │   │   ├── work16-lg.jpg
│   │   │   ├── work16.jpg
│   │   │   ├── work17.jpg
│   │   │   ├── work18.jpg
│   │   │   ├── work19.jpg
│   │   │   ├── work20.jpg
│   │   │   ├── work21.jpg
│   │   │   ├── work22.jpg
│   │   │   ├── work23.jpg
│   │   │   ├── work24.jpg
│   │   │   └── work25.jpg
│   │   ├── favicon.ico
│   │   ├── grabbing.png
│   │   ├── logo-white.svg
│   │   └── logo.svg
│   ├── js
│   │   ├── bootstrap-hover-dropdown.min.js
│   │   ├── bootstrap.min.js
│   │   ├── google.maps.api.v3.js
│   │   ├── html5shiv.js
│   │   ├── jquery.easing.1.3.min.js
│   │   ├── jquery.easytabs.min.js
│   │   ├── jquery.form.js
│   │   ├── jquery.isotope.min.js
│   │   ├── jquery.min.js
│   │   ├── jquery.validate.min.js
│   │   ├── owl.carousel.min.js
│   │   ├── respond.min.js
│   │   ├── scripts.js
│   │   ├── skrollr.min.js
│   │   ├── skrollr.stylesheets.min.js
│   │   ├── viewport-units-buggyfill.js
│   │   ├── waypoints-sticky.min.js
│   │   └── waypoints.min.js
│   └── switchstylesheet
│       └── switchstylesheet.js
├── templates
│   └── base.html
└── views
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   └── home.cpython-35.pyc
    └── home.py

This is one of empty image html element showing up in Chrome development tool:

And corresponding template source code :

(There is {% load staticfiles %} on the  top of template)
This is urls.py:
from django.conf.urls import url, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from views.home import Home
# import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', Home.as_view(), name='home'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is log when runserver : python manage.py runserver:
(chacha_dabang) Chois@Chois-MacPro chacha_dabang $python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

August 02, 2016 - 10:47:40
Django version 1.9.8, using settings 'chacha_dabang.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[02/Aug/2016 10:47:44] "GET / HTTP/1.1" 200 48896
[02/Aug/2016 10:47:44] "GET /static/css/bootstrap.min.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/css/main.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/css/owl.carousel.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/css/green.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/css/animate.min.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/css/owl.transitions.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/fonts/fontello.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/logo.svg HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/art/product01.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/art/product02.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/art/product03.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/art/slider01.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/art/work01.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:44] "GET /static/images/art/work02.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/work03.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/work04.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/work05.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/work06.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/work07.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/product04.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/product05.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/product06.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/slider02.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/logo-white.svg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/slider03.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/slider04.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/slider05.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/images/art/image-background04.jpg HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/blue.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/red.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/pink.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/purple.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/orange.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/navy.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /static/css/gray.css HTTP/1.1" 304 0
[02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello.woff HTTP/1.1" 200 48896
[02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello-social.woff HTTP/1.1" 200 48896
[02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello.ttf HTTP/1.1" 200 48896
[02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello-social.ttf HTTP/1.1" 200 48896


Q: why so many errors are occuring in building the addon? I am unable to resolve these errors and also can't understand their cause.Can anybody help?I have also refreshed dependencies, it is occuring after that too.
I uninstall and then installed g1ant from manage nutmeg package still I am facing this error.

A: First we need to uninstall G1ANT robot from manage nutmeg package present under Project as it is old version and then go to browse menu and Search G1ANT there and install it and then try to build your addon.
Hope it works!

A: You might have to try 2 3 times . I had to re-install g1ant language package 2 times to stop receiving those errors.
Also you can check reference to verify that whether g1ant language is un-installed and then re-install it.


Q: Stop TableView cell UIImage resizing in iOS I have a standard (i.e. not a custom) TableView cell with text and images, the problem is my images are different sizes and I want to put them in as something like UIViewContentModeScaleAspectFill.  I simply want the UIImage to be 54x54 and not resizes all the time - I just want them square!
There are lots of ideas out there but none of them work, the closest I came worked BUT the image was on top of the text (it added another image as a subview).
I am not keen on using a custom cell as I use edit mode to drag stuff about and I have not figured that out yet with custom cells.
EDIT
I latest I have tried;
UIImage *tempImage = [UIImage imageWithData:data];
CGSize size = CGSizeMake(54, 54);
UIGraphicsBeginImageContext(size);
[tempImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = scaledImage;

I have this in the cellForRow which I hoped would do it;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;

This only works on custom cells;
- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,54,54);
}

This works well but it covers the text;
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)];
imgView.backgroundColor=[UIColor clearColor];
[imgView.layer setCornerRadius:8.0f];
[imgView.layer setMasksToBounds:YES];
[imgView setImage:[UIImage imageWithData: imageData]];
[cell.contentView addSubview:imgView];

This shows the exact problem I am having;
Stackoverflow problem
ANOTHER EDIT
okay this worked, thanks;
[cell setIndentationWidth:54];
[cell setIndentationLevel:1];

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)];
imgView.backgroundColor=[UIColor clearColor];
[imgView.layer setMasksToBounds:YES];
[imgView setImage:myImages[indexPath.row]];
[cell.contentView addSubview:imgView];

A: I recommend you to subclass UITableViewCell and create your own custom cell :D
but, anyway... try by adding this
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

UIImageView *imgView = nil;
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

    imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)];
    imgView.backgroundColor=[UIColor clearColor];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.tag = 123;

    [cell.contentView insertSubview:imgView atIndex:0];
    [cell setIndentationWidth:54];
    [cell setIndentationLevel:1];
}
else
{
    imgView = (UIImageView*)[cell.contentView viewWithTag:123];
}
imgView.image = [UIImage imageNamed:@"myImage"];


Q: How can I send datas from web page to serial port of visitor's computer?
Possible Duplicate:
How can I send data from a web page to a serial port?

Is sending data from PHP web page to one of the serial ports of visitor's computer possible or not?
If it is yes, how?
If it is not, basicly, I want to write a client for a web backend that retrieves the data from the web and then writes the retrieved data to a serial port. Can you help about that?

A: Not over the internet, as that would be very dangerous, the user would have to have special software. Otherwise web programs could (very) easily be used for malicious purposes.


Q: how to add serch function using ajax in magento i want to add search function in which firstly there will be three select box but two of will be disabled when user select some value from or or say example year from drop down then second field is enabled which has car company name relevant to that year and after selecting car company relevant model no opens and then after selecting relevant car model no its parts list will be open and following will be search. so can anyone tell me how to start this. which files i have to add or change for this.


Q: How to trigger a DataStage job once a SQL server job has completed? Currently there is a job in SQL server that is scheduled to runs several times a day.
The SQL Job builds a file for the DataStage job that is scheduled shortly after the SQL server job, problem being that if the SQL job hasn't finished building the file, the DataStage job fails.
Is there a trigger/query that can be added on SQL server to trigger DataStage job?

A: Multiple solutions are possible:

*

*Start the DataStage job from command line (via dsjob) and schedule this job in the same scheduler (as the SQL server job) after that job  (or schedule both in another common scheduler)

*Use a wait for file stage in the DataStage Sequence. This could be configured to wait some time for the file.

*Trigger the execution from a database trigger - I have done it for Db2 but it should be possible for you as well - maybe you have to write some code for that...


Q: Integral and sum function I have that
$$\sum_{n=-\infty}^{\infty}\left(\left(\frac{1}{1+n^2}\right)e^{inx}\right)\text{.}$$
Where $f$ is the sumfunction for the serie.
Then I have to find
$\int_{-\pi}^{\pi}f\,sin(x)\mathrm{d}x$ and $\int_{-\pi}^{\pi}f\,cos(x)\mathrm{d}x$.
I think I can find it without finding the sumfunction. Maybe swap the sum and integral?
I think:
$$\sum_{n=-\infty}^{\infty}\left(\int_{-\pi}^{\pi}\left(\frac{e^{inx}}{1+n^2}cos(x)\right)dx\right)\text{}=\sum_{n=-\infty}^{\infty}\left(-\frac{2nsin(n\pi)}{n^4-1}\right)\text{}=\pi$$
Is that correct? And how can I formally show it? For $\int_{-\pi}^{\pi}f\,sin(x)\mathrm{d}x$ I got a expression with complex (with i). How can I deal with that sum?

A: The interchange of sum and integral is justified by uniform convergence. The series is uniformly convergent by M-test since $|e^{inx}|=1$ and $\sum \frac 1 {1+n^{2}} <\infty$. You have found $\int f(x) \cos x dx$ correctly but there are mistakes in what you have written. You cannot have $n^{4}-1$ in the denominator because $n=1$ is included in the sum.  Try to re-write your calculation.
For  $\int f(x) \sin x dx$ the answer is $i\pi$ and this is surely a complex number.
If $f$ was real valued you would get a real number for the integral but our function $f$ is complex valued so there is no contradiction.


Q: I found a strange number pattern in Base 10. Does anyone know what it means? I was trying to think of a good equation for texture smoothing to be used in programming. I came up with this. With texture smoothing however it must be based on division.
$01$ to $10$ = $9$ or $3^2$
$02$ to $20$ = $18$ or $2\times 3^2$
$03$ to $30$ = $27$ or $3^3$
$04$ to $40$ = $36$ or $4\times 3^2$
$05$ to $50$ = $45$ or $5\times 3^2$
$06$ to $60$ = $54$ or $2\times 3^3$
$07$ to $70$ = $63$ or $7\times 3^2$
$08$ to $80$ = $72$ or $8\times 3^2$
$09$ to $90$ = $81$ or $3^4$
Same with 12 to 21, 13 to 31, 14 to 41, 15 to 51, 16, to 61 and so on
243 is $3^5$
Could it be applied to finding prime numbers if I were to elaborate?

A: So what you have observed is that for $k\in\{1,2,3,4,5,6,7,8,9\}$: $10k-k=k*3^2$? That's pretty obvious.
No, that can't be applied to finding primes.

A: Your first pattern follows from
$$
10n - n = 9n.
$$
The second follows from
$$
(10n + 1) - (10 + n) = 9n - 9 = 9(n-1).
$$


Q: Issue with JQuery Image Bubbles in IE I am trying to implement Jquery Image Bubbles as shown here:
http://www.dynamicdrive.com/dynamicindex4/imagebubbles.htm
However Im receiving a JavaScript error in my Fiddle:
http://jsfiddle.net/NinjaSk8ter/hbMzV/
It was determined that loading the JavaScript file from the dynamicdrive Demo Page into the Fiddle would not function.  Copying the JavaScript directly did function.

A: I was receiving an error that the imgbubbles method does not exist. This means the resource wasn't being loaded into the fiddle. The solution was simple.
Rather than trying to load the file into your page from the dynamicdrive domain, copy it to your project folder and load it from there. In your fiddle, I pulled the actual source for the plugin into the JavaScript panel, which resolved the issue of the missing method.
Demo: http://jsfiddle.net/hbMzV/13/ (Tested in IE 7 to 10)

A: JSLint says to throw in some semi-colons, like so:
jQuery(document).ready(function($){
 $('ul#orbs').imgbubbles({factor:3.15, speed:1500});
});

Looks like it works even without them though.


Q: Pixel-wise like assignment In Matlab Is there any good way to assignment some masked pixels with the same color except for-loop?
%% pick a color
cl = uisetcolor; %1-by-3 vector

im = ones(3, 3, 3)  / 2; % gray image

mask = rand(3, 3);
mask_idx = mask > 0.5; % create a mask

%% Something like this
im(mask_idx, :) = cl'; % assignment the pixels to color `cl`

A: You could do it like this making use of repmat():
%% pick a color
cl = uisetcolor; %1-by-3 vector
im = ones(3, 3, 3)/2; % gray image
mask = rand(3, 3);
mask_idx = mask > 0.5; % create a mask

cl_rep = repmat(cl,[sum(mask_idx(:)) 1]);
im(repmat(mask_idx,[1 1 3])) = cl_rep(:);

What I have done is to repeat the mask three times to get all three layers of the image. To be able to match this with the colour-vector cl it also has to be repeated. The number of times it is repeated is the same as the amount of pixels that are to be changed, sum(mask_idx(:)).


Q: Filtering out the outdated items from table my application is built using ruby on rails, backed by mysql DB
It has 2 tables(models) - product(id, name, created_at, updated_at, etc.) and product_details(id, product_type, product_id, expires_on, created_at, updated_at, etc.) (connected by product ID column).
I need to select only those active records OR product_ids from product model/table which satisfy either of the following criteria - the product details for that particular product are out-dated/expired(expires_on column is present in product_details table) or there is no entry for that product in product_details table at all(valid scenario in my use case)
Please note that product_id is a foreign key which references product(id)
Any help is greatly appreciated. Thanks in advance! :)

A: Assuming that:
class Product < ApplicationRecord
  has_one :product_detail
end

and
class ProductDetail < ApplicationRecord
  belongs_to :product
end

You can use simple single-line query to fetch expired products or products without details:
Product.select { |p| p.product_detail.nil? || p.product_detail.expires_on <= Date.today }


Q: Assign name to other rows upon group condition I have a dataset which is of following nature. I would like to replace the names in "MAKE" column if the column contains "PQR" per unique country.
   country     MAKE
1      USA      PQR
2      USA      ABC
3       UK      PQR
4       UK      DEF
5      JPN      DEF
6      JPN      LMN

Desired Output:
   country    MAKE
1      USA    PQR
2      USA    PQR
3       UK    PQR
4       UK    PQR
5      JPN    OTHERS
5      JPN    OTHERS

A: One option is conditional aggregation with analytic functions:
SELECT
    country,
    CASE WHEN SUM(CASE WHEN MAKE = 'PQR' THEN 1 ELSE 0 END) OVER (PARTITION BY country) > 0
         THEN 'PQR' ELSE 'OTHERS' END AS MAKE
FROM yourTable
ORDER BY
    country;

Demo


Q: QtWebView VS D3.js So, I have this school project I'm doing and I needed a visualization tool for the results of some of the processing being done by the software I'm developing.
Since I'm using Qt for the software, I thought of using D3.js on top of a QtWebView widget.
I'm currently testing with the Qt "Fancy browser" example a simple example of D3.js. I know that when I add Javascript in the index.html file, it works on the Fancy browser. For some reason, the Javascript used in the D3 script doesn't.
The thing is, I'm fairly new to both Qt and D3.js, and as such I don't know if I'm missing something regarding the setup to make it possible, or if it's just incorrect code.
Some doubts I had regarding this situation:
 - does QtWebView even support SVG elements in the HTML file?
 - I noticed that jQuery.js had to be added to the Fancy browser projects' resources in order for it to be evaluated by the application. As far as I could tell, this was done to enable the manipulation of the page's content using jQuery. Could it be that I have to do something similar with D3? If so, how?
 - It's very likely that nothing shows up because the instructions I'm giving to D3 aren't actually producing anything in the HTML file, how can I address that?
I tried searching for information online about what I'm trying to achieve, but there aren't that many sources around. I found some stuff online regarding QtWebkit and Javascript, but unfortunately it's not helping me that much.
One final note: in the machine I'm working on I can't access the web because it does not have outside access for everything. Furthermore, I can't even install a Webkit browser (like Chrome or something) for DOM inspection purposes, so it's not getting any simpler. :S
Any help would be much appreciated, thank you all!

A: So, by investigating about this question I got the following conclusions:

*

*QtWebView DOES support SVG elements in the HTML. I figure that this is true at least since Qt V4.7, since it is the one I'm presently using;

*Still don't know why d3.min.js works and the "regular" d3.js doesn't;

*D3.js doesn't have to be added to Qt's resources, calling it in the HTML file is enough.

Hope this helps anyone finding the topic.


Q: How can I analyze an encrypted HDD? I have a HDD which I encrypted few years ago but I can't remember the tool I used. How can I find out if I have used TrueCrypt or VeraCrypt to encrypt my hard drive?
Thanks.

A: Neither VeraCrypt nor TrueCrypt have a header or signature that would allow you to detect which encryption was used. So you just have to determine if that particular tool can successfully decrypt your data by trying.

A: This all depends on how exactly you created the encrypted data. When you use 'full disk encryption' you are really using volume encryption. The disk structures are still in place (master boot record, volume boot record, and sometimes the file system). The data inside the volume is where the encryption is applied.
If you used TrueCrypt or any of its variants, you had an option to create an encryption container. This option creates a file, similar to a zip file, on an already established file system. That file system can also be encrypted.
If you plug the disk in and you see folders with a big file, then you likely used a container. If instead you get a message of an unrecognized volume and possibly a prompt to format the disk, then you might have used volume based encryption (full disk encryption).


Q: How to create "upload image " to registration form? I'm creating a website on wordpress. I wanted to add "upload image" part and after people registered, I'll check the image and if it's true image, I'll accept the registration. Like spotify. Spotify wants student certificate to be sure and if it’s right, after that, they allow to use spotify on student price.
I know there are plugins but they aren't free. So, how can I do that for free? I searched for code or method but couldn't fide any source.

A: Replace existing function
   function um_get_avatar_uri( $image, $attrs ) {
    $uri = false;
    $uri_common = false;
    $find = false;
    $ext = '.' . pathinfo( $image, PATHINFO_EXTENSION );
    $custom_profile_photo = get_user_meta(um_user( 'ID' ), 'profile_photo', 'true');

    if ( is_multisite() ) {
        //multisite fix for old customers
        $multisite_fix_dir = UM()->uploader()->get_upload_base_dir();
        $multisite_fix_url = UM()->uploader()->get_upload_base_url();
        $multisite_fix_dir = str_replace( DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . get_current_blog_id() . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $multisite_fix_dir );
        $multisite_fix_url = str_replace( '/sites/' . get_current_blog_id() . '/', '/', $multisite_fix_url );

        if ( $attrs == 'original' && file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) {
            $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo{$ext}";
        } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}x{$attrs}{$ext}" ) ) {
            $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$attrs}x{$attrs}{$ext}";
        } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}{$ext}" ) ) {
            $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$attrs}{$ext}";
        } else {
            $sizes = UM()->options()->get( 'photo_thumb_sizes' );
            if ( is_array( $sizes ) ) {
                $find = um_closest_num( $sizes, $attrs );
            }

            if ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}x{$find}{$ext}" ) ) {
                $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$find}x{$find}{$ext}";
            } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}{$ext}" ) ) {
                $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$find}{$ext}";
            } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) {
                $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo{$ext}";
            }
        }
    }

    if ( $attrs == 'original' && file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) {
        $uri = UM()->uploader()->get_upload_base_dir()  . um_user( 'ID' ) . "/profile_photo{$ext}";
    } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . $custom_profile_photo ) ) {
        $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . $custom_profile_photo;
    } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}x{$attrs}{$ext}" ) ) {
        $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$attrs}x{$attrs}{$ext}";
    } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}{$ext}" ) ) {
        $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$attrs}{$ext}";
    } else {
        $sizes = UM()->options()->get( 'photo_thumb_sizes' );
        if ( is_array( $sizes ) ) {
            $find = um_closest_num( $sizes, $attrs );
        }

        if ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}x{$find}{$ext}" ) ) {
            $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$find}x{$find}{$ext}";
        } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}{$ext}" ) ) {
            $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$find}{$ext}";
        } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) {
            $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo{$ext}";
        }
    }

    if ( ! empty( $uri_common ) && empty( $uri ) ) {
        $uri = $uri_common;
    }

    $cache_time = apply_filters( 'um_filter_avatar_cache_time', current_time( 'timestamp' ), um_user( 'ID' ) );
    if ( ! empty( $cache_time ) ) {
        $uri .= "?{$cache_time}";
    }

    return $uri;
}


Q: Intelijj среда не видит модулей в Yarn Workspaces После переноса проекта на монорепу некоторые модули просто отказываются полноценно работать. Среда разработки не видит их (даже не смотря на то, что в node_modules корневой папки они есть).

Пока что нашел эту проблему с redux и react-router-dom. С чем может быть связано и как это исправить?


Q: PHP - Regex : I need help to build regex according these rules I need help building a regular expression for preg_match according these rules:

*

*first and last char- letter/digit only.

*empty space not allowed

*char can be  only - letter/digit/'-'/'_'/'.'

Legal examples:

*

*b.t612_rt

*rut-be

*rut7565

Not legal example:

*

*.btr78; btr78-    (first/last allowed chars)

*start end; star  t     end;                (any empty space)

*tr$be; tr*rt; tr/tr ...  (not allowed chars)

Edit: I remove 4 rule with neigbor chars '_'\'-'\'.'
please help me.
Thanks

A: Try this regular expression:
^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$

This matches any sequence that starts with at least one letter or digit (^[A-Za-z0-9]+) that may be followed by zero or more sequences of one of -, _, or . ([-_.]) that must be followed by at least one letter or digit ([A-Za-z0-9]+).

A: Try this:
^[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]$

In PHP:
if (preg_match(
    '%^               # start of string
    [\p{L}\p{N}]      # letter or digit
    [\p{L}\p{N}_.-]*  # any number of letters/digits/-_.
    [\p{L}\p{N}]      # letter or digit
    $                 # end of the string.
    %xu',
    $subject)) {
    # Successful match
} else {
    # Match attempt failed
}

Minimum string length: Two characters.

A: Well, for each of your rules:

*

*First and last letter/digit:
^[a-z0-9]

and
[a-z0-9]$

*empty space not allowed (nothing is needed, since we're doing a positive match and don't allow any whitespace anywhere):

*Only letters/digits/-/_/.
[a-z0-9_.-]*

*No neighboring symbols:
(?!.*[_.-][_.-])

So, all together:
/^[a-z0-9](?!.*[_.-][_.-])[a-z0-9_.-]*[a-z0-9]$/i

But with all regexes, there are multiple solutions, so try it out...
Edit: for your edit:
/^[a-z0-9][a-z0-9_.-]*[a-z0-9]$/i

You just remove the section for the rule you want to change/remote.  it's that easy...

A: This seems to work fine for provided examples: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';


Q: json_encode will not encode more than 6670 rows Someone else had this issue back in '07, but it was not answered:  in PHP, json_encode($someArray) silently fails (returns null) if the array has more than 6,670 rows.  Does someone have a workaround.  Limiting the size of the array to 6600, for example produces the expected result.  I can do some do multiple json calls with partial arrays and concatenate results, but that involves some funky string manipulation to get them to stitch together properly, and I would like to avoid that.

A: You could always just first slice the array into 2 parts (assuming it's not bigger then 2 times those rows). After that encode it, and add them together again. In case that isn't a solution, you need to increase your memory limit.
Here is an example, test it here. On @GeertvanDijk suggestion, I made this a flexible function, in order to increase functionality!
<?php
  $bigarray = array(1,2,3,4,5,6,7,8,9);

function json_encode_big($bigarray,$split_over = 6670){
  $parts = ceil((count($bigarray) / $split_over));

  $start = 0;
  $end = $split_over;

  $jsoneconded = [];

  for($part = 0; $part < $parts; $part++){
    $half1 = array_slice($bigarray,$start,$end);
    $name = "json".$part;
    $$name = ltrim(rtrim(json_encode($half1),"]"),"[");
    $jsoneconded[] = $$name;
    $start += $split_over;
  }

  return "[".implode($jsoneconded,",")."]";
}

print_r(json_encode_big($bigarray));
?>

I have now test this with more rows then 6,670. You can test it online here as well.
Now, I have to mention that I tested the normal json_encode() with a million rows, no problem. Yet, I still hope this solves your problem...

In case that you run out of memory, you can set the memory_limit to a higher value. I would advice against this, instead I would retrieve the data in parts, and procces those in parts. As I don't know how you retrieve this data, I can't give an example how to regulate that.  Here is how you change the memory in case you need to (sometimes it is the only option, and still "good").

ini_set("memory_limit","256M");

In this case, it is the dubbel from the default, you can see that it is 128M in this documentation

A: Possibly depends on your PHP version and the memory allowed for use by PHP (and possibly the actual size of all the data in the array, too).
What you could do if all else fails, is this:
Write a function that checks the size of a given array, then split off a smaller part that will encode, then keep doing this until all parts are encoded, then join them again. If this is the route you end up taking, post a comment on this answer, and perhaps I can help you out with it. (This is based on the answer by Nytrix)
EDIT, example below:
function encodeArray($array, $threshold = 6670) {
    $json = array();
    while (count($array) > 0) {
        $partial_array = array_slice($array, 0, $threshold);
        $json[] = ltrim(rtrim(json_encode($partial_array), "]"), "[");
        $array = array_slice($array, $threshold);
    }

    $json = '[' . implode(',', $json) . ']';
    return $json;
}


Q: How can we show that $\mathcal F_\tau\cap\left\{\tau=t\right\}=\mathcal F_t$? for any $\mathcal F$-stopping time $\tau$? Let

*

*$(\Omega,\mathcal A)$ be a measurable space

*$I\subseteq\mathbb R$

*$(\mathcal F_t)_{t\in I}$ be a filtration of $\mathcal A$

If $\tau$ is an $\mathcal F$-stopping time, then $$\mathcal F_\tau:=\left\{A\in\mathcal A:A\cap\left\{\tau\le t\right\}\in\mathcal F_t\text{ for all }t\in I\right\}\;.$$ If $A\subseteq\Omega$ and $\mathcal G$ is a $\sigma$-algebra on $\Omega$, then $$\left.\mathcal G\right|_A:=\left\{A\cap B:B\in\mathcal G\right\}\;.$$

It's easy to show that $$\left.\mathcal F_\sigma\right|_{\left\{\:\sigma\:\le\:\tau\:\right\}}\subseteq\mathcal F_{\sigma\:\wedge\:\tau}=\mathcal F_\sigma\cap\mathcal F_\tau\tag1$$ for any $\mathcal F$-stopping times $\sigma,\tau$. Now, let $\tau$ be an $\mathcal F$-stopping time and $t\in I$. I want to show that $$\left.\mathcal F_\tau\right|_{\left\{\:\tau\:=\:t\:\right\}}=\mathcal F_t\tag2\;.$$

If $\tau\equiv t$, then it's easy to observe that $$\mathcal F_\tau=\mathcal F_t\;.\tag3$$

How can we conclude $(2)$ from $(1)$ and $(3)$?

A: This is not true because $\{\tau\ne t\}\notin\mathcal{F}_{\tau}\mid_{\{\tau=t\}}$ but $\{\tau\ne t\}\in \mathcal{F}_t$. You may show instead that
$$
\mathcal{F}_{\tau}\mid_{\{\tau=t\}}=\mathcal{F}_t\mid_{\{\tau=t\}} .^1
$$

$^1$ For any $(\mathcal{F}_t)$-stopping times $\tau$ and $\sigma$, $\mathcal{F}_{\sigma}\mid_{\{\sigma=\tau\}}=\mathcal{F}_{\tau}\mid_{\{\tau=\sigma\}}$ (if $A\in\mathcal{F}_{\sigma}\cap \{\sigma=\tau\}$, then for each $t\in I$, $A\cap\{\sigma\le t\}=A\cap\{\tau\le t\}\in \mathcal{F}_t$. Thus $A\in \mathcal{F}_{\tau}$). Now take $\sigma\equiv t$.


Q: Trigger event only on specific div when mouse is over I have six list items and I want to animate the single item only on mouse over.
This is my snippet:

Eye

link

Eye

link

  // other same list items

What I trying to do is to remove the "top_out" class when mouse in over the list item.
I tried this:
$("ul li").hover(function(){
    $(".overview").toggleClass("top_out");
});

but what I obtained is that all divs react together.
How can I do this?
Here an example of what to obtain (section Portfolio): Esample site
I want the same icon animation effect
Thanks

A: try:
$('ul li').on('mouseenter mouseleave', function() {
        $(this).find('.overview').toggleClass('top_out');
});

A: You have to use the hovered over li as the context:
$("ul li").hover(function(){
    $(".overview", this).toggleClass("top_out");
});

Rather than .hover(function() ... you may want to use:
.on('mouseenter mouseleave', function() ...

$("ul li").on('mouseenter mouseleave', function(){
    $(".overview", this).toggleClass("top_out");
});
.top_out {
  background-color: black;
  color: white;
  }

Eye

link

Eye

link

A: It seems like you need to toggle the class based on the context of the element you are hovering over.
Use the jQuery selector $(".overview", this) to select .overview elements within the li element that is currently being moused over.
I also change the hover event to mouseover/mouseout.
$("ul li").on('mouseover mouseout', function () {
    $(".overview", this).toggleClass("top_out");
});

Which is essentially equivalent to
$("ul li").on('mouseover mouseout', function () {
    $(this).find(".overview").toggleClass("top_out");
});


Q: Silex security configuration I'm struggling with silex security:
I have the following:
$app->register(new Silex\Provider\SecurityServiceProvider());

and later on :
$app['security.firewalls'] = array(
    'admin' => array(
        'pattern' => '^/admin',
        'http' => true,
        'users' => array(
            // raw password is foo
            'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
        ),
    ),
);

but when i hit path "localhost/admin" Im getting:
Found error: No route found for "GET /admin"

cant understand the docs on page of silex rly.. Should I register security filters with controllers?
Idefined as follows function in controller:
public function admin(){
        return 'Hello';
    }

and route for this is:
$app->get('/admin', 'app.vendor_controller:admin');

now Im getting:
Hello

as soon as i hit path /admin , without authentication form. So there is no authentication proccess included...
EDIT~~~~~~~~~~~~~~~~~~~~~
OK, so now after hitting url/admin I'm getting authentication banner with fields to put, as user and password, I'm typing admin , foo but there is no effect on this.
`A username and password are being requested by http://localhost:8080. The site says: “Secured”`

the code looks as follows:
$app['security.firewalls'] = array(
    'admin' => array(
        'pattern' => '/admin',
        'http' => true,
        'users' => array(
            'admin' => array('ROLE_ADMIN', 'foo')
        )));
$app['security.access_rules'] = array(
    array('/admin', 'ROLE_ADMIN'),
);

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
    'pattern' => '/admin',
    'http' => true,
    'users' => array(
        // raw password is foo
        'admin' => array('ROLE_ADMIN', 'foo'),
    ))));

A: You configured a firewall that match every /admin* urls, but that don't mean that every URL requires authentication. You can be an anonymous user, and that would be fine. If you want tell silex that "the user need the ROLE_ADMIN to be allowed here", you need to add
$app['security.access_rules'] = array(
    array('^/admin', 'ROLE_ADMIN'),
);


Q: Excel Macro - hide comment after edit I have this for entering a comment on a excel worksheet when user insert C or P, and I need to hide the comment after edit.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    Set KeyCells = Range("A1:S1000")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

            Select Case Range(Target.Address)
                Case "C":
                    minhaCelula = Target.Address
                    Range(minhaCelula).AddComment ("")
                    Range(minhaCelula).Comment.Visible = True
                Case "P":
                    minhaCelula = Target.Address
                    Range(minhaCelula).AddComment ("")
                    Range(minhaCelula).Comment.Visible = True

            End Select

    End If
End Sub

A: Some problems with that code:

*

*Select Case Range(Target.Address) doesn't make sense - it takes the Target range, takes its address and creates a range from that address, which points to the original Target range, and finally VB takes the default property of that range, because its not being used in an object reference context. So the whole thing should be replaced with Target.Value.

*Later same thing happens to minhaCelula.

*Code under "C" and "P" is the same and should be placed under the same Case branch.

*Colons are not used in VB's Select Case.

*AddComment should be called without parentheses. Even better, you should benefit from the fact AddComment returns the reference to the added comment, so you can directly use that (in which case you must keep the parentheses).

So that should be rewriteen as:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then
        Select Case Target.Value
            Case "C", "P"
                Target.AddComment("").Visible = True
        End Select
    End If
End Sub

As for the question, when you use Comment.Visible, Excel stops managing the comment's visibility. To leave the management on Excel side, make the comment's shape visible instead:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then
        Select Case Target.Value
            Case "C", "P"
                With Target.AddComment("").Shape
                    .Visible = msoTrue
                    .Select
                End With
        End Select
    End If
End Sub


Q: universal motor wiring help needed I have a NOS universal ac/dc motor and don't know how to wire it. The motor has 4 unmarked leads. Two black, one red and one white. The motor label is marked VOLTS 115, CYCLES 60, AMPS. 1.0, SER. 12V39607, 900 rpm, thermally protected. Can someone provide the proper the wiring info?
Thanks,
Henry Rancourt


Q: Display one piece of a multidimensional array while entering another from a form? I need to be able to enter a String value, and have it input the id to that row on a table.
I'm trying to get something like a select tag in HTML to work in Ruby. However I need it to programmatically change when new rows are added to the table I'm pulling the values from.
The table itself looks something like this:
Locations
 id    location_cd
| 1  |         SLC|
| 2  |         LAS|

etc.
I used the Location class to pass these values from this table into an array. Here is the Location class.
class Location < ActiveRecord::Base

    def self.select_options
        self.all.sorted.collect{ |q| [q.id, q.location_cd]}
    end

end

Doing this gives me this multidimensional array when I call the select_options method.
[[1, "SLC"], [2, "LAS"]]

Here's what I have in the controller.
def edit
    @pallet = Pallet.find(params[:id])
    @locations = Location.all
  end

  def update
    @pallet = Pallet.find(params[:id])
    if @pallet.update_attributes(pallet_params)
      flash[:notice] = "Pallet Updated Successfully."
      redirect_to(:action => 'show', :id => @pallet.id)
    else
      @pallet_count = Pallet.count
      render('edit')
    end
  end

Pallet is the main class I'm pulling from, and I need to enter the location.id into the pallets table.
Here's what I have in edit.
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>

Update Pallet

    <%= form_for(:pallet, :url => {:action => 'update', :id => @pallet.id}) do |f| %>

        <%= render(:partial => "form", :locals => {:f => f}) %>

            <%= submit_tag("Update Pallet") %>

    <% end %>

This will redirect it to the form, and here's what I have in my form. This is where the problem I'm running into is.

        <%= f.label(:destination) %>

        <%= f.select(:destination, Location.select_options) %>

Doing this will give me a list of the ids like this.
1
2

However I want a list of the location_cds like this.
SLC
LAS

But I need it to be to the point where I can enter SLC, and in the database it would enter 1 instead.
To put this into the perspective of the multidimensional array I need to be able to enter the second value of [[1, "SLC"]] on the user side, and the first value(1) should be entered into the table.

A: I did a lot of digging and I was able to find something that worked.
There is a helper that comes with rails called options_for_select(). What this does is it will take something like this
<%= select_tag(:destination, '<option value="1">SLC</option>...') %>

And it will auto-generate the options using a multidimensional array
Since I already had a multidimensional array by using the select_options method, I was able to use them both in conjunction with each other like so:
<%= select_tag(:destination, options_for_select(Location.select_options)) %>

This pulls up exactly what I needed, and appends the correct value to the database when selected.
Another method is without the options_for_select helper, but it would need to have a parameter for which row is selected available.
@pallet = Pallet.find(2)

<%= select(:pallet, :destination, Location.select_options) %>

The advantage of this one is that it automatically defaults to what was already there. This makes it easier for when you update something that isn't the location.


Q: Adding API key auth to existing API If we have a .NET API currently validating users through B2C flows on azure where the API validates the token from the FE with B2C.
How could we implement functionality for daemons to consume the API as well if there is no user interaction to get a key from b2c?
I believe this is called client credentials flow, but I know this does not exist on b2c?
Any ideas on how we could achieve this?

A: This workaround may work for your case.
"Although the OAuth 2.0 client credentials grant flow is not currently directly supported by the Azure AD B2C authentication service, you can set up client credential flow using Azure AD and the Microsoft identity platform /token endpoint for an application in your Azure AD B2C tenant. An Azure AD B2C tenant shares some functionality with Azure AD enterprise tenants.
To set up client credential flow, see Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow. A successful authentication results in the receipt of a token formatted so that it can be used by Azure AD as described in Azure AD token reference".


Q: dojo datagrid event attach issue I am working with IBM Content Navigator 2.0.3, that uses DOJO 1.8 for the GUI development. I am new in dojo, and I have to enhance one of the forms: add an event handler to the dataGrid so when the row of the grid is selected one of the buttons become enabled.
dataGrid described in HTML as follows:

And the JS file that controls the form behavior mentioned this _selectedDataGrid only once, in the postCreate function:
postCreate: function() {
    this.inherited(arguments);
    this.textDir = has("text-direction");
    this.hoverHelpList = [];
    domClass.add(this._selectedDataGridContainer, "hasSorting");
    this._renderSelectedGrid();

_renderSelectedGrid() is being executed, which contains the only mention:
_renderSelectedGrid: function() {
    .......
    this._selectedDataGrid.appendChild(this._selectedGrid.domNode);

I've tried to add an data-dojo-attach-event onRowClick: enableRemoveUsersButton in the HTML and a
enableRemoveUsersButton: function(evt){
    this.removeUsersButton.set('disabled', true);
},

in js file. Didn't help.
Then I tried:
dojo.connect(myGrid, "onRowclick", function update() {
    this.removeUsersButton.set('disabled', true); });

but I couldn't acquire myGrid object using:
`var myGrid  = dojo.byId("_selectedDataGrid");`

Can anyone tell me how to acquire the grid object and/or add an event handler to this grid, that fires when the row of the grid is selected?
Thank you!

A: You won't be able to get the grid object by dojo.byId("_selectedDataGrid"). It is better to keep the myGrid object at class level (widget level) and connect using dojo.hitch.
dojo.connect(this.myGrid, 'onRowClick', dojo.hitch(this, function(){
        //access myGrid using this.myGrid and do the handling
}));

A: From what you have share, I can see that the node "_selectedDataGrid" is just a Div tag. and your dataGrid widget may be "this._selectedGrid" so you should be add the event on that widget not the container node.
Also there is dijit.byId to get the instance of dijits/widgets. and dojo.byId is used to search of dom nodes.
Hope this was helpful.


Q: Android remove window background when it's not shown? I was watching Romain Guy's video(23:27) about how to make android's UI fast and efficient and I discovered that the window background is always redrawn, even if it can't be seen. However, as it's an old video, I'd like to know if this problem has been addressed or not? Is it a good practice to always set a nobackground theme to activities that don't need it?


Q: Aggregate series from DataFrame based on specific conditions I have the following data structure:
       sls   srx    stx  hostname    m                          @timestamp
0        1  21.1  389.2         A  dev 2021-03-05 05:00:00.112965476+00:00
1        0  0.0   352.4         A  dev 2021-03-05 05:00:00.263778044+00:00
2        0  0.0   351.5         A  dev 2021-03-05 05:00:00.463778044+00:00
3        0  0.0   333.6         A  dev 2021-03-05 05:00:00.663778044+00:00
4        1  13.8  379.1         A  dev 2021-03-05 05:00:00.811431112+00:00
5        1  14.6  369.2         A  dev 2021-03-05 05:00:01.011431112+00:00
6        1  15.4  359.3         A  dev 2021-03-05 05:00:01.211431112+00:00
7        0  0.0   371.5         A  dev 2021-03-05 05:00:01.459895995+00:00
8        1  64.1  353.8         A  dev 2021-03-05 05:00:01.608929154+00:00

And I'm trying to compute a dataframe or series that looks like this:
                                  start                                   end                duration
0   2021-03-05 05:00:00.263778044+00:00 2021-03-05 05:00:00.811431112+00:00 0 days 00:00:00.547653068
1   2021-03-05 05:00:01.459895995+00:00 2021-03-05 05:00:01.608929154+00:00 0 days 00:00:00.149033159

So that I can compute the following things:

*

*Count of 0 to 1 transitions (including 0, 0, 0, 0, 1 sequences) - e.g. 2 for the above data

*Total duration of these 0 to 1 transitions - e.g. 0.696686227 for the above data

So the query is looking for the first row where sls is 0, then for the first row that is 1 after that. And it needs to do this for every occurrence of 0 (excluding those that are between a 0 and a 1).
My naive impl. using pandas is:
# @timestamp is a ISO8601 datetime string
df['@timestamp'] = pd.to_datetime(df['@timestamp'])

df['status_change'] = df['sls'].ne(df['sls'].shift())
df = df.drop(df.index[0])

start = df.loc[(df['sls'] == 0) & (
    df['status_change'] == True)].reset_index()
end = df.loc[(df['sls'] == 1) & (
    df['status_change'] == True)].reset_index()

series = pd.DataFrame()
series['start'] = start['@timestamp']
series['end'] = end['@timestamp']
series['duration'] = series['end'] - series['start']

But I feel like there must be an easier way of doing this that would also result in better performance (currently, for 4M documents, it takes about 0:01:06.819145 which is not great).
I'm just not sure how else to query the data in the way I described it so that performance is at least 2x better.

A: perhaps you're lookig for groupby?
df.groupby(by=["sls"]).sum()
group by docs:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html


Q: Mongodb: use $sample after $group I have the following data set:
{company:"One",  employee:"John"},
{company:"One",  employee:"Mike"},
{company:"One",  employee:"Donald"},
{company:"One",  employee:"Mickey"},
{company:"Two",  employee:"Johnny"},
{company:"Two",  employee:"David"},

Ideally, I want a query that returns all distinct companies, number of employees for each company, random employee for each company
{Company: "One" , employee_count=4, randomemployee="Donald"},
{Company: "Two" , employee_count=2, randomemployee="David"},

I do find a way to get company and employee_count using aggregate/group
However I don't find a way to add the randomemployee with the same query.
My aggregation:
function aggr (collection,cb){
   collection.aggregate(([{$group:{_id:'$company',total:{$sum:1}}},{$sort:{total:-1}}]),function(err, l1){
   cb(null, l1)
})
}

I began an other Sample function:
function onesample (collection,arg,cb){
    collection.aggregate(([{ $match: { "company": arg }},{ $sample: { size: 1 }}]),function(err, item){
   cb(null, item[0].employee)
})
}

But i'm loosing myself with callbacks and loop.
Any elegant way to do this within one query?
Thanks a lot.
following your answer, I tried the following code.
I have an issue with the callback of async.foreachof, seems it doesn't finish before leaving to next step: any clue?
var async = require("async");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/eyc0';

async.waterfall ([
     function(cb) {
            MongoClient.connect(url, function(err, db) {
            cb(null,db)
             })
    },
     function (db, cb) {
             db.collection('kodes', function(err, coll) {
            cb(null,db,coll)
             })
    },
      function (db,coll, cb) {
                 var pipeline = [
                {"$group": {"_id": "$ouat","total": { "$sum": 1}}},
                {"$sort":{"total":-1} },
                {"$project":{"_id": 0,"total":1,"company": "$_id"}}];

                coll.aggregate(pipeline).toArray(function(err, dlist){
                cb(null,db,coll,dlist)
                })
    },
        function (db,coll,dlist, cb) {
            // console.log(dlist)
            cb(null,db,coll,dlist)
    },
          function (db,coll,dlist, cb) {
             var dlist2 = []
                async.forEachOf(
                    dlist,
                    function(item, key, cb){
                        var pipeline = [{ "$match": { "ouat": item.company } },{ "$sample": { size: 1 } }];
                        coll.aggregate(pipeline, function (err, data) {
                        item["randref"] = data[0].code;
                        console.log(item.company)
                        dlist2.push(item)
                        cb()
                    });

                    }
                );
                 cb(null,db,coll,dlist,dlist2);

    },
        function (db,coll,dlist,dlist2, cb) {
            console.log(dlist2)
            console.log(dlist)
    },
    ])

A: There's one approach that involves one query, it could be close but not as performant (as it uses $unwind) and won't give you the desired result (only the filtered company):
var pipeline = [
    {
        "$group": {
            "_id": "$company",
            "total": { "$sum": 1 },
            "employees": { "$push": "$employee" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "company": "$_id",
            "employee_count": "$total"
            "randomemployee": "$employees"
        }
    },
    { "$unwind": "$randomemployee" },
    { "$match": { "company": arg } },
    { "$sample": { size: 1 } }
];
collection.aggregate(pipeline, function(err, result){
    console.log(result);
});

However, for a solution that uses callbacks from multiple queries, this can be handled easily with use of async module.
To get all distinct companies, number of employees for each company, random employee for each company consider using the async.waterfall() function where the first task returns the aggregation results with all distinct companies and number of employees for each company.
The second task uses the results from taks 1 above to iterate over using async.forEachOf(). This allows you to perform an asynchronous task for each item, and when they're all done do something else. With each document from the array, run the aggregation operation that uses the $sample operator to get a random document with the specified company. With each result, create an extra field with the random employee and push that to an array with the final results that you can access at the end of each task.
Below shows this approach:
var async = require("async");
async.waterfall([

        // Load full aggregation results (won't be called before task 1's "task callback" has been called)
        function(callback) {
            var pipeline = [
                {
                    "$group": {
                        "_id": "$company",
                        "total": { "$sum": 1 }
                    }
                },
                {
                    "$project": {
                        "_id": 0,
                        "company": "$_id",
                        "employee_count": "total"
                    }
                }
            ];
            collection.aggregate(pipeline, function(err, results){
                if (err) return callback(err);
                callback(results);
            });
        },

        // Load random employee for each of the aggregated results in task 1
        function(results, callback) {
            var docs = []
            async.forEachOf(
                results,
                function(value, key, callback) {
                    var pipeline = [
                        { "$match": { "company": value.company } },
                        { "$sample": { size: 1 } }
                    ];
                    collection.aggregate(pipeline, function (err, data) {
                        if (err) return callback(err);
                        value["randomemployee"] = data[0].employee;
                        docs.push(value);
                        callback();
                    });
                },
                function(err)
                    callback(null, docs);
                }
            );
        },
    ], function(err, result) {
        if (err) return next(err);
        console.log(JSON.stringify(result, null, 4));
    }
);

With the the async.series() function, this is useful if you need to execute a set of async functions in a certain order.
Consider the following approach if you wish to get the all the distinct companies and their employee count as one result and the other random employee as another:
var async = require("async"),
    locals = {},
    company = "One";
async.series([
        // Load random company
        function(callback) {
            var pipeline = [
                { "$match": { "company": company } },
                { "$sample": { size: 1 } }
            ];
            collection.aggregate(pipeline, function(err, result){
                if (err) return callback(err);
                locals.randomcompany = result[0];
                callback();
            });
        },
        // Load full aggregation results (won't be called before task 1's "task callback" has been called)
        function(callback) {
            var pipeline = [
                {
                    "$group": {
                        "_id": "$company",
                        "total": { "$sum": 1 }
                    }
                },
                {
                    "$project": {
                        "_id": 0,
                        "company": "$_id",
                        "employee_count": "total"
                    }
                }
            ];
            collection.aggregate(pipeline, function(err, result){
                if (err) return callback(err);
                locals.aggregation = result;
                callback();
            });
        }
    ], function(err) { //This function gets called after the two tasks have called their "task callbacks"
        if (err) return next(err);
        //Here locals will be populated with 'randomcompany' and 'aggregation'
        console.log(JSON.stringify(locals, null, 4));
    }
);

A: db.comp.aggregate([
{$group:{_id:'$company',emp:{$addToSet:'$employee'}}},
{$project:{emp:1,employee_count:{'$size':'$emp'},
                 randomvalue:{'$literal':Math.random()}}},
{$project:{emp:1,employee_count:1,
           randomposition:{'$floor':
                    {'$multiply':['$randomvalue', '$employee_count']}}}},
{$project:{'Company':'$_id', _id:0, employee_count:1,
            randomemployee:{'$arrayElemAt':['$emp','$randomposition']}}},
{$sort:{Company:1}} ])

Seems to work!
A couple of results:
{ "employee_count" : 4, "Company" : "One", "randomemployee" : "Mike" }
{ "employee_count" : 2, "Company" : "Two", "randomemployee" : "Johnny" }

{ "employee_count" : 4, "Company" : "One", "randomemployee" : "Mickey" }
{ "employee_count" : 2, "Company" : "Two", "randomemployee" : "David" }


Q: can't enable windows authentication in IIS I've disabled anonymous authentication and I've enabled Windows authentication on my website in IIS 7.
Now, when I browse to the website (http://webserver), Internet Explorer keeps prompting me for a username/password. Since I'm on the intranet, IE should pass on my credentials automatically...
What's more is that if I enter my credentials, they are not even recognized.
I'm out of ideas, if anyone could help....


Q: Plone/Paster - What could cause "paster addcontent dexterity_content" to not work? I'm trying to use paster to create a dexterity content type.
I did a new standalone installation of Plone 4.3.4 in a target folder that's different from the one I was previously working with so it was buildout-cache would be clean.
The OS I am using is Ubuntu 14.04.  So in my downloads folder, in the installer's folder I extracted, I type in the terminal:
./install.sh --target=/home/myusername/Plone2 --instance=MyProject standalone

That installs correctly.  Then I go to MyProject in Plone2.  I edit the buildout to change my password, and the run buildout:
buildout -c develop.cfg

Then I goto the src folder and create a new product with zopeskel:
../bin/zopeskel dexterity project.house

Then I edit my buildout and under eggs I add project.house and under develop, src/project.house.  Then I run buildout again and it builds out correctly.  Then in the project.house folder under sources, I try running paster.
../../bin/paster addcontent dexterity_content

Then I end up with an error:
Traceback (most recent call last):
  File "../../bin/paster", line 264, in <module>
    sys.exit(paste.script.command.run())
  File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 104, in run
    invoke(command, command_name, options, args[1:])
  File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 143, in invoke
    exit_code = runner.run(args)
  File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 238, in run
    result = self.command()
  File "/home/pjdowney/Plone2/buildout-cache/eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/localcommands/__init__.py", line 70, in command
    self._extend_templates(templates, args[0])
  File "/home/pjdowney/Plone2/buildout-cache/eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/localcommands/__init__.py", line 204, in _extend_templates
    tmpl = entry.load()(entry.name)
  File "/home/pjdowney/Plone2/buildout-cache/eggs/setuptools-7.0-py2.7.egg/pkg_resources.py", line 2184, in load
    ['__name__'])
ImportError: No module named dexterity.localcommands.dexterity

I did recently install Plone 4.3.6 in another target folder.  Unfortunately, I never tried using paster because I was creating dexterity content through the web.  Could switching to 4.3.6 have ruined everything?
My earlier target folder works still though.

A: Throwing ""ImportError: No module named dexterity.localcommands.dexterity" + "plone" into a searchengine leads straight to Plone 4.3.4 - ImportError: No module named dexterity.localcommands.dexterity where S. McMahon states it's a bug reported in https://github.com/plone/Installers-UnifiedInstaller/issues/33 and already fixed for Plone-5-installers, but not for Plone-4.
The bug is likely caused of the newest setuptools-version and FWIW, I accidentally found these infos one day in the tweets of "glyph", which look  helpful:

"Public Service Announcement: make @dstufft’s life easier, and do not
  use the `python-pip´ package from Debian or Ubuntu. It’s broken." (1)
"Instead, install pip and virtualenv with get-pip.py, ideally into
  your home directory. (Sadly, https://pip2014.com/  is still
  relevant.)" (2)

I will have a closer look at the salvation-promising-script get-pip.py, when running into probs again, but for now, I simply don't upgrade anything :-D
(1)https://twitter.com/glyph/status/640980540691234816
(2)https://twitter.com/glyph/status/640980540691234816

A: (copied from my own comment on a similar issue in github)

I've had fights like this in the past with zopeskel / paster. Nowadays though I avoid it.... choosing to use:

*

*mrbob for templating eggs

*creating dexterity types through the web see plone training

*OR alternatively creating dexterity types directly in code without templating - there's a lot less boilerplate code in dexterity cf archetypes

I suspect your issue is because your install of 4.3.6 may have upgraded zopeskel or one of it's dependencies to something with different requirements on localcommands/templates.  If you want to continue this fight (and I don't recommend it), then you could try pinning all your zopeskel dependencies to latest versions (though Zopeskel has to be less than 3.0 I believe)


Q: How to create groups of N elements from a PCollection Apache Beam Python I am trying to accomplish something like this:
Batch PCollection in Beam/Dataflow
The answer in the above link is in Java, whereas the language I'm working with is Python. Thus, I require some help getting a similar construction.
Specifically I have this:
 p = beam.Pipeline (options = pipeline_options)
 lines = p | 'File reading' >> ReadFromText (known_args.input)

After this, I need to create another PCollection but with a List of N rows of "lines" since my use case requires a group of rows. I can not operate line by line.
I tried a ParDo Function using variables for count associating with the counter N rows and after groupBy using Map. But these are reset every 1000 records, so it's not the solution I am looking for. I read the example in the link but I do not know how to do something like that in Python.
I tried saving the counters in Datastore, however, the speed difference between Dataflow reading and writing with Datastore is quite significant.
What is the correct way to do this? I don't know how else to approach it.
Regards.

A: Assume the grouping order is not important, you can just group inside a DoFn.
class Group(beam.DoFn):
  def __init__(self, n):
     self._n = n
     self._buffer = []

  def process(self, element):
     self._buffer.append(element)
     if len(self._buffer) == self._n:
        yield list(self._buffer)
        self._buffer = []

  def finish_bundle(self):
     if len(self._buffer) != 0:
        yield list(self._buffer)
        self._buffer = []

lines = p | 'File reading' >> ReadFromText(known_args.input)
          | 'Group' >> beam.ParDo(Group(known_args.N)
          ...


Q: Adobe SiteCatalyst:How to export the groups with list of usernames and report suite i am working on Adobe SiteCatalyst.
i am able to download the groups with column names Group Name,Description,Users and Report Suites.
In above list am getting count of users and report suites.but i need a exact name instead of count how this can be done using Adobe Site Catalyst..
Please help me..

A: I don't know of a built in report that will get you this. If there is a small number of users and you don't need to do it very often then you can do this manually. But it would be a pain.
If you think it is worth investing some time into this because you have a lot of users and/or you need to do this report often then you can use the Enterprise API to automate this report.
You will need to create a user with the Web Services permission. Then using that username and secret (be careful to use the exact format from the Admin tools->Company Settings->Web Services as there is a "loginCompany:username" format and special Shared Secret)
Then you can use the APIs assuming you have some development experience. This is a good starting point. https://developer.omniture.com/en_US/get-started/api-explorer#Permissions.GetGroup  and also look at GetGroups.
Best of luck C.


Q: Fluent Validation C# Unique Id in collection I have an entity that has a nested collection as a property which I will receive from a front-end application.
I just want to make sure that each item in this collection(ICollection ChildClassCollection) has a unique Id within the model I have received.
I am using FluentValidation and would like to add this validation using it too for consistency.
It's something very simple I couldn`t find an elegant way to solve..
An example:
public class ParentClass
{
    public string Name { get; set; }

    public ICollection<ChildClass> ChildClassCollection { get; set; }
}

public class ChildClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

A: Use HashSet. https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.7.2
public class ParentClass
{
    public string Name { get; set; }

    public HashSet<ChildClass> ChildClassCollection { get; set; }
}

public class ChildClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

A: Here is what I ended up with:
PRetty cleand, plus, when it encounters issue, it will exit
           this.RuleFor(or => or.ChildClassCollection)
               .Must(this.IsDistinct)
               .WithMessage("There are more than one entity with the same Id");

        public bool IsDistinct(List<UpdateRoleDTO> elements)
        {
            var encounteredIds = new HashSet<int>();

            foreach (var element in elements)
            {
                if (!encounteredIds.Contains(element.Id))
                {
                   encounteredIds.Add(element.Id);
                }
                else
                {
                    return false;
                }
            }

            return true;
       }

A: Do you want to use only fluentValidator to achieve this without any relationship?
If so, you can custom a validator,then use some logic to confirm whether there is a duplicate value
in database,like this:
public class ChildClassValidator : AbstractValidator<ChildClass>
{
    private readonly MyDbContext _context;
    public ChildClassValidator(MyDbContext context)
    {
        _context = context;
        RuleFor(x => x.Id).NotEmpty().WithMessage("ID is required.").Must(IsUnique).WithMessage("parent have more than one ids");
    }

    private bool IsUnique(int id)
    {
        var model = _context.ParentClasses.GroupBy(x => x.Id)
           .Where(g => g.Count() > 1)
           .Select(y => y.Key)
           .ToList();  //judge whether parentclass has duplicate id
        if (model==null)
            return true;
        else return false;
    }
}

A: I use mine custom helper, based by ansver: Check a property is unique in list in FluentValidation. Because the helper is much more convenient to use than each time to describe the rules. Such a helper can be easily chained with other validators like IsEmpty.
Code:
public static class FluentValidationHelper
{
    public static IRuleBuilder<T, IEnumerable<TSource>> Unique<T, TSource, TResult>(
        this IRuleBuilder<T, IEnumerable<TSource>> ruleBuilder,
        Func<TSource, TResult> selector, string? message = null)
    {
        if (selector == null)
            throw new ArgumentNullException(nameof(selector), "Cannot pass a null selector.");

        ruleBuilder
            .Must(x =>
            {
                var array = x.Select(selector).ToArray();
                return array.Count() == array.Distinct().Count();
            })
            .WithMessage(message ?? "Elements are not unique.");
        return ruleBuilder;
    }
}

Usage:
For example we want to choose unique id
RuleFor(_ => _.ChildClassCollection!)
    .Unique(_ => _.Id);

Or want choose unique id and name
RuleFor(_ => _.ChildClassCollection!)
    .Unique(_ => new { _.Id, _.Name });

Update
I optimization performance using code from answer YoannaKostova
public static class FluentValidationHelper
{

    public static bool IsDistinct<TSource, TResult>(this IEnumerable<TSource> elements, Func<TSource, TResult> selector)
    {
        var hashSet = new HashSet<TResult>();
        foreach (var element in elements.Select(selector))
        {
            if (!hashSet.Contains(element))
                hashSet.Add(element);
            else
                return false;
        }
        return true;
    }

    public static IRuleBuilder<T, IEnumerable<TSource>> Unique<T, TSource, TResult>(
        this IRuleBuilder<T, IEnumerable<TSource>> ruleBuilder,
        Func<TSource, TResult> selector, string? message = null)
    {
        if (selector == null)
            throw new ArgumentNullException(nameof(selector), "Cannot pass a null selector.");

        ruleBuilder
            .Must(x => x.IsDistinct(selector))
            .WithMessage(message ?? "Elements are not unique.");
        return ruleBuilder;
    }
}


Q: Storing information from php script I m working on an html page that contains a form allowing users to enter their informations and upload files. all informations will be inserted in Mysql database.
in Javascript, im using XMLHttpRequest to send the files to the server and "upload.php" to rename (to avoid dupplicated names) and move them in the upload directory.
For better user experience, this will be done before submitting the whole form.
My question is : How can i store the new filenames (defined in upload.php)to use them in the form submission "submit.php"?
the reason for this is that in "submit.php", i insert first the user informations in "user" table and then select the "user_id" (auto increment) that will be inserted with filenames in the "files" table.
Could php sessions be an approach to do this ? is there another way? Thanks for your help
html:
<form action="submit.php" method="post" id="submitform">

<--!user info part1-->

    <input type="file" id="filesList" multiple>

<--!user info part2-->

javascript:
var fd = new FormData()
var xhr = new XMLHttpRequest()
for (var i=0,nb = fichiers.length; i<nb; i++) {
    var fichier = fichiers[i]
    fd.append(fichier.name,fichier)
}
xhr.open('POST', 'upload.php', true)

upload.php :
<?php
foreach($_FILES as $file){
    $filename = date('Y') . date('m') . date('d') . date('H') . date('i') . basename($_FILES[$file]['name']);
    move_uploaded_file( $file['tmp_name'],"../upload_dir/" .$filename);
    }
exit;

A: I would consider using something like md5 for unique filenames.
Nevertheless you can push filenames into some array, and than return those filenames, as a result of post request, and put them back into some input field.
To retrieve the response simply add this lines to your code below open
xhr.onreadystatechange = function {
// If the request completed and status is OK
  if (req.readyState == 4 && req.status == 200) {
    // keep in mind that fileNames here are JSON string
    // as you should call json_encode($arrayOfFilenames)
    // in your php script (upload.php)
    var fileNames = xhr.responseText;
  }
}

If you'd like consider using a simple library for AJAX requests, like axios. It's promise based HTTP client for the browser, really simple to use and saves you some time and effort cause you don't have to memorize all this stuff you and I have just written.
This is one approach, but I think you can use $_SESSION as well, and it's perfectly valid. My guess is you don't have logged in user at this point, so my idea is as follows:

*

*put filenames into the $_SESSION

*use db transactions - as @Marc B suggested - to connect files with
user

*if there were no errors just remove filenames from $_SESSION, if there was some, just redirect the user back to the form (possibly with some info what went wrong), and this way he doesn't have to reupload files, cause you have filenames still in $_SESSION


Q: exponential map of SU(4) Good day,
From my reading, I understand that there are 15 parameters needed to produce an arbitrary element of the SU(4) Lie group. This is because this group contains 15 generators.
My question is: if I select one or two parameters to produce one such element in SU(4), and then multiply it with its transpose, why don't I get the identity matrix?.
Here the example.
Given SU(4) paramterization:
$$U=e^{i\lambda_3\alpha_1}e^{i\lambda_2\alpha_2}e^{i\lambda_3\alpha_3}e^{i\lambda_5\alpha_4}e^{i\lambda_3\alpha_5}e^{i\lambda_{10}\alpha_6}e^{i\lambda_3\alpha_7}e^{i\lambda_2\alpha_8}e^{i\lambda_3\alpha_9}e^{i\lambda_5\alpha_{10}}e^{i\lambda_3\alpha_{11}}e^{i\lambda_2\alpha_{12}}e^{i\lambda_3\alpha_{13}}e^{i\lambda_8\alpha_{14}}e^{i\lambda_{15}\alpha_{15}}$$
My problem is: I want to manipulate the value of parameter $\alpha_2$ with the rest parameter constant by substitute the parameter with 00(make them Identity matrix). Hence, I expand the Exponential with generator $\lambda_2$ given as below,
$$\lambda_2=\begin{pmatrix} 0& -i &
0 & 0 \\ i & 0 & 0 & 0 \\ 0& 0 &
0 & 0 \\ 0 & 0 &
0 & 0
    \end{pmatrix}$$
and I get the expansion :
$$cos\alpha_2\begin{pmatrix} 1& 0 &
0 & 0 \\ 0 & 1 & 0 & 0 \\ 0& 0 &
0 & 0 \\ 0 & 0 &
0 & 0
    \end{pmatrix} + i sin\alpha_2\begin{pmatrix} 0& -i &
0 & 0 \\ i & 0 & 0 & 0 \\ 0& 0 &
0 & 0 \\ 0 & 0 &
0 & 0
    \end{pmatrix}$$
and get the matrix of $e^{i\lambda_2\alpha_2}$
$$\begin{pmatrix} cos\alpha_2& sin\alpha_2 &
0 & 0 \\ -sin\alpha_2 & cos\alpha_2 & 0 & 0 \\ 0& 0 &
0 & 0 \\ 0 & 0 &
0 & 0
    \end{pmatrix}$$
When I make $UU^{\dagger}$, it suppose to get identity matrix. But I cant get it. Why? please help me where the mistake I expansion.
I use this expansion:
$$e^{i\alpha_2\lambda_2}=1+i\alpha_2\lambda_2+\frac{(i\alpha_2\lambda_2)^2}{2!}+\frac{(i\alpha_2\lambda_2)^3}{3!}. . . $$
$$=(1-\frac{(i\alpha_2)^2}{2!}+...)\lambda^2_2 + i (\alpha_2-\frac{(i\alpha_2)^3}{3!}+..)\lambda_2$$
$$= cos\alpha_2\begin{pmatrix} 1& 0 &
0 & 0 \\ 0 & 1 & 0 & 0 \\ 0& 0 &
0 & 0 \\ 0 & 0 &
0 & 0
    \end{pmatrix} + i sin\alpha_2\begin{pmatrix} 0& -i &
0 & 0 \\ i & 0 & 0 & 0 \\ 0& 0 &
0 & 0 \\ 0 & 0 &
0 & 0
    \end{pmatrix}$$
why the two end row not equal to 1. Please correct me the expansion.
I'm really stuck here.
Thank you very much
Thank you

A: $\hskip 1in$
You replaced $1$ (blue) with $1\cdot\lambda_2^2$ (green). That's why you're missing a $2\times 2$ identity matrix in the lower right block. You also have incorrect signs in the second line (first is in red). Since you left the powers of $i$ uncomputed you shouldn't have any minus signs yet.